@cotal-ai/cli 0.174.3 → 0.174.4

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 (205) hide show
  1. package/dist/command.d.ts.map +1 -1
  2. package/dist/command.js +8 -5
  3. package/dist/command.js.map +1 -1
  4. package/dist/commands/agents.d.ts.map +1 -1
  5. package/dist/commands/agents.js +17 -10
  6. package/dist/commands/agents.js.map +1 -1
  7. package/dist/commands/channel-members.d.ts.map +1 -1
  8. package/dist/commands/channel-members.js +9 -7
  9. package/dist/commands/channel-members.js.map +1 -1
  10. package/dist/commands/channels.d.ts.map +1 -1
  11. package/dist/commands/channels.js +16 -7
  12. package/dist/commands/channels.js.map +1 -1
  13. package/dist/commands/chat.js +1 -1
  14. package/dist/commands/chat.js.map +1 -1
  15. package/dist/commands/clean.d.ts.map +1 -1
  16. package/dist/commands/clean.js +5 -3
  17. package/dist/commands/clean.js.map +1 -1
  18. package/dist/commands/config.d.ts.map +1 -1
  19. package/dist/commands/config.js +8 -1
  20. package/dist/commands/config.js.map +1 -1
  21. package/dist/commands/describe.d.ts.map +1 -1
  22. package/dist/commands/describe.js +11 -1
  23. package/dist/commands/describe.js.map +1 -1
  24. package/dist/commands/doctor.d.ts.map +1 -1
  25. package/dist/commands/doctor.js +21 -9
  26. package/dist/commands/doctor.js.map +1 -1
  27. package/dist/commands/down-preserve.d.ts.map +1 -1
  28. package/dist/commands/down-preserve.js +2 -1
  29. package/dist/commands/down-preserve.js.map +1 -1
  30. package/dist/commands/endpoint-authoring.d.ts.map +1 -1
  31. package/dist/commands/endpoint-authoring.js +20 -19
  32. package/dist/commands/endpoint-authoring.js.map +1 -1
  33. package/dist/commands/endpoint.d.ts.map +1 -1
  34. package/dist/commands/endpoint.js +7 -2
  35. package/dist/commands/endpoint.js.map +1 -1
  36. package/dist/commands/endpoints.d.ts.map +1 -1
  37. package/dist/commands/endpoints.js +12 -5
  38. package/dist/commands/endpoints.js.map +1 -1
  39. package/dist/commands/ext.d.ts +2 -6
  40. package/dist/commands/ext.d.ts.map +1 -1
  41. package/dist/commands/ext.js +19 -25
  42. package/dist/commands/ext.js.map +1 -1
  43. package/dist/commands/history-clear.d.ts.map +1 -1
  44. package/dist/commands/history-clear.js +5 -2
  45. package/dist/commands/history-clear.js.map +1 -1
  46. package/dist/commands/join.d.ts.map +1 -1
  47. package/dist/commands/join.js +23 -20
  48. package/dist/commands/join.js.map +1 -1
  49. package/dist/commands/meshes-add.d.ts.map +1 -1
  50. package/dist/commands/meshes-add.js +3 -2
  51. package/dist/commands/meshes-add.js.map +1 -1
  52. package/dist/commands/meshes.d.ts.map +1 -1
  53. package/dist/commands/meshes.js +17 -4
  54. package/dist/commands/meshes.js.map +1 -1
  55. package/dist/commands/persona-remote.d.ts.map +1 -1
  56. package/dist/commands/persona-remote.js +8 -4
  57. package/dist/commands/persona-remote.js.map +1 -1
  58. package/dist/commands/persona.d.ts.map +1 -1
  59. package/dist/commands/persona.js +38 -29
  60. package/dist/commands/persona.js.map +1 -1
  61. package/dist/commands/personas.js +1 -5
  62. package/dist/commands/personas.js.map +1 -1
  63. package/dist/commands/revoke-credential.d.ts.map +1 -1
  64. package/dist/commands/revoke-credential.js +5 -2
  65. package/dist/commands/revoke-credential.js.map +1 -1
  66. package/dist/commands/service-registry.js +1 -1
  67. package/dist/commands/service-registry.js.map +1 -1
  68. package/dist/commands/setup.d.ts.map +1 -1
  69. package/dist/commands/setup.js +2 -2
  70. package/dist/commands/setup.js.map +1 -1
  71. package/dist/commands/space-delete.d.ts.map +1 -1
  72. package/dist/commands/space-delete.js +17 -10
  73. package/dist/commands/space-delete.js.map +1 -1
  74. package/dist/commands/space-registration.d.ts.map +1 -1
  75. package/dist/commands/space-registration.js +11 -9
  76. package/dist/commands/space-registration.js.map +1 -1
  77. package/dist/commands/space.d.ts.map +1 -1
  78. package/dist/commands/space.js +39 -9
  79. package/dist/commands/space.js.map +1 -1
  80. package/dist/commands/spawn-flags.d.ts +5 -7
  81. package/dist/commands/spawn-flags.d.ts.map +1 -1
  82. package/dist/commands/spawn-flags.js +42 -6
  83. package/dist/commands/spawn-flags.js.map +1 -1
  84. package/dist/commands/spawn-preview.d.ts.map +1 -1
  85. package/dist/commands/spawn-preview.js +5 -3
  86. package/dist/commands/spawn-preview.js.map +1 -1
  87. package/dist/commands/spawn.d.ts.map +1 -1
  88. package/dist/commands/spawn.js +9 -2
  89. package/dist/commands/spawn.js.map +1 -1
  90. package/dist/commands/stack-up.d.ts.map +1 -1
  91. package/dist/commands/stack-up.js +12 -6
  92. package/dist/commands/stack-up.js.map +1 -1
  93. package/dist/commands/status-health.d.ts +139 -0
  94. package/dist/commands/status-health.d.ts.map +1 -0
  95. package/dist/commands/status-health.js +651 -0
  96. package/dist/commands/status-health.js.map +1 -0
  97. package/dist/commands/status-meshes.d.ts +26 -0
  98. package/dist/commands/status-meshes.d.ts.map +1 -0
  99. package/dist/commands/status-meshes.js +468 -0
  100. package/dist/commands/status-meshes.js.map +1 -0
  101. package/dist/commands/status-render.d.ts +30 -0
  102. package/dist/commands/status-render.d.ts.map +1 -0
  103. package/dist/commands/status-render.js +782 -0
  104. package/dist/commands/status-render.js.map +1 -0
  105. package/dist/commands/status.d.ts +2 -16
  106. package/dist/commands/status.d.ts.map +1 -1
  107. package/dist/commands/status.js +20 -1877
  108. package/dist/commands/status.js.map +1 -1
  109. package/dist/commands/topology.d.ts.map +1 -1
  110. package/dist/commands/topology.js +4 -0
  111. package/dist/commands/topology.js.map +1 -1
  112. package/dist/commands/up-host.d.ts +19 -0
  113. package/dist/commands/up-host.d.ts.map +1 -0
  114. package/dist/commands/up-host.js +105 -0
  115. package/dist/commands/up-host.js.map +1 -0
  116. package/dist/commands/up-stores.d.ts +42 -0
  117. package/dist/commands/up-stores.d.ts.map +1 -0
  118. package/dist/commands/up-stores.js +242 -0
  119. package/dist/commands/up-stores.js.map +1 -0
  120. package/dist/commands/up-target.d.ts +2 -0
  121. package/dist/commands/up-target.d.ts.map +1 -1
  122. package/dist/commands/up-target.js +9 -0
  123. package/dist/commands/up-target.js.map +1 -1
  124. package/dist/commands/up.d.ts.map +1 -1
  125. package/dist/commands/up.js +27 -363
  126. package/dist/commands/up.js.map +1 -1
  127. package/dist/commands/update-process.d.ts.map +1 -1
  128. package/dist/commands/update-process.js +3 -15
  129. package/dist/commands/update-process.js.map +1 -1
  130. package/dist/commands/update.js +1 -1
  131. package/dist/commands/update.js.map +1 -1
  132. package/dist/commands/use.js +2 -2
  133. package/dist/commands/use.js.map +1 -1
  134. package/dist/console/app.js +5 -5
  135. package/dist/console/app.js.map +1 -1
  136. package/dist/console/commands.d.ts +1 -1
  137. package/dist/console/commands.d.ts.map +1 -1
  138. package/dist/console/commands.js +1 -1
  139. package/dist/console/commands.js.map +1 -1
  140. package/dist/console/ui/Feed.d.ts +2 -2
  141. package/dist/console/ui/Feed.d.ts.map +1 -1
  142. package/dist/console/ui/Feed.js +2 -2
  143. package/dist/console/ui/Feed.js.map +1 -1
  144. package/dist/console/ui/StatusBar.d.ts +1 -1
  145. package/dist/console/ui/StatusBar.d.ts.map +1 -1
  146. package/dist/console/ui/StatusBar.js +1 -1
  147. package/dist/console/ui/StatusBar.js.map +1 -1
  148. package/dist/console/ui/Tabs.d.ts +2 -2
  149. package/dist/console/ui/Tabs.d.ts.map +1 -1
  150. package/dist/console/ui/Tabs.js +4 -4
  151. package/dist/console/ui/Tabs.js.map +1 -1
  152. package/dist/index.d.ts.map +1 -1
  153. package/dist/index.js +6 -1
  154. package/dist/index.js.map +1 -1
  155. package/dist/lib/backup-artifact.d.ts.map +1 -1
  156. package/dist/lib/backup-artifact.js +19 -7
  157. package/dist/lib/backup-artifact.js.map +1 -1
  158. package/dist/lib/choose-target.d.ts +1 -1
  159. package/dist/lib/choose-target.d.ts.map +1 -1
  160. package/dist/lib/choose-target.js +7 -4
  161. package/dist/lib/choose-target.js.map +1 -1
  162. package/dist/lib/completion-install.js +7 -8
  163. package/dist/lib/completion-install.js.map +1 -1
  164. package/dist/lib/control.d.ts +8 -2
  165. package/dist/lib/control.d.ts.map +1 -1
  166. package/dist/lib/control.js +11 -4
  167. package/dist/lib/control.js.map +1 -1
  168. package/dist/lib/manager-choice.d.ts +2 -1
  169. package/dist/lib/manager-choice.d.ts.map +1 -1
  170. package/dist/lib/manager-choice.js +2 -2
  171. package/dist/lib/manager-choice.js.map +1 -1
  172. package/dist/lib/manifest/index.d.ts +1 -1
  173. package/dist/lib/manifest/index.d.ts.map +1 -1
  174. package/dist/lib/manifest/index.js +2 -2
  175. package/dist/lib/manifest/index.js.map +1 -1
  176. package/dist/lib/manifest/resolve.d.ts +1 -1
  177. package/dist/lib/manifest/resolve.d.ts.map +1 -1
  178. package/dist/lib/manifest/resolve.js +4 -4
  179. package/dist/lib/manifest/resolve.js.map +1 -1
  180. package/dist/lib/npm-invocation.d.ts +6 -0
  181. package/dist/lib/npm-invocation.d.ts.map +1 -0
  182. package/dist/lib/npm-invocation.js +18 -0
  183. package/dist/lib/npm-invocation.js.map +1 -0
  184. package/dist/lib/persona-files.d.ts +1 -0
  185. package/dist/lib/persona-files.d.ts.map +1 -1
  186. package/dist/lib/persona-files.js +6 -2
  187. package/dist/lib/persona-files.js.map +1 -1
  188. package/dist/lib/personas.d.ts +1 -2
  189. package/dist/lib/personas.d.ts.map +1 -1
  190. package/dist/lib/personas.js +12 -3
  191. package/dist/lib/personas.js.map +1 -1
  192. package/dist/lib/private-directory.d.ts +3 -3
  193. package/dist/lib/private-directory.d.ts.map +1 -1
  194. package/dist/lib/private-directory.js +17 -7
  195. package/dist/lib/private-directory.js.map +1 -1
  196. package/dist/lib/service-presets.d.ts.map +1 -1
  197. package/dist/lib/service-presets.js +10 -5
  198. package/dist/lib/service-presets.js.map +1 -1
  199. package/dist/lib/stack-journal.d.ts.map +1 -1
  200. package/dist/lib/stack-journal.js +7 -4
  201. package/dist/lib/stack-journal.js.map +1 -1
  202. package/dist/telemetry.d.ts.map +1 -1
  203. package/dist/telemetry.js +3 -2
  204. package/dist/telemetry.js.map +1 -1
  205. package/package.json +4 -4
@@ -4,14 +4,13 @@ import {} from "node:child_process";
4
4
  import { openBrokerLog, prepareForegroundBrokerLog } from "../lib/broker-log.js";
5
5
  import { spawnBroker } from "../lib/broker-spawn.js";
6
6
  import { randomUUID } from "node:crypto";
7
- import { createConnection, createServer, isIP } from "node:net";
7
+ import { createConnection, isIP } from "node:net";
8
8
  import { homedir, hostname } from "node:os";
9
9
  import { accessSync, constants, mkdirSync, readFileSync, existsSync, statSync, closeSync, lstatSync, realpathSync, readdirSync, rmdirSync, } from "node:fs";
10
10
  import { basename, dirname, isAbsolute, join, resolve } from "node:path";
11
- import { isReachable, dialerFor, DEFAULT_SERVER, DEFAULT_SPACE, SERVICE_AUTHORITY_MAX_BYTES, SERVICE_CALLER_PAYLOAD_FLOOR, CONTRACT_ARTIFACT_MAX_BYTES, MANAGER_START_PAYLOAD_FLOOR, createSpaceAuth, serverConfig, openServerConfig, credsProblem, mintCreds, mintLifecycleUid, DEV_OWNER, mintConnectionEvictorCreds, mintMembershipObserverCreds, newIdentity, setupSpaceStreams, removeIssuedStoresBeforeRetention, IssuedStoreBeforeRetentionError, IssuedStoreRecreateRefusal, reconcileSpaceMemoryBuckets, recreateMembershipStore, membershipStoreDefinition, LEGACY_MEMBERSHIP_MAX_BYTES, MEMBERSHIP_MAX_VALUE_SIZE, ttlBuckets, standaloneConnectOpts, requireBrokerFloor, parseServerVersion, presenceBucket, spaceDeletionStreams, isJetStreamMissing, seedChannelRegistry, ensureDefaultDeliveryClass, UndecodableRegistryEntry, LEASE_TTL_MS, EpEnvelopeError, mkSecretDir, writeSecretFile, } from "@cotal-ai/core";
12
- import { JetStreamApiCodes, jetstreamManager, StorageType } from "@nats-io/jetstream";
13
- import { Kvm } from "@nats-io/kv";
14
- import { assertManagerName, processStopped, readManagerName, readManagerSeatCap, recordManagerName, parseSeatCapFlag, seatCapText, CommandFailure, codeSpan, commandFailureReport, failureEnvelope, writeEnvelope, isCommandFailure, protectedLocalDirectory, jsonFlag, plainFlag, renderReport, assertSingleSpaceBroker, assertUserAuthInfo, authDir, brokerAddressForDisplay, getSoleSpaceAuth, soleSpaceOf, getSpaceAuth, hasUserAuthState, listSpaceAccounts, preloadSpaceAccounts, putSpaceAuth, brokerAddressKey, canonicalRoot, rootPathProblem, rootControlProblem, clearCurrent, findMesh, findPreparedSpace, homeCotalDir, legacyStackOtherHome, stackHomeRemedy, getCurrent, loadMeshes, preparedSpaceAt, removePreparedSpace, localMeshesForRoot, keepsRegistration, oneLine, presentationOf, writeResult, connectionEvictorCredsKey, membershipConfigPath, membershipObserverCredsKey, membershipRwCredsKey, MEMBERSHIP_CONFIG_KIND, MEMBERSHIP_RW_CREDS_KIND, WEB_CREDS_KIND, webCredsKey, parsePositiveIntegerFlag, recordMesh, retainedLegacyBroker, meshesForRoot, removeMesh, rotateSystemCreds, setAdoptedCurrent, staleSystemCreds, SYSTEM_CREDS_FILES, userAuthStateDir, userAuthSpacesOnDisk, workspaceSecretStore, acquireMaintenanceLock, assertStoreIdentity, assessMaintenanceClaim, assessRestoreClaim, beginOrdinaryResume, bindOrdinaryResumeListener, consumeRetiredMaintenance, markOrdinaryResumeActive, markOrdinaryResumeDegraded, replaceDeadOrdinaryResumeListener, localProcessOwnerStatus, readMaintenanceJournal, rootNamesNoSpace, readMaintenanceResumeDocument, readStoreIdentity, recordOrdinaryResumeManagerCommit, releaseMaintenanceLock, retireOrdinaryResume, settleTokenHandoff, sweepTokenHandoff, writeTokenHandoff, sameStoreIdentity, cutController, readBrokerPolicy, brokerAccountResolver, removePidPair, writePidPair, verifyIdentityPin, processesNaming, isLoopbackHost, connectUserControlOrThrow, userViewAuth, recordOperationSpace, recordOperationWarning, retainSystemSigningSeed, restoreLeftOut, SPACE_NAME_MAX, spaceNameTooLong, NATS_PIDFILE, MANAGER_PIDFILE, DELIVERY_PIDFILE, AUTH_PIDFILE, localProcessPath, UNTRUSTED_CERTIFICATE, exitCode, canonicalLocalProcessPath, DELIVERY_LOGFILE, terminalWidth, } from "@cotal-ai/workspace";
11
+ import { isReachable, dialerFor, DEFAULT_SERVER, DEFAULT_SPACE, SERVICE_AUTHORITY_MAX_BYTES, SERVICE_CALLER_PAYLOAD_FLOOR, CONTRACT_ARTIFACT_MAX_BYTES, MANAGER_START_PAYLOAD_FLOOR, createSpaceAuth, serverConfig, openServerConfig, credsProblem, mintCreds, mintLifecycleUid, DEV_OWNER, mintConnectionEvictorCreds, mintMembershipObserverCreds, newIdentity, reconcileSpaceMemoryBuckets, standaloneConnectOpts, requireBrokerFloor, parseServerVersion, presenceBucket, LEASE_TTL_MS, EpEnvelopeError, mkSecretDir, writeSecretFile, } from "@cotal-ai/core";
12
+ import { jetstreamManager, StorageType } from "@nats-io/jetstream";
13
+ import { assertManagerName, processStopped, readManagerName, readManagerSeatCap, DEFAULT_SEAT_CAP, recordManagerName, parseSeatCapFlag, seatCapText, CommandFailure, codeSpan, commandFailureReport, failureEnvelope, writeEnvelope, isCommandFailure, protectedLocalDirectory, jsonFlag, plainFlag, renderReport, assertSingleSpaceBroker, assertUserAuthInfo, authDir, brokerAddressForDisplay, getSoleSpaceAuth, soleSpaceOf, getSpaceAuth, hasUserAuthState, listSpaceAccounts, preloadSpaceAccounts, putSpaceAuth, brokerAddressKey, canonicalRoot, rootPathProblem, rootControlProblem, clearCurrent, findMesh, findPreparedSpace, homeCotalDir, legacyStackOtherHome, stackHomeRemedy, getCurrent, loadMeshes, preparedSpaceAt, removePreparedSpace, localMeshesForRoot, keepsRegistration, oneLine, presentationOf, writeResult, connectionEvictorCredsKey, membershipConfigPath, membershipObserverCredsKey, membershipRwCredsKey, MEMBERSHIP_CONFIG_KIND, MEMBERSHIP_RW_CREDS_KIND, WEB_CREDS_KIND, webCredsKey, parsePositiveIntegerFlag, recordMesh, retainedLegacyBroker, meshesForRoot, removeMesh, rotateSystemCreds, setAdoptedCurrent, staleSystemCreds, SYSTEM_CREDS_FILES, userAuthStateDir, userAuthSpacesOnDisk, workspaceSecretStore, acquireMaintenanceLock, assertStoreIdentity, assessMaintenanceClaim, assessRestoreClaim, beginOrdinaryResume, bindOrdinaryResumeListener, consumeRetiredMaintenance, markOrdinaryResumeActive, markOrdinaryResumeDegraded, replaceDeadOrdinaryResumeListener, localProcessOwnerStatus, readMaintenanceJournal, rootNamesNoSpace, readMaintenanceResumeDocument, readStoreIdentity, recordOrdinaryResumeManagerCommit, releaseMaintenanceLock, retireOrdinaryResume, settleTokenHandoff, sweepTokenHandoff, writeTokenHandoff, sameStoreIdentity, cutController, readBrokerPolicy, brokerAccountResolver, removePidPair, writePidPair, verifyIdentityPin, processesNaming, isLoopbackHost, connectUserControlOrThrow, userViewAuth, recordOperationSpace, recordOperationWarning, retainSystemSigningSeed, restoreLeftOut, SPACE_NAME_MAX, spaceNameTooLong, NATS_PIDFILE, MANAGER_PIDFILE, DELIVERY_PIDFILE, AUTH_PIDFILE, localProcessPath, UNTRUSTED_CERTIFICATE, exitCode, canonicalLocalProcessPath, DELIVERY_LOGFILE, terminalWidth, } from "@cotal-ai/workspace";
15
14
  import { FlagValueRefusal } from "../lib/flag-value-refusal.js";
16
15
  import { ensureAuthService, resolveAuthProvider, stopAuthService } from "../lib/auth-proc.js";
17
16
  import { resolveSpace } from "../lib/status.js";
@@ -43,7 +42,7 @@ import { failManifest, refuseManifestSpaceMismatch } from "./topology.js";
43
42
  import { liveMeshProcesses } from "./clean.js";
44
43
  import { checkSpaceFlagValue, checkSpaceName } from "./meshes-add.js";
45
44
  import { checkLocalSpace } from "./space-registration.js";
46
- import { checkNewUpSpace, preparedUpRoot } from "./up-target.js";
45
+ import { checkNewUpSpace, checkPublicExchangePort, preparedUpRoot } from "./up-target.js";
47
46
  import { cleanedManifestStart, interruptedStartBroker, namedOpenConfig, retainedOpenSpace } from "../lib/legacy-start.js";
48
47
  import { bindReaches, canonicalServer, controllerStackApplies, recheckExistingStore, requestedStackMode, refuseForegroundStackHolder, requestsTls, stackUp, stackUpForegroundNotice, stackUpInterrupted, keptOnUp, selectedOnUp, unparsableDaemonCredsNotice, } from "./stack-up.js";
49
48
  import { exitInterrupted, handOverStartupNotice, noticeOnInterrupt, releaseStartupNotice } from "../lib/interrupt-notice.js";
@@ -74,6 +73,8 @@ import { askManager } from "@cotal-ai/workspace/control";
74
73
  import { cliControl } from "../lib/control.js";
75
74
  import { pendingRestores, pendingOrdinaryResumes } from "./up-pending.js";
76
75
  import { parseMaxFileStore, parseAuthTimeout, parseMaxPayload, assertManagerPayload, parseAccountResolver, authTimeoutArgs, loadChannelsFile, refuseRunningElsewhere, refuseRecordsElsewhere, resolveTransport, assertTlsIntentServed, assertTlsAddressServed, commitTransportPolicy, tlsAddress, announceTransport, liveListenerRequiresTls, assertServesDialHost, adoptedTlsRequired, refuseUnnamedLastStore, reopenLastStore, refuseMissingNamedStore, checkStartStore, } from "./up-transport.js";
76
+ import { WILDCARD_HOSTS, reconcileHostAndServer, assertFreshTeamBindAvailable } from "./up-host.js";
77
+ import { registeredAddressHolder, refuseRegisteredAddress, membershipConversionRefusal, fileMembershipStore, postStart, recreateMemoryBuckets, recreateAdoptedMemoryBuckets, recreateDeletedStreams, } from "./up-stores.js";
77
78
  const restoreSinks = new Map();
78
79
  /** Run the guarded `up --restore` startup and return its result instead of printing it. The
79
80
  * restore inputs and fences are exactly `up --restore`'s; this adds no route, flag or authority. */
@@ -110,12 +111,12 @@ export const upFlags = [
110
111
  { name: "open", type: "boolean", description: "unauthenticated dev mesh (no JWT/ACLs)" },
111
112
  { name: "user-auth", type: "boolean", description: "per-USER auth: login + bearer through the space's auth service" },
112
113
  { name: "idp", type: "string", value: "<url>", description: "with --user-auth: the IdP auth base URL to pin (first enable)" },
113
- { name: "exchange-public-port", type: "string", value: "<n>", description: "with --user-auth: also serve the PUBLIC exchange face on this loopback port (TLS terminates at a reverse proxy)" },
114
- { name: "exchange-public-url", type: "string", value: "<https://…>", description: "with --exchange-public-port: the advertised public base URL (the reverse proxy's address)" },
115
- { name: "exchange-trusted-proxy", type: "boolean", description: "with --exchange-public-port: attribute peers by the last X-Forwarded-For hop (opt-in; default: socket address)" },
116
- { name: "advertised-server", type: "string", value: "<url>", description: "with --exchange-public-port: the broker address the public bundle advertises - what participants dial (default: --server)" },
114
+ { name: "exchange-public-port", type: "string", value: "<n>", description: "legacy user-auth startup only: public loopback port (0 to 65535) for an HTTPS reverse proxy" },
115
+ { name: "exchange-public-url", type: "string", value: "<https://…>", description: "legacy user-auth startup only, with --exchange-public-port: advertise the reverse proxy's HTTPS URL" },
116
+ { name: "exchange-trusted-proxy", type: "boolean", description: "legacy user-auth startup only, with --exchange-public-port: attribute peers by the last X-Forwarded-For hop (default: socket address)" },
117
+ { name: "advertised-server", type: "string", value: "<url>", description: "legacy user-auth startup only, with --exchange-public-port: broker address to advertise (default: --server)" },
117
118
  { name: "service-endpoints", type: "boolean", description: "with --user-auth: the auth service also hosts service endpoints (the registration door and the owner-decision host route)" },
118
- { name: "agent-provisioning-url", type: "string", value: "<https://…>", description: "with --exchange-public-port: the deployment's remote agent-provisioning endpoint the public bundle advertises" },
119
+ { name: "agent-provisioning-url", type: "string", value: "<https://…>", description: "legacy user-auth startup only, with --exchange-public-port: agent-provisioning endpoint to advertise" },
119
120
  { name: "rotate-sys", type: "boolean", description: "renew the expired/expiring $SYS creds by rotating the system account (agents, data and creds survive; needs a stopped mesh)" },
120
121
  { name: "recreate-membership-store", type: "boolean", description: "replace a stopped space's legacy File-backed derived membership feed with the current Memory-backed store" },
121
122
  { name: "recreate-issued-stores", type: "string", value: "<backup-dir>", description: "back up this space's issued-authority stores created before 0.111.0 into a new <backup-dir>, delete them and create them again (needs a stopped stack and every other issuer of the space stopped)" },
@@ -175,6 +176,8 @@ export function validateUpArguments(args) {
175
176
  publicExchangeArgs(args.values, false);
176
177
  serviceEndpointsArgs(args.values, false);
177
178
  }
179
+ else if (typeof args.values["exchange-public-port"] === "string")
180
+ checkPublicExchangePort(args.values["exchange-public-port"]);
178
181
  if (args.values.idp !== undefined && args.values["user-auth"] !== true && !args.values.file)
179
182
  throw new CommandFailure("refused", "USAGE_INVALID", '--idp is for user-auth spaces; pair it with --user-auth, or set broker.auth: "user" in a manifest', { remedy: "use --user-auth --idp <auth base URL>, without --open" });
180
183
  if (args.values.restore !== undefined && args.values["no-manager"] === true)
@@ -274,6 +277,8 @@ export function validateUpArguments(args) {
274
277
  throw new CommandFailure("refused", "USAGE_INVALID", `--restore-only takes registry (got ${JSON.stringify(restoreOnly)})`);
275
278
  if (!args.values.restore && (restoreOnly !== undefined || args.values["accept-missing-source"] === true))
276
279
  throw new CommandFailure("refused", "USAGE_INVALID", "--restore-only and --accept-missing-source require --restore <dir>");
280
+ if (args.values.file !== undefined && args.values["accept-stale-checkpoint"] === true)
281
+ throw new FlagValueRefusal("--accept-stale-checkpoint cannot be combined with --file/-f: a manifest starts a fresh mesh, not a preserved stack", "drop --accept-stale-checkpoint for a fresh start, or omit --file/-f to resume a preserved stack");
277
282
  if (args.values.restore && (args.values.file !== undefined || args.values.channels !== undefined))
278
283
  throw new CommandFailure("refused", "USAGE_INVALID", "--restore cannot be combined with --file/-f or --channels");
279
284
  if (args.values.restore && args.values["rotate-sys"] === true)
@@ -1366,7 +1371,7 @@ async function runUp(args, invokedFrom, inheritedLock, onAdopt, freshTeamBoot =
1366
1371
  // address never reaches the later pin in startMeshDetached, so the catch used to discard it.
1367
1372
  let prepared;
1368
1373
  try {
1369
- prepared = loadManifest(resolve(values.file));
1374
+ prepared = loadManifest(resolve(values.file), logFile);
1370
1375
  }
1371
1376
  catch {
1372
1377
  // Manifest errors are reported by the -f path with the same load; do not double-print.
@@ -1395,7 +1400,7 @@ async function runUp(args, invokedFrom, inheritedLock, onAdopt, freshTeamBoot =
1395
1400
  const managerSeatCap = parseSeatCapFlag("--seat-cap", values["seat-cap"]);
1396
1401
  if (managerSeatCap !== undefined) {
1397
1402
  const capped = { root: cotalRoot(), space: values.space ?? folderSpace() };
1398
- if (readManagerSeatCap(capped) !== managerSeatCap && managerRecordState(capped.space, capped.root).state === "alive")
1403
+ if ((readManagerSeatCap(capped) ?? DEFAULT_SEAT_CAP) !== managerSeatCap && managerRecordState(capped.space, capped.root).state === "alive")
1399
1404
  throw new CommandFailure("refused", "LIFECYCLE_BLOCKED", `a manager already runs for space ${capped.space}, and it keeps the seat cap it started with`, { target: { root: capped.root, space: capped.space }, remedy: `stop it with \`cotal down\`, then run \`cotal up --seat-cap ${seatCapText(managerSeatCap)}\`` });
1400
1405
  }
1401
1406
  // THE TRANSPORT IS DECIDED HERE, ABOVE EVERY BRANCH, AND THIS POSITION IS THE FIX.
@@ -1530,7 +1535,7 @@ async function runUp(args, invokedFrom, inheritedLock, onAdopt, freshTeamBoot =
1530
1535
  // Structured and plain manifest refusals report file errors before checking startup support.
1531
1536
  if (values.json || values.plain) {
1532
1537
  try {
1533
- loadManifest(path);
1538
+ loadManifest(path, logFile);
1534
1539
  }
1535
1540
  catch (e) {
1536
1541
  throw manifestFileRefusal(e, path);
@@ -3500,7 +3505,7 @@ function manifestFileRefusal(e, path) {
3500
3505
  async function upManifest(file, opts) {
3501
3506
  let prepared;
3502
3507
  try {
3503
- prepared = loadManifest(resolve(file));
3508
+ prepared = loadManifest(resolve(file), opts.logFile);
3504
3509
  }
3505
3510
  catch (e) {
3506
3511
  if (opts.freshTeamBoot)
@@ -3589,9 +3594,7 @@ async function upManifest(file, opts) {
3589
3594
  assertFreshTeamBootOwnership(cotalRoot(), m.space, open ? "open" : userAuth ? "user" : "auth");
3590
3595
  await assertFreshTeamBindAvailable(server, host, m.space);
3591
3596
  }
3592
- // A manifest's agents are booted BY the manager `up -f` starts with the mesh, so `--no-manager`
3593
- // against a manifest declaring agents asks for a boot that cannot deliver its own plan. Refused
3594
- // before the dry-run print and before anything boots.
3597
+ // A manifest needs its manager to boot declared agents.
3595
3598
  if (opts.noManager && eff.agents.length)
3596
3599
  throw new FlagValueRefusal(`--no-manager cannot launch this manifest: it declares ${eff.agents.length} agent(s), and a manifest's agents are booted by its manager (which --no-manager omits)`, "drop --no-manager, or use a broker-only manifest with no agents");
3597
3600
  const effectiveNoManager = Boolean(opts.noManager);
@@ -3610,9 +3613,10 @@ async function upManifest(file, opts) {
3610
3613
  if (userAuth)
3611
3614
  await preflightUserStack(cotalRoot(), m.space, userAuth.idpUrl);
3612
3615
  checkStartStore(opts.storeDir, m.space);
3613
- // Preview and apply resolve and probe the same runtime before showing a plan or starting a broker.
3616
+ // Preview and apply only probe a runtime when starting a manager.
3614
3617
  try {
3615
- await preflightRuntime(runtime);
3618
+ if (!effectiveNoManager)
3619
+ await preflightRuntime(runtime);
3616
3620
  }
3617
3621
  catch (error) {
3618
3622
  throw new CommandFailure("refused", "DEPENDENCY_UNAVAILABLE", `the requested runtime did not pass preflight; ${opts.freshTeamBoot ? "no fresh boot intent or broker was started" : "no broker was started"}`, { target: { space: m.space, runtime }, remedy: error instanceof Error ? error.message : "inspect the selected runtime provider" });
@@ -4265,14 +4269,14 @@ function ensureRootForSpace(space) {
4265
4269
  remedy: gone ? `forget it with \`cotal space forget ${space}\`, then start it here` : `start it in its folder with \`cotal up --root ${shellWord(prepared.root)} --space ${space}\`, or \`cotal space forget ${space}\` to start it here`,
4266
4270
  });
4267
4271
  }
4268
- // What spaces does this root already host? Prefer auth material; fall back to a live MeshEntry
4269
- // whose root is this directory (open meshes have no auth dir).
4272
+ // Auth material, a locally started registration, or a preparation names what this root hosts.
4273
+ // A remote registration uses the root as a connection folder, not as a stack root.
4270
4274
  const hosted = listSpaceAccounts(authDir(root));
4271
4275
  if (hosted.includes(space))
4272
4276
  return;
4273
4277
  const existing = hosted.length
4274
4278
  ? hosted
4275
- : [loadMeshes().find((m) => m.root === root || realpathSafe(m.root) === realpathSafe(root))?.space ?? preparedSpaceAt(root)?.space].filter((s) => !!s);
4279
+ : [localMeshesForRoot(root)[0]?.space ?? preparedSpaceAt(root)?.space].filter((s) => !!s);
4276
4280
  if (existing.length === 0 || existing.includes(space))
4277
4281
  return;
4278
4282
  const names = existing.map((s) => `"${s}"`).join(", ");
@@ -4332,14 +4336,6 @@ function assertSelectionNotMoved(root, space) {
4332
4336
  remedy: `if this is that folder moved, forget it with \`cotal space forget ${current}\`, then prepare it here with \`cotal space create ${current}\` and run \`cotal up\`; to start "${space}" here, pass --space ${space}`,
4333
4337
  });
4334
4338
  }
4335
- function realpathSafe(p) {
4336
- try {
4337
- return realpathSync(p);
4338
- }
4339
- catch {
4340
- return p;
4341
- }
4342
- }
4343
4339
  /** The remedy for a hand-registered (`origin === "manual"`) space `claimSpace` refuses to touch.
4344
4340
  * Branches on whether the REGISTERED server is loopback, the one authority for that being
4345
4341
  * `isLoopbackHost` (`@cotal-ai/workspace`) — never a second opinion here.
@@ -4659,338 +4655,6 @@ function belowPresenceSafeBroker(version) {
4659
4655
  return p.minor < 14;
4660
4656
  return p.patch < 5;
4661
4657
  }
4662
- /** Wildcard binds mean "every interface", so they are NOT an address a client can be told to dial:
4663
- * the probe/registry URL stays whatever it already is (loopback by default), which the wildcard
4664
- * bind necessarily covers. */
4665
- const WILDCARD_HOSTS = new Set(["0.0.0.0", "::", "[::]"]);
4666
- /** Establish that a bind-host value IS a host, BEFORE anything brackets it, and return the
4667
- * bracketed literal a URL can hold (#1697).
4668
- *
4669
- * `--host` is the bind address; its sibling `--server` takes a URL, the registry stores and prints
4670
- * URLs, and every message in this area shows one — so an operator plausibly types the URL here
4671
- * (the manifest's `broker.host` carries the same ambiguity against `broker.servers`). Unrejected,
4672
- * the IPv6 bracketing wrapped it into `nats://[nats://127.0.0.1:4222]:4222`, which is not a URL at
4673
- * all. Nothing checked the derived string: the first code to look at it compared it with the
4674
- * space's registry record, failed for a reason unrelated to what was typed, and showed the
4675
- * operator the "registered by hand" refusal whose remedy de-registers a live mesh. Refused by name
4676
- * here instead — pointing at the URL-carrying sibling — and a value that still cannot serve as a
4677
- * URL host (a `host:port` spelling, say) is refused rather than reaching that comparison as a
4678
- * silently wrong server string. Never rewritten: a value this flag cannot use is an error, not a
4679
- * URL to derive from. */
4680
- function assertBindableHost(host, source, urlSource) {
4681
- if (/^[a-z][a-z0-9+.-]*:\/\//i.test(host)) {
4682
- console.error(c.red(`✗ ${source} ${host} looks like a URL - it takes a bind host only (an IP or hostname, no scheme); pass the broker URL with ${urlSource} instead`));
4683
- process.exit(1);
4684
- }
4685
- const literal = host.includes(":") && !host.startsWith("[") ? `[${host}]` : host;
4686
- try {
4687
- // ONE parse, both consumers served from it: `literal` builds the derived URL (a URL host needs
4688
- // the brackets), `hostname` compares against the explicit server's (the URL API strips them).
4689
- return { literal, hostname: new URL(`nats://${literal}:1`).hostname };
4690
- }
4691
- catch {
4692
- console.error(c.red(`✗ ${source} ${host} is not a valid bind host - an IP or hostname only, with no port; the port comes from ${urlSource} (or its default), never from the bind host`));
4693
- process.exit(1);
4694
- }
4695
- }
4696
- /**
4697
- * Reconcile the bind address (`--host`, manifest `broker.host`) with the broker URL the readiness
4698
- * probe, the mesh registry, and every later client use.
4699
- *
4700
- * They must name the same address. Left independent, `--host <non-loopback>` bound correctly and was
4701
- * then probed at the loopback default: the probe found nothing, timed out, and the caller SIGTERM'd
4702
- * a broker that had started perfectly, so `--host` alone could never succeed. With no explicit URL,
4703
- * derive one from the host (keeping the implicit URL's port); with both, refuse a contradicting pair rather
4704
- * than starting a broker that nothing can reach.
4705
- */
4706
- function reconcileHostAndServer(host, explicitServer, source = "--host", urlSource = "--server", implicitServer = DEFAULT_SERVER) {
4707
- const url = new URL(explicitServer ?? implicitServer);
4708
- if (WILDCARD_HOSTS.has(host))
4709
- return explicitServer ?? implicitServer;
4710
- const { literal, hostname } = assertBindableHost(host, source, urlSource);
4711
- if (!explicitServer)
4712
- return `nats://${literal}:${url.port || "4222"}`;
4713
- // NO parse on this path: `assertBindableHost` just parsed the identical literal above, so the
4714
- // mismatch check compares two parsed hostnames and can only ever print its diagnostic and exit 1
4715
- // — the "never throw a raw Invalid URL" requirement (#1697) holds by construction, not by a
4716
- // second guard that no input could reach.
4717
- if (url.hostname !== hostname) {
4718
- console.error(c.red(`✗ ${source} ${host} and ${urlSource} ${explicitServer} name different addresses - the broker would bind ${host} but be probed at ${url.hostname}. Pass one, or make them agree.`));
4719
- process.exit(1);
4720
- }
4721
- return explicitServer;
4722
- }
4723
- /** Bind the manifest's exact listener address before any team-boot write. Releasing this
4724
- * socket is not a reservation: the real broker still owns the final bind verdict. */
4725
- async function assertFreshTeamBindAvailable(server, host, space) {
4726
- const url = new URL(server), port = Number(url.port || "4222");
4727
- const displayServer = brokerAddressForDisplay(server) ?? "not displayable";
4728
- if (!Number.isSafeInteger(port) || port < 1 || port > 65535)
4729
- throw new CommandFailure("refused", "USAGE_INVALID", "the fresh team broker needs a concrete TCP port before it can check its bind address", { target: { space } });
4730
- await new Promise((resolve, reject) => {
4731
- const socket = createServer(), controller = new AbortController();
4732
- socket.unref();
4733
- let settled = false;
4734
- const finish = (error) => {
4735
- if (settled)
4736
- return;
4737
- settled = true;
4738
- clearTimeout(timer);
4739
- if (error)
4740
- reject(error);
4741
- else
4742
- resolve();
4743
- };
4744
- const timer = setTimeout(() => {
4745
- controller.abort();
4746
- finish(new CommandFailure("refused", "TARGET_UNAVAILABLE", "the local broker bind inspection did not complete within its deadline; no absence or startup eligibility was inferred", { target: { space, server: displayServer } }));
4747
- }, 1500);
4748
- socket.once("error", () => finish(new CommandFailure("refused", "TARGET_UNAVAILABLE", "the selected broker address cannot be bound as a new local listener; no existing or remote broker was adopted", { target: { space, server: displayServer }, remedy: "inspect this local bind address and any process already listening there" })));
4749
- try {
4750
- socket.listen({ port, host, signal: controller.signal }, () => {
4751
- if (settled)
4752
- return;
4753
- socket.close((error) => finish(error ? new CommandFailure("failed", "OPERATION_FAILED", "the temporary bind inspection did not confirm closure; no broker was started", { target: { space, server: displayServer } }) : undefined));
4754
- });
4755
- }
4756
- catch {
4757
- controller.abort();
4758
- finish(new CommandFailure("refused", "TARGET_UNAVAILABLE", "the selected broker bind address was rejected before startup; no other listener was chosen", { target: { space, server: displayServer } }));
4759
- }
4760
- });
4761
- }
4762
- function registeredAddressHolder(server, space) {
4763
- const key = brokerAddressKey(server);
4764
- if (key === undefined)
4765
- return undefined;
4766
- const root = canonicalRoot(cotalRoot());
4767
- return loadMeshes().find((m) => m.space !== space && canonicalRoot(m.root) !== root && brokerAddressKey(m.server) === key);
4768
- }
4769
- /** Refuse an address that a space registered for another folder keeps while its broker is stopped,
4770
- * as an occupied one is refused. Starting there would leave two registrations naming one broker:
4771
- * whichever stack runs answers for both, and the other one's `down` and reads reach it. Every
4772
- * start that names its own address asks this, a manifest's `broker.servers` included, and
4773
- * `elsewhere` names the way to move the one being started. A space this start takes the name of is
4774
- * left to the name rules. */
4775
- function refuseRegisteredAddress(server, space, elsewhere) {
4776
- const held = registeredAddressHolder(server, space);
4777
- if (!held)
4778
- return;
4779
- throw new CommandFailure("refused", "CONFLICT", `${server} is the broker address of "${held.space}", registered for ${held.root} and stopped; nothing was started`, {
4780
- target: { root: cotalRoot(), server, space, heldSpace: held.space, heldBy: held.root },
4781
- remedy: `${elsewhere}, or free that one with \`cotal space forget ${held.space}\``,
4782
- });
4783
- }
4784
- function membershipConversionRefusal(space, remedy = "stop the stack with `cotal down --yes`, then run `cotal up --recreate-membership-store`") {
4785
- return new CommandFailure("refused", "LIFECYCLE_BLOCKED", `space ${space} has a legacy File-backed membership store; it was not changed while its broker or membership services may be in use`, {
4786
- target: { space }, remedy,
4787
- });
4788
- }
4789
- async function fileMembershipStore(server, space, creds, stockOnly = false) {
4790
- const nc = await dialerFor(server)({ servers: server, ...standaloneConnectOpts({ creds, tls: false }) });
4791
- try {
4792
- requireBrokerFloor(nc);
4793
- const { config } = await (await jetstreamManager(nc)).streams.info(`KV_${membershipStoreDefinition(space).bucket}`);
4794
- if (config.storage !== StorageType.File)
4795
- return false;
4796
- if (stockOnly && (![-1, LEGACY_MEMBERSHIP_MAX_BYTES].includes(config.max_bytes) || config.max_msgs_per_subject !== 1 || ![-1, MEMBERSHIP_MAX_VALUE_SIZE].includes(config.max_msg_size)))
4797
- throw membershipConversionRefusal(space);
4798
- return true;
4799
- }
4800
- catch (error) {
4801
- if (isJetStreamMissing(error, JetStreamApiCodes.StreamNotFound))
4802
- return false;
4803
- throw error;
4804
- }
4805
- finally {
4806
- await drainAndClose(nc);
4807
- }
4808
- }
4809
- /** Create or verify space infrastructure before any services start on this broker.
4810
- * Only a fresh owned local boot may automatically replace its derived legacy membership feed. */
4811
- async function postStart(server, space, setup, seedFile, recreateIssuedStores, recreateMembershipStore, freshOwnedLocalBroker = false) {
4812
- if (recreateIssuedStores !== undefined)
4813
- await recreateIssuedStoresBeforeSetup(server, space, setup !== undefined, recreateIssuedStores);
4814
- const legacyMembership = await fileMembershipStore(server, space, setup?.creds, recreateMembershipStore !== true);
4815
- if (legacyMembership) {
4816
- const running = serviceInstances(space).filter((row) => row.record.value.definition !== STACK_DEFINITION.broker).some((row) => !["gone", "previous-boot", "foreign-pid"].includes(observeServiceProcess(row.record.value)));
4817
- if ((!freshOwnedLocalBroker && !recreateMembershipStore) || running)
4818
- throw membershipConversionRefusal(space);
4819
- }
4820
- const convertMembership = legacyMembership && (freshOwnedLocalBroker || recreateMembershipStore === true);
4821
- let recreateCreds;
4822
- if (convertMembership && setup !== undefined) {
4823
- const auth = await getSpaceAuth(workspaceSecretStore(cotalRoot()), space);
4824
- if (!auth)
4825
- throw new Error(`space "${space}" has no trust material under ${authDir(cotalRoot())}; its membership store was not touched`);
4826
- recreateCreds = await mintCreds(auth, newIdentity(), "membership-store-recreate");
4827
- }
4828
- try {
4829
- await setupSpaceStreams({
4830
- servers: server,
4831
- space,
4832
- creds: setup?.creds,
4833
- ...(convertMembership ? { recreateFileMembership: { creds: recreateCreds } } : {}),
4834
- });
4835
- }
4836
- catch (error) {
4837
- // Nothing of the stack runs yet, and the caller stops this broker again, so this is a refusal.
4838
- if (error instanceof IssuedStoreBeforeRetentionError)
4839
- throw new CommandFailure("refused", "CONFLICT", error.message, { target: { space, store: error.bucket }, remedy: `stop every other issuer and resolver of space ${space}, then add --recreate-issued-stores <backup-dir> to the \`cotal up\` that starts it` });
4840
- throw error;
4841
- }
4842
- if (convertMembership)
4843
- console.error(`Converted ${membershipStoreDefinition(space).bucket} from File to Memory; broker-sourced membership rebuilds on startup.`);
4844
- try {
4845
- if (seedFile) {
4846
- await seedChannelRegistry({ servers: server, space, creds: setup?.creds, file: seedFile });
4847
- }
4848
- // SPEC §4: `defaults.deliveryClass` MUST be written at space creation so the effective default is
4849
- // discoverable on the wire, never inferred from the `?? "durable"` resolution fallback. Auth mode
4850
- // (`setup` present ⇒ the delivery daemon is up) is local/self-hosted ⇒ `durable`; open mode has no
4851
- // daemon and is live-only ⇒ `live`. Runs after the seed so an explicit `channels.json` default wins.
4852
- // A key that does not decode is not replaced by either write.
4853
- await ensureDefaultDeliveryClass({
4854
- servers: server,
4855
- space,
4856
- creds: setup?.creds,
4857
- deliveryClass: setup ? "durable" : "live",
4858
- });
4859
- }
4860
- catch (error) {
4861
- if (!(error instanceof UndecodableRegistryEntry))
4862
- throw error;
4863
- throw new CommandFailure("refused", "CONFLICT", error.message, { target: { space }, remedy: "read the key and replace the value; the bytes were left as they are" });
4864
- }
4865
- }
4866
- /** `--recreate-issued-stores`: on the broker this boot just started, before any issuer or resolver
4867
- * of the space runs, back up and delete the space's issued-authority stores created before bounded
4868
- * retention, so the stream setup that follows creates them in the current shape. It runs the core
4869
- * step an embedder runs, on a one-shot `issued-store-recreate` credential minted from the root's
4870
- * trust; an open space uses its bare connection, as stream setup does. */
4871
- async function recreateIssuedStoresBeforeSetup(server, space, authenticated, backupDir) {
4872
- let creds;
4873
- let inboxPrefix = "_INBOX";
4874
- if (authenticated) {
4875
- const auth = await getSpaceAuth(workspaceSecretStore(cotalRoot()), space);
4876
- if (!auth)
4877
- throw new Error(`space "${space}" has no trust material under ${authDir(cotalRoot())}; its issued-authority stores were not touched`);
4878
- const identity = newIdentity();
4879
- creds = await mintCreds(auth, identity, "issued-store-recreate");
4880
- inboxPrefix = `_INBOX_${identity.id}`;
4881
- }
4882
- const nc = await dialerFor(server)({ servers: server, ...standaloneConnectOpts({ creds, tls: false }), inboxPrefix });
4883
- let removed;
4884
- try {
4885
- removed = await removeIssuedStoresBeforeRetention(nc, { space, backupDir, inboxPrefix });
4886
- }
4887
- catch (error) {
4888
- if (error instanceof IssuedStoreRecreateRefusal)
4889
- throw new CommandFailure("refused", error.reason === "nothing-to-recreate" ? "CONFLICT" : "USAGE_INVALID", error.message, { target: { space, backupDir }, remedy: error.reason === "nothing-to-recreate" ? "start the space without --recreate-issued-stores" : "name a directory that does not exist yet, inside one that does" });
4890
- throw error;
4891
- }
4892
- finally {
4893
- await drainAndClose(nc);
4894
- }
4895
- for (const store of removed)
4896
- console.log(`→ backed up ${store.stream} (${store.messages} messages) to ${store.backup}, then deleted it`);
4897
- console.log(c.dim("• the issued-authority stores are created again in the current shape; every generation issued before the upgrade is refused from now on"));
4898
- }
4899
- /** A resume or restore skips `postStart` because the preserved store already holds every canonical
4900
- * stream. A memory-backed bucket is the exception: the broker stop that preserved the store emptied
4901
- * it, stream and all (#1356 made presence memory-backed). Recreate those, and only those, from the
4902
- * same `ttlBuckets` list `setupSpaceStreams` creates them from, before any daemon opens them.
4903
- * Only an ordinary resume that just started this listener may opt into replacing a File feed. */
4904
- async function recreateMemoryBuckets(server, space, setup, ownedResume) {
4905
- const legacy = await fileMembershipStore(server, space, setup?.creds);
4906
- if (legacy) {
4907
- if (!ownedResume?.convertMembership)
4908
- throw membershipConversionRefusal(space, ownedResume && "retry this preserved resume with `cotal up --recreate-membership-store`");
4909
- const running = serviceInstances(space).filter((row) => row.record.value.definition !== STACK_DEFINITION.broker).some((row) => !["gone", "previous-boot", "foreign-pid"].includes(observeServiceProcess(row.record.value)));
4910
- if (running)
4911
- throw membershipConversionRefusal(space, "stop the remaining membership services, then retry the preserved resume with `cotal up --recreate-membership-store`");
4912
- try {
4913
- const auth = setup && await getSpaceAuth(workspaceSecretStore(cotalRoot()), space);
4914
- if (setup && !auth)
4915
- throw new Error(`space "${space}" has no trust material under ${authDir(cotalRoot())}`);
4916
- await recreateMembershipStore({
4917
- servers: server, space, provisionerCreds: setup?.creds,
4918
- recreateCreds: auth ? await mintCreds(auth, newIdentity(), "membership-store-recreate") : undefined,
4919
- });
4920
- }
4921
- catch (error) {
4922
- throw new CommandFailure("failed", "OPERATION_FAILED", `could not convert the preserved membership store: ${error.message}`, {
4923
- target: { space }, remedy: "fix the reported cause, then retry this preserved resume with `cotal up --recreate-membership-store`",
4924
- });
4925
- }
4926
- console.error(`Converted ${membershipStoreDefinition(space).bucket} from File to Memory; broker-sourced membership rebuilds on startup.`);
4927
- }
4928
- const nc = await dialerFor(server)({ servers: server, ...standaloneConnectOpts({ creds: setup?.creds, tls: false }) });
4929
- try {
4930
- requireBrokerFloor(nc);
4931
- const kvm = new Kvm(nc);
4932
- for (const [bucket, ttl, storage] of ttlBuckets(space))
4933
- if (storage === StorageType.Memory)
4934
- await kvm.create(bucket, { ttl, storage });
4935
- if (!legacy) {
4936
- const membership = membershipStoreDefinition(space);
4937
- await kvm.create(membership.bucket, membership.createOptions);
4938
- }
4939
- }
4940
- finally {
4941
- await drainAndClose(nc);
4942
- }
4943
- }
4944
- /** An adopted listener may have been bound by an `up` that stopped before {@link recreateMemoryBuckets},
4945
- * so the memory buckets the daemons open can be missing on it. An existing bucket is left as it is. */
4946
- async function recreateAdoptedMemoryBuckets(root, space, server, mode) {
4947
- if (mode === "open")
4948
- return recreateMemoryBuckets(server, space);
4949
- const auth = await getSpaceAuth(workspaceSecretStore(root), space);
4950
- if (!auth)
4951
- throw new Error(`space "${space}" has no trust material under ${authDir(root)}; cannot recreate its memory buckets on the adopted listener`);
4952
- await recreateMemoryBuckets(server, space, { creds: await mintCreds(auth, newIdentity(), "provisioner") });
4953
- }
4954
- /** `cotal space delete` removes a space's streams from a broker that keeps running. When a stack
4955
- * reuses that broker and every canonical stream of the space is gone, create them again, empty, as
4956
- * a broker start does, and return true. A broker that still holds any of them is left as it is. */
4957
- async function recreateDeletedStreams(opts) {
4958
- let setup;
4959
- if (opts.mode !== "open") {
4960
- const auth = await getSpaceAuth(workspaceSecretStore(opts.root), opts.space);
4961
- if (!auth)
4962
- throw new Error(`space "${opts.space}" has no trust material under ${authDir(opts.root)}; cannot read its streams on the running broker`);
4963
- setup = { creds: await mintCreds(auth, newIdentity(), "provisioner") };
4964
- }
4965
- if (await fileMembershipStore(opts.server, opts.space, setup?.creds))
4966
- throw membershipConversionRefusal(opts.space);
4967
- if (opts.mode === "user")
4968
- return false; // User-auth running stacks retain their existing stream lifecycle.
4969
- const nc = await dialerFor(opts.server)({ servers: opts.server, ...standaloneConnectOpts({ creds: setup?.creds, tls: false }) });
4970
- let held = false;
4971
- try {
4972
- requireBrokerFloor(nc);
4973
- const jsm = await jetstreamManager(nc);
4974
- for (const name of spaceDeletionStreams(opts.space)) {
4975
- try {
4976
- await jsm.streams.info(name);
4977
- held = true;
4978
- break;
4979
- }
4980
- catch (error) {
4981
- if (!isJetStreamMissing(error, JetStreamApiCodes.StreamNotFound))
4982
- throw error;
4983
- }
4984
- }
4985
- }
4986
- finally {
4987
- await drainAndClose(nc);
4988
- }
4989
- if (held)
4990
- return false;
4991
- await postStart(opts.server, opts.space, setup, opts.seed ?? loadChannelsFile(opts.channels));
4992
- return true;
4993
- }
4994
4658
  /**
4995
4659
  * Render and write the config for an OPEN (no-auth) broker, returning its path. It names `space`,
4996
4660
  * because an open root holds no account that would ({@link namedOpenConfig}).