@cotal-ai/cli 0.99.3 → 0.100.1

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 (241) 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 +51 -8
  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 +17 -11
  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 +97 -19
  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 +8 -1
  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 +28 -11
  104. package/dist/commands/send.js.map +1 -1
  105. package/dist/commands/setup.js +3 -3
  106. package/dist/commands/setup.js.map +1 -1
  107. package/dist/commands/space-delete.d.ts.map +1 -1
  108. package/dist/commands/space-delete.js +31 -6
  109. package/dist/commands/space-delete.js.map +1 -1
  110. package/dist/commands/space-registration.d.ts +3 -1
  111. package/dist/commands/space-registration.d.ts.map +1 -1
  112. package/dist/commands/space-registration.js +85 -16
  113. package/dist/commands/space-registration.js.map +1 -1
  114. package/dist/commands/space.d.ts +1 -1
  115. package/dist/commands/space.js +1 -1
  116. package/dist/commands/space.js.map +1 -1
  117. package/dist/commands/stack-down.d.ts +3 -2
  118. package/dist/commands/stack-down.d.ts.map +1 -1
  119. package/dist/commands/stack-down.js +19 -10
  120. package/dist/commands/stack-down.js.map +1 -1
  121. package/dist/commands/stack-up.d.ts.map +1 -1
  122. package/dist/commands/stack-up.js +68 -20
  123. package/dist/commands/stack-up.js.map +1 -1
  124. package/dist/commands/status.d.ts +5 -1
  125. package/dist/commands/status.d.ts.map +1 -1
  126. package/dist/commands/status.js +134 -46
  127. package/dist/commands/status.js.map +1 -1
  128. package/dist/commands/team-boot-controller.d.ts.map +1 -1
  129. package/dist/commands/team-boot-controller.js +3 -1
  130. package/dist/commands/team-boot-controller.js.map +1 -1
  131. package/dist/commands/team.d.ts.map +1 -1
  132. package/dist/commands/team.js +28 -6
  133. package/dist/commands/team.js.map +1 -1
  134. package/dist/commands/telemetry.d.ts +3 -1
  135. package/dist/commands/telemetry.d.ts.map +1 -1
  136. package/dist/commands/telemetry.js +9 -3
  137. package/dist/commands/telemetry.js.map +1 -1
  138. package/dist/commands/up.d.ts +6 -3
  139. package/dist/commands/up.d.ts.map +1 -1
  140. package/dist/commands/up.js +248 -41
  141. package/dist/commands/up.js.map +1 -1
  142. package/dist/commands/use.d.ts.map +1 -1
  143. package/dist/commands/use.js +4 -1
  144. package/dist/commands/use.js.map +1 -1
  145. package/dist/commands/watch.d.ts.map +1 -1
  146. package/dist/commands/watch.js +11 -5
  147. package/dist/commands/watch.js.map +1 -1
  148. package/dist/console/mesh.d.ts +6 -1
  149. package/dist/console/mesh.d.ts.map +1 -1
  150. package/dist/console/mesh.js +18 -2
  151. package/dist/console/mesh.js.map +1 -1
  152. package/dist/help.d.ts.map +1 -1
  153. package/dist/help.js +14 -6
  154. package/dist/help.js.map +1 -1
  155. package/dist/index.d.ts.map +1 -1
  156. package/dist/index.js +9 -2
  157. package/dist/index.js.map +1 -1
  158. package/dist/lib/completion-install.d.ts.map +1 -1
  159. package/dist/lib/completion-install.js +78 -11
  160. package/dist/lib/completion-install.js.map +1 -1
  161. package/dist/lib/control.d.ts +6 -0
  162. package/dist/lib/control.d.ts.map +1 -1
  163. package/dist/lib/control.js +16 -1
  164. package/dist/lib/control.js.map +1 -1
  165. package/dist/lib/default-persona.js +1 -1
  166. package/dist/lib/default-persona.js.map +1 -1
  167. package/dist/lib/endpoint-errors.d.ts +2 -0
  168. package/dist/lib/endpoint-errors.d.ts.map +1 -1
  169. package/dist/lib/endpoint-errors.js +13 -7
  170. package/dist/lib/endpoint-errors.js.map +1 -1
  171. package/dist/lib/interrupt-notice.d.ts +5 -0
  172. package/dist/lib/interrupt-notice.d.ts.map +1 -0
  173. package/dist/lib/interrupt-notice.js +23 -0
  174. package/dist/lib/interrupt-notice.js.map +1 -0
  175. package/dist/lib/isolated-broker.d.ts +5 -0
  176. package/dist/lib/isolated-broker.d.ts.map +1 -1
  177. package/dist/lib/isolated-broker.js +36 -0
  178. package/dist/lib/isolated-broker.js.map +1 -1
  179. package/dist/lib/legacy-start.d.ts +17 -0
  180. package/dist/lib/legacy-start.d.ts.map +1 -0
  181. package/dist/lib/legacy-start.js +66 -0
  182. package/dist/lib/legacy-start.js.map +1 -0
  183. package/dist/lib/manager-choice.d.ts +21 -0
  184. package/dist/lib/manager-choice.d.ts.map +1 -0
  185. package/dist/lib/manager-choice.js +57 -0
  186. package/dist/lib/manager-choice.js.map +1 -0
  187. package/dist/lib/manifest/resolve.d.ts.map +1 -1
  188. package/dist/lib/manifest/resolve.js +9 -1
  189. package/dist/lib/manifest/resolve.js.map +1 -1
  190. package/dist/lib/missing-flags.d.ts +1 -1
  191. package/dist/lib/missing-flags.d.ts.map +1 -1
  192. package/dist/lib/missing-flags.js +2 -2
  193. package/dist/lib/missing-flags.js.map +1 -1
  194. package/dist/lib/persona-files.d.ts +2 -0
  195. package/dist/lib/persona-files.d.ts.map +1 -1
  196. package/dist/lib/persona-files.js +98 -24
  197. package/dist/lib/persona-files.js.map +1 -1
  198. package/dist/lib/restore.d.ts +27 -1
  199. package/dist/lib/restore.d.ts.map +1 -1
  200. package/dist/lib/restore.js +106 -14
  201. package/dist/lib/restore.js.map +1 -1
  202. package/dist/lib/service-process.d.ts +12 -2
  203. package/dist/lib/service-process.d.ts.map +1 -1
  204. package/dist/lib/service-process.js +25 -2
  205. package/dist/lib/service-process.js.map +1 -1
  206. package/dist/lib/setup-log.js +1 -1
  207. package/dist/lib/setup-log.js.map +1 -1
  208. package/dist/lib/stack-journal.d.ts +22 -1
  209. package/dist/lib/stack-journal.d.ts.map +1 -1
  210. package/dist/lib/stack-journal.js +104 -23
  211. package/dist/lib/stack-journal.js.map +1 -1
  212. package/dist/lib/stdout-owner.d.ts +7 -3
  213. package/dist/lib/stdout-owner.d.ts.map +1 -1
  214. package/dist/lib/stdout-owner.js +17 -4
  215. package/dist/lib/stdout-owner.js.map +1 -1
  216. package/dist/lib/store-dir.d.ts +8 -0
  217. package/dist/lib/store-dir.d.ts.map +1 -0
  218. package/dist/lib/store-dir.js +50 -0
  219. package/dist/lib/store-dir.js.map +1 -0
  220. package/dist/lib/team-additive-attempt.d.ts +1 -1
  221. package/dist/lib/team-fresh.d.ts +11 -1
  222. package/dist/lib/team-fresh.d.ts.map +1 -1
  223. package/dist/lib/team-fresh.js +24 -9
  224. package/dist/lib/team-fresh.js.map +1 -1
  225. package/dist/lib/transient.d.ts +2 -1
  226. package/dist/lib/transient.d.ts.map +1 -1
  227. package/dist/lib/transient.js +9 -3
  228. package/dist/lib/transient.js.map +1 -1
  229. package/dist/render.d.ts +4 -2
  230. package/dist/render.d.ts.map +1 -1
  231. package/dist/render.js +23 -16
  232. package/dist/render.js.map +1 -1
  233. package/dist/ui.d.ts +4 -2
  234. package/dist/ui.d.ts.map +1 -1
  235. package/dist/ui.js +13 -8
  236. package/dist/ui.js.map +1 -1
  237. package/dist/view/mesh-view.d.ts +3 -0
  238. package/dist/view/mesh-view.d.ts.map +1 -1
  239. package/dist/view/mesh-view.js +10 -0
  240. package/dist/view/mesh-view.js.map +1 -1
  241. package/package.json +4 -4
@@ -2,13 +2,13 @@ import { spawn } from "node:child_process";
2
2
  import { createHash, randomUUID } from "node:crypto";
3
3
  import { createConnection, createServer } from "node:net";
4
4
  import { homedir, hostname } from "node:os";
5
- import { mkdirSync, readFileSync, existsSync, openSync, fstatSync, statSync, readSync, closeSync, lstatSync, realpathSync, readdirSync, } from "node:fs";
5
+ import { accessSync, constants, 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)
@@ -158,6 +171,23 @@ export function validateUpArguments(args) {
158
171
  }
159
172
  if (args.values.restore !== undefined)
160
173
  refuseControllerCut(args.values.root !== undefined ? preparedUpRoot(String(args.values.root)) : cotalRoot(), "up --restore");
174
+ if (!(args.values.file && args.values["dry-run"] === true))
175
+ assertUpRootWritable(args.values.root !== undefined ? preparedUpRoot(String(args.values.root)) : cotalRoot());
176
+ }
177
+ /** Every launch route writes under the root's .cotal first, or makes it when it is missing. A folder
178
+ * this account cannot write is refused here, by name, instead of as the raw error of whichever
179
+ * write came first. */
180
+ function assertUpRootWritable(root) {
181
+ const path = existsSync(join(root, ".cotal")) ? join(root, ".cotal") : root;
182
+ try {
183
+ accessSync(path, constants.W_OK | constants.X_OK);
184
+ }
185
+ catch (error) {
186
+ const code = error.code;
187
+ if (code !== "EACCES" && code !== "EPERM" && code !== "EROFS")
188
+ throw error;
189
+ throw new CommandFailure("refused", "PERMISSION_DENIED", `${path} is not writable by this account (${code}); nothing was started or written`, { target: { root, path }, remedy: `make it writable by you, for example with chmod u+w ${path}` });
190
+ }
161
191
  }
162
192
  /** Why `--server` cannot be the address a local broker listens on, or undefined when it can. Both
163
193
  * launch routes need one nats:// or tls:// URL with a host and a TCP port, and without this check
@@ -287,10 +317,49 @@ function assertFreshTeamBootOwnership(root, space, mode, own) {
287
317
  if (bootAttempts.refused.length || summaries.refused.length || unsettled.length)
288
318
  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
319
  }
320
+ /** The guarded whole-stack stop a foreground signal runs, acknowledged by that signal's exit code. A
321
+ * failed or unknown stop is reported with its retained members; nothing is force-killed. */
322
+ function stopForegroundStack(root, signal) {
323
+ return stackDown(root, { yes: true }).catch((error) => {
324
+ 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`);
325
+ }).finally(() => { process.exitCode = signal === "SIGINT" ? 130 : 143; });
326
+ }
290
327
  /** 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) {
328
+ * which runs the same guarded whole-stack stop as bare `down`. `start`, when given, is the startup
329
+ * this terminal already holds: a signal during it lets the start settle, then runs that stop. A
330
+ * failed start still runs the stop, and its failure is thrown once the stop returns. The hold's end
331
+ * sets the exit code: 0 when another command completed the stop or preserve, 130 or 143 after a
332
+ * signal, whatever the start receipt set. */
333
+ export async function holdForegroundStack(root, start) {
334
+ if (start) {
335
+ let requested;
336
+ const request = (signal) => {
337
+ if (requested)
338
+ return;
339
+ requested = signal;
340
+ process.stderr.write("Stop requested; the whole-stack stop runs once the start settles\n");
341
+ };
342
+ const interrupt = () => request("SIGINT"), terminate = () => request("SIGTERM");
343
+ process.on("SIGINT", interrupt);
344
+ process.on("SIGTERM", terminate);
345
+ let failure;
346
+ try {
347
+ await start();
348
+ }
349
+ catch (error) {
350
+ failure = { error };
351
+ }
352
+ finally {
353
+ process.off("SIGINT", interrupt);
354
+ process.off("SIGTERM", terminate);
355
+ }
356
+ if (requested)
357
+ await stopForegroundStack(root, requested);
358
+ if (failure)
359
+ throw failure.error;
360
+ if (requested)
361
+ return;
362
+ }
294
363
  return new Promise((resolveHold) => {
295
364
  // The hold ends on its own when another command completes a whole-stack stop or preserve of this
296
365
  // root: a later operation recorded as completed is that evidence. Any other later operation,
@@ -313,6 +382,7 @@ export function holdForegroundStack(root) {
313
382
  process.off("SIGTERM", terminate);
314
383
  clearInterval(lifetime);
315
384
  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`);
385
+ process.exitCode = 0;
316
386
  resolveHold();
317
387
  }, 1000);
318
388
  const stop = (signal) => {
@@ -322,9 +392,7 @@ export function holdForegroundStack(root) {
322
392
  process.off("SIGINT", interrupt);
323
393
  process.off("SIGTERM", terminate);
324
394
  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(); });
395
+ void stopForegroundStack(root, signal).finally(resolveHold);
328
396
  };
329
397
  const interrupt = () => stop("SIGINT");
330
398
  const terminate = () => stop("SIGTERM");
@@ -392,6 +460,9 @@ async function runUp(args, inheritedLock, onAdopt, freshTeamBoot = false, restor
392
460
  const values = args.values;
393
461
  if (freshTeamBoot && (!values.file || values.restore || values.__restoreAttempt || values.__ordinaryResumeAttempt || values["rotate-sys"] || values["no-manager"]))
394
462
  throw new CommandFailure("refused", "USAGE_INVALID", "fresh team boot accepts one manifest and its selected lifetime, not a restore, rotation or manager-free override");
463
+ // `space create` and `down` refuse a root other local accounts can write, so `up` refuses it too,
464
+ // before anything is written: a stack started there could not be stopped from it.
465
+ protectedLocalDirectory(canonicalRoot(cotalRoot()), "the project root");
395
466
  if (values.restore) {
396
467
  if (values.file || values.channels)
397
468
  throw new Error("--restore cannot be combined with --file/-f or --channels");
@@ -495,6 +566,8 @@ async function runUp(args, inheritedLock, onAdopt, freshTeamBoot = false, restor
495
566
  // Refuse first-enable IdP failures and explicit pin conflicts before even recovery's lock
496
567
  // creates its layout. Existing recovery keeps its own recorded startup and trust checks.
497
568
  const stackSpace = values.space ?? folderSpace();
569
+ if (values.space === undefined)
570
+ assertSelectionNotMoved(root, stackSpace);
498
571
  recordOperationSpace(stackSpace);
499
572
  if (!readMaintenanceJournal(root) && controllerStackApplies(root, stackSpace, values)) {
500
573
  const recordedStack = readStackJournal(root);
@@ -516,7 +589,8 @@ async function runUp(args, inheritedLock, onAdopt, freshTeamBoot = false, restor
516
589
  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
590
  }
518
591
  }
519
- const lock = acquireMaintenanceLock(root);
592
+ // A concurrent whole-stack operation is a known refusal that names its pid, as for `down`.
593
+ const lock = acquireStackOperationLock(root);
520
594
  let pending;
521
595
  let recoveredRestore;
522
596
  // Set only at the moment the lock is passed to a re-entry, which then owns releasing it. Any
@@ -528,12 +602,10 @@ async function runUp(args, inheritedLock, onAdopt, freshTeamBoot = false, restor
528
602
  // Ordinary up NEVER rolls back an in-progress restore: a live attempt's target may still be
529
603
  // written by its isolated broker. Refuse with the exact recovery recourse instead.
530
604
  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\``);
605
+ const assessment = assessRestoreClaim(journal, { unrecordedOwnersDead: attemptProcessesGone(root) });
606
+ if (assessment !== "stale")
607
+ throw heldClaim(root, attempt, journal.claim, "cotal up", assessment);
608
+ 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
609
  }
538
610
  const controllerCut = journal ? cutController(journal.cut) : undefined;
539
611
  if (journal && controllerCut && journal.state !== "cut-intent" && journal.state !== "cut-committed" && journal.state !== "resume-retired") {
@@ -571,6 +643,11 @@ async function runUp(args, inheritedLock, onAdopt, freshTeamBoot = false, restor
571
643
  }
572
644
  }
573
645
  else if (journal?.state === "ready") {
646
+ const source = preservedSourceState(root, journal.source);
647
+ if (source.state === "moved")
648
+ throw movedFolderRefusal(root, journal.space, journal.source.path, source, "run cotal up");
649
+ if (source.state === "missing")
650
+ 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
651
  const resume = readMaintenanceResumeDocument(root, journal.resume);
575
652
  const attemptId = `resume-${randomUUID()}`;
576
653
  const launch = resume.launch;
@@ -704,6 +781,14 @@ async function runUp(args, inheritedLock, onAdopt, freshTeamBoot = false, restor
704
781
  else if (journal?.state === "resume-retired") {
705
782
  consumeRetiredMaintenance(lock);
706
783
  }
784
+ else if (journal?.state === "claimed") {
785
+ // An interrupted backup create holds the cut. Refuse with its holder or its release.
786
+ const attempt = journal.claim.attemptId;
787
+ const assessment = assessMaintenanceClaim(journal.claim, { unrecordedOwnersDead: attemptProcessesGone(root) });
788
+ if (assessment !== "stale")
789
+ throw heldClaim(root, attempt, journal.claim, "cotal up", assessment);
790
+ 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` });
791
+ }
707
792
  else if (journal) {
708
793
  throw new Error(`cotal up is refused while maintenance state is ${journal.state}; follow the recorded recovery`);
709
794
  }
@@ -857,6 +942,9 @@ async function runUp(args, inheritedLock, onAdopt, freshTeamBoot = false, restor
857
942
  persist: false,
858
943
  quiet: true,
859
944
  });
945
+ // The manifest route checks its own effective address, which `--server` only overrides.
946
+ if (!values.file && values.server !== undefined)
947
+ assertTlsIntentServed(values.server, transport, "--server");
860
948
  // CONTROLLER-OWNED STACK. A root whose stack the service controller owns, or a fresh prepared
861
949
  // static-auth, open or user-auth root with nothing legacy retained, starts as exact controller members instead
862
950
  // of the pidfile launcher. The decision is made once here; neither route falls back to the other.
@@ -868,16 +956,21 @@ async function runUp(args, inheritedLock, onAdopt, freshTeamBoot = false, restor
868
956
  const presentation = presentationOf(values);
869
957
  const stackLock = acquireStackOperationLock(meshRoot);
870
958
  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
- }
959
+ // A foreground terminal holds the start as well, so a signal during it stops what it started.
960
+ const start = async () => {
961
+ try {
962
+ if (values.foreground && presentation !== "json")
963
+ stackUpForegroundNotice(presentation, stackSpace);
964
+ 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);
965
+ }
966
+ finally {
967
+ releaseMaintenanceLock(stackLock);
968
+ }
969
+ };
879
970
  if (values.foreground)
880
- await holdForegroundStack(meshRoot);
971
+ await holdForegroundStack(meshRoot, start);
972
+ else
973
+ await start();
881
974
  return;
882
975
  }
883
976
  if (values.json || values.plain)
@@ -902,12 +995,13 @@ async function runUp(args, inheritedLock, onAdopt, freshTeamBoot = false, restor
902
995
  rotateSys: values["rotate-sys"],
903
996
  maxSessions,
904
997
  noManager,
998
+ storeDir: values["store-dir"],
905
999
  });
906
1000
  if (previewRoot)
907
1001
  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
1002
  return;
909
1003
  }
910
- const lock = acquireMaintenanceLock(cotalRoot());
1004
+ const lock = acquireStackOperationLock(cotalRoot());
911
1005
  try {
912
1006
  if (freshTeamBoot) {
913
1007
  if (!values.space)
@@ -931,6 +1025,7 @@ async function runUp(args, inheritedLock, onAdopt, freshTeamBoot = false, restor
931
1025
  rotateSys: values["rotate-sys"],
932
1026
  maxSessions,
933
1027
  noManager,
1028
+ storeDir: values["store-dir"],
934
1029
  });
935
1030
  }
936
1031
  finally {
@@ -969,7 +1064,7 @@ async function runUp(args, inheritedLock, onAdopt, freshTeamBoot = false, restor
969
1064
  // that journals, give it `heldLock` and hand it down from here; do not audit by call-site shape.
970
1065
  // The one caller that does NOT pass it is the prepare-failure path above, where the lock has
971
1066
  // genuinely not been taken yet in this frame and the helper is meant to take its own.
972
- let startupLock = inheritedLock ?? acquireMaintenanceLock(cotalRoot());
1067
+ let startupLock = inheritedLock ?? acquireStackOperationLock(cotalRoot());
973
1068
  onAdopt?.(); // from here the release below owns it, inherited or not
974
1069
  const releaseStartupLock = () => {
975
1070
  if (!startupLock)
@@ -985,7 +1080,24 @@ async function runUp(args, inheritedLock, onAdopt, freshTeamBoot = false, restor
985
1080
  // on a free port, which this root's record keeps; a re-run must start from that URL, or every
986
1081
  // lookup below misses its own mesh and the space claim refuses it (#3889).
987
1082
  const recordedSpace = values.space ?? folderSpace();
988
- const implicitServer = localMeshesForRoot(cotalRoot()).find((m) => m.space === recordedSpace)?.server ?? DEFAULT_SERVER;
1083
+ const registeredServer = localMeshesForRoot(cotalRoot()).find((m) => m.space === recordedSpace)?.server;
1084
+ // A stopped legacy root's `down` dropped the registration that kept its address, so its own files
1085
+ // decide. With no address flag, it starts again at the address its last start rendered, and in
1086
+ // open mode when that start was open and no mode is asked for. After `clean all` only a fresh
1087
+ // team summary remains, and a start that would differ from it refuses, naming its manifest.
1088
+ const implicit = !resumeAttempt && registeredServer === undefined && values.server === undefined && values.host === undefined && !values["user-auth"];
1089
+ const retained = implicit ? retainedLegacyBroker(cotalRoot()) : undefined;
1090
+ if (retained) {
1091
+ if (retained.open)
1092
+ values.open = true;
1093
+ console.log(c.dim(`starting this folder's stopped stack as it last ran: ${retained.server}${values.open ? ", open" : ""}`));
1094
+ }
1095
+ else if (implicit) {
1096
+ const cleaned = cleanedManifestStart(cotalRoot(), recordedSpace, values.open === true);
1097
+ if (cleaned)
1098
+ 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}` });
1099
+ }
1100
+ const implicitServer = registeredServer ?? retained?.server ?? DEFAULT_SERVER;
989
1101
  let server = values.server ?? implicitServer;
990
1102
  const host = values.host ?? "127.0.0.1";
991
1103
  // `--host` is the BIND address; `server` is the URL the readiness probe, the mesh registry, and
@@ -1002,12 +1114,14 @@ async function runUp(args, inheritedLock, onAdopt, freshTeamBoot = false, restor
1002
1114
  // Never runs during a resume attempt, which keeps its own store checks. The reachability probe
1003
1115
  // here is reused as `listenerReachable` further down instead of probing twice.
1004
1116
  let repairProbe;
1117
+ let repairing = false;
1005
1118
  if (!resumeAttempt) {
1006
1119
  const repairSpace = values.space ?? folderSpace();
1007
1120
  const repairRoot = cotalRoot();
1008
1121
  const heldForRepair = loadMeshes().find((m) => m.origin !== "manual" && m.origin !== "catalog" && m.server === server && m.root === repairRoot && m.space === repairSpace);
1009
1122
  if (heldForRepair) {
1010
1123
  repairProbe = await isReachable(server);
1124
+ repairing = !repairProbe;
1011
1125
  if (!repairProbe) {
1012
1126
  if (values["store-dir"] !== undefined) {
1013
1127
  const requestedStoreDir = resolve(values["store-dir"]);
@@ -1287,6 +1401,16 @@ async function runUp(args, inheritedLock, onAdopt, freshTeamBoot = false, restor
1287
1401
  seedPersonaAfterUp(root);
1288
1402
  return;
1289
1403
  }
1404
+ // The broker answering here is the named space's own, started from another folder.
1405
+ const owner = values.space !== undefined ? findMesh(space) : undefined;
1406
+ if (owner && owner.server === server && owner.root !== root) {
1407
+ let controller = false;
1408
+ try {
1409
+ controller = readStackJournal(owner.root)?.journal.space === space;
1410
+ }
1411
+ catch { /* named with the legacy stop */ }
1412
+ 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}` });
1413
+ }
1290
1414
  const who = held ? `mesh "${held.space}" (${held.root})` : "a broker not started here";
1291
1415
  // Reaching here with `--rotate-sys` means something IS answering at the requested address and it
1292
1416
  // is not this root's recorded mesh (that case was refused above). The ordinary response is to pick
@@ -1310,6 +1434,9 @@ async function runUp(args, inheritedLock, onAdopt, freshTeamBoot = false, restor
1310
1434
  process.exit(1);
1311
1435
  }
1312
1436
  }
1437
+ // A repair keeps its own store rules above, and a resume or restore names its store.
1438
+ if (!resumeAttempt && !repairing && values["store-dir"] === undefined)
1439
+ refuseUnnamedLastStore(cotalPath("nats"));
1313
1440
  const restored = resumeAttempt ? pendingRestores.get(resumeAttempt) : undefined;
1314
1441
  const boundListener = restored ? {
1315
1442
  serverName: restored.serverName,
@@ -1604,8 +1731,10 @@ function assertOrdinaryUpAllowed(root, storeDir) {
1604
1731
  throw new Error(`ordinary startup after restore must use the recorded active target store ${maintenance.restore.target.path}, not ${storeDir}`);
1605
1732
  return;
1606
1733
  }
1734
+ // A preserved cut resumes only through bare `up`, which journals the resume attempt. Nothing has
1735
+ // started here, so this is a refusal.
1607
1736
  if (maintenance.state === "ready")
1608
- throw new Error("ordinary resume must begin through the attempt-bound startup path");
1737
+ 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
1738
  throw new Error(`cotal up is refused while maintenance state is ${maintenance.state}; follow the recorded restore recovery`);
1610
1739
  }
1611
1740
  function markPendingResumeDegraded(attemptId, reason, heldLock) {
@@ -2044,6 +2173,7 @@ async function verifySpawnedOrdinaryListener(pending) {
2044
2173
  }
2045
2174
  async function resumeProvenOrdinaryListener(pending, heldLock) {
2046
2175
  await proveOrdinaryResumeListener(pending);
2176
+ await recreateAdoptedMemoryBuckets(pending.root, pending.space, pending.server, pending.mode);
2047
2177
  const svc = await ensureRecoveredUserAuth(pending);
2048
2178
  // Read the recorded exposure BEFORE re-recording: `recordOurMesh` writes the entry whole, so a
2049
2179
  // record built without this field would erase the operator's decision, and the adopted manager
@@ -2091,6 +2221,7 @@ async function ensureRecoveredUserAuth(prepared) {
2091
2221
  }
2092
2222
  async function resumeProvenRestoreListener(prepared, heldLock) {
2093
2223
  await provePreparedRestoreListener(prepared);
2224
+ await recreateAdoptedMemoryBuckets(prepared.root, prepared.space, prepared.server, prepared.mode);
2094
2225
  const svc = await ensureRecoveredUserAuth(prepared);
2095
2226
  // Same ordering constraint as the pending-adopt path above: capture the recorded exposure before
2096
2227
  // `recordOurMesh` rewrites the entry, or a restore silently demotes the mesh to loopback attach.
@@ -2560,6 +2691,7 @@ async function upManifest(file, opts) {
2560
2691
  // Same bind-vs-probe reconciliation as the flag path: a manifest that sets `broker.host` without
2561
2692
  // an explicit `broker.servers` would otherwise bind one address and be probed at another.
2562
2693
  const server = m.broker?.host ? reconcileHostAndServer(m.broker.host, m.broker?.servers, "broker.host", "broker.servers") : (m.broker?.servers ?? DEFAULT_SERVER);
2694
+ assertTlsIntentServed(server, opts.transport, opts.server !== undefined ? "--server" : "the manifest's broker.servers");
2563
2695
  const open = m.broker?.auth === false; // default is auth
2564
2696
  const userAuth = m.broker?.auth === "user" ? { idpUrl: m.broker.idp } : undefined;
2565
2697
  const runtime = m.runtime ?? "pty";
@@ -2587,6 +2719,9 @@ async function upManifest(file, opts) {
2587
2719
  // exists to remove. Before the dry-run print and before anything boots.
2588
2720
  if (opts.rotateSys && open)
2589
2721
  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");
2722
+ // Before the dry-run print and before connector preflight or any write, as the refusals above.
2723
+ if (!opts.storeDir)
2724
+ refuseUnnamedLastStore(cotalPath("nats"));
2590
2725
  if (opts.dryRun) {
2591
2726
  // Dial-host SAN must refuse here too (S6). The real route runs assertServesDialHost after
2592
2727
  // the plan is computed; dry-run used to return before that check and green-lit a launch
@@ -2622,6 +2757,12 @@ async function upManifest(file, opts) {
2622
2757
  if (await isReachable(server)) {
2623
2758
  if (opts.freshTeamBoot)
2624
2759
  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" });
2760
+ // This folder's own mesh for the manifest's space is named as running, as a bare `up` names it,
2761
+ // with the routes that change it instead of the advice for a foreign broker.
2762
+ if (loadMeshes().some((row) => row.server === server && row.root === cotalRoot() && row.space === m.space)) {
2763
+ 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}\``));
2764
+ process.exit(1);
2765
+ }
2625
2766
  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
2767
  process.exit(1);
2627
2768
  }
@@ -2706,7 +2847,7 @@ async function upManifest(file, opts) {
2706
2847
  try {
2707
2848
  // `m.broker?.host`, not the defaulted `host`: same reason as the flag path — only a host the
2708
2849
  // 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 }));
2850
+ ({ 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
2851
  }
2711
2852
  catch (e) {
2712
2853
  if (opts.freshTeamBoot)
@@ -3147,11 +3288,13 @@ function ensureRootForSpace(space) {
3147
3288
  // A prepared space starts only in the root `cotal space create` gave it. Checked before the mkdir
3148
3289
  // below, so a refused start leaves nothing behind.
3149
3290
  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}`, {
3291
+ if (prepared && canonicalRoot(prepared.root) !== canonicalRoot(root)) {
3292
+ const gone = !existsSync(prepared.root);
3293
+ throw new CommandFailure("refused", "TARGET_UNAVAILABLE", `space "${space}" is prepared in ${prepared.root}${gone ? ", which no longer exists" : ""}`, {
3152
3294
  target: { space, root: prepared.root },
3153
- remedy: `start it with \`cotal up\` there, or \`cotal space forget ${space}\` to start it here`,
3295
+ 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
3296
  });
3297
+ }
3155
3298
  // What spaces does this root already host? Prefer auth material; fall back to a live MeshEntry
3156
3299
  // whose root is this directory (open meshes have no auth dir).
3157
3300
  const hosted = listSpaceAccounts(authDir(root));
@@ -3197,6 +3340,21 @@ function folderSpace() {
3197
3340
  }
3198
3341
  return resolveSpace(process.cwd());
3199
3342
  }
3343
+ /** A bare `up` in a folder that names no space starts the default space. When the selected space
3344
+ * is prepared in a folder that no longer exists, as after that folder was moved, the default is not
3345
+ * what was meant, so `up` refuses with the step that prepares the selection here. */
3346
+ function assertSelectionNotMoved(root, space) {
3347
+ if (space !== DEFAULT_SPACE || soleSpaceOf(authDir(root)) !== undefined || preparedSpaceAt(root) || localMeshesForRoot(root).length || readStackJournal(root))
3348
+ return;
3349
+ const current = getCurrent();
3350
+ const prepared = current === undefined || current === space ? undefined : findPreparedSpace(current);
3351
+ if (!prepared || existsSync(prepared.root))
3352
+ return;
3353
+ 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`, {
3354
+ target: { root, space: current, preparedRoot: prepared.root },
3355
+ 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}`,
3356
+ });
3357
+ }
3200
3358
  function realpathSafe(p) {
3201
3359
  try {
3202
3360
  return realpathSync(p);
@@ -3621,19 +3779,44 @@ async function recreateMemoryBuckets(server, space, setup) {
3621
3779
  await nc.drain();
3622
3780
  }
3623
3781
  }
3782
+ /** An adopted listener may have been bound by an `up` that stopped before {@link recreateMemoryBuckets},
3783
+ * so the memory buckets the daemons open can be missing on it. An existing bucket is left as it is. */
3784
+ async function recreateAdoptedMemoryBuckets(root, space, server, mode) {
3785
+ if (mode === "open")
3786
+ return recreateMemoryBuckets(server, space);
3787
+ const auth = await getSpaceAuth(workspaceSecretStore(root), space);
3788
+ if (!auth)
3789
+ throw new Error(`space "${space}" has no trust material under ${authDir(root)}; cannot recreate its memory buckets on the adopted listener`);
3790
+ await recreateMemoryBuckets(server, space, { creds: await mintCreds(auth, newIdentity(), "provisioner") });
3791
+ }
3624
3792
  /** Load the declarative channels-config file to seed the registry. An explicit `--channels`
3625
3793
  * path that's missing is a hard error; the default `.cotal/channels.json` is optional (absent
3626
3794
  * ⇒ nothing to seed). */
3627
3795
  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
- }
3796
+ if (explicit)
3797
+ return readChannelsFile(resolve(explicit));
3798
+ const path = cotalPath("channels.json");
3799
+ if (!existsSync(path))
3633
3800
  return undefined;
3634
- }
3635
3801
  return JSON.parse(readFileSync(path, "utf8"));
3636
3802
  }
3803
+ /** Read and parse an explicit `--channels` file. One that is missing, unreadable or not JSON is a
3804
+ * usage refusal that names its path. */
3805
+ function readChannelsFile(path) {
3806
+ let text;
3807
+ try {
3808
+ text = readFileSync(path, "utf8");
3809
+ }
3810
+ catch {
3811
+ 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" });
3812
+ }
3813
+ try {
3814
+ return JSON.parse(text);
3815
+ }
3816
+ catch (error) {
3817
+ throw new CommandFailure("refused", "USAGE_INVALID", `the channels file ${path} is not valid JSON (${error.message})`, { remedy: "fix the file, or omit --channels" });
3818
+ }
3819
+ }
3637
3820
  /**
3638
3821
  * Turn the `--tls-cert`/`--tls-key` pair into a validated {@link BrokerTransport}, or `plaintext`
3639
3822
  * when neither was given.
@@ -3694,6 +3877,13 @@ opts = {}) {
3694
3877
  writeBrokerPolicy(root, { version: 1, transport: validated });
3695
3878
  return validated;
3696
3879
  }
3880
+ /** A `tls://` broker address is recorded as required TLS, and every later dial through the record
3881
+ * trusts it. Refuse it, before anything starts, when this start would serve plaintext. */
3882
+ function assertTlsIntentServed(server, transport, source) {
3883
+ const tls = server.split(",").some((url) => url.trim().toLowerCase().startsWith("tls://"));
3884
+ if (tls && transport.kind !== "tls-required")
3885
+ 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" });
3886
+ }
3697
3887
  /** Persist a transport after its listener starts; a structured boot leaves stdout to its receipt. */
3698
3888
  function commitTransportPolicy(root, transport, quietBoot = false) {
3699
3889
  if (transport.kind !== "tls-required")
@@ -3819,6 +4009,23 @@ function validateRecorded(transport, dialHost, opts = {}) {
3819
4009
  }
3820
4010
  return transport;
3821
4011
  }
4012
+ /** `down` drops the record that named a custom or restored store, so a later start that names none
4013
+ * would open an empty second store and leave the data where it was. Each real start writes its
4014
+ * `store_dir` into the broker config it renders, and that file outlives `down`: while the store it
4015
+ * names differs and still holds JetStream data, and the default store holds none, refuse and name it. */
4016
+ function refuseUnnamedLastStore(storeDir) {
4017
+ if (existsSync(join(storeDir, "jetstream")))
4018
+ return;
4019
+ for (const conf of [join(authDir(cotalRoot()), "server.conf"), cotalPath("server-open.conf")]) {
4020
+ if (!existsSync(conf))
4021
+ continue;
4022
+ // The core renderer writes the path as a JSON string.
4023
+ const named = /jetstream \{ store_dir: ("(?:[^"\\]|\\.)*")/.exec(readFileSync(conf, "utf8"))?.[1];
4024
+ const last = named === undefined ? undefined : resolve(JSON.parse(named));
4025
+ if (last !== undefined && last !== resolve(storeDir) && existsSync(join(last, "jetstream")))
4026
+ 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` });
4027
+ }
4028
+ }
3822
4029
  /**
3823
4030
  * Render and write the config for an OPEN (no-auth) broker, returning its path.
3824
4031
  *