@cotal-ai/cli 0.99.1 → 0.100.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 (255) hide show
  1. package/dist/chat/chat-view.d.ts.map +1 -1
  2. package/dist/chat/chat-view.js +9 -1
  3. package/dist/chat/chat-view.js.map +1 -1
  4. package/dist/chat/controller.d.ts.map +1 -1
  5. package/dist/chat/controller.js +6 -2
  6. package/dist/chat/controller.js.map +1 -1
  7. package/dist/chat/native-session.d.ts +8 -0
  8. package/dist/chat/native-session.d.ts.map +1 -1
  9. package/dist/chat/native-session.js +31 -6
  10. package/dist/chat/native-session.js.map +1 -1
  11. package/dist/chat/plain.d.ts.map +1 -1
  12. package/dist/chat/plain.js +33 -7
  13. package/dist/chat/plain.js.map +1 -1
  14. package/dist/chat/session.d.ts +3 -0
  15. package/dist/chat/session.d.ts.map +1 -1
  16. package/dist/chat/static-session.d.ts.map +1 -1
  17. package/dist/chat/static-session.js +2 -1
  18. package/dist/chat/static-session.js.map +1 -1
  19. package/dist/chat/stdio-io.js +2 -2
  20. package/dist/chat/stdio-io.js.map +1 -1
  21. package/dist/chat/stdio.d.ts +9 -2
  22. package/dist/chat/stdio.d.ts.map +1 -1
  23. package/dist/chat/stdio.js +33 -13
  24. package/dist/chat/stdio.js.map +1 -1
  25. package/dist/chat/view.d.ts +16 -4
  26. package/dist/chat/view.d.ts.map +1 -1
  27. package/dist/chat/view.js +21 -8
  28. package/dist/chat/view.js.map +1 -1
  29. package/dist/command.d.ts.map +1 -1
  30. package/dist/command.js +59 -13
  31. package/dist/command.js.map +1 -1
  32. package/dist/commands/agents.d.ts.map +1 -1
  33. package/dist/commands/agents.js +3 -2
  34. package/dist/commands/agents.js.map +1 -1
  35. package/dist/commands/backup-maintenance.d.ts.map +1 -1
  36. package/dist/commands/backup-maintenance.js +75 -16
  37. package/dist/commands/backup-maintenance.js.map +1 -1
  38. package/dist/commands/backup-read.d.ts.map +1 -1
  39. package/dist/commands/backup-read.js +14 -1
  40. package/dist/commands/backup-read.js.map +1 -1
  41. package/dist/commands/backup-restore.d.ts.map +1 -1
  42. package/dist/commands/backup-restore.js +4 -1
  43. package/dist/commands/backup-restore.js.map +1 -1
  44. package/dist/commands/backup.d.ts.map +1 -1
  45. package/dist/commands/backup.js +51 -11
  46. package/dist/commands/backup.js.map +1 -1
  47. package/dist/commands/channel-members.d.ts.map +1 -1
  48. package/dist/commands/channel-members.js +6 -3
  49. package/dist/commands/channel-members.js.map +1 -1
  50. package/dist/commands/channels.d.ts.map +1 -1
  51. package/dist/commands/channels.js +12 -9
  52. package/dist/commands/channels.js.map +1 -1
  53. package/dist/commands/chat.d.ts +4 -3
  54. package/dist/commands/chat.d.ts.map +1 -1
  55. package/dist/commands/chat.js +6 -3
  56. package/dist/commands/chat.js.map +1 -1
  57. package/dist/commands/clean.d.ts +4 -3
  58. package/dist/commands/clean.d.ts.map +1 -1
  59. package/dist/commands/clean.js +24 -14
  60. package/dist/commands/clean.js.map +1 -1
  61. package/dist/commands/completion.d.ts.map +1 -1
  62. package/dist/commands/completion.js +3 -1
  63. package/dist/commands/completion.js.map +1 -1
  64. package/dist/commands/config.d.ts +7 -0
  65. package/dist/commands/config.d.ts.map +1 -1
  66. package/dist/commands/config.js +42 -7
  67. package/dist/commands/config.js.map +1 -1
  68. package/dist/commands/console.js +1 -1
  69. package/dist/commands/console.js.map +1 -1
  70. package/dist/commands/doctor.d.ts.map +1 -1
  71. package/dist/commands/doctor.js +27 -7
  72. package/dist/commands/doctor.js.map +1 -1
  73. package/dist/commands/down.d.ts +3 -2
  74. package/dist/commands/down.d.ts.map +1 -1
  75. package/dist/commands/down.js +103 -21
  76. package/dist/commands/down.js.map +1 -1
  77. package/dist/commands/endpoints.js +4 -2
  78. package/dist/commands/endpoints.js.map +1 -1
  79. package/dist/commands/ext.js +1 -1
  80. package/dist/commands/ext.js.map +1 -1
  81. package/dist/commands/join.d.ts.map +1 -1
  82. package/dist/commands/join.js +17 -7
  83. package/dist/commands/join.js.map +1 -1
  84. package/dist/commands/meshes-add.d.ts.map +1 -1
  85. package/dist/commands/meshes-add.js +12 -6
  86. package/dist/commands/meshes-add.js.map +1 -1
  87. package/dist/commands/models.d.ts.map +1 -1
  88. package/dist/commands/models.js +3 -1
  89. package/dist/commands/models.js.map +1 -1
  90. package/dist/commands/persona.d.ts.map +1 -1
  91. package/dist/commands/persona.js +9 -2
  92. package/dist/commands/persona.js.map +1 -1
  93. package/dist/commands/personas.d.ts.map +1 -1
  94. package/dist/commands/personas.js +20 -9
  95. package/dist/commands/personas.js.map +1 -1
  96. package/dist/commands/reset-store-apply.d.ts.map +1 -1
  97. package/dist/commands/reset-store-apply.js +22 -7
  98. package/dist/commands/reset-store-apply.js.map +1 -1
  99. package/dist/commands/reset.js +1 -1
  100. package/dist/commands/reset.js.map +1 -1
  101. package/dist/commands/send.d.ts +1 -1
  102. package/dist/commands/send.d.ts.map +1 -1
  103. package/dist/commands/send.js +68 -14
  104. package/dist/commands/send.js.map +1 -1
  105. package/dist/commands/setup.d.ts +1 -1
  106. package/dist/commands/setup.d.ts.map +1 -1
  107. package/dist/commands/setup.js +10 -9
  108. package/dist/commands/setup.js.map +1 -1
  109. package/dist/commands/space-delete.d.ts.map +1 -1
  110. package/dist/commands/space-delete.js +31 -6
  111. package/dist/commands/space-delete.js.map +1 -1
  112. package/dist/commands/space-registration.d.ts +3 -1
  113. package/dist/commands/space-registration.d.ts.map +1 -1
  114. package/dist/commands/space-registration.js +85 -16
  115. package/dist/commands/space-registration.js.map +1 -1
  116. package/dist/commands/space.d.ts +1 -1
  117. package/dist/commands/space.d.ts.map +1 -1
  118. package/dist/commands/space.js +15 -3
  119. package/dist/commands/space.js.map +1 -1
  120. package/dist/commands/stack-down.d.ts +3 -2
  121. package/dist/commands/stack-down.d.ts.map +1 -1
  122. package/dist/commands/stack-down.js +31 -13
  123. package/dist/commands/stack-down.js.map +1 -1
  124. package/dist/commands/stack-up.d.ts.map +1 -1
  125. package/dist/commands/stack-up.js +88 -22
  126. package/dist/commands/stack-up.js.map +1 -1
  127. package/dist/commands/status.d.ts +5 -1
  128. package/dist/commands/status.d.ts.map +1 -1
  129. package/dist/commands/status.js +134 -46
  130. package/dist/commands/status.js.map +1 -1
  131. package/dist/commands/sync.d.ts +3 -3
  132. package/dist/commands/sync.d.ts.map +1 -1
  133. package/dist/commands/sync.js +7 -5
  134. package/dist/commands/sync.js.map +1 -1
  135. package/dist/commands/team-boot-controller.d.ts.map +1 -1
  136. package/dist/commands/team-boot-controller.js +3 -1
  137. package/dist/commands/team-boot-controller.js.map +1 -1
  138. package/dist/commands/team.d.ts.map +1 -1
  139. package/dist/commands/team.js +28 -6
  140. package/dist/commands/team.js.map +1 -1
  141. package/dist/commands/telemetry.d.ts +3 -1
  142. package/dist/commands/telemetry.d.ts.map +1 -1
  143. package/dist/commands/telemetry.js +9 -3
  144. package/dist/commands/telemetry.js.map +1 -1
  145. package/dist/commands/up.d.ts +6 -3
  146. package/dist/commands/up.d.ts.map +1 -1
  147. package/dist/commands/up.js +230 -40
  148. package/dist/commands/up.js.map +1 -1
  149. package/dist/commands/use.d.ts.map +1 -1
  150. package/dist/commands/use.js +4 -1
  151. package/dist/commands/use.js.map +1 -1
  152. package/dist/commands/watch.d.ts.map +1 -1
  153. package/dist/commands/watch.js +11 -5
  154. package/dist/commands/watch.js.map +1 -1
  155. package/dist/console/mesh.d.ts +6 -1
  156. package/dist/console/mesh.d.ts.map +1 -1
  157. package/dist/console/mesh.js +18 -2
  158. package/dist/console/mesh.js.map +1 -1
  159. package/dist/help.d.ts.map +1 -1
  160. package/dist/help.js +14 -6
  161. package/dist/help.js.map +1 -1
  162. package/dist/index.d.ts.map +1 -1
  163. package/dist/index.js +9 -2
  164. package/dist/index.js.map +1 -1
  165. package/dist/lib/completion-install.d.ts.map +1 -1
  166. package/dist/lib/completion-install.js +78 -11
  167. package/dist/lib/completion-install.js.map +1 -1
  168. package/dist/lib/control.d.ts +6 -0
  169. package/dist/lib/control.d.ts.map +1 -1
  170. package/dist/lib/control.js +16 -1
  171. package/dist/lib/control.js.map +1 -1
  172. package/dist/lib/default-persona.js +1 -1
  173. package/dist/lib/default-persona.js.map +1 -1
  174. package/dist/lib/endpoint-errors.d.ts +2 -0
  175. package/dist/lib/endpoint-errors.d.ts.map +1 -1
  176. package/dist/lib/endpoint-errors.js +13 -7
  177. package/dist/lib/endpoint-errors.js.map +1 -1
  178. package/dist/lib/interrupt-notice.d.ts +5 -0
  179. package/dist/lib/interrupt-notice.d.ts.map +1 -0
  180. package/dist/lib/interrupt-notice.js +23 -0
  181. package/dist/lib/interrupt-notice.js.map +1 -0
  182. package/dist/lib/isolated-broker.d.ts +5 -0
  183. package/dist/lib/isolated-broker.d.ts.map +1 -1
  184. package/dist/lib/isolated-broker.js +36 -0
  185. package/dist/lib/isolated-broker.js.map +1 -1
  186. package/dist/lib/legacy-start.d.ts +17 -0
  187. package/dist/lib/legacy-start.d.ts.map +1 -0
  188. package/dist/lib/legacy-start.js +66 -0
  189. package/dist/lib/legacy-start.js.map +1 -0
  190. package/dist/lib/manager-choice.d.ts +21 -0
  191. package/dist/lib/manager-choice.d.ts.map +1 -0
  192. package/dist/lib/manager-choice.js +57 -0
  193. package/dist/lib/manager-choice.js.map +1 -0
  194. package/dist/lib/manifest/resolve.d.ts.map +1 -1
  195. package/dist/lib/manifest/resolve.js +9 -1
  196. package/dist/lib/manifest/resolve.js.map +1 -1
  197. package/dist/lib/missing-flags.d.ts +7 -0
  198. package/dist/lib/missing-flags.d.ts.map +1 -0
  199. package/dist/lib/missing-flags.js +9 -0
  200. package/dist/lib/missing-flags.js.map +1 -0
  201. package/dist/lib/persona-files.d.ts +6 -2
  202. package/dist/lib/persona-files.d.ts.map +1 -1
  203. package/dist/lib/persona-files.js +89 -29
  204. package/dist/lib/persona-files.js.map +1 -1
  205. package/dist/lib/restore.d.ts +27 -1
  206. package/dist/lib/restore.d.ts.map +1 -1
  207. package/dist/lib/restore.js +106 -14
  208. package/dist/lib/restore.js.map +1 -1
  209. package/dist/lib/service-process.d.ts +12 -2
  210. package/dist/lib/service-process.d.ts.map +1 -1
  211. package/dist/lib/service-process.js +25 -2
  212. package/dist/lib/service-process.js.map +1 -1
  213. package/dist/lib/setup-log.js +1 -1
  214. package/dist/lib/setup-log.js.map +1 -1
  215. package/dist/lib/stack-journal.d.ts +22 -1
  216. package/dist/lib/stack-journal.d.ts.map +1 -1
  217. package/dist/lib/stack-journal.js +104 -23
  218. package/dist/lib/stack-journal.js.map +1 -1
  219. package/dist/lib/stdout-owner.d.ts +7 -3
  220. package/dist/lib/stdout-owner.d.ts.map +1 -1
  221. package/dist/lib/stdout-owner.js +17 -4
  222. package/dist/lib/stdout-owner.js.map +1 -1
  223. package/dist/lib/store-dir.d.ts +8 -0
  224. package/dist/lib/store-dir.d.ts.map +1 -0
  225. package/dist/lib/store-dir.js +50 -0
  226. package/dist/lib/store-dir.js.map +1 -0
  227. package/dist/lib/team-additive-attempt.d.ts +1 -1
  228. package/dist/lib/team-fresh.d.ts +11 -1
  229. package/dist/lib/team-fresh.d.ts.map +1 -1
  230. package/dist/lib/team-fresh.js +24 -9
  231. package/dist/lib/team-fresh.js.map +1 -1
  232. package/dist/lib/transient.d.ts +2 -1
  233. package/dist/lib/transient.d.ts.map +1 -1
  234. package/dist/lib/transient.js +9 -3
  235. package/dist/lib/transient.js.map +1 -1
  236. package/dist/render.d.ts +4 -2
  237. package/dist/render.d.ts.map +1 -1
  238. package/dist/render.js +23 -16
  239. package/dist/render.js.map +1 -1
  240. package/dist/seed/lock.d.ts +6 -1
  241. package/dist/seed/lock.d.ts.map +1 -1
  242. package/dist/seed/lock.js +9 -1
  243. package/dist/seed/lock.js.map +1 -1
  244. package/dist/seed/reconcile.d.ts.map +1 -1
  245. package/dist/seed/reconcile.js +37 -6
  246. package/dist/seed/reconcile.js.map +1 -1
  247. package/dist/ui.d.ts +4 -2
  248. package/dist/ui.d.ts.map +1 -1
  249. package/dist/ui.js +13 -8
  250. package/dist/ui.js.map +1 -1
  251. package/dist/view/mesh-view.d.ts +3 -0
  252. package/dist/view/mesh-view.d.ts.map +1 -1
  253. package/dist/view/mesh-view.js +10 -0
  254. package/dist/view/mesh-view.js.map +1 -1
  255. package/package.json +4 -4
@@ -4,11 +4,11 @@ import { createConnection, createServer } from "node:net";
4
4
  import { homedir, hostname } from "node:os";
5
5
  import { mkdirSync, readFileSync, existsSync, openSync, fstatSync, statSync, readSync, closeSync, lstatSync, realpathSync, readdirSync, } from "node:fs";
6
6
  import { dirname, isAbsolute, join, resolve } from "node:path";
7
- import { isReachable, DEFAULT_SERVER, createSpaceAuth, serverConfig, openServerConfig, validateTlsMaterial, mintCreds, mintLifecycleUid, DEV_OWNER, mintConnectionEvictorCreds, mintMembershipObserverCreds, newIdentity, setupSpaceStreams, reconcileSpaceTtls, ttlBuckets, standaloneConnectOpts, requireBrokerFloor, parseServerVersion, presenceBucket, seedChannelRegistry, ensureDefaultDeliveryClass, LEASE_TTL_MS, mkSecretDir, openPrivateAppend, realDirNoSymlink, writeSecretFile, } from "@cotal-ai/core";
7
+ import { isReachable, DEFAULT_SERVER, DEFAULT_SPACE, createSpaceAuth, serverConfig, openServerConfig, validateTlsMaterial, mintCreds, mintLifecycleUid, DEV_OWNER, mintConnectionEvictorCreds, mintMembershipObserverCreds, newIdentity, setupSpaceStreams, reconcileSpaceTtls, ttlBuckets, standaloneConnectOpts, requireBrokerFloor, parseServerVersion, presenceBucket, seedChannelRegistry, ensureDefaultDeliveryClass, LEASE_TTL_MS, mkSecretDir, openPrivateAppend, realDirNoSymlink, writeSecretFile, } from "@cotal-ai/core";
8
8
  import { connect } from "@nats-io/transport-node";
9
9
  import { jetstreamManager, StorageType } from "@nats-io/jetstream";
10
10
  import { Kvm } from "@nats-io/kv";
11
- import { CommandFailure, commandFailureReport, isCommandFailure, jsonFlag, plainFlag, renderReport, terminalWidth, assertSingleSpaceBroker, assertUserAuthInfo, authDir, brokerAddressForDisplay, getSoleSpaceAuth, soleSpaceOf, getSpaceAuth, hasUserAuthState, listSpaceAccounts, preloadSpaceAccounts, putSpaceAuth, canonicalRoot, clearCurrent, findMesh, findPreparedSpace, homeCotalDir, getCurrent, loadMeshes, preparedSpaceAt, removePreparedSpace, localMeshesForRoot, oneLine, presentationOf, writeResult, connectionEvictorCredsKey, membershipConfigPath, membershipObserverCredsKey, membershipRwCredsKey, MEMBERSHIP_CONFIG_KIND, MEMBERSHIP_RW_CREDS_KIND, parsePositiveIntegerFlag, recordMesh, meshesForRoot, removeMesh, rotateSystemCreds, setCurrent, staleSystemCreds, SYSTEM_CREDS_FILES, userAuthStateDir, userAuthSpacesOnDisk, workspaceSecretStore, acquireMaintenanceLock, assertStoreIdentity, assessRestoreClaim, beginOrdinaryResume, bindOrdinaryResumeListener, consumeRetiredMaintenance, markOrdinaryResumeActive, markOrdinaryResumeDegraded, replaceDeadOrdinaryResumeListener, localProcessOwnerStatus, readMaintenanceJournal, readMaintenanceResumeDocument, seatCheckpointDir, readStoreIdentity, recordOrdinaryResumeManagerCommit, releaseMaintenanceLock, retireOrdinaryResume, settleTokenHandoff, sweepTokenHandoff, writeTokenHandoff, sameStoreIdentity, cutController, readBrokerPolicy, writeBrokerPolicy, removePidPair, writePidPair, isLoopbackHost, connectUserControlOrThrow, userViewAuth, recordOperationSpace, retainSystemSigningSeed, } from "@cotal-ai/workspace";
11
+ import { CommandFailure, commandFailureReport, isCommandFailure, protectedLocalDirectory, jsonFlag, plainFlag, renderReport, terminalWidth, assertSingleSpaceBroker, assertUserAuthInfo, authDir, brokerAddressForDisplay, getSoleSpaceAuth, soleSpaceOf, getSpaceAuth, hasUserAuthState, listSpaceAccounts, preloadSpaceAccounts, putSpaceAuth, canonicalRoot, clearCurrent, findMesh, findPreparedSpace, homeCotalDir, getCurrent, loadMeshes, preparedSpaceAt, removePreparedSpace, localMeshesForRoot, oneLine, presentationOf, writeResult, connectionEvictorCredsKey, membershipConfigPath, membershipObserverCredsKey, membershipRwCredsKey, MEMBERSHIP_CONFIG_KIND, MEMBERSHIP_RW_CREDS_KIND, parsePositiveIntegerFlag, recordMesh, meshesForRoot, removeMesh, rotateSystemCreds, setCurrent, staleSystemCreds, SYSTEM_CREDS_FILES, userAuthStateDir, userAuthSpacesOnDisk, workspaceSecretStore, acquireMaintenanceLock, assertStoreIdentity, assessMaintenanceClaim, assessRestoreClaim, beginOrdinaryResume, bindOrdinaryResumeListener, consumeRetiredMaintenance, markOrdinaryResumeActive, markOrdinaryResumeDegraded, replaceDeadOrdinaryResumeListener, localProcessOwnerStatus, readMaintenanceJournal, readMaintenanceResumeDocument, seatCheckpointDir, readStoreIdentity, recordOrdinaryResumeManagerCommit, releaseMaintenanceLock, retireOrdinaryResume, settleTokenHandoff, sweepTokenHandoff, writeTokenHandoff, sameStoreIdentity, cutController, readBrokerPolicy, writeBrokerPolicy, removePidPair, writePidPair, isLoopbackHost, connectUserControlOrThrow, userViewAuth, recordOperationSpace, retainSystemSigningSeed, } from "@cotal-ai/workspace";
12
12
  import { ensureAuthService, resolveAuthProvider, stopAuthService } from "../lib/auth-proc.js";
13
13
  import { resolveSpace } from "../lib/status.js";
14
14
  import { c } from "../ui.js";
@@ -31,6 +31,7 @@ import { renderUpPlan, renderInherited, renderWarnings } from "../lib/manifest/r
31
31
  import { idpUrlProblem, serverUrlProblems } from "../lib/manifest/resolve.js";
32
32
  import { failManifest, refuseManifestSpaceMismatch } from "./topology.js";
33
33
  import { liveMeshProcesses } from "./clean.js";
34
+ import { cleanedManifestStart, retainedLegacyBroker } from "../lib/legacy-start.js";
34
35
  import { controllerStackApplies, recheckExistingStore, requestedStackMode, stackUp, stackUpForegroundNotice } from "./stack-up.js";
35
36
  import { assertUserStackTransport, preflightUserStack } from "./stack-user-auth.js";
36
37
  import { stackDown } from "./stack-down.js";
@@ -42,11 +43,13 @@ import { serviceSupervisorStore } from "../lib/service-supervision.js";
42
43
  import { serviceInstallIntents } from "../lib/service-install-intent.js";
43
44
  import { serviceUninstallIntents } from "../lib/service-uninstall-intent.js";
44
45
  import { serviceUnitActionStore } from "../lib/service-unit-action.js";
46
+ import { assertStoreDirArgument } from "../lib/store-dir.js";
45
47
  import { extensionNames, preflightRuntime } from "../ext-loader.js";
46
48
  import { completingFlagValue } from "../lib/completion.js";
47
49
  import { metadataPositionals } from "../lib/command-path.js";
48
50
  import { askManager } from "../lib/control.js";
49
- import { bindPreparedRestoreListener, isManagerCommitResult, isManagerFinalizeResult, isManagerCommittedRestore, markPreparedRestoreActive, markPreparedRestoreDegraded, heldRestoreAttempt, prepareRestore, recordPreparedRestoreManagerCommit, rehydratePreparedRestore, replacePreparedDeadRestoreListener, } from "../lib/restore.js";
51
+ import { bindPreparedRestoreListener, isManagerCommitResult, isManagerFinalizeResult, isManagerCommittedRestore, markPreparedRestoreActive, markPreparedRestoreDegraded, heldRestoreAttempt, heldClaim, movedFolderRefusal, prepareRestore, preservedSourceState, recordPreparedRestoreManagerCommit, rehydratePreparedRestore, replacePreparedDeadRestoreListener, } from "../lib/restore.js";
52
+ import { attemptProcessesGone } from "../lib/isolated-broker.js";
50
53
  const pendingRestores = new Map();
51
54
  const restoreSinks = new Map();
52
55
  /** Run the guarded `up --restore` startup and return its result instead of printing it. The
@@ -63,7 +66,7 @@ export async function startRestore(values) {
63
66
  const pendingOrdinaryResumes = new Map();
64
67
  /** `cotal up` flags — colocated with the command (like `spawnFlags`) so its completion can read them. */
65
68
  export const upFlags = [
66
- { name: "server", type: "string", value: "<url>", description: "listen URL override" },
69
+ { name: "server", type: "string", value: "<url>", description: "listen URL; a stack's first up records it and later ups keep it" },
67
70
  { name: "host", type: "string", value: "<host>", description: "bind host override (an IP/hostname, not a URL; the URL is --server)" },
68
71
  { name: "space", type: "string", value: "<s>", description: "space name (default: the folder's)" },
69
72
  { name: "root", type: "string", value: "<dir>", description: "use this existing prepared local root instead of the current folder" },
@@ -132,6 +135,10 @@ export function validateUpArguments(args) {
132
135
  const serverProblem = args.values.server !== undefined && !args.values.file ? upServerProblem(String(args.values.server)) : undefined;
133
136
  if (serverProblem)
134
137
  throw new CommandFailure("refused", "USAGE_INVALID", `${serverProblem}; nothing was started or written`, { remedy: "pass the address the local broker listens on, for example --server nats://127.0.0.1:4222" });
138
+ // A URL or port-bearing --host, or one naming another address than --server, refuses here, before
139
+ // the controller stack writes its journal or trust.
140
+ if (args.values.host !== undefined && !args.values.file)
141
+ reconcileHostAndServer(String(args.values.host), args.values.server === undefined ? undefined : String(args.values.server));
135
142
  if (args.values.file !== undefined && args.values.foreground === true)
136
143
  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");
137
144
  if (args.values.foreground === true && (args.values.json === true || args.values.plain === true))
@@ -140,6 +147,8 @@ export function validateUpArguments(args) {
140
147
  // its own checks for maintenance re-entries, which do not pass through this validation.
141
148
  parsePositiveIntegerFlag("--max-sessions", args.values["max-sessions"]);
142
149
  parsePositiveIntegerFlag("--max-file-store", args.values["max-file-store"]);
150
+ if (typeof args.values["store-dir"] === "string")
151
+ assertStoreDirArgument(args.values["store-dir"], typeof args.values.root === "string" ? resolve(args.values.root) : cotalRoot());
143
152
  const restoreOnly = args.values["restore-only"];
144
153
  if (restoreOnly !== undefined && restoreOnly !== "registry")
145
154
  throw new CommandFailure("refused", "USAGE_INVALID", `--restore-only takes registry (got ${JSON.stringify(restoreOnly)})`);
@@ -147,6 +156,10 @@ export function validateUpArguments(args) {
147
156
  throw new CommandFailure("refused", "USAGE_INVALID", "--restore-only and --accept-missing-source require --restore <dir>");
148
157
  if (args.values.restore && (args.values.file !== undefined || args.values.channels !== undefined))
149
158
  throw new CommandFailure("refused", "USAGE_INVALID", "--restore cannot be combined with --file/-f or --channels");
159
+ // The broker reads an explicit channels file only once it is being prepared, so a file it would
160
+ // refuse is named here, before the stack journal or anything else is written.
161
+ if (typeof args.values.channels === "string")
162
+ readChannelsFile(resolve(args.values.channels));
150
163
  if (args.values.restore && args.values["rotate-sys"] === true)
151
164
  throw new CommandFailure("refused", "USAGE_INVALID", "--restore cannot be combined with --rotate-sys", { remedy: "restore the space and verify it first, then rotate: cotal down, then cotal up --rotate-sys" });
152
165
  if (args.values.root !== undefined)
@@ -287,10 +300,49 @@ function assertFreshTeamBootOwnership(root, space, mode, own) {
287
300
  if (bootAttempts.refused.length || summaries.refused.length || unsettled.length)
288
301
  throw new CommandFailure("refused", "LIFECYCLE_BLOCKED", "a prior fresh boot attempt lacks a matching readable summary, or an attempt/summary is unreadable; its outcome was not treated as absent", { target: { root, space, unsettledIds: unsettled.map((attempt) => attempt.deploymentId), unreadable: [...bootAttempts.refused, ...summaries.refused].map(({ path }) => path) }, remedy: "inspect each full boot attempt and its original listener before another fresh start; do not retry an unknown boot" });
289
302
  }
303
+ /** The guarded whole-stack stop a foreground signal runs, acknowledged by that signal's exit code. A
304
+ * failed or unknown stop is reported with its retained members; nothing is force-killed. */
305
+ function stopForegroundStack(root, signal) {
306
+ return stackDown(root, { yes: true }).catch((error) => {
307
+ process.stderr.write(`${renderReport(commandFailureReport(isCommandFailure(error) ? error : new CommandFailure("unknown", "OPERATION_UNKNOWN", "the foreground stack stop did not confirm its outcome; its members were retained")), "rich", terminalWidth(process.stderr))}\n`);
308
+ }).finally(() => { process.exitCode = signal === "SIGINT" ? 130 : 143; });
309
+ }
290
310
  /** Foreground controller stack: the terminal holds the stack's lifetime until SIGINT or SIGTERM,
291
- * which runs the same guarded whole-stack stop as bare `down`, acknowledged by the signal. A failed
292
- * or unknown stop is reported with its retained members; nothing is force-killed. */
293
- export function holdForegroundStack(root) {
311
+ * which runs the same guarded whole-stack stop as bare `down`. `start`, when given, is the startup
312
+ * this terminal already holds: a signal during it lets the start settle, then runs that stop. A
313
+ * failed start still runs the stop, and its failure is thrown once the stop returns. The hold's end
314
+ * sets the exit code: 0 when another command completed the stop or preserve, 130 or 143 after a
315
+ * signal, whatever the start receipt set. */
316
+ export async function holdForegroundStack(root, start) {
317
+ if (start) {
318
+ let requested;
319
+ const request = (signal) => {
320
+ if (requested)
321
+ return;
322
+ requested = signal;
323
+ process.stderr.write("Stop requested; the whole-stack stop runs once the start settles\n");
324
+ };
325
+ const interrupt = () => request("SIGINT"), terminate = () => request("SIGTERM");
326
+ process.on("SIGINT", interrupt);
327
+ process.on("SIGTERM", terminate);
328
+ let failure;
329
+ try {
330
+ await start();
331
+ }
332
+ catch (error) {
333
+ failure = { error };
334
+ }
335
+ finally {
336
+ process.off("SIGINT", interrupt);
337
+ process.off("SIGTERM", terminate);
338
+ }
339
+ if (requested)
340
+ await stopForegroundStack(root, requested);
341
+ if (failure)
342
+ throw failure.error;
343
+ if (requested)
344
+ return;
345
+ }
294
346
  return new Promise((resolveHold) => {
295
347
  // The hold ends on its own when another command completes a whole-stack stop or preserve of this
296
348
  // root: a later operation recorded as completed is that evidence. Any other later operation,
@@ -313,6 +365,7 @@ export function holdForegroundStack(root) {
313
365
  process.off("SIGTERM", terminate);
314
366
  clearInterval(lifetime);
315
367
  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", terminalWidth(process.stderr))}\n`);
368
+ process.exitCode = 0;
316
369
  resolveHold();
317
370
  }, 1000);
318
371
  const stop = (signal) => {
@@ -322,9 +375,7 @@ export function holdForegroundStack(root) {
322
375
  process.off("SIGINT", interrupt);
323
376
  process.off("SIGTERM", terminate);
324
377
  clearInterval(lifetime);
325
- void stackDown(root, { yes: true }).catch((error) => {
326
- process.stderr.write(`${renderReport(commandFailureReport(isCommandFailure(error) ? error : new CommandFailure("unknown", "OPERATION_UNKNOWN", "the foreground stack stop did not confirm its outcome; its members were retained")), "rich", terminalWidth(process.stderr))}\n`);
327
- }).finally(() => { process.exitCode = signal === "SIGINT" ? 130 : 143; resolveHold(); });
378
+ void stopForegroundStack(root, signal).finally(resolveHold);
328
379
  };
329
380
  const interrupt = () => stop("SIGINT");
330
381
  const terminate = () => stop("SIGTERM");
@@ -392,6 +443,9 @@ async function runUp(args, inheritedLock, onAdopt, freshTeamBoot = false, restor
392
443
  const values = args.values;
393
444
  if (freshTeamBoot && (!values.file || values.restore || values.__restoreAttempt || values.__ordinaryResumeAttempt || values["rotate-sys"] || values["no-manager"]))
394
445
  throw new CommandFailure("refused", "USAGE_INVALID", "fresh team boot accepts one manifest and its selected lifetime, not a restore, rotation or manager-free override");
446
+ // `space create` and `down` refuse a root other local accounts can write, so `up` refuses it too,
447
+ // before anything is written: a stack started there could not be stopped from it.
448
+ protectedLocalDirectory(canonicalRoot(cotalRoot()), "the project root");
395
449
  if (values.restore) {
396
450
  if (values.file || values.channels)
397
451
  throw new Error("--restore cannot be combined with --file/-f or --channels");
@@ -495,6 +549,8 @@ async function runUp(args, inheritedLock, onAdopt, freshTeamBoot = false, restor
495
549
  // Refuse first-enable IdP failures and explicit pin conflicts before even recovery's lock
496
550
  // creates its layout. Existing recovery keeps its own recorded startup and trust checks.
497
551
  const stackSpace = values.space ?? folderSpace();
552
+ if (values.space === undefined)
553
+ assertSelectionNotMoved(root, stackSpace);
498
554
  recordOperationSpace(stackSpace);
499
555
  if (!readMaintenanceJournal(root) && controllerStackApplies(root, stackSpace, values)) {
500
556
  const recordedStack = readStackJournal(root);
@@ -516,7 +572,8 @@ async function runUp(args, inheritedLock, onAdopt, freshTeamBoot = false, restor
516
572
  throw new CommandFailure("refused", "DEPENDENCY_UNAVAILABLE", "the requested runtime did not pass preflight; nothing was started", { target: { root, space: stackSpace, runtime: values.runtime }, remedy: error instanceof Error ? error.message : "inspect the selected runtime provider" });
517
573
  }
518
574
  }
519
- const lock = acquireMaintenanceLock(root);
575
+ // A concurrent whole-stack operation is a known refusal that names its pid, as for `down`.
576
+ const lock = acquireStackOperationLock(root);
520
577
  let pending;
521
578
  let recoveredRestore;
522
579
  // Set only at the moment the lock is passed to a re-entry, which then owns releasing it. Any
@@ -528,12 +585,10 @@ async function runUp(args, inheritedLock, onAdopt, freshTeamBoot = false, restor
528
585
  // Ordinary up NEVER rolls back an in-progress restore: a live attempt's target may still be
529
586
  // written by its isolated broker. Refuse with the exact recovery recourse instead.
530
587
  const attempt = journal.restore.attemptId;
531
- const assessment = assessRestoreClaim(journal);
532
- if (assessment === "live")
533
- throw new Error(`cotal up is refused: restore attempt ${attempt} is in progress (claim live until ${journal.claim.deadline}); wait for it to complete or become provably stale`);
534
- if (assessment === "ambiguous")
535
- throw new Error(`cotal up is refused: restore attempt ${attempt} owners cannot be proven dead; inspect the recorded coordinator, watchdog, and broker processes before recovery`);
536
- throw new Error(`cotal up is refused: stale restore attempt ${attempt} holds the store; roll it back with \`cotal clean restore-attempt --attempt ${attempt} --force\`, or recover it with \`cotal up --restore\``);
588
+ const assessment = assessRestoreClaim(journal, { unrecordedOwnersDead: attemptProcessesGone(root) });
589
+ if (assessment !== "stale")
590
+ throw heldClaim(root, attempt, journal.claim, "cotal up", assessment);
591
+ throw new CommandFailure("refused", "LIFECYCLE_BLOCKED", `cotal up is refused: restore attempt ${attempt} stopped before it committed and still holds the store; nothing was changed`, { target: { root, attemptId: attempt }, remedy: `roll it back with cotal backup recover ${attempt} --yes, then run cotal up; or run the restore again` });
537
592
  }
538
593
  const controllerCut = journal ? cutController(journal.cut) : undefined;
539
594
  if (journal && controllerCut && journal.state !== "cut-intent" && journal.state !== "cut-committed" && journal.state !== "resume-retired") {
@@ -571,6 +626,11 @@ async function runUp(args, inheritedLock, onAdopt, freshTeamBoot = false, restor
571
626
  }
572
627
  }
573
628
  else if (journal?.state === "ready") {
629
+ const source = preservedSourceState(root, journal.source);
630
+ if (source.state === "moved")
631
+ throw movedFolderRefusal(root, journal.space, journal.source.path, source, "run cotal up");
632
+ if (source.state === "missing")
633
+ throw new CommandFailure("refused", "TARGET_NOT_FOUND", `the preserved store recorded at ${journal.source.path} is missing, so up cannot resume it; nothing was started`, { target: { root, space: journal.space, recordedStore: journal.source.path }, remedy: "if this folder was moved, move it back so that path exists again; if the store is lost, restore a backup here with cotal backup restore <dir> --accept-missing-source" });
574
634
  const resume = readMaintenanceResumeDocument(root, journal.resume);
575
635
  const attemptId = `resume-${randomUUID()}`;
576
636
  const launch = resume.launch;
@@ -704,6 +764,14 @@ async function runUp(args, inheritedLock, onAdopt, freshTeamBoot = false, restor
704
764
  else if (journal?.state === "resume-retired") {
705
765
  consumeRetiredMaintenance(lock);
706
766
  }
767
+ else if (journal?.state === "claimed") {
768
+ // An interrupted backup create holds the cut. Refuse with its holder or its release.
769
+ const attempt = journal.claim.attemptId;
770
+ const assessment = assessMaintenanceClaim(journal.claim, { unrecordedOwnersDead: attemptProcessesGone(root) });
771
+ if (assessment !== "stale")
772
+ throw heldClaim(root, attempt, journal.claim, "cotal up", assessment);
773
+ throw new CommandFailure("refused", "LIFECYCLE_BLOCKED", `cotal up is refused: backup attempt ${attempt} stopped before it finished and still holds this root; nothing was changed`, { target: { root, attemptId: attempt }, remedy: `release it with cotal backup recover ${attempt} --yes, then run cotal up` });
774
+ }
707
775
  else if (journal) {
708
776
  throw new Error(`cotal up is refused while maintenance state is ${journal.state}; follow the recorded recovery`);
709
777
  }
@@ -857,6 +925,9 @@ async function runUp(args, inheritedLock, onAdopt, freshTeamBoot = false, restor
857
925
  persist: false,
858
926
  quiet: true,
859
927
  });
928
+ // The manifest route checks its own effective address, which `--server` only overrides.
929
+ if (!values.file && values.server !== undefined)
930
+ assertTlsIntentServed(values.server, transport, "--server");
860
931
  // CONTROLLER-OWNED STACK. A root whose stack the service controller owns, or a fresh prepared
861
932
  // static-auth, open or user-auth root with nothing legacy retained, starts as exact controller members instead
862
933
  // of the pidfile launcher. The decision is made once here; neither route falls back to the other.
@@ -868,16 +939,21 @@ async function runUp(args, inheritedLock, onAdopt, freshTeamBoot = false, restor
868
939
  const presentation = presentationOf(values);
869
940
  const stackLock = acquireStackOperationLock(meshRoot);
870
941
  const native = controllerStackNative();
871
- try {
872
- if (values.foreground && presentation !== "json")
873
- stackUpForegroundNotice(presentation, stackSpace);
874
- await stackUp({ maintenanceLock: stackLock, root: meshRoot, space: stackSpace, server: stackServer, transport, runtime: values.runtime ?? "pty", noManager, ...(stackMode ? { mode: stackMode } : {}), ...(values.idp ? { idp: values.idp } : {}), ...(values.host ? { host: values.host } : {}), ...(values["store-dir"] ? { storeDir: values["store-dir"] } : {}), ...(maxFileStore !== undefined ? { maxFileStore } : {}), ...(maxSessions !== undefined ? { maxSessions } : {}), ...(values.channels ? { channels: values.channels } : {}), foreground: values.foreground === true, presentation }, native);
875
- }
876
- finally {
877
- releaseMaintenanceLock(stackLock);
878
- }
942
+ // A foreground terminal holds the start as well, so a signal during it stops what it started.
943
+ const start = async () => {
944
+ try {
945
+ if (values.foreground && presentation !== "json")
946
+ stackUpForegroundNotice(presentation, stackSpace);
947
+ await stackUp({ maintenanceLock: stackLock, root: meshRoot, space: stackSpace, server: stackServer, transport, runtime: values.runtime ?? "pty", noManager, ...(stackMode ? { mode: stackMode } : {}), ...(values.idp ? { idp: values.idp } : {}), ...(values.host ? { host: values.host } : {}), ...(values["store-dir"] ? { storeDir: values["store-dir"] } : {}), ...(maxFileStore !== undefined ? { maxFileStore } : {}), ...(maxSessions !== undefined ? { maxSessions } : {}), ...(values.channels ? { channels: values.channels } : {}), foreground: values.foreground === true, presentation }, native);
948
+ }
949
+ finally {
950
+ releaseMaintenanceLock(stackLock);
951
+ }
952
+ };
879
953
  if (values.foreground)
880
- await holdForegroundStack(meshRoot);
954
+ await holdForegroundStack(meshRoot, start);
955
+ else
956
+ await start();
881
957
  return;
882
958
  }
883
959
  if (values.json || values.plain)
@@ -902,12 +978,13 @@ async function runUp(args, inheritedLock, onAdopt, freshTeamBoot = false, restor
902
978
  rotateSys: values["rotate-sys"],
903
979
  maxSessions,
904
980
  noManager,
981
+ storeDir: values["store-dir"],
905
982
  });
906
983
  if (previewRoot)
907
984
  console.log(c.yellow("! this preview used the invoking folder, not the inherited home store; before applying, prepare it with `cotal space create <space> --root .`"));
908
985
  return;
909
986
  }
910
- const lock = acquireMaintenanceLock(cotalRoot());
987
+ const lock = acquireStackOperationLock(cotalRoot());
911
988
  try {
912
989
  if (freshTeamBoot) {
913
990
  if (!values.space)
@@ -931,6 +1008,7 @@ async function runUp(args, inheritedLock, onAdopt, freshTeamBoot = false, restor
931
1008
  rotateSys: values["rotate-sys"],
932
1009
  maxSessions,
933
1010
  noManager,
1011
+ storeDir: values["store-dir"],
934
1012
  });
935
1013
  }
936
1014
  finally {
@@ -969,7 +1047,7 @@ async function runUp(args, inheritedLock, onAdopt, freshTeamBoot = false, restor
969
1047
  // that journals, give it `heldLock` and hand it down from here; do not audit by call-site shape.
970
1048
  // The one caller that does NOT pass it is the prepare-failure path above, where the lock has
971
1049
  // genuinely not been taken yet in this frame and the helper is meant to take its own.
972
- let startupLock = inheritedLock ?? acquireMaintenanceLock(cotalRoot());
1050
+ let startupLock = inheritedLock ?? acquireStackOperationLock(cotalRoot());
973
1051
  onAdopt?.(); // from here the release below owns it, inherited or not
974
1052
  const releaseStartupLock = () => {
975
1053
  if (!startupLock)
@@ -985,7 +1063,24 @@ async function runUp(args, inheritedLock, onAdopt, freshTeamBoot = false, restor
985
1063
  // on a free port, which this root's record keeps; a re-run must start from that URL, or every
986
1064
  // lookup below misses its own mesh and the space claim refuses it (#3889).
987
1065
  const recordedSpace = values.space ?? folderSpace();
988
- const implicitServer = localMeshesForRoot(cotalRoot()).find((m) => m.space === recordedSpace)?.server ?? DEFAULT_SERVER;
1066
+ const registeredServer = localMeshesForRoot(cotalRoot()).find((m) => m.space === recordedSpace)?.server;
1067
+ // A stopped legacy root's `down` dropped the registration that kept its address, so its own files
1068
+ // decide. With no address flag, it starts again at the address its last start rendered, and in
1069
+ // open mode when that start was open and no mode is asked for. After `clean all` only a fresh
1070
+ // team summary remains, and a start that would differ from it refuses, naming its manifest.
1071
+ const implicit = !resumeAttempt && registeredServer === undefined && values.server === undefined && values.host === undefined && !values["user-auth"];
1072
+ const retained = implicit ? retainedLegacyBroker(cotalRoot()) : undefined;
1073
+ if (retained) {
1074
+ if (retained.open)
1075
+ values.open = true;
1076
+ console.log(c.dim(`starting this folder's stopped stack as it last ran: ${retained.server}${values.open ? ", open" : ""}`));
1077
+ }
1078
+ else if (implicit) {
1079
+ const cleaned = cleanedManifestStart(cotalRoot(), recordedSpace, values.open === true);
1080
+ if (cleaned)
1081
+ throw new CommandFailure("refused", "CONFLICT", `this folder was deployed from a manifest as "${cleaned.space}" at ${cleaned.server} in ${cleaned.mode === "open" ? "open" : "static auth"} mode, and its identity and broker configuration were removed, so a bare up would not start it as it was deployed; nothing was started`, { target: { root: cotalRoot(), space: cleaned.space, server: cleaned.server }, remedy: `deploy it again with ${cleaned.command}` });
1082
+ }
1083
+ const implicitServer = registeredServer ?? retained?.server ?? DEFAULT_SERVER;
989
1084
  let server = values.server ?? implicitServer;
990
1085
  const host = values.host ?? "127.0.0.1";
991
1086
  // `--host` is the BIND address; `server` is the URL the readiness probe, the mesh registry, and
@@ -1002,12 +1097,14 @@ async function runUp(args, inheritedLock, onAdopt, freshTeamBoot = false, restor
1002
1097
  // Never runs during a resume attempt, which keeps its own store checks. The reachability probe
1003
1098
  // here is reused as `listenerReachable` further down instead of probing twice.
1004
1099
  let repairProbe;
1100
+ let repairing = false;
1005
1101
  if (!resumeAttempt) {
1006
1102
  const repairSpace = values.space ?? folderSpace();
1007
1103
  const repairRoot = cotalRoot();
1008
1104
  const heldForRepair = loadMeshes().find((m) => m.origin !== "manual" && m.origin !== "catalog" && m.server === server && m.root === repairRoot && m.space === repairSpace);
1009
1105
  if (heldForRepair) {
1010
1106
  repairProbe = await isReachable(server);
1107
+ repairing = !repairProbe;
1011
1108
  if (!repairProbe) {
1012
1109
  if (values["store-dir"] !== undefined) {
1013
1110
  const requestedStoreDir = resolve(values["store-dir"]);
@@ -1287,6 +1384,16 @@ async function runUp(args, inheritedLock, onAdopt, freshTeamBoot = false, restor
1287
1384
  seedPersonaAfterUp(root);
1288
1385
  return;
1289
1386
  }
1387
+ // The broker answering here is the named space's own, started from another folder.
1388
+ const owner = values.space !== undefined ? findMesh(space) : undefined;
1389
+ if (owner && owner.server === server && owner.root !== root) {
1390
+ let controller = false;
1391
+ try {
1392
+ controller = readStackJournal(owner.root)?.journal.space === space;
1393
+ }
1394
+ catch { /* named with the legacy stop */ }
1395
+ throw new CommandFailure("refused", "CONFLICT", `space "${space}" runs at ${server}, started in ${owner.root}, so up did not start it again`, { target: { space, root: owner.root, server }, remedy: `use it from here with --space ${space}, or stop it with cotal down${controller ? " --yes" : ""} in ${owner.root}` });
1396
+ }
1290
1397
  const who = held ? `mesh "${held.space}" (${held.root})` : "a broker not started here";
1291
1398
  // Reaching here with `--rotate-sys` means something IS answering at the requested address and it
1292
1399
  // is not this root's recorded mesh (that case was refused above). The ordinary response is to pick
@@ -1310,6 +1417,9 @@ async function runUp(args, inheritedLock, onAdopt, freshTeamBoot = false, restor
1310
1417
  process.exit(1);
1311
1418
  }
1312
1419
  }
1420
+ // A repair keeps its own store rules above, and a resume or restore names its store.
1421
+ if (!resumeAttempt && !repairing && values["store-dir"] === undefined)
1422
+ refuseUnnamedLastStore(cotalPath("nats"));
1313
1423
  const restored = resumeAttempt ? pendingRestores.get(resumeAttempt) : undefined;
1314
1424
  const boundListener = restored ? {
1315
1425
  serverName: restored.serverName,
@@ -1604,8 +1714,10 @@ function assertOrdinaryUpAllowed(root, storeDir) {
1604
1714
  throw new Error(`ordinary startup after restore must use the recorded active target store ${maintenance.restore.target.path}, not ${storeDir}`);
1605
1715
  return;
1606
1716
  }
1717
+ // A preserved cut resumes only through bare `up`, which journals the resume attempt. Nothing has
1718
+ // started here, so this is a refusal.
1607
1719
  if (maintenance.state === "ready")
1608
- throw new Error("ordinary resume must begin through the attempt-bound startup path");
1720
+ throw new CommandFailure("refused", "LIFECYCLE_BLOCKED", "this root holds a stack preserved by `cotal down --preserve-state`, which only bare `cotal up` resumes; nothing was started", { target: { root, space: maintenance.space }, remedy: `resume it with bare \`cotal up\` in ${root}` });
1609
1721
  throw new Error(`cotal up is refused while maintenance state is ${maintenance.state}; follow the recorded restore recovery`);
1610
1722
  }
1611
1723
  function markPendingResumeDegraded(attemptId, reason, heldLock) {
@@ -2044,6 +2156,7 @@ async function verifySpawnedOrdinaryListener(pending) {
2044
2156
  }
2045
2157
  async function resumeProvenOrdinaryListener(pending, heldLock) {
2046
2158
  await proveOrdinaryResumeListener(pending);
2159
+ await recreateAdoptedMemoryBuckets(pending.root, pending.space, pending.server, pending.mode);
2047
2160
  const svc = await ensureRecoveredUserAuth(pending);
2048
2161
  // Read the recorded exposure BEFORE re-recording: `recordOurMesh` writes the entry whole, so a
2049
2162
  // record built without this field would erase the operator's decision, and the adopted manager
@@ -2091,6 +2204,7 @@ async function ensureRecoveredUserAuth(prepared) {
2091
2204
  }
2092
2205
  async function resumeProvenRestoreListener(prepared, heldLock) {
2093
2206
  await provePreparedRestoreListener(prepared);
2207
+ await recreateAdoptedMemoryBuckets(prepared.root, prepared.space, prepared.server, prepared.mode);
2094
2208
  const svc = await ensureRecoveredUserAuth(prepared);
2095
2209
  // Same ordering constraint as the pending-adopt path above: capture the recorded exposure before
2096
2210
  // `recordOurMesh` rewrites the entry, or a restore silently demotes the mesh to loopback attach.
@@ -2560,6 +2674,7 @@ async function upManifest(file, opts) {
2560
2674
  // Same bind-vs-probe reconciliation as the flag path: a manifest that sets `broker.host` without
2561
2675
  // an explicit `broker.servers` would otherwise bind one address and be probed at another.
2562
2676
  const server = m.broker?.host ? reconcileHostAndServer(m.broker.host, m.broker?.servers, "broker.host", "broker.servers") : (m.broker?.servers ?? DEFAULT_SERVER);
2677
+ assertTlsIntentServed(server, opts.transport, opts.server !== undefined ? "--server" : "the manifest's broker.servers");
2563
2678
  const open = m.broker?.auth === false; // default is auth
2564
2679
  const userAuth = m.broker?.auth === "user" ? { idpUrl: m.broker.idp } : undefined;
2565
2680
  const runtime = m.runtime ?? "pty";
@@ -2587,6 +2702,9 @@ async function upManifest(file, opts) {
2587
2702
  // exists to remove. Before the dry-run print and before anything boots.
2588
2703
  if (opts.rotateSys && open)
2589
2704
  throw new Error("--rotate-sys is for auth meshes: this manifest sets broker.auth: false (open), so there is no system account or $SYS credentials to rotate");
2705
+ // Before the dry-run print and before connector preflight or any write, as the refusals above.
2706
+ if (!opts.storeDir)
2707
+ refuseUnnamedLastStore(cotalPath("nats"));
2590
2708
  if (opts.dryRun) {
2591
2709
  // Dial-host SAN must refuse here too (S6). The real route runs assertServesDialHost after
2592
2710
  // the plan is computed; dry-run used to return before that check and green-lit a launch
@@ -2622,6 +2740,12 @@ async function upManifest(file, opts) {
2622
2740
  if (await isReachable(server)) {
2623
2741
  if (opts.freshTeamBoot)
2624
2742
  throw new CommandFailure("refused", "CONFLICT", "the selected address already has a broker; fresh boot did not adopt it or start a competing listener", { target: { space: m.space, server: brokerAddressForDisplay(server) ?? "not displayable" }, remedy: "inspect the existing broker and selected local records, or use another prepared address" });
2743
+ // This folder's own mesh for the manifest's space is named as running, as a bare `up` names it,
2744
+ // with the routes that change it instead of the advice for a foreign broker.
2745
+ if (loadMeshes().some((row) => row.server === server && row.root === cotalRoot() && row.space === m.space)) {
2746
+ console.error(c.red(`✗ mesh "${m.space}" is already running at ${brokerAddressForDisplay(server) ?? "its address"} from this folder - \`up -f\` boots a fresh mesh and does not apply a manifest to a running one; \`cotal team deploy ${file}\` adds all-new channels and agents to it, or \`cotal down\` it first, then \`cotal up -f ${file}\``));
2747
+ process.exit(1);
2748
+ }
2625
2749
  console.error(c.red(`✗ ${brokerAddressForDisplay(server) ?? "selected address"} already has a broker - a fresh boot will not adopt it. Stop the owned stack or select another address; team deploy supports only all-new channel cards, not agent apply.`));
2626
2750
  process.exit(1);
2627
2751
  }
@@ -2706,7 +2830,7 @@ async function upManifest(file, opts) {
2706
2830
  try {
2707
2831
  // `m.broker?.host`, not the defaulted `host`: same reason as the flag path — only a host the
2708
2832
  // manifest actually declared is an exposure decision worth persisting.
2709
- ({ pid, controlPlane, authService, deliveryResponderBound } = await startMeshDetached({ transport: opts.transport, server, space: m.space, open, userAuth, rotateSys: opts.rotateSys, host: m.broker?.host, seed: manifestToChannels(eff), runtime, launch: specPath, maxSessions: opts.maxSessions, noManager: effectiveNoManager, quietBoot: opts.freshTeamBoot }));
2833
+ ({ pid, controlPlane, authService, deliveryResponderBound } = await startMeshDetached({ transport: opts.transport, server, space: m.space, open, userAuth, rotateSys: opts.rotateSys, host: m.broker?.host, seed: manifestToChannels(eff), runtime, launch: specPath, maxSessions: opts.maxSessions, noManager: effectiveNoManager, quietBoot: opts.freshTeamBoot, ...(opts.storeDir ? { storeDir: opts.storeDir } : {}) }));
2710
2834
  }
2711
2835
  catch (e) {
2712
2836
  if (opts.freshTeamBoot)
@@ -3147,11 +3271,13 @@ function ensureRootForSpace(space) {
3147
3271
  // A prepared space starts only in the root `cotal space create` gave it. Checked before the mkdir
3148
3272
  // below, so a refused start leaves nothing behind.
3149
3273
  const prepared = findPreparedSpace(space);
3150
- if (prepared && canonicalRoot(prepared.root) !== canonicalRoot(root))
3151
- throw new CommandFailure("refused", "TARGET_UNAVAILABLE", `space "${space}" is prepared in ${prepared.root}`, {
3274
+ if (prepared && canonicalRoot(prepared.root) !== canonicalRoot(root)) {
3275
+ const gone = !existsSync(prepared.root);
3276
+ throw new CommandFailure("refused", "TARGET_UNAVAILABLE", `space "${space}" is prepared in ${prepared.root}${gone ? ", which no longer exists" : ""}`, {
3152
3277
  target: { space, root: prepared.root },
3153
- remedy: `start it with \`cotal up\` there, or \`cotal space forget ${space}\` to start it here`,
3278
+ remedy: gone ? `forget it with \`cotal space forget ${space}\`, then start it here` : `start it with \`cotal up\` there, or \`cotal space forget ${space}\` to start it here`,
3154
3279
  });
3280
+ }
3155
3281
  // What spaces does this root already host? Prefer auth material; fall back to a live MeshEntry
3156
3282
  // whose root is this directory (open meshes have no auth dir).
3157
3283
  const hosted = listSpaceAccounts(authDir(root));
@@ -3197,6 +3323,21 @@ function folderSpace() {
3197
3323
  }
3198
3324
  return resolveSpace(process.cwd());
3199
3325
  }
3326
+ /** A bare `up` in a folder that names no space starts the default space. When the selected space
3327
+ * is prepared in a folder that no longer exists, as after that folder was moved, the default is not
3328
+ * what was meant, so `up` refuses with the step that prepares the selection here. */
3329
+ function assertSelectionNotMoved(root, space) {
3330
+ if (space !== DEFAULT_SPACE || soleSpaceOf(authDir(root)) !== undefined || preparedSpaceAt(root) || localMeshesForRoot(root).length || readStackJournal(root))
3331
+ return;
3332
+ const current = getCurrent();
3333
+ const prepared = current === undefined || current === space ? undefined : findPreparedSpace(current);
3334
+ if (!prepared || existsSync(prepared.root))
3335
+ return;
3336
+ throw new CommandFailure("refused", "TARGET_UNAVAILABLE", `the selected space "${current}" is prepared in ${prepared.root}, which no longer exists, and this folder names no space, so up did not start "${space}" here`, {
3337
+ target: { root, space: current, preparedRoot: prepared.root },
3338
+ 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}`,
3339
+ });
3340
+ }
3200
3341
  function realpathSafe(p) {
3201
3342
  try {
3202
3343
  return realpathSync(p);
@@ -3621,19 +3762,44 @@ async function recreateMemoryBuckets(server, space, setup) {
3621
3762
  await nc.drain();
3622
3763
  }
3623
3764
  }
3765
+ /** An adopted listener may have been bound by an `up` that stopped before {@link recreateMemoryBuckets},
3766
+ * so the memory buckets the daemons open can be missing on it. An existing bucket is left as it is. */
3767
+ async function recreateAdoptedMemoryBuckets(root, space, server, mode) {
3768
+ if (mode === "open")
3769
+ return recreateMemoryBuckets(server, space);
3770
+ const auth = await getSpaceAuth(workspaceSecretStore(root), space);
3771
+ if (!auth)
3772
+ throw new Error(`space "${space}" has no trust material under ${authDir(root)}; cannot recreate its memory buckets on the adopted listener`);
3773
+ await recreateMemoryBuckets(server, space, { creds: await mintCreds(auth, newIdentity(), "provisioner") });
3774
+ }
3624
3775
  /** Load the declarative channels-config file to seed the registry. An explicit `--channels`
3625
3776
  * path that's missing is a hard error; the default `.cotal/channels.json` is optional (absent
3626
3777
  * ⇒ nothing to seed). */
3627
3778
  function loadChannelsFile(explicit) {
3628
- const path = explicit ? resolve(explicit) : cotalPath("channels.json");
3629
- if (!existsSync(path)) {
3630
- if (explicit) {
3631
- throw new Error(`channels file not found: ${path}`);
3632
- }
3779
+ if (explicit)
3780
+ return readChannelsFile(resolve(explicit));
3781
+ const path = cotalPath("channels.json");
3782
+ if (!existsSync(path))
3633
3783
  return undefined;
3634
- }
3635
3784
  return JSON.parse(readFileSync(path, "utf8"));
3636
3785
  }
3786
+ /** Read and parse an explicit `--channels` file. One that is missing, unreadable or not JSON is a
3787
+ * usage refusal that names its path. */
3788
+ function readChannelsFile(path) {
3789
+ let text;
3790
+ try {
3791
+ text = readFileSync(path, "utf8");
3792
+ }
3793
+ catch {
3794
+ throw new CommandFailure("refused", "USAGE_INVALID", `the channels file ${path} is missing or unreadable`, { remedy: "name an existing channels file with --channels <path>, or omit --channels" });
3795
+ }
3796
+ try {
3797
+ return JSON.parse(text);
3798
+ }
3799
+ catch (error) {
3800
+ throw new CommandFailure("refused", "USAGE_INVALID", `the channels file ${path} is not valid JSON (${error.message})`, { remedy: "fix the file, or omit --channels" });
3801
+ }
3802
+ }
3637
3803
  /**
3638
3804
  * Turn the `--tls-cert`/`--tls-key` pair into a validated {@link BrokerTransport}, or `plaintext`
3639
3805
  * when neither was given.
@@ -3694,6 +3860,13 @@ opts = {}) {
3694
3860
  writeBrokerPolicy(root, { version: 1, transport: validated });
3695
3861
  return validated;
3696
3862
  }
3863
+ /** A `tls://` broker address is recorded as required TLS, and every later dial through the record
3864
+ * trusts it. Refuse it, before anything starts, when this start would serve plaintext. */
3865
+ function assertTlsIntentServed(server, transport, source) {
3866
+ const tls = server.split(",").some((url) => url.trim().toLowerCase().startsWith("tls://"));
3867
+ if (tls && transport.kind !== "tls-required")
3868
+ throw new CommandFailure("refused", "USAGE_INVALID", `${source} names a tls:// address, but no TLS certificate and key are configured, so the broker would serve plaintext; nothing was started`, { target: { server: brokerAddressForDisplay(server) ?? "not displayable" }, remedy: "serve TLS with --tls-cert <cert.pem> --tls-key <key.pem>, or use a nats:// address" });
3869
+ }
3697
3870
  /** Persist a transport after its listener starts; a structured boot leaves stdout to its receipt. */
3698
3871
  function commitTransportPolicy(root, transport, quietBoot = false) {
3699
3872
  if (transport.kind !== "tls-required")
@@ -3819,6 +3992,23 @@ function validateRecorded(transport, dialHost, opts = {}) {
3819
3992
  }
3820
3993
  return transport;
3821
3994
  }
3995
+ /** `down` drops the record that named a custom or restored store, so a later start that names none
3996
+ * would open an empty second store and leave the data where it was. Each real start writes its
3997
+ * `store_dir` into the broker config it renders, and that file outlives `down`: while the store it
3998
+ * names differs and still holds JetStream data, and the default store holds none, refuse and name it. */
3999
+ function refuseUnnamedLastStore(storeDir) {
4000
+ if (existsSync(join(storeDir, "jetstream")))
4001
+ return;
4002
+ for (const conf of [join(authDir(cotalRoot()), "server.conf"), cotalPath("server-open.conf")]) {
4003
+ if (!existsSync(conf))
4004
+ continue;
4005
+ // The core renderer writes the path as a JSON string.
4006
+ const named = /jetstream \{ store_dir: ("(?:[^"\\]|\\.)*")/.exec(readFileSync(conf, "utf8"))?.[1];
4007
+ const last = named === undefined ? undefined : resolve(JSON.parse(named));
4008
+ if (last !== undefined && last !== resolve(storeDir) && existsSync(join(last, "jetstream")))
4009
+ throw new CommandFailure("refused", "CONFLICT", `this root's last broker served the store ${last}, and this start names no store, so it would open a new empty one at ${storeDir}; nothing was started`, { target: { root: cotalRoot(), storeDir: last }, remedy: `reopen it with --store-dir ${last}, or move that store away to start empty` });
4010
+ }
4011
+ }
3822
4012
  /**
3823
4013
  * Render and write the config for an OPEN (no-auth) broker, returning its path.
3824
4014
  *