@cotal-ai/cli 0.172.2 → 0.174.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 (218) hide show
  1. package/dist/command.d.ts.map +1 -1
  2. package/dist/command.js +32 -16
  3. package/dist/command.js.map +1 -1
  4. package/dist/commands/agents.d.ts.map +1 -1
  5. package/dist/commands/agents.js +22 -11
  6. package/dist/commands/agents.js.map +1 -1
  7. package/dist/commands/backup.d.ts.map +1 -1
  8. package/dist/commands/backup.js +15 -10
  9. package/dist/commands/backup.js.map +1 -1
  10. package/dist/commands/channel-members.d.ts.map +1 -1
  11. package/dist/commands/channel-members.js +29 -2
  12. package/dist/commands/channel-members.js.map +1 -1
  13. package/dist/commands/channels.d.ts.map +1 -1
  14. package/dist/commands/channels.js +12 -2
  15. package/dist/commands/channels.js.map +1 -1
  16. package/dist/commands/clean.d.ts +1 -0
  17. package/dist/commands/clean.d.ts.map +1 -1
  18. package/dist/commands/clean.js +20 -5
  19. package/dist/commands/clean.js.map +1 -1
  20. package/dist/commands/doctor.d.ts.map +1 -1
  21. package/dist/commands/doctor.js +36 -14
  22. package/dist/commands/doctor.js.map +1 -1
  23. package/dist/commands/down-preserve.d.ts +74 -0
  24. package/dist/commands/down-preserve.d.ts.map +1 -0
  25. package/dist/commands/down-preserve.js +626 -0
  26. package/dist/commands/down-preserve.js.map +1 -0
  27. package/dist/commands/down.d.ts +2 -61
  28. package/dist/commands/down.d.ts.map +1 -1
  29. package/dist/commands/down.js +10 -621
  30. package/dist/commands/down.js.map +1 -1
  31. package/dist/commands/ext.d.ts.map +1 -1
  32. package/dist/commands/ext.js +22 -5
  33. package/dist/commands/ext.js.map +1 -1
  34. package/dist/commands/help.d.ts +1 -1
  35. package/dist/commands/help.js +1 -1
  36. package/dist/commands/history.d.ts +10 -2
  37. package/dist/commands/history.d.ts.map +1 -1
  38. package/dist/commands/history.js +21 -9
  39. package/dist/commands/history.js.map +1 -1
  40. package/dist/commands/join.js +5 -1
  41. package/dist/commands/join.js.map +1 -1
  42. package/dist/commands/meshes-add.d.ts +2 -3
  43. package/dist/commands/meshes-add.d.ts.map +1 -1
  44. package/dist/commands/meshes-add.js +3 -19
  45. package/dist/commands/meshes-add.js.map +1 -1
  46. package/dist/commands/mint-endpoint-caller.d.ts.map +1 -1
  47. package/dist/commands/mint-endpoint-caller.js +13 -2
  48. package/dist/commands/mint-endpoint-caller.js.map +1 -1
  49. package/dist/commands/mint.d.ts.map +1 -1
  50. package/dist/commands/mint.js +10 -2
  51. package/dist/commands/mint.js.map +1 -1
  52. package/dist/commands/persona.js +3 -3
  53. package/dist/commands/persona.js.map +1 -1
  54. package/dist/commands/personas.js +1 -1
  55. package/dist/commands/personas.js.map +1 -1
  56. package/dist/commands/send.d.ts.map +1 -1
  57. package/dist/commands/send.js +10 -6
  58. package/dist/commands/send.js.map +1 -1
  59. package/dist/commands/setup.d.ts.map +1 -1
  60. package/dist/commands/setup.js +17 -1
  61. package/dist/commands/setup.js.map +1 -1
  62. package/dist/commands/space-registration.d.ts.map +1 -1
  63. package/dist/commands/space-registration.js +8 -8
  64. package/dist/commands/space-registration.js.map +1 -1
  65. package/dist/commands/space.d.ts.map +1 -1
  66. package/dist/commands/space.js +16 -6
  67. package/dist/commands/space.js.map +1 -1
  68. package/dist/commands/spawn-managed-launch.d.ts.map +1 -1
  69. package/dist/commands/spawn-managed-launch.js +6 -4
  70. package/dist/commands/spawn-managed-launch.js.map +1 -1
  71. package/dist/commands/spawn-preview.d.ts.map +1 -1
  72. package/dist/commands/spawn-preview.js +8 -5
  73. package/dist/commands/spawn-preview.js.map +1 -1
  74. package/dist/commands/spawn.d.ts.map +1 -1
  75. package/dist/commands/spawn.js +3 -3
  76. package/dist/commands/spawn.js.map +1 -1
  77. package/dist/commands/stack-up.d.ts +3 -1
  78. package/dist/commands/stack-up.d.ts.map +1 -1
  79. package/dist/commands/stack-up.js +50 -16
  80. package/dist/commands/stack-up.js.map +1 -1
  81. package/dist/commands/status-delivery.d.ts +9 -0
  82. package/dist/commands/status-delivery.d.ts.map +1 -0
  83. package/dist/commands/status-delivery.js +19 -0
  84. package/dist/commands/status-delivery.js.map +1 -0
  85. package/dist/commands/status-legacy.d.ts +7 -0
  86. package/dist/commands/status-legacy.d.ts.map +1 -0
  87. package/dist/commands/status-legacy.js +35 -0
  88. package/dist/commands/status-legacy.js.map +1 -0
  89. package/dist/commands/status.d.ts.map +1 -1
  90. package/dist/commands/status.js +45 -86
  91. package/dist/commands/status.js.map +1 -1
  92. package/dist/commands/team-agent-apply.js +11 -11
  93. package/dist/commands/team-agent-apply.js.map +1 -1
  94. package/dist/commands/team-deploy-apply.d.ts.map +1 -1
  95. package/dist/commands/team-deploy-apply.js +2 -4
  96. package/dist/commands/team-deploy-apply.js.map +1 -1
  97. package/dist/commands/team.js +12 -19
  98. package/dist/commands/team.js.map +1 -1
  99. package/dist/commands/up-pending.d.ts +24 -0
  100. package/dist/commands/up-pending.d.ts.map +1 -0
  101. package/dist/commands/up-pending.js +5 -0
  102. package/dist/commands/up-pending.js.map +1 -0
  103. package/dist/commands/up.d.ts +3 -1
  104. package/dist/commands/up.d.ts.map +1 -1
  105. package/dist/commands/up.js +56 -80
  106. package/dist/commands/up.js.map +1 -1
  107. package/dist/commands/update-continuity.d.ts +47 -0
  108. package/dist/commands/update-continuity.d.ts.map +1 -0
  109. package/dist/commands/update-continuity.js +430 -0
  110. package/dist/commands/update-continuity.js.map +1 -0
  111. package/dist/commands/update-process.d.ts +26 -0
  112. package/dist/commands/update-process.d.ts.map +1 -0
  113. package/dist/commands/update-process.js +283 -0
  114. package/dist/commands/update-process.js.map +1 -0
  115. package/dist/commands/update-release.d.ts +32 -0
  116. package/dist/commands/update-release.d.ts.map +1 -0
  117. package/dist/commands/update-release.js +232 -0
  118. package/dist/commands/update-release.js.map +1 -0
  119. package/dist/commands/update.d.ts +6 -54
  120. package/dist/commands/update.d.ts.map +1 -1
  121. package/dist/commands/update.js +25 -949
  122. package/dist/commands/update.js.map +1 -1
  123. package/dist/commands/use.d.ts.map +1 -1
  124. package/dist/commands/use.js +4 -7
  125. package/dist/commands/use.js.map +1 -1
  126. package/dist/commands/watch.d.ts.map +1 -1
  127. package/dist/commands/watch.js +5 -2
  128. package/dist/commands/watch.js.map +1 -1
  129. package/dist/commands/whoami.d.ts.map +1 -1
  130. package/dist/commands/whoami.js +3 -2
  131. package/dist/commands/whoami.js.map +1 -1
  132. package/dist/console/commands.js +2 -2
  133. package/dist/console/commands.js.map +1 -1
  134. package/dist/help.d.ts +1 -1
  135. package/dist/help.d.ts.map +1 -1
  136. package/dist/help.js +5 -1
  137. package/dist/help.js.map +1 -1
  138. package/dist/index.d.ts.map +1 -1
  139. package/dist/index.js +7 -5
  140. package/dist/index.js.map +1 -1
  141. package/dist/lib/choose-target.d.ts +2 -0
  142. package/dist/lib/choose-target.d.ts.map +1 -1
  143. package/dist/lib/choose-target.js +28 -10
  144. package/dist/lib/choose-target.js.map +1 -1
  145. package/dist/lib/credential-authority.d.ts +1 -1
  146. package/dist/lib/credential-authority.d.ts.map +1 -1
  147. package/dist/lib/credential-authority.js +8 -3
  148. package/dist/lib/credential-authority.js.map +1 -1
  149. package/dist/lib/endpoint-errors.d.ts.map +1 -1
  150. package/dist/lib/endpoint-errors.js +9 -2
  151. package/dist/lib/endpoint-errors.js.map +1 -1
  152. package/dist/lib/foreground-hold.d.ts +2 -0
  153. package/dist/lib/foreground-hold.d.ts.map +1 -1
  154. package/dist/lib/foreground-hold.js +47 -1
  155. package/dist/lib/foreground-hold.js.map +1 -1
  156. package/dist/lib/mint-renewal.d.ts +5 -0
  157. package/dist/lib/mint-renewal.d.ts.map +1 -0
  158. package/dist/lib/mint-renewal.js +60 -0
  159. package/dist/lib/mint-renewal.js.map +1 -0
  160. package/dist/lib/persona-files.d.ts +1 -1
  161. package/dist/lib/persona-files.d.ts.map +1 -1
  162. package/dist/lib/persona-files.js +6 -7
  163. package/dist/lib/persona-files.js.map +1 -1
  164. package/dist/lib/restore-streams.d.ts +18 -0
  165. package/dist/lib/restore-streams.d.ts.map +1 -0
  166. package/dist/lib/restore-streams.js +275 -0
  167. package/dist/lib/restore-streams.js.map +1 -0
  168. package/dist/lib/restore.d.ts +2 -0
  169. package/dist/lib/restore.d.ts.map +1 -1
  170. package/dist/lib/restore.js +5 -273
  171. package/dist/lib/restore.js.map +1 -1
  172. package/dist/lib/self-exec.d.ts +5 -2
  173. package/dist/lib/self-exec.d.ts.map +1 -1
  174. package/dist/lib/self-exec.js +6 -3
  175. package/dist/lib/self-exec.js.map +1 -1
  176. package/dist/lib/spawn-defaults.d.ts +2 -0
  177. package/dist/lib/spawn-defaults.d.ts.map +1 -1
  178. package/dist/lib/spawn-defaults.js +11 -0
  179. package/dist/lib/spawn-defaults.js.map +1 -1
  180. package/dist/lib/stack-journal.d.ts +3 -1
  181. package/dist/lib/stack-journal.d.ts.map +1 -1
  182. package/dist/lib/stack-journal.js +20 -1
  183. package/dist/lib/stack-journal.js.map +1 -1
  184. package/dist/lib/store-dir.d.ts +3 -1
  185. package/dist/lib/store-dir.d.ts.map +1 -1
  186. package/dist/lib/store-dir.js +20 -4
  187. package/dist/lib/store-dir.js.map +1 -1
  188. package/dist/lib/team-deploy-inspection.d.ts +2 -1
  189. package/dist/lib/team-deploy-inspection.d.ts.map +1 -1
  190. package/dist/lib/team-deploy-inspection.js +6 -1
  191. package/dist/lib/team-deploy-inspection.js.map +1 -1
  192. package/dist/lib/update-connector-config.d.ts +2 -0
  193. package/dist/lib/update-connector-config.d.ts.map +1 -1
  194. package/dist/lib/update-connector-config.js +15 -1
  195. package/dist/lib/update-connector-config.js.map +1 -1
  196. package/dist/lib/update-managers.d.ts.map +1 -1
  197. package/dist/lib/update-managers.js +11 -3
  198. package/dist/lib/update-managers.js.map +1 -1
  199. package/dist/lib/update-recovery-state.d.ts +7 -0
  200. package/dist/lib/update-recovery-state.d.ts.map +1 -1
  201. package/dist/lib/update-recovery-state.js +55 -2
  202. package/dist/lib/update-recovery-state.js.map +1 -1
  203. package/dist/lib/update-snapshot.d.ts.map +1 -1
  204. package/dist/lib/update-snapshot.js +14 -7
  205. package/dist/lib/update-snapshot.js.map +1 -1
  206. package/dist/seed/launch.d.ts +1 -1
  207. package/dist/seed/launch.d.ts.map +1 -1
  208. package/dist/seed/launch.js +3 -3
  209. package/dist/seed/launch.js.map +1 -1
  210. package/dist/seed/lock.d.ts +1 -1
  211. package/dist/seed/lock.d.ts.map +1 -1
  212. package/dist/seed/lock.js +3 -2
  213. package/dist/seed/lock.js.map +1 -1
  214. package/dist/telemetry.d.ts +6 -0
  215. package/dist/telemetry.d.ts.map +1 -1
  216. package/dist/telemetry.js +6 -3
  217. package/dist/telemetry.js.map +1 -1
  218. package/package.json +5 -5
@@ -45,9 +45,9 @@ import { checkSpaceFlagValue, checkSpaceName } from "./meshes-add.js";
45
45
  import { checkLocalSpace } from "./space-registration.js";
46
46
  import { checkNewUpSpace, preparedUpRoot } from "./up-target.js";
47
47
  import { cleanedManifestStart, interruptedStartBroker, namedOpenConfig, retainedOpenSpace } from "../lib/legacy-start.js";
48
- import { bindReaches, canonicalServer, controllerStackApplies, recheckExistingStore, requestedStackMode, requestsTls, stackUp, stackUpForegroundNotice, stackUpInterrupted, keptOnUp, selectedOnUp, unparsableDaemonCredsNotice, } from "./stack-up.js";
49
- import { handOverStartupNotice, noticeOnInterrupt, releaseStartupNotice } from "../lib/interrupt-notice.js";
50
- import { claimForegroundHold, foregroundHolder, releaseForegroundHold } from "../lib/foreground-hold.js";
48
+ import { bindReaches, canonicalServer, controllerStackApplies, recheckExistingStore, requestedStackMode, refuseForegroundStackHolder, requestsTls, stackUp, stackUpForegroundNotice, stackUpInterrupted, keptOnUp, selectedOnUp, unparsableDaemonCredsNotice, } from "./stack-up.js";
49
+ import { exitInterrupted, handOverStartupNotice, noticeOnInterrupt, releaseStartupNotice } from "../lib/interrupt-notice.js";
50
+ import { claimForegroundHold, foregroundHolder, foregroundStackEnd, releaseForegroundHold } from "../lib/foreground-hold.js";
51
51
  import { settleInterruptedLaunches } from "../lib/service-process.js";
52
52
  import { assertUserStackTransport, preflightUserStack } from "./stack-user-auth.js";
53
53
  import { stackDown } from "./stack-down.js";
@@ -61,18 +61,18 @@ import { serviceSupervisorStore } from "../lib/service-supervision.js";
61
61
  import { serviceInstallIntents } from "../lib/service-install-intent.js";
62
62
  import { serviceUninstallIntents } from "../lib/service-uninstall-intent.js";
63
63
  import { serviceUnitActionStore } from "../lib/service-unit-action.js";
64
- import { assertStoreDirArgument, configuredStoreDir, lastServedStore, lastServedStores, missingStoreWarning, servedStore, sharedStoreAtStart, sharedStoreWarning, storeWriteProblem, warnForeignStoreEntries } from "../lib/store-dir.js";
64
+ import { assertStoreDirArgument, configuredStoreDir, lastServedStore, lastServedStores, missingStoreWarning, servedStore, sharedStoreAtStart, sharedStoreWarning, startupStoreProblem, warnForeignStoreEntries } from "../lib/store-dir.js";
65
65
  import { extensionNames, preflightRuntime } from "../ext-loader.js";
66
66
  import { completingFlagValue } from "../lib/completion.js";
67
67
  import { metadataPositionals } from "../lib/command-path.js";
68
- import { bindPreparedRestoreListener, isManagerCommitResult, isManagerFinalizeResult, isManagerCommittedRestore, markPreparedRestoreActive, markPreparedRestoreDegraded, heldRestoreAttempt, heldClaim, movedFolderRefusal, prepareRestore, restoreArtifactPath, restoreLaunch, preservedSourceState, recordPreparedRestoreManagerCommit, rehydratePreparedRestore, journaledMaxFileStore, journaledRestoredStreams, leftOutNotes, rearmUnboundRestore, replacePreparedDeadRestoreListener, restoreComposition, restoreNextStep, restoreOnlyCopy, } from "../lib/restore.js";
68
+ import { bindPreparedRestoreListener, isManagerCommitResult, isManagerFinalizeResult, isManagerCommittedRestore, markPreparedRestoreActive, markPreparedRestoreDegraded, heldRestoreAttempt, heldClaim, movedFolderRefusal, prepareRestore, restoreArtifactPath, restoreLaunch, preservedSourceState, recordPreparedRestoreManagerCommit, rehydratePreparedRestore, journaledMaxFileStore, journaledRestoredStreams, leftOutNotes, rearmUnboundRestore, replacePreparedDeadRestoreListener, restoreComposition, restoreInterruptNotice, restoreNextStep, restoreOnlyCopy, } from "../lib/restore.js";
69
69
  import { attemptProcessesGone } from "../lib/isolated-broker.js";
70
70
  import { assertEndpointUnreachable } from "../lib/endpoint-cut.js";
71
71
  import { addressHolder, brokerListenAddress, listenerBindError } from "../lib/broker-service.js";
72
72
  import { freePort, freshStackServer, retryStackAddress, serverWithFreePort } from "../lib/up-broker-address.js";
73
73
  import { askManager } from "@cotal-ai/workspace/control";
74
74
  import { cliControl } from "../lib/control.js";
75
- const pendingRestores = new Map();
75
+ import { pendingRestores, pendingOrdinaryResumes } from "./up-pending.js";
76
76
  const restoreSinks = new Map();
77
77
  /** Run the guarded `up --restore` startup and return its result instead of printing it. The
78
78
  * restore inputs and fences are exactly `up --restore`'s; this adds no route, flag or authority. */
@@ -85,7 +85,6 @@ export async function startRestore(values) {
85
85
  }
86
86
  return returned;
87
87
  }
88
- const pendingOrdinaryResumes = new Map();
89
88
  /** `cotal up` flags — colocated with the command (like `spawnFlags`) so its completion can read them. */
90
89
  export const upFlags = [
91
90
  { name: "server", type: "string", value: "<url>", description: "listen URL; a stack's first up records it and later ups keep it" },
@@ -100,7 +99,7 @@ export const upFlags = [
100
99
  { name: "auth-timeout", type: "string", value: "<seconds>", description: "user-auth only: how long the broker waits for the auth callout, 1 to 60 seconds (default: nats-server's 2); the auth service answers inside it. Fixed at broker start and recorded for the next `up`" },
101
100
  { name: "max-payload", type: "string", value: "<bytes>", description: `broker-wide message size limit in bytes (default: nats-server's ${NATS_DEFAULT_MAX_PAYLOAD}). A manager-backed start needs at least 263168, and service endpoint caller grants need at least 2098176. Fixed at broker start and recorded for the next \`up\`` },
102
101
  { name: "account-resolver", type: "string", value: "<memory|full>", description: "how the broker resolves space accounts: memory (default) knows only the accounts its configuration lists, so adding one means a reload; full also keeps pushed account claims in .cotal/account-jwts, so a host can add and retire accounts on the running broker without a reload. Fixed at broker start and recorded for the next `up`" },
103
- { name: "channels", type: "string", value: "<path>", description: "channel-registry seed file (JSON; default .cotal/channels.json)" },
102
+ { name: "channels", type: "string", value: "<path>", description: "channel-registry seed file (JSON; default .cotal/channels.json); not used with -f" },
104
103
  { name: "tls-cert", type: "string", value: "<file>", description: "serve the broker over TLS with this certificate (requires --tls-key)" },
105
104
  { name: "tls-key", type: "string", value: "<file>", description: "the private key for --tls-cert" },
106
105
  { name: "restore", type: "string", value: "<dir>", description: "restore an offline backup before exposing the normal listener" },
@@ -128,8 +127,8 @@ export const upFlags = [
128
127
  { name: "no-manager", type: "boolean", description: "broker-only boot: start the broker and, in auth mode, the delivery daemon, and no local manager (refuses on a mesh whose manager is live)" },
129
128
  { name: "file", type: "string", short: "f", value: "<cotal.yaml>", description: "launch a whole mesh from a manifest" },
130
129
  { name: "dry-run", type: "boolean", description: "with -f: print the plan, mutate nothing" },
131
- { ...jsonFlag, description: "controller-owned stack only: one structured receipt on stdout" },
132
- { ...plainFlag, description: "controller-owned stack only: plain line-oriented receipt" },
130
+ { ...jsonFlag, description: "one structured receipt on stdout (controller-owned stack only, without --foreground)" },
131
+ { ...plainFlag, description: "plain line-oriented receipt (controller-owned stack only, without --foreground)" },
133
132
  ];
134
133
  /** Completion for `cotal up` — `--runtime <TAB>` offers `pty` + installed runtime providers (the same
135
134
  * offline source `spawn` uses; a <TAB> never imports or probes). Run `cotal runtimes` to also see the
@@ -220,7 +219,7 @@ export function validateUpArguments(args) {
220
219
  if (args.values.file !== undefined && args.values.foreground === true)
221
220
  throw new CommandFailure("refused", "UNSUPPORTED", "manifest boot has no native foreground custody path; a detached broker was not substituted for the requested terminal-bound lifetime");
222
221
  if (args.values.foreground === true && (args.values.json === true || args.values.plain === true))
223
- throw new CommandFailure("refused", "USAGE_INVALID", "foreground up keeps native terminal custody and cannot produce a finite JSON or plain receipt");
222
+ throw new CommandFailure("refused", "USAGE_INVALID", "foreground up keeps native terminal custody and cannot produce a finite JSON or plain receipt", { remedy: `omit ${args.values.json ? "--json" : "--plain"} to keep the stack in this terminal, or omit --foreground for a finite receipt from a controller-owned stack` });
224
223
  // Flag values and combinations are usage, so they refuse here, before any effect. The run keeps
225
224
  // its own checks for maintenance re-entries, which do not pass through this validation.
226
225
  parsePositiveIntegerFlag("--max-sessions", args.values["max-sessions"]);
@@ -341,24 +340,7 @@ function assertUpRootWritable(root) {
341
340
  * a start here opens, as `--store-dir` names it, as the stack or legacy records name it, or `.cotal/nats`,
342
341
  * is refused here, by name, when this account cannot write it. */
343
342
  function assertUpStoreWritable(root, storeDir) {
344
- let recorded;
345
- try {
346
- recorded = readStackJournal(root)?.journal.broker?.storeDir;
347
- }
348
- catch {
349
- recorded = undefined;
350
- }
351
- const defaultStore = join(root, ".cotal", "nats");
352
- if (storeDir === undefined && recorded === undefined) {
353
- const local = localMeshesForRoot(root);
354
- recorded = local.length === 1 ? local[0].storeDir : undefined;
355
- if (recorded === undefined && !existsSync(join(defaultStore, "jetstream"))) {
356
- const served = lastServedStores(root, defaultStore);
357
- if (served.length === 1)
358
- recorded = served[0];
359
- }
360
- }
361
- const problem = storeWriteProblem(storeDir !== undefined ? resolve(storeDir) : recorded ?? defaultStore);
343
+ const problem = startupStoreProblem(root, storeDir);
362
344
  if (problem)
363
345
  throw new CommandFailure("refused", "PERMISSION_DENIED", `${problem.message}; nothing was started or written`, { target: { root, path: problem.path }, remedy: problem.remedy });
364
346
  }
@@ -619,7 +601,7 @@ function hangupForegroundStack(root) {
619
601
  * exits 129, naming `cotal down`. `start`, when given, is the startup this terminal already holds: a
620
602
  * signal during it lets the start settle, then a stop signal runs that stop and a hangup leaves what
621
603
  * the start left. A failed start still runs the stop, and its failure is thrown once the stop returns.
622
- * The hold's end sets the exit code: 0 when another command completed the stop or preserve, 129 after
604
+ * The hold exits 0 after a completed external stop or preserve, 5 after a broker crash, 129 after
623
605
  * a hangup, 130 or 143 after a stop signal, whatever the start receipt set. */
624
606
  export async function holdForegroundStack(root, start, releaseRestoreNotice) {
625
607
  claimForegroundHold(root);
@@ -670,29 +652,26 @@ async function holdStack(root, start, releaseRestoreNotice) {
670
652
  return;
671
653
  }
672
654
  return new Promise((resolveHold) => {
673
- // The hold ends on its own when another command completes a whole-stack stop or preserve of this
674
- // root: a later operation recorded as completed is that evidence. Any other later operation,
675
- // such as a refresh, keeps the hold. The poll also keeps Node alive, which a pending promise and
676
- // signal listeners alone do not.
677
- const recorded = () => { try {
678
- return readStackJournal(root)?.journal.operation;
655
+ // The poll keeps Node alive and observes the recorded broker and external stack operations.
656
+ const held = (() => { try {
657
+ return readStackJournal(root)?.journal.operation.id;
679
658
  }
680
659
  catch {
681
660
  return undefined;
682
- } };
683
- const held = recorded()?.id;
661
+ } })();
684
662
  let stopping = false;
685
663
  const lifetime = setInterval(() => {
686
- const operation = recorded();
687
- if (stopping || !operation || operation.id === held || operation.phase !== "completed" || operation.kind !== "down" && operation.kind !== "preserve")
664
+ if (stopping)
665
+ return;
666
+ const code = foregroundStackEnd(root, held);
667
+ if (code === undefined)
688
668
  return;
689
669
  stopping = true;
690
670
  process.off("SIGINT", interrupt);
691
671
  process.off("SIGTERM", terminate);
692
672
  process.off("SIGHUP", hangup);
693
673
  clearInterval(lifetime);
694
- process.stderr.write(`${renderReport({ sections: [{ title: "Foreground stack released", blocks: [{ kind: "lines", lines: [`Another command completed a ${operation.kind === "down" ? "stop" : "preserve"} of this stack (operation ${operation.id}). This terminal no longer holds it.`] }] }] }, "rich", process.stderr)}\n`);
695
- process.exitCode = 0;
674
+ process.exitCode = code;
696
675
  resolveHold();
697
676
  }, 1000);
698
677
  const stop = (signal) => {
@@ -768,9 +747,10 @@ export async function up(args, inheritedLock, freshTeamBoot = false, restoreSink
768
747
  const root = args.values.root === undefined ? undefined : preparedUpRoot(String(args.values.root));
769
748
  const fresh = args.values.root === undefined ? freshFolderRoot(args.values) : undefined;
770
749
  checkNewUpSpace(args.values.space, root ?? fresh);
771
- // The broker reads an explicit channels file only once it is being prepared, so a file it would
772
- // refuse is named here, before the stack journal or anything else is written.
773
- if (typeof args.values.channels === "string")
750
+ // Validate a seed before writing stack records only on the route that uses it.
751
+ if (typeof args.values.channels === "string" && args.values.file)
752
+ recordOperationWarning({ code: "MANIFEST_CHANNEL_SEED_IGNORED", target: null, message: "--channels is not used with -f. Set channels and defaults in the manifest." }, { echo: args.values.json !== true });
753
+ else if (typeof args.values.channels === "string")
774
754
  readChannelsFile(resolve(args.values.channels));
775
755
  const folderNamed = folderNamedSpace(args.values);
776
756
  if (folderNamed)
@@ -1490,7 +1470,7 @@ async function runUp(args, invokedFrom, inheritedLock, onAdopt, freshTeamBoot =
1490
1470
  // one, it takes that stack's lifetime over and says so before it blocks.
1491
1471
  const holder = values.foreground ? foregroundHolder(meshRoot) : undefined;
1492
1472
  if (holder !== undefined)
1493
- throw new CommandFailure("refused", "CONFLICT", `a foreground \`cotal up\` in process ${holder} already holds this stack's lifetime; this terminal did not take it over and nothing was started`, { target: { root: meshRoot, space: stackSpace, holderPid: holder }, remedy: `use the terminal that runs process ${holder}, where Ctrl-C stops the stack, or stop it with \`cotal down --yes\` from ${meshRoot} and run \`cotal up --foreground\` again` });
1473
+ refuseForegroundStackHolder(meshRoot, stackSpace, holder);
1494
1474
  const takeover = values.foreground === true && STACK_ROLES.some((role) => serviceInstances(stackSpace, STACK_DEFINITION[role]).some((row) => observeServiceProcess(row.record.value) === "running"));
1495
1475
  // A signal ends a detached start where it is, after it records a launch it had not yet pinned to
1496
1476
  // its child, and the notice names what it left running. It is installed before the lock, so no
@@ -1503,7 +1483,7 @@ async function runUp(args, invokedFrom, inheritedLock, onAdopt, freshTeamBoot =
1503
1483
  return `${failure.message} ${failure.remedy}`;
1504
1484
  });
1505
1485
  try {
1506
- const stackLock = acquireStackOperationLock(meshRoot);
1486
+ const stackLock = acquireStackOperationLock(meshRoot, values.foreground ? "foreground up" : undefined);
1507
1487
  const native = controllerStackNative();
1508
1488
  // A foreground terminal holds the start as well, so a signal during it stops what it started.
1509
1489
  const start = async () => {
@@ -1541,34 +1521,33 @@ async function runUp(args, invokedFrom, inheritedLock, onAdopt, freshTeamBoot =
1541
1521
  // that name over, as `down` there does not stop it.
1542
1522
  if (!values.file && values.space === undefined)
1543
1523
  await refuseRecordsElsewhere(meshRoot);
1544
- if (values.json || values.plain) {
1545
- // `up -f` always takes the retained launcher, so the controller route is no remedy there. Its
1546
- // manifest is checked first, so a manifest that does not validate gets its own refusal.
1547
- if (values.file) {
1548
- const path = resolve(values.file);
1524
+ if (!values.file && (values.json || values.plain))
1525
+ throw retainedStartupPresentationRefusal(meshRoot);
1526
+ // `up -f cotal.yaml` is a distinct path: bring up a FRESH mesh described by a manifest (broker +
1527
+ // channels + booted agents). It owns the whole space; the additive team deploy route is separate.
1528
+ // CLI flags override the manifest (flag > manifest > default) so the same file runs at a different
1529
+ // port / runtime / auth without editing it. Its space is its target: `--space` may only repeat it.
1530
+ if (values.file) {
1531
+ const path = resolve(values.file);
1532
+ // Structured and plain manifest refusals report file errors before checking startup support.
1533
+ if (values.json || values.plain) {
1549
1534
  try {
1550
1535
  loadManifest(path);
1551
1536
  }
1552
1537
  catch (e) {
1553
1538
  throw manifestFileRefusal(e, path);
1554
1539
  }
1555
- throw new CommandFailure("refused", "UNSUPPORTED", "up -f starts its manifest on the retained native launcher, which has no structured or plain receipt; nothing was started", { target: { root: meshRoot, path }, remedy: `omit ${values.json ? "--json" : "--plain"}` });
1556
1540
  }
1557
- throw retainedStartupPresentationRefusal(meshRoot);
1558
- }
1559
- // `up -f cotal.yaml` is a distinct path: bring up a FRESH mesh described by a manifest (broker +
1560
- // channels + booted agents). It owns the whole space; the additive team deploy route is separate.
1561
- // CLI flags override the manifest (flag > manifest > default) so the same file runs at a different
1562
- // port / runtime / auth without editing it. Its space is its target: `--space` may only repeat it.
1563
- if (values.file) {
1564
1541
  // A manifest start takes the legacy launcher, which never runs beside a controller stack, running
1565
1542
  // or stopped, so a dry run refuses as the start would.
1566
1543
  const controller = freshTeamBoot ? undefined : readStackJournal(meshRoot);
1567
1544
  if (controller)
1568
1545
  throw new CommandFailure("refused", "CONFLICT", `this root holds the controller stack of space ${controller.journal.space}, and up -f does not start a manifest beside it; nothing was started`, {
1569
1546
  target: { root: meshRoot, space: controller.journal.space },
1570
- remedy: controllerManifestRemedy(meshRoot, controller.journal.space, resolve(values.file)),
1547
+ remedy: controllerManifestRemedy(meshRoot, controller.journal.space, path),
1571
1548
  });
1549
+ if (values.json || values.plain)
1550
+ throw new CommandFailure("refused", "UNSUPPORTED", "up -f starts its manifest on the retained native launcher, which has no structured or plain receipt; nothing was started", { target: { root: meshRoot, path }, remedy: `omit ${values.json ? "--json" : "--plain"}` });
1572
1551
  if (values["dry-run"]) {
1573
1552
  await upManifest(values.file, {
1574
1553
  transport,
@@ -2314,11 +2293,8 @@ async function runUp(args, invokedFrom, inheritedLock, onAdopt, freshTeamBoot =
2314
2293
  if (!resumeAttempt)
2315
2294
  process.exit(1);
2316
2295
  });
2317
- // The control plane is coupled to the broker: stop the detached manager AND the delivery daemon
2318
- // (AND the space's user-auth service) when this `up` stops (Ctrl-C), so none outlives the broker
2319
- // it serves — a surviving manager would reconnect-loop invisibly against the dead (or the NEXT)
2320
- // broker (the documented orphan-supervisor failure mode). All kill by pidfile, symmetric; the
2321
- // auth service's pid is space-scoped so no other space's daemon can ever be hit.
2296
+ // Stop the detached manager, delivery daemon and space's user-auth service before their broker,
2297
+ // so none outlives it. The auth service's process record is space-scoped.
2322
2298
  // The manager goes first, in `cotal down`'s order, through the stop `cotal down` runs (#1307): it
2323
2299
  // holds the stop reservation, asserts the exact manager can spare its seats before any signal,
2324
2300
  // reports the seats left behind, and escalates a wedged manager to SIGKILL. When that stop throws
@@ -2331,10 +2307,9 @@ async function runUp(args, invokedFrom, inheritedLock, onAdopt, freshTeamBoot =
2331
2307
  // the failure is logged, never swallowed silently. Teardown is AWAITED before the broker is
2332
2308
  // signalled, so it never races a broker that is already going away.
2333
2309
  let stopping = false;
2334
- // The signal that asked for the stop. The broker is then signalled SIGTERM, so its own exit
2335
- // status is not the command's: SIGINT exits 130 and SIGTERM exits 143, as a controller stack's
2336
- // foreground stop does.
2310
+ // The operator's signal sets the command's exit status, not the broker's SIGTERM.
2337
2311
  let stopSignal;
2312
+ let stoppedListener = false;
2338
2313
  let teardown;
2339
2314
  const stop = (signal) => {
2340
2315
  if (stopping)
@@ -2358,15 +2333,13 @@ async function runUp(args, invokedFrom, inheritedLock, onAdopt, freshTeamBoot =
2358
2333
  }
2359
2334
  await stopDelivery(space).catch((e) => console.error(`! delivery teardown: ${e.message}`));
2360
2335
  await stopAuthService(space).catch((e) => console.error(`! auth teardown: ${e.message}`));
2361
- child.kill("SIGTERM");
2336
+ stoppedListener = child.kill("SIGTERM");
2362
2337
  })();
2363
2338
  };
2364
2339
  process.on("SIGINT", () => stop("SIGINT"));
2365
2340
  process.on("SIGTERM", () => stop("SIGTERM"));
2366
2341
  restored?.releaseInterruptNotice?.();
2367
- // The broker is gone. Drop the registration this stop recorded, and the `current` pointer when it
2368
- // names that registration, so a later `cotal spawn` does not join a dead mesh. A space named after
2369
- // its folder keeps both, as `cotal down` does, so the name stays the folder's.
2342
+ // On exit, drop only this stop's registration and matching `current` pointer, unless folder-named.
2370
2343
  child.on("exit", async (code, signal) => {
2371
2344
  if (failedListeners.has(child))
2372
2345
  return;
@@ -2433,7 +2406,12 @@ async function runUp(args, invokedFrom, inheritedLock, onAdopt, freshTeamBoot =
2433
2406
  process.exit(exitCode("failed", "OPERATION_FAILED"));
2434
2407
  }
2435
2408
  });
2436
- await awaitSpawnedListener({ child, executable: natsServer, server, space, creds: setup?.creds, tls: transport.kind === "tls-required", log: brokerOutput, boundListener });
2409
+ await awaitSpawnedListener({ child, executable: natsServer, server, space, creds: setup?.creds, tls: transport.kind === "tls-required", log: brokerOutput, boundListener }).catch((error) => {
2410
+ if (!restored || !stoppedListener || !stopSignal || (child.exitCode === null && child.signalCode === null))
2411
+ throw error;
2412
+ releaseStartupLock();
2413
+ exitInterrupted(stopSignal, restoreInterruptNotice(restored.root, restored.attemptId));
2414
+ });
2437
2415
  listenerReady = true;
2438
2416
  {
2439
2417
  // A DAEMON THAT DIES UNDER THIS RUNNING BROKER IS RESTARTED HERE (#2469). It exits on its own once
@@ -3488,7 +3466,7 @@ export async function recheckFreshTeamBoot(plan, own) {
3488
3466
  export function controllerStackNative() {
3489
3467
  return {
3490
3468
  prepareBroker: async (opts) => {
3491
- const prepared = await prepareBrokerStart({ transport: opts.transport, server: opts.server, space: opts.space, ...(opts.open ? { open: true } : {}), ...(opts.userAuth ? { userAuth: opts.userAuth } : {}), ...(opts.host ? { host: opts.host } : {}), ...(opts.storeDir ? { storeDir: opts.storeDir } : {}), ...(opts.existingStore ? { existingStore: opts.existingStore } : {}), ...(opts.maxFileStore !== undefined ? { maxFileStore: opts.maxFileStore } : {}), ...(opts.logFile !== undefined ? { logFile: opts.logFile } : {}), ...(opts.logfileSizeLimit !== undefined ? { logfileSizeLimit: opts.logfileSizeLimit } : {}), ...(opts.logfileMaxNum !== undefined ? { logfileMaxNum: opts.logfileMaxNum } : {}), ...(opts.authTimeout !== undefined ? { authTimeout: opts.authTimeout } : {}), ...(opts.maxPayload !== undefined ? { maxPayload: opts.maxPayload } : {}), ...(opts.accountResolver !== undefined ? { accountResolver: opts.accountResolver } : {}), ...(opts.noManager ? { noManager: true } : {}), ...(opts.seed !== undefined ? { seed: opts.seed } : opts.channels ? { channels: opts.channels } : {}), quietBoot: true });
3469
+ const prepared = await prepareBrokerStart({ transport: opts.transport, server: opts.server, space: opts.space, ...(opts.open ? { open: true } : {}), ...(opts.userAuth ? { userAuth: opts.userAuth } : {}), ...(opts.host ? { host: opts.host } : {}), ...(opts.wsPort !== undefined ? { wsPort: opts.wsPort } : {}), ...(opts.storeDir ? { storeDir: opts.storeDir } : {}), ...(opts.existingStore ? { existingStore: opts.existingStore } : {}), ...(opts.maxFileStore !== undefined ? { maxFileStore: opts.maxFileStore } : {}), ...(opts.logFile !== undefined ? { logFile: opts.logFile } : {}), ...(opts.logfileSizeLimit !== undefined ? { logfileSizeLimit: opts.logfileSizeLimit } : {}), ...(opts.logfileMaxNum !== undefined ? { logfileMaxNum: opts.logfileMaxNum } : {}), ...(opts.authTimeout !== undefined ? { authTimeout: opts.authTimeout } : {}), ...(opts.maxPayload !== undefined ? { maxPayload: opts.maxPayload } : {}), ...(opts.accountResolver !== undefined ? { accountResolver: opts.accountResolver } : {}), ...(opts.noManager ? { noManager: true } : {}), ...(opts.seed !== undefined ? { seed: opts.seed } : opts.channels ? { channels: opts.channels } : {}), quietBoot: true });
3492
3470
  return { root: prepared.root, server: prepared.server, space: prepared.space, storeDir: prepared.storeDir, transport: prepared.transport, ...(prepared.setup ? { setup: { mintProvisioner: prepared.setup.mintProvisioner, wsPort: prepared.setup.wsPort, moveWebsocketPort: prepared.setup.moveWebsocketPort } } : {}), ...(prepared.setup?.prepared && prepared.setup.stateDir ? { user: { prepared: prepared.setup.prepared, stateDir: prepared.setup.stateDir } } : {}), confPath: prepared.confPath, bin: prepared.bin, source: prepared.source, version: prepared.version, seedFile: prepared.seedFile, ...(prepared.setup?.authTimeout !== undefined ? { authTimeout: prepared.setup.authTimeout } : {}), ...(prepared.maxPayload !== undefined ? { maxPayload: prepared.maxPayload } : {}), ...(prepared.setup?.accountResolver !== undefined ? { accountResolver: prepared.setup.accountResolver } : {}) };
3493
3471
  },
3494
3472
  initializeStreams: async (server, space, setup, seedFile, recreateIssuedStores, recreateMembershipStore) => postStart(server, space, setup && { creds: await setup.mintProvisioner() }, seedFile, recreateIssuedStores, recreateMembershipStore, true),
@@ -4153,7 +4131,7 @@ export async function prepareBrokerStart(opts) {
4153
4131
  closeSync(fd);
4154
4132
  }
4155
4133
  }
4156
- const setup = useAuth ? await authSetup(storeDir, server, space, host, opts.userAuth, transport, opts.rotateSys, opts.maxFileStore, opts.quietBoot, { authTimeout: opts.authTimeout, maxPayload: opts.maxPayload, accountResolver: opts.accountResolver, manager: opts.noManager !== true, logFile, logfileSizeLimit: opts.logfileSizeLimit, logfileMaxNum: opts.logfileMaxNum }) : undefined;
4134
+ const setup = useAuth ? await authSetup(storeDir, server, space, host, opts.userAuth, transport, opts.rotateSys, opts.maxFileStore, opts.quietBoot, { authTimeout: opts.authTimeout, maxPayload: opts.maxPayload, accountResolver: opts.accountResolver, manager: opts.noManager !== true, logFile, logfileSizeLimit: opts.logfileSizeLimit, logfileMaxNum: opts.logfileMaxNum, wsPort: opts.wsPort }) : undefined;
4157
4135
  const maxPayload = setup?.maxPayload ?? opts.maxPayload ?? readBrokerPolicy(root)?.maxPayload;
4158
4136
  const port = Number(new URL(server).port) || 4222;
4159
4137
  // Same rule as the foreground path: every route to a listener names its transport (see
@@ -5525,10 +5503,8 @@ requested = {}) {
5525
5503
  }
5526
5504
  }
5527
5505
  const port = Number(new URL(server).port) || 4222;
5528
- // P2 item 6: allocate the broker's loopback WebSocket listener port — the console page becomes a
5529
- // mesh §13.6 session client over it (a NEW same-host attack surface, localhost-bound, no TLS). The
5530
- // manager's establisher builds its wsUrl from this; threaded to `supervise --ws-port`.
5531
- const wsPort = await freePort(host);
5506
+ // A reused controller manager advertises its launch-time WebSocket port.
5507
+ const wsPort = requested.wsPort ?? await freePort(host);
5532
5508
  const confPath = resolve(dir, "server.conf");
5533
5509
  // EVERY tenant of this root, not just the one being booted: `resolver_preload` is a whole-broker
5534
5510
  // map, so a config rendered from one space evicts the rest silently. `auth` leads the list because