@cotal-ai/cli 0.172.1 → 0.173.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 (237) hide show
  1. package/dist/command.d.ts.map +1 -1
  2. package/dist/command.js +34 -20
  3. package/dist/command.js.map +1 -1
  4. package/dist/commands/agents.d.ts.map +1 -1
  5. package/dist/commands/agents.js +8 -6
  6. package/dist/commands/agents.js.map +1 -1
  7. package/dist/commands/backup.d.ts.map +1 -1
  8. package/dist/commands/backup.js +15 -10
  9. package/dist/commands/backup.js.map +1 -1
  10. package/dist/commands/channel-members.d.ts.map +1 -1
  11. package/dist/commands/channel-members.js +2 -1
  12. package/dist/commands/channel-members.js.map +1 -1
  13. package/dist/commands/channels.d.ts.map +1 -1
  14. package/dist/commands/channels.js +19 -9
  15. package/dist/commands/channels.js.map +1 -1
  16. package/dist/commands/clean.d.ts.map +1 -1
  17. package/dist/commands/clean.js +2 -3
  18. package/dist/commands/clean.js.map +1 -1
  19. package/dist/commands/doctor.js +5 -2
  20. package/dist/commands/doctor.js.map +1 -1
  21. package/dist/commands/down-preserve.d.ts +74 -0
  22. package/dist/commands/down-preserve.d.ts.map +1 -0
  23. package/dist/commands/down-preserve.js +626 -0
  24. package/dist/commands/down-preserve.js.map +1 -0
  25. package/dist/commands/down.d.ts +2 -61
  26. package/dist/commands/down.d.ts.map +1 -1
  27. package/dist/commands/down.js +26 -617
  28. package/dist/commands/down.js.map +1 -1
  29. package/dist/commands/endpoint-authoring.d.ts.map +1 -1
  30. package/dist/commands/endpoint-authoring.js +16 -4
  31. package/dist/commands/endpoint-authoring.js.map +1 -1
  32. package/dist/commands/history-clear.d.ts.map +1 -1
  33. package/dist/commands/history-clear.js +10 -3
  34. package/dist/commands/history-clear.js.map +1 -1
  35. package/dist/commands/history-limit.js +2 -2
  36. package/dist/commands/history-limit.js.map +1 -1
  37. package/dist/commands/history.d.ts.map +1 -1
  38. package/dist/commands/history.js +49 -19
  39. package/dist/commands/history.js.map +1 -1
  40. package/dist/commands/join.d.ts.map +1 -1
  41. package/dist/commands/join.js +30 -7
  42. package/dist/commands/join.js.map +1 -1
  43. package/dist/commands/manager-service.d.ts.map +1 -1
  44. package/dist/commands/manager-service.js +5 -1
  45. package/dist/commands/manager-service.js.map +1 -1
  46. package/dist/commands/meshes-add.d.ts +4 -1
  47. package/dist/commands/meshes-add.d.ts.map +1 -1
  48. package/dist/commands/meshes-add.js +19 -1
  49. package/dist/commands/meshes-add.js.map +1 -1
  50. package/dist/commands/meshes-wizard.d.ts.map +1 -1
  51. package/dist/commands/meshes-wizard.js +5 -5
  52. package/dist/commands/meshes-wizard.js.map +1 -1
  53. package/dist/commands/meshes.d.ts.map +1 -1
  54. package/dist/commands/meshes.js +4 -3
  55. package/dist/commands/meshes.js.map +1 -1
  56. package/dist/commands/persona-remote.js +2 -2
  57. package/dist/commands/persona-remote.js.map +1 -1
  58. package/dist/commands/persona.d.ts.map +1 -1
  59. package/dist/commands/persona.js +13 -5
  60. package/dist/commands/persona.js.map +1 -1
  61. package/dist/commands/personas.d.ts.map +1 -1
  62. package/dist/commands/personas.js +4 -1
  63. package/dist/commands/personas.js.map +1 -1
  64. package/dist/commands/reset-space-apply.js +2 -2
  65. package/dist/commands/reset-space-apply.js.map +1 -1
  66. package/dist/commands/reset-store-apply.d.ts +2 -2
  67. package/dist/commands/reset-store-apply.d.ts.map +1 -1
  68. package/dist/commands/reset-store-apply.js +10 -7
  69. package/dist/commands/reset-store-apply.js.map +1 -1
  70. package/dist/commands/reset.js +2 -2
  71. package/dist/commands/reset.js.map +1 -1
  72. package/dist/commands/send.d.ts.map +1 -1
  73. package/dist/commands/send.js +21 -9
  74. package/dist/commands/send.js.map +1 -1
  75. package/dist/commands/service-actions.d.ts.map +1 -1
  76. package/dist/commands/service-actions.js +15 -4
  77. package/dist/commands/service-actions.js.map +1 -1
  78. package/dist/commands/service-registry.d.ts.map +1 -1
  79. package/dist/commands/service-registry.js +16 -5
  80. package/dist/commands/service-registry.js.map +1 -1
  81. package/dist/commands/space-delete.d.ts.map +1 -1
  82. package/dist/commands/space-delete.js +46 -31
  83. package/dist/commands/space-delete.js.map +1 -1
  84. package/dist/commands/space-registration.d.ts +4 -3
  85. package/dist/commands/space-registration.d.ts.map +1 -1
  86. package/dist/commands/space-registration.js +65 -45
  87. package/dist/commands/space-registration.js.map +1 -1
  88. package/dist/commands/space.d.ts.map +1 -1
  89. package/dist/commands/space.js +18 -6
  90. package/dist/commands/space.js.map +1 -1
  91. package/dist/commands/spawn-flags.d.ts +205 -0
  92. package/dist/commands/spawn-flags.d.ts.map +1 -0
  93. package/dist/commands/spawn-flags.js +34 -0
  94. package/dist/commands/spawn-flags.js.map +1 -0
  95. package/dist/commands/spawn-foreground.d.ts +74 -0
  96. package/dist/commands/spawn-foreground.d.ts.map +1 -0
  97. package/dist/commands/spawn-foreground.js +355 -0
  98. package/dist/commands/spawn-foreground.js.map +1 -0
  99. package/dist/commands/spawn-managed-launch.d.ts +43 -0
  100. package/dist/commands/spawn-managed-launch.d.ts.map +1 -0
  101. package/dist/commands/spawn-managed-launch.js +631 -0
  102. package/dist/commands/spawn-managed-launch.js.map +1 -0
  103. package/dist/commands/spawn-preview.d.ts.map +1 -1
  104. package/dist/commands/spawn-preview.js +10 -7
  105. package/dist/commands/spawn-preview.js.map +1 -1
  106. package/dist/commands/spawn.d.ts +6 -220
  107. package/dist/commands/spawn.d.ts.map +1 -1
  108. package/dist/commands/spawn.js +21 -1009
  109. package/dist/commands/spawn.js.map +1 -1
  110. package/dist/commands/stack-down.d.ts.map +1 -1
  111. package/dist/commands/stack-down.js +7 -4
  112. package/dist/commands/stack-down.js.map +1 -1
  113. package/dist/commands/stack-up.d.ts +5 -1
  114. package/dist/commands/stack-up.d.ts.map +1 -1
  115. package/dist/commands/stack-up.js +46 -15
  116. package/dist/commands/stack-up.js.map +1 -1
  117. package/dist/commands/status-delivery.d.ts +9 -0
  118. package/dist/commands/status-delivery.d.ts.map +1 -0
  119. package/dist/commands/status-delivery.js +19 -0
  120. package/dist/commands/status-delivery.js.map +1 -0
  121. package/dist/commands/status-legacy.d.ts +7 -0
  122. package/dist/commands/status-legacy.d.ts.map +1 -0
  123. package/dist/commands/status-legacy.js +35 -0
  124. package/dist/commands/status-legacy.js.map +1 -0
  125. package/dist/commands/status-stop-impact.d.ts +3 -0
  126. package/dist/commands/status-stop-impact.d.ts.map +1 -0
  127. package/dist/commands/status-stop-impact.js +34 -0
  128. package/dist/commands/status-stop-impact.js.map +1 -0
  129. package/dist/commands/status.d.ts.map +1 -1
  130. package/dist/commands/status.js +48 -105
  131. package/dist/commands/status.js.map +1 -1
  132. package/dist/commands/team-agent-apply.js +11 -11
  133. package/dist/commands/team-agent-apply.js.map +1 -1
  134. package/dist/commands/team-boot-controller.d.ts.map +1 -1
  135. package/dist/commands/team-boot-controller.js +21 -4
  136. package/dist/commands/team-boot-controller.js.map +1 -1
  137. package/dist/commands/team-deploy-apply.js +2 -2
  138. package/dist/commands/team-deploy-apply.js.map +1 -1
  139. package/dist/commands/team.d.ts.map +1 -1
  140. package/dist/commands/team.js +37 -42
  141. package/dist/commands/team.js.map +1 -1
  142. package/dist/commands/telemetry.d.ts +1 -1
  143. package/dist/commands/telemetry.d.ts.map +1 -1
  144. package/dist/commands/telemetry.js +17 -7
  145. package/dist/commands/telemetry.js.map +1 -1
  146. package/dist/commands/up-target.d.ts +7 -0
  147. package/dist/commands/up-target.d.ts.map +1 -0
  148. package/dist/commands/up-target.js +42 -0
  149. package/dist/commands/up-target.js.map +1 -0
  150. package/dist/commands/up.d.ts +5 -10
  151. package/dist/commands/up.d.ts.map +1 -1
  152. package/dist/commands/up.js +55 -156
  153. package/dist/commands/up.js.map +1 -1
  154. package/dist/commands/update-caches.d.ts +4 -0
  155. package/dist/commands/update-caches.d.ts.map +1 -0
  156. package/dist/commands/update-caches.js +82 -0
  157. package/dist/commands/update-caches.js.map +1 -0
  158. package/dist/commands/update.d.ts.map +1 -1
  159. package/dist/commands/update.js +35 -121
  160. package/dist/commands/update.js.map +1 -1
  161. package/dist/commands/watch.d.ts.map +1 -1
  162. package/dist/commands/watch.js +5 -2
  163. package/dist/commands/watch.js.map +1 -1
  164. package/dist/commands/whoami.d.ts.map +1 -1
  165. package/dist/commands/whoami.js +3 -2
  166. package/dist/commands/whoami.js.map +1 -1
  167. package/dist/help.d.ts +1 -1
  168. package/dist/help.d.ts.map +1 -1
  169. package/dist/help.js +5 -2
  170. package/dist/help.js.map +1 -1
  171. package/dist/index.d.ts.map +1 -1
  172. package/dist/index.js +4 -2
  173. package/dist/index.js.map +1 -1
  174. package/dist/lib/broker-log.d.ts +8 -0
  175. package/dist/lib/broker-log.d.ts.map +1 -0
  176. package/dist/lib/broker-log.js +27 -0
  177. package/dist/lib/broker-log.js.map +1 -0
  178. package/dist/lib/choose-target.d.ts.map +1 -1
  179. package/dist/lib/choose-target.js +12 -9
  180. package/dist/lib/choose-target.js.map +1 -1
  181. package/dist/lib/credential-authority.d.ts.map +1 -1
  182. package/dist/lib/credential-authority.js +22 -5
  183. package/dist/lib/credential-authority.js.map +1 -1
  184. package/dist/lib/endpoint-errors.d.ts.map +1 -1
  185. package/dist/lib/endpoint-errors.js +9 -2
  186. package/dist/lib/endpoint-errors.js.map +1 -1
  187. package/dist/lib/persona-files.d.ts.map +1 -1
  188. package/dist/lib/persona-files.js +2 -3
  189. package/dist/lib/persona-files.js.map +1 -1
  190. package/dist/lib/restore.d.ts +2 -1
  191. package/dist/lib/restore.d.ts.map +1 -1
  192. package/dist/lib/restore.js +4 -3
  193. package/dist/lib/restore.js.map +1 -1
  194. package/dist/lib/service-preset-target.d.ts.map +1 -1
  195. package/dist/lib/service-preset-target.js +6 -2
  196. package/dist/lib/service-preset-target.js.map +1 -1
  197. package/dist/lib/service-presets.d.ts +2 -0
  198. package/dist/lib/service-presets.d.ts.map +1 -1
  199. package/dist/lib/service-presets.js +19 -2
  200. package/dist/lib/service-presets.js.map +1 -1
  201. package/dist/lib/spawn-defaults.d.ts +7 -0
  202. package/dist/lib/spawn-defaults.d.ts.map +1 -1
  203. package/dist/lib/spawn-defaults.js +16 -0
  204. package/dist/lib/spawn-defaults.js.map +1 -1
  205. package/dist/lib/stack-journal.d.ts +4 -4
  206. package/dist/lib/stack-journal.d.ts.map +1 -1
  207. package/dist/lib/stack-journal.js +16 -6
  208. package/dist/lib/stack-journal.js.map +1 -1
  209. package/dist/lib/store-dir.d.ts +3 -1
  210. package/dist/lib/store-dir.d.ts.map +1 -1
  211. package/dist/lib/store-dir.js +20 -4
  212. package/dist/lib/store-dir.js.map +1 -1
  213. package/dist/lib/team-deploy-inspection.d.ts +2 -1
  214. package/dist/lib/team-deploy-inspection.d.ts.map +1 -1
  215. package/dist/lib/team-deploy-inspection.js +6 -1
  216. package/dist/lib/team-deploy-inspection.js.map +1 -1
  217. package/dist/lib/up-broker-address.d.ts +7 -0
  218. package/dist/lib/up-broker-address.d.ts.map +1 -0
  219. package/dist/lib/up-broker-address.js +76 -0
  220. package/dist/lib/up-broker-address.js.map +1 -0
  221. package/dist/lib/up-report.d.ts +2 -0
  222. package/dist/lib/up-report.d.ts.map +1 -1
  223. package/dist/lib/up-report.js +8 -1
  224. package/dist/lib/up-report.js.map +1 -1
  225. package/dist/lib/update-connector-config.d.ts +6 -0
  226. package/dist/lib/update-connector-config.d.ts.map +1 -0
  227. package/dist/lib/update-connector-config.js +44 -0
  228. package/dist/lib/update-connector-config.js.map +1 -0
  229. package/dist/seed/launch.d.ts +1 -1
  230. package/dist/seed/launch.d.ts.map +1 -1
  231. package/dist/seed/launch.js +3 -3
  232. package/dist/seed/launch.js.map +1 -1
  233. package/dist/seed/reconcile.d.ts +1 -1
  234. package/dist/seed/reconcile.d.ts.map +1 -1
  235. package/dist/seed/reconcile.js +28 -11
  236. package/dist/seed/reconcile.js.map +1 -1
  237. package/package.json +4 -4
@@ -1,20 +1,18 @@
1
- import { existsSync, lstatSync, readdirSync, rmSync, statSync } from "node:fs";
1
+ import { existsSync, lstatSync, readdirSync, rmSync } from "node:fs";
2
2
  import { displayCmd } from "../lib/self-exec.js";
3
- import { drainAndClose } from "@cotal-ai/core";
4
3
  import { homedir } from "node:os";
5
- import { basename, join, relative, resolve as resolvePath } from "node:path";
4
+ import { basename, join, relative } from "node:path";
6
5
  import {} from "@cotal-ai/core";
7
- import { CommandFailure, codeSpan, ConfirmationRequired, isCommandFailure, localRecordName, oneLine, presentationOf, renderReport, abortMaintenanceCut, acquireMaintenanceLock, assertSingleSpaceBroker, authDir, beginMaintenanceCut, clearPreservationCommitIntent, clearPreservationPrepareIntent, completeMaintenanceCut, loadMeshes, maintenanceLockHolder, meshesForRoot, localProcessPath, localProcessPathCandidates, canonicalRoot, brokerAddressForDisplay, findMesh, findPreparedSpace, getCurrent, localProcessOwnerStatus, legacyStackElsewhere, legacyStackOtherHome, stackHomeRemedy, localMeshesForRoot, preparedSpaceAt, retainedLegacyBroker, retainedOpenSpace, soleSpaceOf, writeResult, readMaintenanceJournal, readMaintenanceLockHolder, readContainedRecord, readMaintenanceResumeDocument, readPreservationCommitIntent, readPreservationPrepareIntent, readStoreIdentity, recordPreservationManagerCommit, keepsRegistration, recordMesh, releaseMaintenanceLock, removeMeshesByRoot, sameStoreIdentity, writePreservationCommitIntent, writePreservationPrepareIntent, DELIVERY_PIDFILE, MANAGER_DELIVERY_AWARE_MARKER, MANAGER_PIDFILE, AUTH_PIDFILE, NATS_PIDFILE, WEB_PIDFILE, MAINTENANCE_RESUME_DOCUMENT_VERSION, writeMaintenanceResumeDocument, loadSeatWriterGeneration, materializeFromManifest, seatCheckpointDir, restoreLeftOut, resolveControlTarget, } from "@cotal-ai/workspace";
8
- import { jetstreamManager } from "@nats-io/jetstream";
9
- import { DEV_OWNER, dialerFor, isReachable, realDirNoSymlink, LEASE_TTL_MS, MANAGER_LEASE_KEY, MANAGER_LEASE_TTL_MS, deliveryBucket, managerBucket, presenceBucket, isPresenceRow, parsePrincipalKey, principalKey, standaloneConnectOpts, } from "@cotal-ai/core";
6
+ import { CommandFailure, codeSpan, ConfirmationRequired, isCommandFailure, localRecordName, oneLine, presentationOf, renderReport, assertSingleSpaceBroker, authDir, loadMeshes, maintenanceLockHolder, meshesForRoot, localProcessPath, localProcessPathCandidates, canonicalRoot, brokerAddressForDisplay, findMesh, findPreparedSpace, getCurrent, localProcessOwnerStatus, legacyStackElsewhere, legacyStackOtherHome, stackHomeRemedy, localMeshesForRoot, preparedSpaceAt, retainedLegacyBroker, retainedOpenSpace, soleSpaceOf, writeResult, readMaintenanceJournal, readMaintenanceLockHolder, readContainedRecord, keepsRegistration, recordMesh, removeMeshesByRoot, DELIVERY_PIDFILE, MANAGER_DELIVERY_AWARE_MARKER, MANAGER_PIDFILE, AUTH_PIDFILE, NATS_PIDFILE, WEB_PIDFILE, } from "@cotal-ai/workspace";
7
+ import { isReachable, realDirNoSymlink, } from "@cotal-ai/core";
10
8
  import { localProcessSurface } from "../ext-loader.js";
11
9
  import { c, stderrLine } from "../ui.js";
12
10
  import { cotalRoot, linkedCotalRefusal } from "../lib/paths.js";
13
- import { parsePid, probeLiveness, readPidfile, verifyIdentityPin } from "@cotal-ai/workspace";
11
+ import { verifyIdentityPin } from "@cotal-ai/workspace";
14
12
  import { resolveRuntimeSpace } from "../lib/status.js";
15
13
  import { interruptedStartBroker } from "../lib/legacy-start.js";
16
14
  import { downManifest } from "./down-manifest.js";
17
- import { directKvValue, refuseLiveUnrecordedDaemons } from "./down-live-lease.js";
15
+ import { refuseLiveUnrecordedDaemons } from "./down-live-lease.js";
18
16
  import { listLedgerFiles } from "../lib/manifest/ledger.js";
19
17
  import { loadManifest } from "../lib/manifest/index.js";
20
18
  import { freshTeamAttemptSettled, listFreshTeamAttempts, listFreshTeamSummaries } from "../lib/team-fresh.js";
@@ -24,28 +22,21 @@ import { service, serviceComplete, validateServiceArguments } from "./service-re
24
22
  import { stopNamedServiceSet } from "./service-set-stop.js";
25
23
  import { readLocalServiceCensus } from "../lib/service-census.js";
26
24
  import { assertNoLiveServices, bareDownServicesView, liveServicesRefusal, planBareDownServices } from "./down-services.js";
27
- import { connectOrExit, userViewAuthOrExit } from "../lib/connect.js";
28
- import { assertEndpointUnreachable, waitForEndpointUnreachable } from "../lib/endpoint-cut.js";
29
- import { captureSeatCheckpoint } from "../lib/seat-capture.js";
25
+ import { assertEndpointUnreachable } from "../lib/endpoint-cut.js";
30
26
  import { processRecorded, stopInFlight, stopLocalProcess, UnattributableRecord, unattributableRecordSteps } from "../lib/local-process-stop.js";
31
27
  import { stopManager } from "../lib/manager-proc.js";
32
- import { ensureDelivery, removeDeliveryCredentials, stopDelivery } from "../lib/delivery-proc.js";
28
+ import { removeDeliveryCredentials, stopDelivery } from "../lib/delivery-proc.js";
33
29
  import { controllerStackRecorded, deliveryLeaseAfterStop, nothingRunning, sameDown, stackDown, stackRootElsewhere, validateStackDownArguments } from "./stack-down.js";
34
30
  import { noticeBetweenSteps } from "../lib/interrupt-notice.js";
35
31
  import { goneRootDown, goneRootStackDown, validateGoneRootDownArguments } from "./stack-gone.js";
36
32
  import { readStackJournal, recordedProcessLine, recordedProcessesUnder } from "../lib/stack-journal.js";
37
- import { restoreNextStep } from "../lib/restore.js";
38
33
  import { ownStdoutErrors } from "../lib/stdout-owner.js";
39
- import { askManager } from "@cotal-ai/workspace/control";
40
- import { cliControl } from "../lib/control.js";
41
34
  import { canPrompt } from "./meshes-wizard.js";
42
35
  import * as prompts from "../lib/prompts.js";
43
36
  import { yesRequired } from "../lib/confirmation-required.js";
44
37
  import { shellWord } from "../lib/endpoint-errors.js";
45
- /** How a live unmanaged endpoint is named in the preserve refusal. A missing or whitespace-only name is the id. */
46
- export function unmanagedEndpointLabel(name, id) {
47
- return name.trim() ? `${name} (${id})` : id;
48
- }
38
+ import { sleep, processAlive, assertSessionStores, preserveStateDown, pidfileState } from "./down-preserve.js";
39
+ export { unmanagedEndpointLabel, processAlive, mayBeRunning, retainedPrincipalKeys, assertSeatsCheckpointable, captureSeatCheckpoints, assertControlPlaneQuiesced, readPresenceWithoutConsumer, pidfileState } from "./down-preserve.js";
49
40
  /** Complete selective component names without importing installed packages. */
50
41
  export function downComplete(argv) {
51
42
  if (argv.some((word) => word === "-f" || word === "--file" || word === "--run"))
@@ -122,7 +113,7 @@ export function validateDownArguments(args) {
122
113
  return;
123
114
  // A folder holding another folder's registered space answers with a refusal, not with the lines a
124
115
  // bare stop prints, so structured output carries it rather than refusing the flag.
125
- if ((args.values.json !== undefined || args.values.plain !== undefined) && !(bareStop(args.values) && (stoppedLegacyStack() || readMaintenanceJournal(cotalRoot())?.state === "ready" || recordsElsewhere(canonicalRoot(cotalRoot()), "stop")))) {
116
+ if ((args.values.json !== undefined || args.values.plain !== undefined) && !(stoppedLegacyStack(args.values) || bareStop(args.values) && (readMaintenanceJournal(cotalRoot())?.state === "ready" || recordsElsewhere(canonicalRoot(cotalRoot()), "stop")))) {
126
117
  // A missing stop target keeps its diagnosis in every presentation mode.
127
118
  if (bareStop(args.values)) {
128
119
  const absent = noOwnedStack(canonicalRoot(cotalRoot()));
@@ -304,7 +295,10 @@ const pidRecordsUnder = (root) => readdirSync(join(root, ".cotal")).some((name)
304
295
  * is missing, so bare down refuses rather than guess. `started` says whether a start rendered that
305
296
  * broker configuration. `nothingRunning` reads every other record a local-process descriptor names
306
297
  * under the root, for any space, before it answers. */
307
- function stoppedLegacyStack() {
298
+ function stoppedLegacyStack(values) {
299
+ const { space: requested, ...flags } = values;
300
+ if (!bareStop(flags) || (requested !== undefined && values["with-agents"] !== undefined))
301
+ return undefined;
308
302
  const root = canonicalRoot(cotalRoot());
309
303
  if (root === canonicalRoot(homedir()) || !realDirNoSymlink(root, ".cotal") || pidRecordsUnder(root))
310
304
  return undefined;
@@ -330,6 +324,12 @@ function stoppedLegacyStack() {
330
324
  if (!prepared && !started)
331
325
  return undefined;
332
326
  space ??= prepared?.space;
327
+ // An explicit name only qualifies a never-started prepared root; it cannot select a legacy stop.
328
+ if (requested !== undefined) {
329
+ if (typeof requested !== "string" || started || kept || prepared?.space !== requested || space !== requested)
330
+ return undefined;
331
+ refuseSpaceElsewhere(root, requested, values["dry-run"] === true);
332
+ }
333
333
  if (space !== undefined && planBareDownServices(space).some((row) => row.action !== "already-stopped"))
334
334
  return undefined;
335
335
  const retired = kept?.space === space && kept?.stoppedByDown === true && kept.stoppedWithAgents === true;
@@ -610,11 +610,12 @@ async function downCommand(args) {
610
610
  throw new CommandFailure("refused", "TARGET_UNAVAILABLE", "this folder's running stack belongs to another Cotal home; nothing was stopped", { target: { root: cotalRoot(), home: ownerHome }, remedy: stackHomeRemedy(ownerHome) });
611
611
  const values = args.values;
612
612
  // A legacy root whose stack is already stopped: a bare down and its preview stop nothing.
613
- if (bareStop(args.values)) {
613
+ const bare = bareStop(args.values);
614
+ if (bare || stoppedLegacyStack(args.values)) {
614
615
  const root = canonicalRoot(cotalRoot());
615
- await awaitForegroundStartup(root, values["dry-run"] === true);
616
+ await awaitForegroundStartup(root, !bare || values["dry-run"] === true);
616
617
  const maintenance = readMaintenanceJournal(root);
617
- if (maintenance?.state === "ready") {
618
+ if (bare && maintenance?.state === "ready") {
618
619
  const space = maintenance.space, server = maintenance.cut.launch.server;
619
620
  const target = { root, space, server, state: maintenance.state };
620
621
  const blocked = (why) => new CommandFailure("refused", "LIFECYCLE_BLOCKED", `this stack's preserved cut is ready, but ${why}; nothing was stopped`, { target, remedy: "run `cotal status` to inspect the stack and its maintenance state" });
@@ -644,7 +645,7 @@ async function downCommand(args) {
644
645
  { title: "Next", blocks: [{ kind: "commands", items: [{ command: "cotal status", description: "See the next maintenance step" }] }] },
645
646
  ] }));
646
647
  }
647
- const stopped = maintenance && maintenance.state !== "active" ? undefined : stoppedLegacyStack();
648
+ const stopped = maintenance && maintenance.state !== "active" ? undefined : stoppedLegacyStack(args.values);
648
649
  // A root that never started a stack never ran a manager, so it has no agents to stop.
649
650
  if (stopped) {
650
651
  const { started, retired, ...target } = stopped;
@@ -870,7 +871,6 @@ function legacyStopInterruptNotice(members, context, stopped, cut, cleaned) {
870
871
  return `${head} Run \`cotal down --yes\` to finish the stop.`;
871
872
  return cleaned ? `${head} Run \`cotal up\` to start it again.` : `${head} Run \`cotal down --yes\` to finish its cleanup.`;
872
873
  }
873
- const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
874
874
  /** Registered brokers for this root that answer and have no nats pidfile. Never a kill list. */
875
875
  async function liveUnownedBrokers(context) {
876
876
  const nats = localProcessSurface().find((component) => component.name === "nats");
@@ -884,573 +884,6 @@ async function liveUnownedBrokers(context) {
884
884
  }
885
885
  return live;
886
886
  }
887
- /** Whether a component's pidfile names a process the `@cotal-ai/workspace` pid-attribution contract
888
- * (`parsePid` + `probeLiveness`) reports alive. */
889
- export function processAlive(component, context) {
890
- return pidfileState(localProcessPath(component.pidFile, context)).liveness === "alive";
891
- }
892
- /** Whether a component MIGHT still be running. It fails CLOSED on uncertainty. A component with NO
893
- * pidfile, an EMPTY husk, or a valid pid PROVEN dead (ESRCH) is not running. ANY other state - an
894
- * unparsable/unattributable record, or a valid pid that is alive or whose liveness cannot be
895
- * confirmed (`unknown`) - MIGHT be running. `down --preserve-state` asks it to fence an uncertain
896
- * delivery daemon, to treat an uncertain manager as alive, and to refuse to call a cut complete.
897
- * `processAlive` collapses unparsable and `unknown` to "not alive", which is fine for "is it worth
898
- * stopping" but WRONG for those questions: it would count a live auth signer behind a torn pidfile
899
- * as stopped. Only an ESRCH-confirmed death (or no record) clears a component. */
900
- export function mayBeRunning(component, context) {
901
- return pidfileState(localProcessPath(component.pidFile, context)).liveness !== "dead";
902
- }
903
- /** The principal keys of every retained agent in a preservation inventory — the dot-form ids that
904
- * appear in the presence roster, so a caller can tell which retained agents are still live. */
905
- export function retainedPrincipalKeys(inventory) {
906
- const agents = (inventory.agents ?? []);
907
- return new Set(agents.map((agent) => {
908
- if (agent.identity?.mode === "user" && agent.identity.owner && agent.identity.actor)
909
- return principalKey(agent.identity.owner, agent.identity.actor).key;
910
- if (agent.identity?.id)
911
- return principalKey(DEV_OWNER, agent.identity.id).key;
912
- return undefined;
913
- }).filter((id) => Boolean(id)));
914
- }
915
- /**
916
- * The operator's `--session-store` paths, resolved and proven to be directories.
917
- *
918
- * There is no default and nothing is inferred from a connector name: this repository does not know
919
- * where a harness keeps its transcript, and a guess recorded as a fact would produce a checkpoint
920
- * promising `exact` over bytes nobody chose. A path that does not exist or is not a directory is
921
- * refused HERE, before a single process is stopped, because a cut that discovers it after the stack
922
- * is down costs the operator the whole cut.
923
- */
924
- function assertSessionStores(paths) {
925
- return paths.map((path) => {
926
- const resolved = resolvePath(path);
927
- let stat;
928
- try {
929
- stat = statSync(resolved);
930
- }
931
- catch (error) {
932
- throw new CommandFailure("refused", "USAGE_INVALID", `--session-store ${resolved} cannot be read (${error.code ?? error.message}); name the harness transcript store directory for this host`);
933
- }
934
- if (!stat.isDirectory())
935
- throw new CommandFailure("refused", "USAGE_INVALID", `--session-store ${resolved} is not a directory; name the harness transcript store directory for this host`);
936
- return resolved;
937
- });
938
- }
939
- /** Start the delivery daemon a refused cut stopped as its Plane 3 fence. Resolves to nothing when
940
- * the daemon is running again, and to the reason when it is not, so the refusal can say so. */
941
- async function restartFencedDelivery(space, server, tls) {
942
- try {
943
- const ensured = await ensureDelivery({ space, server, tls });
944
- if (!ensured.running)
945
- return "no delivery daemon is running after the attempt";
946
- console.error(c.dim(`• delivery daemon started again after the refused cut${ensured.pid !== undefined ? ` (pid ${ensured.pid})` : ""}`));
947
- return undefined;
948
- }
949
- catch (e) {
950
- return e.message;
951
- }
952
- }
953
- async function preserveStateDown(storeOverride, sessionStores = []) {
954
- const root = cotalRoot();
955
- const matching = loadMeshes().filter((mesh) => mesh.root === root);
956
- if (matching.length !== 1)
957
- throw new CommandFailure("refused", matching.length ? "TARGET_AMBIGUOUS" : "TARGET_NOT_FOUND", `down --preserve-state requires exactly one recorded mesh for this root; found ${matching.length}, and nothing was stopped`, { target: { root, spaces: matching.map((mesh) => mesh.space) } });
958
- const mesh = matching[0];
959
- // The broker runs on the store its record names, such as a restore's --store-dir target, so that
960
- // is the store to cut. A record from before the field names none and keeps the default.
961
- if (storeOverride !== undefined && mesh.storeDir !== undefined && resolvePath(storeOverride) !== mesh.storeDir)
962
- throw new CommandFailure("refused", "CONFLICT", `the broker for "${mesh.space}" runs on the store ${mesh.storeDir}, not ${resolvePath(storeOverride)}; nothing was stopped`, { target: { root, space: mesh.space, storeDir: mesh.storeDir }, remedy: `omit --store-dir, or pass --store-dir ${mesh.storeDir}` });
963
- const storeDir = storeOverride ? resolveStore(storeOverride) : mesh.storeDir ?? join(root, ".cotal", "nats");
964
- // The store cap the broker was started with travels with the store, so the resume re-renders it.
965
- const cap = mesh.maxFileStore !== undefined ? { maxFileStore: mesh.maxFileStore } : {};
966
- const lock = acquireMaintenanceLock(root);
967
- try {
968
- const additiveAttempts = listAdditiveTeamAttempts(root);
969
- if (retainedAdditiveTeamAttempts(additiveAttempts).length || additiveAttempts.refused.length)
970
- throw new CommandFailure("refused", "LIFECYCLE_BLOCKED", "an additive attempt or returned additive deployment remains; preserve-state down did not fold its resources into the retained stack", { target: { root, space: mesh.space, deploymentIds: retainedAdditiveTeamAttempts(additiveAttempts).map((attempt) => attempt.deploymentId), unreadable: additiveAttempts.refused.map(({ path }) => path) } });
971
- const all = localProcessSurface();
972
- const context = { root, space: mesh.space };
973
- const existing = readMaintenanceJournal(root);
974
- // A completed restore keeps its journal, and a new cut begins only after that journal is retired.
975
- if (existing && "restore" in existing && existing.state === "active")
976
- throw new CommandFailure("refused", "LIFECYCLE_BLOCKED", "a completed restore still holds this root's maintenance journal; a new preserve begins only after it is retired, so nothing was stopped", { target: { root, space: mesh.space, attemptId: existing.restore.attemptId }, remedy: restoreNextStep(existing.state, existing.restore.attemptId, restoreLeftOut(existing)) });
977
- if (existing && existing.state !== "cut-intent" && existing.state !== "cut-committed" && existing.state !== "ready")
978
- throw new Error(`cannot preserve while maintenance state is ${existing.state}`);
979
- if (existing && (existing.space !== mesh.space || existing.mode !== mesh.mode ||
980
- !sameStoreIdentity(existing.source, readStoreIdentity(storeDir)) || existing.cut.launch.server !== mesh.server))
981
- throw new Error(`preservation retry ${existing.cut.attemptId} does not match the current mesh launch`);
982
- if (existing?.state === "ready") {
983
- await waitForEndpointUnreachable(mesh.server);
984
- console.log(c.dim(`state for "${mesh.space}" is already preserved and offline`));
985
- return;
986
- }
987
- // A saved service depends on the broker, so the cut does not stop the broker under one. It
988
- // refuses and stops nothing, as bare down does.
989
- assertNoLiveServices(mesh.space, "down --preserve-state");
990
- let attemptId;
991
- let resume;
992
- // Set when recovery force-commits a cut whose manager died AFTER stopping children (commit-intent
993
- // present): the shared commit block below is then skipped — the cut is already committed.
994
- let managerCommitJournaled = false;
995
- if (existing?.state === "cut-intent" || existing?.state === "cut-committed") {
996
- attemptId = existing.cut.attemptId;
997
- resume = existing.resume;
998
- if (existing.state === "cut-intent") {
999
- // A cut-intent retry must not depend on volatile manager memory: re-prepare the SAME
1000
- // attempt (idempotent on the fenced manager, a fresh fence on a restarted one) and prove
1001
- // the re-prepared inventory is byte-identical to the journaled resume document.
1002
- const manager = all.find((component) => component.name === "manager");
1003
- if (!manager)
1004
- throw new Error("local process registry has no manager descriptor");
1005
- if (!mayBeRunning(manager, context)) { // fail-closed: an uncertain manager is treated as alive, not dead
1006
- const committing = readPreservationCommitIntent(root);
1007
- if (!committing || committing.attemptId !== attemptId) {
1008
- // No commit intent recorded: the child-stopping RPC was never invoked, so nothing was
1009
- // stopped with suppression. Safe to abandon instead of wedging.
1010
- abortMaintenanceCut(lock);
1011
- clearPreservationPrepareIntent(lock);
1012
- throw new Error(`preservation attempt ${attemptId} lost its manager before commit; the cut intent was aborted - heal the stack with \`cotal up\` if needed, then rerun \`cotal down --preserve-state\``);
1013
- }
1014
- // Commit intent is durable: the manager was asked to stop its children and may already have
1015
- // done so. Deleting the cut here would lose the retained inventory (this was the bug). While
1016
- // the broker outlives the manager in this window, confirm no retained principal is still live
1017
- // before finishing forward; if the broker is already gone we cannot check, but preserving the
1018
- // cut still beats deleting it. Then journal cut-committed and finish WITHOUT the dead manager.
1019
- if (await isReachable(mesh.server)) {
1020
- const retained = retainedPrincipalKeys(readMaintenanceResumeDocument(root, existing.resume).inventory);
1021
- if (retained.size) {
1022
- const stillLive = (await readPresenceWithoutConsumer(mesh.space, mesh.server))
1023
- .roster.filter((presence) => retained.has(presence.card.id)).map((presence) => presence.card.id);
1024
- if (stillLive.length)
1025
- throw new Error(`preservation attempt ${attemptId} lost its manager mid-commit and ${stillLive.length} retained principal(s) are still live (${stillLive.join(", ")}); the cut intent is PRESERVED for inspection - stop them, then rerun \`cotal down --preserve-state\``);
1026
- }
1027
- }
1028
- recordPreservationManagerCommit(lock, { operation: "commitPreservation", attemptId, state: "preserved" });
1029
- clearPreservationCommitIntent(lock);
1030
- clearPreservationPrepareIntent(lock);
1031
- managerCommitJournaled = true;
1032
- }
1033
- if (!managerCommitJournaled) {
1034
- const retryTarget = await resolveControlTarget({ space: mesh.space, server: mesh.server }, "control-caller-admin");
1035
- // Plane-3 fence precedes the re-prepared inventory, exactly as on the fresh path.
1036
- const retryDelivery = all.find((component) => component.name === "delivery");
1037
- if (retryDelivery && mayBeRunning(retryDelivery, context))
1038
- await stopLocalProcess(retryDelivery, context); // fence an uncertain delivery too (stopLocalProcess throws loud on unattributable → abort)
1039
- const reprepared = await askManager(cliControl, retryTarget.space, retryTarget.server, "preparePreservation", { attemptId }, retryTarget.auth, "any", 60_000);
1040
- const replan = reprepared.ok ? reprepared.data : undefined;
1041
- if (!replan?.inventory || (replan.failures?.length ?? 0) !== 0 || (replan.state !== "prepared" && replan.state !== "preserved"))
1042
- throw new Error(reprepared.error ?? "manager could not re-prepare the recorded preservation attempt");
1043
- try {
1044
- writeMaintenanceResumeDocument(lock, {
1045
- version: MAINTENANCE_RESUME_DOCUMENT_VERSION,
1046
- inventory: replan.inventory,
1047
- launch: { attemptId, space: mesh.space, server: mesh.server, storeDir, ...cap, mode: mesh.mode },
1048
- });
1049
- }
1050
- catch (cause) {
1051
- // A restarted manager prepared a DIFFERENT inventory: the journaled cut no longer
1052
- // matches reality. Release its fence and abandon the stale intent; a rerun cuts fresh.
1053
- try {
1054
- await askManager(cliControl, retryTarget.space, retryTarget.server, "abortPreservation", { attemptId }, retryTarget.auth, "any", 30_000);
1055
- }
1056
- catch { /* best effort - the fence dies with the manager */ }
1057
- abortMaintenanceCut(lock);
1058
- clearPreservationPrepareIntent(lock);
1059
- throw new Error(`preservation attempt ${attemptId} no longer matches its manager's inventory (${cause.message}); the stale cut intent was aborted - rerun \`cotal down --preserve-state\``);
1060
- }
1061
- }
1062
- }
1063
- }
1064
- else {
1065
- // The cut takes its agent inventory from the manager that serves the space. A stack with no
1066
- // manager, such as one started with --no-manager, refuses here, before the prepare intent, the
1067
- // delivery stop or any other effect.
1068
- if ((await readPresenceAndLease(mesh.space, mesh.server)).managerId === undefined)
1069
- throw new CommandFailure("refused", "TARGET_UNAVAILABLE", "no manager serves this space, so --preserve-state cannot take the agent inventory it preserves; nothing was stopped", {
1070
- target: { root, space: mesh.space, server: mesh.server },
1071
- remedy: "start this stack's manager with `cotal up`, then run `cotal down --preserve-state` again",
1072
- });
1073
- // The attempt binding is durable BEFORE the manager is fenced: a crash between manager
1074
- // preparation and the cut-intent journal retries with the exact attempt the manager holds.
1075
- const intent = readPreservationPrepareIntent(root);
1076
- if (intent) {
1077
- if (intent.space !== mesh.space || intent.mode !== mesh.mode || intent.server !== mesh.server || intent.storeDir !== storeDir)
1078
- throw new Error(`preservation prepare intent ${intent.attemptId} does not match the current mesh launch; inspect .cotal/maintenance before retrying`);
1079
- attemptId = intent.attemptId;
1080
- }
1081
- else {
1082
- attemptId = `preserve-${Date.now()}-${process.pid}`;
1083
- writePreservationPrepareIntent(lock, {
1084
- attemptId, space: mesh.space, mode: mesh.mode, server: mesh.server, storeDir,
1085
- });
1086
- }
1087
- const target = await resolveControlTarget({ space: mesh.space, server: mesh.server }, "control-caller-admin");
1088
- // Fence Plane 3 BEFORE any inventory work: with the delivery daemon stopped, no durable
1089
- // join/leave can mutate MEMBERS at or after the moment the inventory is taken.
1090
- const delivery = all.find((component) => component.name === "delivery");
1091
- const deliveryFenced = delivery !== undefined && mayBeRunning(delivery, context);
1092
- if (delivery && deliveryFenced)
1093
- await stopLocalProcess(delivery, context); // fence an uncertain delivery: no MEMBERS mutation may race the inventory
1094
- const prepared = await askManager(cliControl, target.space, target.server, "preparePreservation", { attemptId }, target.auth, "any", 60_000);
1095
- let plan;
1096
- try {
1097
- if (!prepared.ok)
1098
- throw new Error(prepared.error ?? "manager preservation prepare failed");
1099
- plan = prepared.data;
1100
- if (!plan?.inventory || (plan.failures?.length ?? 0) !== 0 || (plan.state !== "prepared" && plan.state !== "preserved"))
1101
- throw new Error("manager returned an invalid or incomplete preservation plan");
1102
- const retainedPrincipals = retainedPrincipalKeys(plan.inventory);
1103
- let observed = await readPresenceWithoutConsumer(mesh.space, mesh.server);
1104
- retainedPrincipals.add(observed.managerId);
1105
- let unmanaged = observed.roster.filter((presence) => !retainedPrincipals.has(presence.card.id));
1106
- if (unmanaged.length) {
1107
- await sleep(11_000); // Let stopped predecessor presence and manager leases expire before refusing.
1108
- observed = await readPresenceWithoutConsumer(mesh.space, mesh.server);
1109
- retainedPrincipals.add(observed.managerId);
1110
- unmanaged = observed.roster.filter((presence) => !retainedPrincipals.has(presence.card.id));
1111
- }
1112
- // A known, clean refusal, classified as one: it used to be a bare Error, reported as an
1113
- // unknown outcome (`OPERATION_UNKNOWN`) with no next step (#4510).
1114
- if (unmanaged.length)
1115
- throw new CommandFailure("refused", "LIFECYCLE_BLOCKED", `cannot preserve while unmanaged endpoints are live: ${unmanaged.map((presence) => unmanagedEndpointLabel(presence.card.name, presence.card.id)).join(", ")} (manager lease holder: ${observed.managerId}); nothing was preserved`, { remedy: "stop those endpoints, or wait for their presence to expire, then run `cotal down --preserve-state` again" });
1116
- // A seat that cannot be checkpointed is refused HERE, at prepare time, while every child is
1117
- // still running. This reads only the prepared inventory, so it needs nothing that stopping
1118
- // would provide, and refusing after the stack is down would cost the operator a running mesh
1119
- // to tell them the cut was never going to complete.
1120
- assertSeatsCheckpointable(plan.inventory);
1121
- }
1122
- catch (cause) {
1123
- // A refused prepare (or a live-unmanaged / uncheckpointable refusal) must not leave the
1124
- // manager fenced in "preserving" mode with no running preservation to finish: abort the
1125
- // attempt (best effort, the same shape as the stale-inventory retry above) and clear the
1126
- // intent, so the operator is left with a running, unfenced mesh and the refusal reason.
1127
- try {
1128
- await askManager(cliControl, target.space, target.server, "abortPreservation", { attemptId }, target.auth, "any", 30_000);
1129
- }
1130
- catch { /* best effort - the fence dies with the manager */ }
1131
- clearPreservationPrepareIntent(lock);
1132
- // The delivery daemon was stopped above as the Plane 3 fence, and a refusal used to leave
1133
- // it stopped: the operator read "running, unfenced mesh" while no spawn, retirement or join
1134
- // could complete until the next `cotal up` (#4510). Start it again, and when that fails say
1135
- // so in the refusal, so what it names is what is actually left. An open mesh runs no
1136
- // daemon, so one an earlier open boot left behind stays stopped.
1137
- if (deliveryFenced && mesh.mode !== "open") {
1138
- const notRestarted = await restartFencedDelivery(mesh.space, mesh.server, target.auth.tls === true);
1139
- if (notRestarted !== undefined) {
1140
- const message = `${cause instanceof Error ? cause.message : String(cause)}; the delivery daemon stopped for the cut could not be started again (${notRestarted})`;
1141
- throw new CommandFailure("refused", isCommandFailure(cause) ? cause.code : "LIFECYCLE_BLOCKED", message, { remedy: "start the delivery daemon with `cotal up`, then address the refusal and run `cotal down --preserve-state` again" });
1142
- }
1143
- }
1144
- throw cause;
1145
- }
1146
- resume = writeMaintenanceResumeDocument(lock, {
1147
- version: MAINTENANCE_RESUME_DOCUMENT_VERSION,
1148
- inventory: plan.inventory,
1149
- launch: {
1150
- attemptId,
1151
- space: mesh.space,
1152
- server: mesh.server,
1153
- storeDir,
1154
- ...cap,
1155
- mode: mesh.mode,
1156
- },
1157
- });
1158
- beginMaintenanceCut(lock, {
1159
- attemptId,
1160
- space: mesh.space,
1161
- mode: mesh.mode,
1162
- sourcePath: storeDir,
1163
- resume,
1164
- launch: { server: mesh.server, storeDir, ...cap },
1165
- });
1166
- clearPreservationPrepareIntent(lock);
1167
- }
1168
- // Stop the children through the manager, then journal cut-committed. A commit-intent marker is
1169
- // written FIRST (the stop RPC is about to execute) and cleared once cut-committed is durable, so a
1170
- // crash in the gap leaves proof the stop may already have run — recovery finishes forward instead
1171
- // of deleting the cut. `managerCommitJournaled` means a dead-manager recovery already committed above.
1172
- if (existing?.state !== "cut-committed" && !managerCommitJournaled) {
1173
- const manager = all.find((component) => component.name === "manager");
1174
- if (!manager)
1175
- throw new Error("local process registry has no manager descriptor");
1176
- // This one DELIBERATELY keeps `processAlive` (provably alive), not `mayBeRunning`: here we must
1177
- // USE the manager to prove every retained child stopped, so anything short of provably-alive -
1178
- // dead OR uncertain - must fail closed and preserve the cut. `processAlive` already returns
1179
- // false on `unknown`, so an uncertain manager throws here rather than being trusted to attest.
1180
- if (!processAlive(manager, context))
1181
- throw new Error("cannot complete preservation because the attempt-bound manager is not alive to prove every retained child stopped; recovery must preserve the cut-intent journal for inspection");
1182
- // Fault window: cut-intent journaled but the child-stopping RPC not yet invoked (no commit
1183
- // intent). A crash here is genuinely pre-commit — recovery MUST still abort, not finish forward.
1184
- if (process.env.COTAL_SMOKE_EXIT_AFTER_CUT_INTENT_BEFORE_COMMIT === "1")
1185
- process.exit(93);
1186
- writePreservationCommitIntent(lock, { attemptId });
1187
- const target = await resolveControlTarget({ space: mesh.space, server: mesh.server }, "control-caller-admin");
1188
- const commit = await askManager(cliControl, target.space, target.server, "commitPreservation", { attemptId }, target.auth, "any", 120_000);
1189
- if (!commit.ok)
1190
- throw new Error(commit.error ?? "manager preservation commit was incomplete");
1191
- const result = commit.data;
1192
- if (result?.state !== "preserved" || (result.failures?.length ?? 0) !== 0)
1193
- throw new Error("manager could not prove every retained child stopped");
1194
- // Fault window: the manager has COMMITTED (children stopped, preservation irreversible) but the
1195
- // coordinator has not yet journaled cut-committed. A crash here leaves the journal at cut-intent
1196
- // WITH the commit-intent marker set — the exact window recovery must not treat as pre-commit.
1197
- if (process.env.COTAL_SMOKE_EXIT_AFTER_MANAGER_STOP_BEFORE_JOURNAL === "1")
1198
- process.exit(92);
1199
- recordPreservationManagerCommit(lock, { operation: "commitPreservation", attemptId, state: "preserved" });
1200
- clearPreservationCommitIntent(lock);
1201
- if (process.env.COTAL_SMOKE_EXIT_AFTER_PRESERVATION_MANAGER_COMMIT === "1")
1202
- process.exit(90);
1203
- }
1204
- const rank = (component) => {
1205
- if (component.name === "delivery")
1206
- return 20;
1207
- if (component.name === "manager")
1208
- return 30;
1209
- if (component.name === "auth")
1210
- return 40;
1211
- if (component.stopLast)
1212
- return 100;
1213
- return 10;
1214
- };
1215
- const ranked = [...all].sort((a, b) => rank(a) - rank(b) || (a.order ?? 50) - (b.order ?? 50));
1216
- // The quiescence proof runs BETWEEN two stop phases. Everything it proves dead — the
1217
- // lease-holding daemons, delivery and manager — stops before it. The user-auth service holds no
1218
- // lease, so the proof does not cover it, and on a USER mesh the proof's own broker connect
1219
- // exchanges through that service: stop it first and the cut can no longer prove itself, ending
1220
- // at cut-committed with the broker still up. It stops after the proof, still before the broker.
1221
- const afterQuiescence = (component) => component.stopLast || component.name === "auth";
1222
- for (const component of ranked.filter((component) => !afterQuiescence(component)))
1223
- await stopLocalProcess(component, context);
1224
- // Wire-truth quiescence while the broker still answers: every control-plane daemon must be
1225
- // provably lease-dead, not merely pidfile-absent, before the broker stops and ready publishes.
1226
- // An already-unreachable broker is itself the proof - nothing can mutate broker-resident state
1227
- // through a dead endpoint, and the final unreachable check below re-verifies it.
1228
- if (await isReachable(mesh.server))
1229
- await assertControlPlaneQuiesced(mesh.space, mesh.server);
1230
- // rank() keeps auth (40) ahead of the broker (stopLast, 100) within this phase.
1231
- for (const component of ranked.filter(afterQuiescence))
1232
- await stopLocalProcess(component, context);
1233
- // Fail-closed: a component we cannot PROVE stopped (unattributable/unknown pidfile) leaves the
1234
- // cut partial - it must not be silently counted as gone, or `unknown` becomes a "successful cut".
1235
- const stillRunning = all.filter((component) => mayBeRunning(component, context));
1236
- if (stillRunning.length)
1237
- throw new Error(`preservation cut is partial; still running (or liveness unconfirmed): ${stillRunning.map((component) => component.name).join(", ")}`);
1238
- await waitForEndpointUnreachable(mesh.server);
1239
- // Step 7 and 8 of the cut. ONLY here: the manager has proven every child exited
1240
- // (`commitPreservation` above returned state "preserved" with no failures) and the whole stack
1241
- // is down, so nothing is writing to a working tree or a transcript. A capture any earlier races
1242
- // the harness by construction.
1243
- const captured = await captureSeatCheckpoints(root, mesh.space, resume, seatCheckpointDir(root, attemptId), sessionStores);
1244
- completeMaintenanceCut(lock, {
1245
- attemptId,
1246
- observedAt: new Date().toISOString(),
1247
- managerCommit: { operation: "commitPreservation", attemptId, state: "preserved" },
1248
- stopped: { manager: true, broker: true, localProcesses: true },
1249
- listener: { endpoint: mesh.server, unreachable: true },
1250
- });
1251
- console.log(c.green(`✓ preserved state for "${mesh.space}"`));
1252
- console.log(c.dim(` source: ${storeDir}`));
1253
- console.log(c.dim(` resume inventory: ${join(root, ".cotal", "maintenance", "v1", resume.file)}`));
1254
- for (const seat of captured)
1255
- console.log(c.dim(` checkpoint: ${seat.name} (${seat.session.continuity}, generation ${seat.generation}) -> ${join(seatCheckpointDir(root, attemptId), seat.name)}`));
1256
- console.log(c.dim(" stack remains stopped; create a backup or deliberately resume with `cotal up`"));
1257
- }
1258
- finally {
1259
- releaseMaintenanceLock(lock);
1260
- }
1261
- }
1262
- /**
1263
- * Refuse any seat the cut could not checkpoint, from the prepared inventory alone.
1264
- *
1265
- * Called at prepare time, before a single child is stopped. The capture itself must wait until the
1266
- * stack is proven down, but the DECISION about whether a capture is possible reads only the
1267
- * inventory, so it belongs where the operator still has a running mesh.
1268
- *
1269
- * A seat the manager would refuse to resume is refused here too, with the manager's own wording:
1270
- * `Manager.inventoryReferenceError` says `imperative launch options have no non-secret durable
1271
- * source`, and a checkpoint inherits that refusal rather than writing something that will not
1272
- * reproduce the seat.
1273
- */
1274
- export function assertSeatsCheckpointable(inventory) {
1275
- for (const entry of (inventory.agents ?? [])) {
1276
- const keys = entry.launch?.unresolvedLaunchOptionKeys ?? [];
1277
- if (keys.length)
1278
- throw new Error(`imperative launch options have no non-secret durable source (${keys.join(", ")}): seat ${entry.name} cannot be checkpointed`);
1279
- if (!entry.launch?.cwd)
1280
- throw new Error(`seat ${entry.name} has no launch cwd to capture`);
1281
- }
1282
- }
1283
- /** Capture one checkpoint per retained seat, after the cut has proven the whole stack down. */
1284
- export async function captureSeatCheckpoints(root, space, resume, destination, sessionStores) {
1285
- const document = readMaintenanceResumeDocument(root, resume);
1286
- const inventory = document.inventory;
1287
- const agents = inventory?.agents ?? [];
1288
- const sealed = [];
1289
- for (const entry of agents) {
1290
- // Re-asserted over the document that was actually written, not the plan read at prepare time.
1291
- assertSeatsCheckpointable({ agents: [entry] });
1292
- const cwd = entry.launch.cwd;
1293
- // The generation this cut is taken at, from what this host holds. A destination claims the
1294
- // successor by exclusive create before it launches anything.
1295
- const held = loadSeatWriterGeneration(root, space, entry.name);
1296
- const connector = await connectorCapabilities(entry.launch.connector);
1297
- // The store is applied to every CONTINUATION-CAPABLE seat and to no other. A connector that
1298
- // does not reopen a session has nothing to reopen it from, and carrying a transcript for it
1299
- // would put harness bytes in an artifact that can never use them.
1300
- const carriesSession = Boolean(connector?.supportsSessionContinuation);
1301
- sealed.push(captureSeatCheckpoint(join(destination, entry.name), entry, {
1302
- cwd,
1303
- space,
1304
- name: entry.name,
1305
- lifecycleUid: entry.identity.lifecycleUid,
1306
- generation: held?.generation ?? 0,
1307
- workspaceRoot: root,
1308
- profile: {
1309
- configSha256: entry.launch.source.configSha256,
1310
- ...(entry.launch.source.manifestSha256 ? { manifestSha256: entry.launch.source.manifestSha256 } : {}),
1311
- ...(entry.launch.source.hash ? { hash: entry.launch.source.hash } : {}),
1312
- },
1313
- connector,
1314
- ...(entry.launch.sessionId ? { sessionId: entry.launch.sessionId } : {}),
1315
- ...(carriesSession && entry.launch.sessionStatePath ? { sessionStatePath: entry.launch.sessionStatePath } : {}),
1316
- ...(carriesSession && sessionStores.length ? { sessionStorePaths: sessionStores } : {}),
1317
- }));
1318
- }
1319
- return sealed;
1320
- }
1321
- /** Resolve a connector's DECLARED capabilities. An unresolvable connector is `undefined`, which
1322
- * `sessionContinuityClass` reads as drain-only: unknown capabilities are default-deny and no
1323
- * continuation promise may be inferred from a package name or a host-local probe. */
1324
- async function connectorCapabilities(name) {
1325
- try {
1326
- return await materializeFromManifest({ kind: "connector", name });
1327
- }
1328
- catch {
1329
- return undefined;
1330
- }
1331
- }
1332
- function resolveStore(path) {
1333
- const resolved = path.startsWith("/") ? path : join(process.cwd(), path);
1334
- return resolved;
1335
- }
1336
- /** Wire-truth control-plane quiescence: a live manager/delivery daemon renews its lease
1337
- * continuously, so the cut publishes `ready` only once BOTH lease buckets hold no live value —
1338
- * a dead daemon's lease expires by TTL, a pidless live one keeps renewing and is refused here.
1339
- * Pidfiles are hints; leases are proof. */
1340
- export async function assertControlPlaneQuiesced(space, server) {
1341
- const resolved = await connectOrExit({ space, server }, "deployer");
1342
- const user = resolved.bearer ? await userViewAuthOrExit(resolved, "deployer") : undefined;
1343
- const nc = await dialerFor(server)({
1344
- servers: server,
1345
- ...standaloneConnectOpts({ ...(user ?? { creds: resolved.creds }), tls: resolved.tls }),
1346
- maxReconnectAttempts: 0,
1347
- });
1348
- try {
1349
- const jsm = await jetstreamManager(nc);
1350
- const liveKeys = async (bucket) => {
1351
- let subjects;
1352
- try {
1353
- const info = await jsm.streams.info(`KV_${bucket}`, { subjects_filter: `$KV.${bucket}.>` });
1354
- subjects = Object.keys(info.state.subjects ?? {});
1355
- }
1356
- catch (error) {
1357
- if (/stream not found/i.test(error.message))
1358
- return [];
1359
- throw error;
1360
- }
1361
- const live = [];
1362
- for (const subject of subjects) {
1363
- if (await directKvValue(nc, `KV_${bucket}`, subject, true) !== undefined)
1364
- live.push(subject);
1365
- }
1366
- return live;
1367
- };
1368
- const deadline = Date.now() + Math.max(LEASE_TTL_MS, MANAGER_LEASE_TTL_MS) + 5_000;
1369
- for (;;) {
1370
- const deliveryLive = await liveKeys(deliveryBucket(space));
1371
- const managerLive = await liveKeys(managerBucket(space));
1372
- if (deliveryLive.length === 0 && managerLive.length === 0)
1373
- return;
1374
- if (Date.now() >= deadline)
1375
- throw new Error(`control-plane leases are still live past their TTL (delivery: ${deliveryLive.length}, manager: ${managerLive.length}); a pidless daemon may still be running - the cut refuses to publish ready`);
1376
- await sleep(500);
1377
- }
1378
- }
1379
- finally {
1380
- await drainAndClose(nc).catch(() => { });
1381
- }
1382
- }
1383
- /** Read current KV subjects by Direct Get so the cut check leaves no ephemeral/native consumer.
1384
- *
1385
- * Exported for the gated tombstone cell. A regression test for the lease walk has to run through
1386
- * THIS function, not a transcription of it: a copy carries its own `allowEmpty` parameter, so it
1387
- * stays green when the argument at the real call site is removed and proves nothing about the fix. */
1388
- export async function readPresenceWithoutConsumer(space, server) {
1389
- const { roster, managerId } = await readPresenceAndLease(space, server);
1390
- if (managerId === undefined)
1391
- throw new Error("manager lease has no authoritative holder principal");
1392
- return { roster, managerId };
1393
- }
1394
- /** The roster and the principal holding the space's manager lease, or no holder when no manager
1395
- * serves the space. */
1396
- async function readPresenceAndLease(space, server) {
1397
- const resolved = await connectOrExit({ space, server }, "deployer");
1398
- const user = resolved.bearer ? await userViewAuthOrExit(resolved, "deployer") : undefined;
1399
- const nc = await dialerFor(server)({
1400
- servers: server,
1401
- ...standaloneConnectOpts({ ...(user ?? { creds: resolved.creds }), tls: resolved.tls }),
1402
- maxReconnectAttempts: 0,
1403
- });
1404
- try {
1405
- const directValue = async (stream, subject, allowEmpty = false) => directKvValue(nc, stream, subject, allowEmpty);
1406
- const bucket = presenceBucket(space);
1407
- const stream = `KV_${bucket}`;
1408
- const prefix = `$KV.${bucket}.`;
1409
- const info = await (await jetstreamManager(nc)).streams.info(stream, { subjects_filter: `${prefix}>` });
1410
- const roster = [];
1411
- for (const subject of Object.keys(info.state.subjects ?? {})) {
1412
- const presence = await directValue(stream, subject, true);
1413
- if (presence === undefined)
1414
- continue; // A positively identified KV tombstone has no value bytes.
1415
- if (!isPresenceRow(presence, subject.slice(prefix.length)))
1416
- throw new Error(`presence record ${subject} is malformed`);
1417
- roster.push(presence);
1418
- }
1419
- // ENUMERATE THE PER-INSTANCE LEASE KEYS. P2 item 3 demoted this bucket from a single `lease` key to
1420
- // one `lease.<instanceId>` per manager, and NOTHING WRITES THE BARE PREFIX ANY MORE — the supervisor's
1421
- // grant is `$KV.<bucket>.lease.*`, which does not even cover it, so no writer can legalise it. Reading
1422
- // the bare subject threw inside `directKvValue` on every preserve-state cut, which meant the holder
1423
- // guard on the next line was unreachable and the operator saw "maintenance inventory read failed"
1424
- // instead. Same STREAM.INFO + point-get shape as `liveKeys` above: no consumer, no new grant.
1425
- const leaseBucket = managerBucket(space);
1426
- const leaseStream = `KV_${leaseBucket}`;
1427
- // `lease.*`, not `lease.>`: `managerLeaseKey` is contractually ONE lowercase-alnum token, so `*`
1428
- // matches exactly the key space that can exist while `>` would additionally admit a malformed
1429
- // multi-token key. Matches `readManagerLease`'s filter — two probes of one bucket disagreeing on
1430
- // their wildcard is drift the next reader has to adjudicate from scratch.
1431
- const leaseInfo = await (await jetstreamManager(nc)).streams.info(leaseStream, { subjects_filter: `$KV.${leaseBucket}.${MANAGER_LEASE_KEY}.*` });
1432
- let lease;
1433
- for (const subject of Object.keys(leaseInfo.state.subjects ?? {})) {
1434
- // `allowEmpty` MUST be true here. STREAM.INFO lists tombstoned subjects, so a cleanly stopped
1435
- // manager's released key is in this walk; without it `directKvValue` THROWS on the tombstone
1436
- // instead of returning undefined, and the cut dies naming a dead manager's key before a live
1437
- // holder later in the list is ever examined. `Object.keys` order decides whether it fires, so
1438
- // it is a coin flip on exactly the clean-stop scenario. Both sibling walks in this function
1439
- // (`liveKeys`, the presence roster) already pass true; this one was copied from them without it.
1440
- const held = await directValue(leaseStream, subject, true);
1441
- if (held?.holder) {
1442
- lease = held;
1443
- break;
1444
- }
1445
- }
1446
- if (!lease?.holder)
1447
- return { roster };
1448
- return { roster, managerId: parsePrincipalKey(lease.holder) ? lease.holder : principalKey(DEV_OWNER, lease.holder).key };
1449
- }
1450
- finally {
1451
- await drainAndClose(nc).catch(() => { });
1452
- }
1453
- }
1454
887
  /**
1455
888
  * Compatibility inventory for `clean`; lifecycle commands use the registered descriptors above.
1456
889
  *
@@ -1472,28 +905,4 @@ export function pidfileTargets(space, root) {
1472
905
  ...every(NATS_PIDFILE, "nats-server"),
1473
906
  ];
1474
907
  }
1475
- /** The one classifier of a pidfile, read through `readPidfile`, `parsePid` and `probeLiveness` in
1476
- * `@cotal-ai/workspace`: positive integers only, and `EPERM` means the process exists.
1477
- * `processAlive` and `mayBeRunning` are its two directions. */
1478
- export function pidfileState(path) {
1479
- const raw = readPidfile(path);
1480
- if (raw === undefined)
1481
- return { liveness: "dead", note: "no pidfile" };
1482
- if (raw.startsWith("removing:"))
1483
- return { liveness: "unknown", note: "extension removal in progress" };
1484
- const pid = parsePid(raw);
1485
- if (!pid)
1486
- return { liveness: raw ? "unknown" : "dead", note: "bad pidfile" };
1487
- const pin = verifyIdentityPin(path);
1488
- if (pin.kind === "mismatch")
1489
- return { pid, liveness: "dead", note: "foreign pid" };
1490
- if (pin.kind === "gone" || pin.kind === "no-pid")
1491
- return { pid, liveness: "dead", note: "stale pidfile" };
1492
- if (pin.kind !== "match" && pin.kind !== "legacy")
1493
- return { pid, liveness: "unknown", note: `identity ${pin.kind}` };
1494
- const liveness = probeLiveness(pid);
1495
- if (liveness === "alive")
1496
- return { pid, liveness };
1497
- return { pid, liveness, note: liveness === "dead" ? "stale pidfile" : "liveness unknown" };
1498
- }
1499
908
  //# sourceMappingURL=down.js.map