@cotal-ai/cli 0.172.2 → 0.174.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (218) hide show
  1. package/dist/command.d.ts.map +1 -1
  2. package/dist/command.js +32 -16
  3. package/dist/command.js.map +1 -1
  4. package/dist/commands/agents.d.ts.map +1 -1
  5. package/dist/commands/agents.js +22 -11
  6. package/dist/commands/agents.js.map +1 -1
  7. package/dist/commands/backup.d.ts.map +1 -1
  8. package/dist/commands/backup.js +15 -10
  9. package/dist/commands/backup.js.map +1 -1
  10. package/dist/commands/channel-members.d.ts.map +1 -1
  11. package/dist/commands/channel-members.js +29 -2
  12. package/dist/commands/channel-members.js.map +1 -1
  13. package/dist/commands/channels.d.ts.map +1 -1
  14. package/dist/commands/channels.js +12 -2
  15. package/dist/commands/channels.js.map +1 -1
  16. package/dist/commands/clean.d.ts +1 -0
  17. package/dist/commands/clean.d.ts.map +1 -1
  18. package/dist/commands/clean.js +20 -5
  19. package/dist/commands/clean.js.map +1 -1
  20. package/dist/commands/doctor.d.ts.map +1 -1
  21. package/dist/commands/doctor.js +36 -14
  22. package/dist/commands/doctor.js.map +1 -1
  23. package/dist/commands/down-preserve.d.ts +74 -0
  24. package/dist/commands/down-preserve.d.ts.map +1 -0
  25. package/dist/commands/down-preserve.js +626 -0
  26. package/dist/commands/down-preserve.js.map +1 -0
  27. package/dist/commands/down.d.ts +2 -61
  28. package/dist/commands/down.d.ts.map +1 -1
  29. package/dist/commands/down.js +10 -621
  30. package/dist/commands/down.js.map +1 -1
  31. package/dist/commands/ext.d.ts.map +1 -1
  32. package/dist/commands/ext.js +22 -5
  33. package/dist/commands/ext.js.map +1 -1
  34. package/dist/commands/help.d.ts +1 -1
  35. package/dist/commands/help.js +1 -1
  36. package/dist/commands/history.d.ts +10 -2
  37. package/dist/commands/history.d.ts.map +1 -1
  38. package/dist/commands/history.js +21 -9
  39. package/dist/commands/history.js.map +1 -1
  40. package/dist/commands/join.js +5 -1
  41. package/dist/commands/join.js.map +1 -1
  42. package/dist/commands/meshes-add.d.ts +2 -3
  43. package/dist/commands/meshes-add.d.ts.map +1 -1
  44. package/dist/commands/meshes-add.js +3 -19
  45. package/dist/commands/meshes-add.js.map +1 -1
  46. package/dist/commands/mint-endpoint-caller.d.ts.map +1 -1
  47. package/dist/commands/mint-endpoint-caller.js +13 -2
  48. package/dist/commands/mint-endpoint-caller.js.map +1 -1
  49. package/dist/commands/mint.d.ts.map +1 -1
  50. package/dist/commands/mint.js +10 -2
  51. package/dist/commands/mint.js.map +1 -1
  52. package/dist/commands/persona.js +3 -3
  53. package/dist/commands/persona.js.map +1 -1
  54. package/dist/commands/personas.js +1 -1
  55. package/dist/commands/personas.js.map +1 -1
  56. package/dist/commands/send.d.ts.map +1 -1
  57. package/dist/commands/send.js +10 -6
  58. package/dist/commands/send.js.map +1 -1
  59. package/dist/commands/setup.d.ts.map +1 -1
  60. package/dist/commands/setup.js +17 -1
  61. package/dist/commands/setup.js.map +1 -1
  62. package/dist/commands/space-registration.d.ts.map +1 -1
  63. package/dist/commands/space-registration.js +8 -8
  64. package/dist/commands/space-registration.js.map +1 -1
  65. package/dist/commands/space.d.ts.map +1 -1
  66. package/dist/commands/space.js +16 -6
  67. package/dist/commands/space.js.map +1 -1
  68. package/dist/commands/spawn-managed-launch.d.ts.map +1 -1
  69. package/dist/commands/spawn-managed-launch.js +6 -4
  70. package/dist/commands/spawn-managed-launch.js.map +1 -1
  71. package/dist/commands/spawn-preview.d.ts.map +1 -1
  72. package/dist/commands/spawn-preview.js +8 -5
  73. package/dist/commands/spawn-preview.js.map +1 -1
  74. package/dist/commands/spawn.d.ts.map +1 -1
  75. package/dist/commands/spawn.js +3 -3
  76. package/dist/commands/spawn.js.map +1 -1
  77. package/dist/commands/stack-up.d.ts +3 -1
  78. package/dist/commands/stack-up.d.ts.map +1 -1
  79. package/dist/commands/stack-up.js +50 -16
  80. package/dist/commands/stack-up.js.map +1 -1
  81. package/dist/commands/status-delivery.d.ts +9 -0
  82. package/dist/commands/status-delivery.d.ts.map +1 -0
  83. package/dist/commands/status-delivery.js +19 -0
  84. package/dist/commands/status-delivery.js.map +1 -0
  85. package/dist/commands/status-legacy.d.ts +7 -0
  86. package/dist/commands/status-legacy.d.ts.map +1 -0
  87. package/dist/commands/status-legacy.js +35 -0
  88. package/dist/commands/status-legacy.js.map +1 -0
  89. package/dist/commands/status.d.ts.map +1 -1
  90. package/dist/commands/status.js +45 -86
  91. package/dist/commands/status.js.map +1 -1
  92. package/dist/commands/team-agent-apply.js +11 -11
  93. package/dist/commands/team-agent-apply.js.map +1 -1
  94. package/dist/commands/team-deploy-apply.d.ts.map +1 -1
  95. package/dist/commands/team-deploy-apply.js +2 -4
  96. package/dist/commands/team-deploy-apply.js.map +1 -1
  97. package/dist/commands/team.js +12 -19
  98. package/dist/commands/team.js.map +1 -1
  99. package/dist/commands/up-pending.d.ts +24 -0
  100. package/dist/commands/up-pending.d.ts.map +1 -0
  101. package/dist/commands/up-pending.js +5 -0
  102. package/dist/commands/up-pending.js.map +1 -0
  103. package/dist/commands/up.d.ts +3 -1
  104. package/dist/commands/up.d.ts.map +1 -1
  105. package/dist/commands/up.js +56 -80
  106. package/dist/commands/up.js.map +1 -1
  107. package/dist/commands/update-continuity.d.ts +47 -0
  108. package/dist/commands/update-continuity.d.ts.map +1 -0
  109. package/dist/commands/update-continuity.js +430 -0
  110. package/dist/commands/update-continuity.js.map +1 -0
  111. package/dist/commands/update-process.d.ts +26 -0
  112. package/dist/commands/update-process.d.ts.map +1 -0
  113. package/dist/commands/update-process.js +283 -0
  114. package/dist/commands/update-process.js.map +1 -0
  115. package/dist/commands/update-release.d.ts +32 -0
  116. package/dist/commands/update-release.d.ts.map +1 -0
  117. package/dist/commands/update-release.js +232 -0
  118. package/dist/commands/update-release.js.map +1 -0
  119. package/dist/commands/update.d.ts +6 -54
  120. package/dist/commands/update.d.ts.map +1 -1
  121. package/dist/commands/update.js +25 -949
  122. package/dist/commands/update.js.map +1 -1
  123. package/dist/commands/use.d.ts.map +1 -1
  124. package/dist/commands/use.js +4 -7
  125. package/dist/commands/use.js.map +1 -1
  126. package/dist/commands/watch.d.ts.map +1 -1
  127. package/dist/commands/watch.js +5 -2
  128. package/dist/commands/watch.js.map +1 -1
  129. package/dist/commands/whoami.d.ts.map +1 -1
  130. package/dist/commands/whoami.js +3 -2
  131. package/dist/commands/whoami.js.map +1 -1
  132. package/dist/console/commands.js +2 -2
  133. package/dist/console/commands.js.map +1 -1
  134. package/dist/help.d.ts +1 -1
  135. package/dist/help.d.ts.map +1 -1
  136. package/dist/help.js +5 -1
  137. package/dist/help.js.map +1 -1
  138. package/dist/index.d.ts.map +1 -1
  139. package/dist/index.js +7 -5
  140. package/dist/index.js.map +1 -1
  141. package/dist/lib/choose-target.d.ts +2 -0
  142. package/dist/lib/choose-target.d.ts.map +1 -1
  143. package/dist/lib/choose-target.js +28 -10
  144. package/dist/lib/choose-target.js.map +1 -1
  145. package/dist/lib/credential-authority.d.ts +1 -1
  146. package/dist/lib/credential-authority.d.ts.map +1 -1
  147. package/dist/lib/credential-authority.js +8 -3
  148. package/dist/lib/credential-authority.js.map +1 -1
  149. package/dist/lib/endpoint-errors.d.ts.map +1 -1
  150. package/dist/lib/endpoint-errors.js +9 -2
  151. package/dist/lib/endpoint-errors.js.map +1 -1
  152. package/dist/lib/foreground-hold.d.ts +2 -0
  153. package/dist/lib/foreground-hold.d.ts.map +1 -1
  154. package/dist/lib/foreground-hold.js +47 -1
  155. package/dist/lib/foreground-hold.js.map +1 -1
  156. package/dist/lib/mint-renewal.d.ts +5 -0
  157. package/dist/lib/mint-renewal.d.ts.map +1 -0
  158. package/dist/lib/mint-renewal.js +60 -0
  159. package/dist/lib/mint-renewal.js.map +1 -0
  160. package/dist/lib/persona-files.d.ts +1 -1
  161. package/dist/lib/persona-files.d.ts.map +1 -1
  162. package/dist/lib/persona-files.js +6 -7
  163. package/dist/lib/persona-files.js.map +1 -1
  164. package/dist/lib/restore-streams.d.ts +18 -0
  165. package/dist/lib/restore-streams.d.ts.map +1 -0
  166. package/dist/lib/restore-streams.js +275 -0
  167. package/dist/lib/restore-streams.js.map +1 -0
  168. package/dist/lib/restore.d.ts +2 -0
  169. package/dist/lib/restore.d.ts.map +1 -1
  170. package/dist/lib/restore.js +5 -273
  171. package/dist/lib/restore.js.map +1 -1
  172. package/dist/lib/self-exec.d.ts +5 -2
  173. package/dist/lib/self-exec.d.ts.map +1 -1
  174. package/dist/lib/self-exec.js +6 -3
  175. package/dist/lib/self-exec.js.map +1 -1
  176. package/dist/lib/spawn-defaults.d.ts +2 -0
  177. package/dist/lib/spawn-defaults.d.ts.map +1 -1
  178. package/dist/lib/spawn-defaults.js +11 -0
  179. package/dist/lib/spawn-defaults.js.map +1 -1
  180. package/dist/lib/stack-journal.d.ts +3 -1
  181. package/dist/lib/stack-journal.d.ts.map +1 -1
  182. package/dist/lib/stack-journal.js +20 -1
  183. package/dist/lib/stack-journal.js.map +1 -1
  184. package/dist/lib/store-dir.d.ts +3 -1
  185. package/dist/lib/store-dir.d.ts.map +1 -1
  186. package/dist/lib/store-dir.js +20 -4
  187. package/dist/lib/store-dir.js.map +1 -1
  188. package/dist/lib/team-deploy-inspection.d.ts +2 -1
  189. package/dist/lib/team-deploy-inspection.d.ts.map +1 -1
  190. package/dist/lib/team-deploy-inspection.js +6 -1
  191. package/dist/lib/team-deploy-inspection.js.map +1 -1
  192. package/dist/lib/update-connector-config.d.ts +2 -0
  193. package/dist/lib/update-connector-config.d.ts.map +1 -1
  194. package/dist/lib/update-connector-config.js +15 -1
  195. package/dist/lib/update-connector-config.js.map +1 -1
  196. package/dist/lib/update-managers.d.ts.map +1 -1
  197. package/dist/lib/update-managers.js +11 -3
  198. package/dist/lib/update-managers.js.map +1 -1
  199. package/dist/lib/update-recovery-state.d.ts +7 -0
  200. package/dist/lib/update-recovery-state.d.ts.map +1 -1
  201. package/dist/lib/update-recovery-state.js +55 -2
  202. package/dist/lib/update-recovery-state.js.map +1 -1
  203. package/dist/lib/update-snapshot.d.ts.map +1 -1
  204. package/dist/lib/update-snapshot.js +14 -7
  205. package/dist/lib/update-snapshot.js.map +1 -1
  206. package/dist/seed/launch.d.ts +1 -1
  207. package/dist/seed/launch.d.ts.map +1 -1
  208. package/dist/seed/launch.js +3 -3
  209. package/dist/seed/launch.js.map +1 -1
  210. package/dist/seed/lock.d.ts +1 -1
  211. package/dist/seed/lock.d.ts.map +1 -1
  212. package/dist/seed/lock.js +3 -2
  213. package/dist/seed/lock.js.map +1 -1
  214. package/dist/telemetry.d.ts +6 -0
  215. package/dist/telemetry.d.ts.map +1 -1
  216. package/dist/telemetry.js +6 -3
  217. package/dist/telemetry.js.map +1 -1
  218. package/package.json +5 -5
@@ -0,0 +1,626 @@
1
+ import { readFileSync, statSync } from "node:fs";
2
+ import { drainAndClose, DEV_OWNER, dialerFor, isReachable, LEASE_TTL_MS, MANAGER_LEASE_KEY, MANAGER_LEASE_TTL_MS, deliveryBucket, managerBucket, presenceBucket, isPresenceRow, parsePrincipalKey, principalKey, standaloneConnectOpts, } from "@cotal-ai/core";
3
+ import { join, resolve as resolvePath } from "node:path";
4
+ import { CommandFailure, isCommandFailure, abortMaintenanceCut, acquireMaintenanceLock, beginMaintenanceCut, clearPreservationCommitIntent, clearPreservationPrepareIntent, completeMaintenanceCut, loadMeshes, localProcessPath, readMaintenanceJournal, readMaintenanceResumeDocument, readPreservationCommitIntent, readPreservationPrepareIntent, readStoreIdentity, recordPreservationManagerCommit, releaseMaintenanceLock, sameStoreIdentity, writePreservationCommitIntent, writePreservationPrepareIntent, MAINTENANCE_RESUME_DOCUMENT_VERSION, writeMaintenanceResumeDocument, loadSeatWriterGeneration, materializeFromManifest, seatCheckpointDir, restoreLeftOut, resolveControlTarget, parsePid, probeLiveness, readPidfile, verifyIdentityPin, } from "@cotal-ai/workspace";
5
+ import { jetstreamManager } from "@nats-io/jetstream";
6
+ import { localProcessSurface } from "../ext-loader.js";
7
+ import { c } from "../ui.js";
8
+ import { cotalRoot } from "../lib/paths.js";
9
+ import { directKvValue } from "./down-live-lease.js";
10
+ import { listAdditiveTeamAttempts, retainedAdditiveTeamAttempts } from "../lib/team-additive-attempt.js";
11
+ import { assertNoLiveServices } from "./down-services.js";
12
+ import { connectOrExit, userViewAuthOrExit } from "../lib/connect.js";
13
+ import { waitForEndpointUnreachable } from "../lib/endpoint-cut.js";
14
+ import { captureSeatCheckpoint } from "../lib/seat-capture.js";
15
+ import { stopLocalProcess } from "../lib/local-process-stop.js";
16
+ import { ensureDelivery } from "../lib/delivery-proc.js";
17
+ import { restoreNextStep } from "../lib/restore.js";
18
+ import { askManager } from "@cotal-ai/workspace/control";
19
+ import { cliControl } from "../lib/control.js";
20
+ /** How a live unmanaged endpoint is named in the preserve refusal. A missing or whitespace-only name is the id. */
21
+ export function unmanagedEndpointLabel(name, id) {
22
+ return name.trim() ? `${name} (${id})` : id;
23
+ }
24
+ export const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
25
+ /** Whether a component's pidfile names a process the `@cotal-ai/workspace` pid-attribution contract
26
+ * (`parsePid` + `probeLiveness`) reports alive. */
27
+ export function processAlive(component, context) {
28
+ return pidfileState(localProcessPath(component.pidFile, context)).liveness === "alive";
29
+ }
30
+ /** Whether a component MIGHT still be running. It fails CLOSED on uncertainty. A component with NO
31
+ * pidfile, an EMPTY husk, or a valid pid PROVEN dead (ESRCH) is not running. ANY other state - an
32
+ * unparsable/unattributable record, or a valid pid that is alive or whose liveness cannot be
33
+ * confirmed (`unknown`) - MIGHT be running. `down --preserve-state` asks it to fence an uncertain
34
+ * delivery daemon, to treat an uncertain manager as alive, and to refuse to call a cut complete.
35
+ * `processAlive` collapses unparsable and `unknown` to "not alive", which is fine for "is it worth
36
+ * stopping" but WRONG for those questions: it would count a live auth signer behind a torn pidfile
37
+ * as stopped. Only an ESRCH-confirmed death (or no record) clears a component. */
38
+ export function mayBeRunning(component, context) {
39
+ return pidfileState(localProcessPath(component.pidFile, context)).liveness !== "dead";
40
+ }
41
+ /** The principal keys of every retained agent in a preservation inventory — the dot-form ids that
42
+ * appear in the presence roster, so a caller can tell which retained agents are still live. */
43
+ export function retainedPrincipalKeys(inventory) {
44
+ const agents = (inventory.agents ?? []);
45
+ return new Set(agents.map((agent) => {
46
+ if (agent.identity?.mode === "user" && agent.identity.owner && agent.identity.actor)
47
+ return principalKey(agent.identity.owner, agent.identity.actor).key;
48
+ if (agent.identity?.id)
49
+ return principalKey(DEV_OWNER, agent.identity.id).key;
50
+ return undefined;
51
+ }).filter((id) => Boolean(id)));
52
+ }
53
+ /**
54
+ * The operator's `--session-store` paths, resolved and proven to be directories.
55
+ *
56
+ * There is no default and nothing is inferred from a connector name: this repository does not know
57
+ * where a harness keeps its transcript, and a guess recorded as a fact would produce a checkpoint
58
+ * promising `exact` over bytes nobody chose. A path that does not exist or is not a directory is
59
+ * refused HERE, before a single process is stopped, because a cut that discovers it after the stack
60
+ * is down costs the operator the whole cut.
61
+ */
62
+ export function assertSessionStores(paths) {
63
+ return paths.map((path) => {
64
+ const resolved = resolvePath(path);
65
+ let stat;
66
+ try {
67
+ stat = statSync(resolved);
68
+ }
69
+ catch (error) {
70
+ 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`);
71
+ }
72
+ if (!stat.isDirectory())
73
+ throw new CommandFailure("refused", "USAGE_INVALID", `--session-store ${resolved} is not a directory; name the harness transcript store directory for this host`);
74
+ return resolved;
75
+ });
76
+ }
77
+ /** Start the delivery daemon a refused cut stopped as its Plane 3 fence. Resolves to nothing when
78
+ * the daemon is running again, and to the reason when it is not, so the refusal can say so. */
79
+ async function restartFencedDelivery(space, server, tls) {
80
+ try {
81
+ const ensured = await ensureDelivery({ space, server, tls });
82
+ if (!ensured.running)
83
+ return "no delivery daemon is running after the attempt";
84
+ console.error(c.dim(`• delivery daemon started again after the refused cut${ensured.pid !== undefined ? ` (pid ${ensured.pid})` : ""}`));
85
+ return undefined;
86
+ }
87
+ catch (e) {
88
+ return e.message;
89
+ }
90
+ }
91
+ export async function preserveStateDown(storeOverride, sessionStores = []) {
92
+ const root = cotalRoot();
93
+ const matching = loadMeshes().filter((mesh) => mesh.root === root);
94
+ if (matching.length !== 1)
95
+ 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) } });
96
+ const mesh = matching[0];
97
+ // The broker runs on the store its record names, such as a restore's --store-dir target, so that
98
+ // is the store to cut. A record from before the field names none and keeps the default.
99
+ if (storeOverride !== undefined && mesh.storeDir !== undefined && resolvePath(storeOverride) !== mesh.storeDir)
100
+ 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}` });
101
+ const storeDir = storeOverride ? resolveStore(storeOverride) : mesh.storeDir ?? join(root, ".cotal", "nats");
102
+ // The store cap the broker was started with travels with the store, so the resume re-renders it.
103
+ const cap = mesh.maxFileStore !== undefined ? { maxFileStore: mesh.maxFileStore } : {};
104
+ const lock = acquireMaintenanceLock(root);
105
+ try {
106
+ const additiveAttempts = listAdditiveTeamAttempts(root);
107
+ if (retainedAdditiveTeamAttempts(additiveAttempts).length || additiveAttempts.refused.length)
108
+ 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) } });
109
+ const all = localProcessSurface();
110
+ const context = { root, space: mesh.space };
111
+ const existing = readMaintenanceJournal(root);
112
+ // A completed restore keeps its journal, and a new cut begins only after that journal is retired.
113
+ if (existing && "restore" in existing && existing.state === "active")
114
+ 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)) });
115
+ if (existing && existing.state !== "cut-intent" && existing.state !== "cut-committed" && existing.state !== "ready")
116
+ throw new Error(`cannot preserve while maintenance state is ${existing.state}`);
117
+ if (existing && (existing.space !== mesh.space || existing.mode !== mesh.mode ||
118
+ !sameStoreIdentity(existing.source, readStoreIdentity(storeDir)) || existing.cut.launch.server !== mesh.server))
119
+ throw new Error(`preservation retry ${existing.cut.attemptId} does not match the current mesh launch`);
120
+ if (existing?.state === "ready") {
121
+ await waitForEndpointUnreachable(mesh.server);
122
+ console.log(c.dim(`state for "${mesh.space}" is already preserved and offline`));
123
+ return;
124
+ }
125
+ // A saved service depends on the broker, so the cut does not stop the broker under one. It
126
+ // refuses and stops nothing, as bare down does.
127
+ assertNoLiveServices(mesh.space, "down --preserve-state");
128
+ let attemptId;
129
+ let resume;
130
+ // Set when recovery force-commits a cut whose manager died AFTER stopping children (commit-intent
131
+ // present): the shared commit block below is then skipped — the cut is already committed.
132
+ let managerCommitJournaled = false;
133
+ if (existing?.state === "cut-intent" || existing?.state === "cut-committed") {
134
+ attemptId = existing.cut.attemptId;
135
+ resume = existing.resume;
136
+ if (existing.state === "cut-intent") {
137
+ // A cut-intent retry must not depend on volatile manager memory: re-prepare the SAME
138
+ // attempt (idempotent on the fenced manager, a fresh fence on a restarted one) and prove
139
+ // the re-prepared inventory is byte-identical to the journaled resume document.
140
+ const manager = all.find((component) => component.name === "manager");
141
+ if (!manager)
142
+ throw new Error("local process registry has no manager descriptor");
143
+ if (!mayBeRunning(manager, context)) { // fail-closed: an uncertain manager is treated as alive, not dead
144
+ const committing = readPreservationCommitIntent(root);
145
+ if (!committing || committing.attemptId !== attemptId) {
146
+ // No commit intent recorded: the child-stopping RPC was never invoked, so nothing was
147
+ // stopped with suppression. Safe to abandon instead of wedging.
148
+ abortMaintenanceCut(lock);
149
+ clearPreservationPrepareIntent(lock);
150
+ 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\``);
151
+ }
152
+ // Commit intent is durable: the manager was asked to stop its children and may already have
153
+ // done so. Deleting the cut here would lose the retained inventory (this was the bug). While
154
+ // the broker outlives the manager in this window, confirm no retained principal is still live
155
+ // before finishing forward; if the broker is already gone we cannot check, but preserving the
156
+ // cut still beats deleting it. Then journal cut-committed and finish WITHOUT the dead manager.
157
+ if (await isReachable(mesh.server)) {
158
+ const retained = retainedPrincipalKeys(readMaintenanceResumeDocument(root, existing.resume).inventory);
159
+ if (retained.size) {
160
+ const stillLive = (await readPresenceWithoutConsumer(mesh.space, mesh.server))
161
+ .roster.filter((presence) => retained.has(presence.card.id)).map((presence) => presence.card.id);
162
+ if (stillLive.length)
163
+ 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\``);
164
+ }
165
+ }
166
+ recordPreservationManagerCommit(lock, { operation: "commitPreservation", attemptId, state: "preserved" });
167
+ clearPreservationCommitIntent(lock);
168
+ clearPreservationPrepareIntent(lock);
169
+ managerCommitJournaled = true;
170
+ }
171
+ if (!managerCommitJournaled) {
172
+ const retryTarget = await resolveControlTarget({ space: mesh.space, server: mesh.server }, "control-caller-admin");
173
+ // Plane-3 fence precedes the re-prepared inventory, exactly as on the fresh path.
174
+ const retryDelivery = all.find((component) => component.name === "delivery");
175
+ if (retryDelivery && mayBeRunning(retryDelivery, context))
176
+ await stopLocalProcess(retryDelivery, context); // fence an uncertain delivery too (stopLocalProcess throws loud on unattributable → abort)
177
+ const reprepared = await askManager(cliControl, retryTarget.space, retryTarget.server, "preparePreservation", { attemptId }, retryTarget.auth, "any", 60_000);
178
+ const replan = reprepared.ok ? reprepared.data : undefined;
179
+ if (!replan?.inventory || (replan.failures?.length ?? 0) !== 0 || (replan.state !== "prepared" && replan.state !== "preserved"))
180
+ throw new Error(reprepared.error ?? "manager could not re-prepare the recorded preservation attempt");
181
+ try {
182
+ writeMaintenanceResumeDocument(lock, {
183
+ version: MAINTENANCE_RESUME_DOCUMENT_VERSION,
184
+ inventory: replan.inventory,
185
+ launch: { attemptId, space: mesh.space, server: mesh.server, storeDir, ...cap, mode: mesh.mode },
186
+ });
187
+ }
188
+ catch (cause) {
189
+ // A restarted manager prepared a DIFFERENT inventory: the journaled cut no longer
190
+ // matches reality. Release its fence and abandon the stale intent; a rerun cuts fresh.
191
+ try {
192
+ await askManager(cliControl, retryTarget.space, retryTarget.server, "abortPreservation", { attemptId }, retryTarget.auth, "any", 30_000);
193
+ }
194
+ catch { /* best effort - the fence dies with the manager */ }
195
+ abortMaintenanceCut(lock);
196
+ clearPreservationPrepareIntent(lock);
197
+ 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\``);
198
+ }
199
+ }
200
+ }
201
+ }
202
+ else {
203
+ // The cut takes its agent inventory from the manager that serves the space. A stack with no
204
+ // manager, such as one started with --no-manager, refuses here, before the prepare intent, the
205
+ // delivery stop or any other effect.
206
+ if ((await readPresenceAndLease(mesh.space, mesh.server)).managerId === undefined)
207
+ throw new CommandFailure("refused", "TARGET_UNAVAILABLE", "no manager serves this space, so --preserve-state cannot take the agent inventory it preserves; nothing was stopped", {
208
+ target: { root, space: mesh.space, server: mesh.server },
209
+ remedy: "start this stack's manager with `cotal up`, then run `cotal down --preserve-state` again",
210
+ });
211
+ // The attempt binding is durable BEFORE the manager is fenced: a crash between manager
212
+ // preparation and the cut-intent journal retries with the exact attempt the manager holds.
213
+ const intent = readPreservationPrepareIntent(root);
214
+ if (intent) {
215
+ if (intent.space !== mesh.space || intent.mode !== mesh.mode || intent.server !== mesh.server || intent.storeDir !== storeDir)
216
+ throw new Error(`preservation prepare intent ${intent.attemptId} does not match the current mesh launch; inspect .cotal/maintenance before retrying`);
217
+ attemptId = intent.attemptId;
218
+ }
219
+ else {
220
+ attemptId = `preserve-${Date.now()}-${process.pid}`;
221
+ writePreservationPrepareIntent(lock, {
222
+ attemptId, space: mesh.space, mode: mesh.mode, server: mesh.server, storeDir,
223
+ });
224
+ }
225
+ const target = await resolveControlTarget({ space: mesh.space, server: mesh.server }, "control-caller-admin");
226
+ // Fence Plane 3 BEFORE any inventory work: with the delivery daemon stopped, no durable
227
+ // join/leave can mutate MEMBERS at or after the moment the inventory is taken.
228
+ const delivery = all.find((component) => component.name === "delivery");
229
+ const deliveryFenced = delivery !== undefined && mayBeRunning(delivery, context);
230
+ if (delivery && deliveryFenced)
231
+ await stopLocalProcess(delivery, context); // fence an uncertain delivery: no MEMBERS mutation may race the inventory
232
+ const prepared = await askManager(cliControl, target.space, target.server, "preparePreservation", { attemptId }, target.auth, "any", 60_000);
233
+ let plan;
234
+ try {
235
+ if (!prepared.ok)
236
+ throw new Error(prepared.error ?? "manager preservation prepare failed");
237
+ plan = prepared.data;
238
+ if (!plan?.inventory || (plan.failures?.length ?? 0) !== 0 || (plan.state !== "prepared" && plan.state !== "preserved"))
239
+ throw new Error("manager returned an invalid or incomplete preservation plan");
240
+ const retainedPrincipals = retainedPrincipalKeys(plan.inventory);
241
+ let observed = await readPresenceWithoutConsumer(mesh.space, mesh.server);
242
+ retainedPrincipals.add(observed.managerId);
243
+ let unmanaged = observed.roster.filter((presence) => !retainedPrincipals.has(presence.card.id));
244
+ if (unmanaged.length) {
245
+ await sleep(11_000); // Let stopped predecessor presence and manager leases expire before refusing.
246
+ observed = await readPresenceWithoutConsumer(mesh.space, mesh.server);
247
+ retainedPrincipals.add(observed.managerId);
248
+ unmanaged = observed.roster.filter((presence) => !retainedPrincipals.has(presence.card.id));
249
+ }
250
+ // A known, clean refusal, classified as one: it used to be a bare Error, reported as an
251
+ // unknown outcome (`OPERATION_UNKNOWN`) with no next step (#4510).
252
+ if (unmanaged.length)
253
+ 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" });
254
+ // A seat that cannot be checkpointed is refused HERE, at prepare time, while every child is
255
+ // still running. This reads only the prepared inventory, so it needs nothing that stopping
256
+ // would provide, and refusing after the stack is down would cost the operator a running mesh
257
+ // to tell them the cut was never going to complete.
258
+ assertSeatsCheckpointable(plan.inventory);
259
+ }
260
+ catch (cause) {
261
+ // A refused prepare (or a live-unmanaged / uncheckpointable refusal) must not leave the
262
+ // manager fenced in "preserving" mode with no running preservation to finish: abort the
263
+ // attempt (best effort, the same shape as the stale-inventory retry above) and clear the
264
+ // intent, so the operator is left with a running, unfenced mesh and the refusal reason.
265
+ try {
266
+ await askManager(cliControl, target.space, target.server, "abortPreservation", { attemptId }, target.auth, "any", 30_000);
267
+ }
268
+ catch { /* best effort - the fence dies with the manager */ }
269
+ clearPreservationPrepareIntent(lock);
270
+ // The delivery daemon was stopped above as the Plane 3 fence, and a refusal used to leave
271
+ // it stopped: the operator read "running, unfenced mesh" while no spawn, retirement or join
272
+ // could complete until the next `cotal up` (#4510). Start it again, and when that fails say
273
+ // so in the refusal, so what it names is what is actually left. An open mesh runs no
274
+ // daemon, so one an earlier open boot left behind stays stopped.
275
+ if (deliveryFenced && mesh.mode !== "open") {
276
+ const notRestarted = await restartFencedDelivery(mesh.space, mesh.server, target.auth.tls === true);
277
+ if (notRestarted !== undefined) {
278
+ const message = `${cause instanceof Error ? cause.message : String(cause)}; the delivery daemon stopped for the cut could not be started again (${notRestarted})`;
279
+ 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" });
280
+ }
281
+ }
282
+ throw cause;
283
+ }
284
+ resume = writeMaintenanceResumeDocument(lock, {
285
+ version: MAINTENANCE_RESUME_DOCUMENT_VERSION,
286
+ inventory: plan.inventory,
287
+ launch: {
288
+ attemptId,
289
+ space: mesh.space,
290
+ server: mesh.server,
291
+ storeDir,
292
+ ...cap,
293
+ mode: mesh.mode,
294
+ },
295
+ });
296
+ beginMaintenanceCut(lock, {
297
+ attemptId,
298
+ space: mesh.space,
299
+ mode: mesh.mode,
300
+ sourcePath: storeDir,
301
+ resume,
302
+ launch: { server: mesh.server, storeDir, ...cap },
303
+ });
304
+ clearPreservationPrepareIntent(lock);
305
+ }
306
+ // Stop the children through the manager, then journal cut-committed. A commit-intent marker is
307
+ // written FIRST (the stop RPC is about to execute) and cleared once cut-committed is durable, so a
308
+ // crash in the gap leaves proof the stop may already have run — recovery finishes forward instead
309
+ // of deleting the cut. `managerCommitJournaled` means a dead-manager recovery already committed above.
310
+ if (existing?.state !== "cut-committed" && !managerCommitJournaled) {
311
+ const manager = all.find((component) => component.name === "manager");
312
+ if (!manager)
313
+ throw new Error("local process registry has no manager descriptor");
314
+ // This one DELIBERATELY keeps `processAlive` (provably alive), not `mayBeRunning`: here we must
315
+ // USE the manager to prove every retained child stopped, so anything short of provably-alive -
316
+ // dead OR uncertain - must fail closed and preserve the cut. `processAlive` already returns
317
+ // false on `unknown`, so an uncertain manager throws here rather than being trusted to attest.
318
+ if (!processAlive(manager, context))
319
+ 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");
320
+ // Fault window: cut-intent journaled but the child-stopping RPC not yet invoked (no commit
321
+ // intent). A crash here is genuinely pre-commit — recovery MUST still abort, not finish forward.
322
+ if (process.env.COTAL_SMOKE_EXIT_AFTER_CUT_INTENT_BEFORE_COMMIT === "1")
323
+ process.exit(93);
324
+ writePreservationCommitIntent(lock, { attemptId });
325
+ const target = await resolveControlTarget({ space: mesh.space, server: mesh.server }, "control-caller-admin");
326
+ const commit = await askManager(cliControl, target.space, target.server, "commitPreservation", { attemptId }, target.auth, "any", 120_000);
327
+ if (!commit.ok)
328
+ throw new Error(commit.error ?? "manager preservation commit was incomplete");
329
+ const result = commit.data;
330
+ if (result?.state !== "preserved" || (result.failures?.length ?? 0) !== 0)
331
+ throw new Error("manager could not prove every retained child stopped");
332
+ // Fault window: the manager has COMMITTED (children stopped, preservation irreversible) but the
333
+ // coordinator has not yet journaled cut-committed. A crash here leaves the journal at cut-intent
334
+ // WITH the commit-intent marker set — the exact window recovery must not treat as pre-commit.
335
+ if (process.env.COTAL_SMOKE_EXIT_AFTER_MANAGER_STOP_BEFORE_JOURNAL === "1")
336
+ process.exit(92);
337
+ recordPreservationManagerCommit(lock, { operation: "commitPreservation", attemptId, state: "preserved" });
338
+ clearPreservationCommitIntent(lock);
339
+ if (process.env.COTAL_SMOKE_EXIT_AFTER_PRESERVATION_MANAGER_COMMIT === "1")
340
+ process.exit(90);
341
+ }
342
+ const rank = (component) => {
343
+ if (component.name === "delivery")
344
+ return 20;
345
+ if (component.name === "manager")
346
+ return 30;
347
+ if (component.name === "auth")
348
+ return 40;
349
+ if (component.stopLast)
350
+ return 100;
351
+ return 10;
352
+ };
353
+ const ranked = [...all].sort((a, b) => rank(a) - rank(b) || (a.order ?? 50) - (b.order ?? 50));
354
+ // The quiescence proof runs BETWEEN two stop phases. Everything it proves dead — the
355
+ // lease-holding daemons, delivery and manager — stops before it. The user-auth service holds no
356
+ // lease, so the proof does not cover it, and on a USER mesh the proof's own broker connect
357
+ // exchanges through that service: stop it first and the cut can no longer prove itself, ending
358
+ // at cut-committed with the broker still up. It stops after the proof, still before the broker.
359
+ const afterQuiescence = (component) => component.stopLast || component.name === "auth";
360
+ for (const component of ranked.filter((component) => !afterQuiescence(component)))
361
+ await stopLocalProcess(component, context);
362
+ // Wire-truth quiescence while the broker still answers: every control-plane daemon must be
363
+ // provably lease-dead, not merely pidfile-absent, before the broker stops and ready publishes.
364
+ // An already-unreachable broker is itself the proof - nothing can mutate broker-resident state
365
+ // through a dead endpoint, and the final unreachable check below re-verifies it.
366
+ if (await isReachable(mesh.server))
367
+ await assertControlPlaneQuiesced(mesh.space, mesh.server);
368
+ // rank() keeps auth (40) ahead of the broker (stopLast, 100) within this phase.
369
+ for (const component of ranked.filter(afterQuiescence))
370
+ await stopLocalProcess(component, context);
371
+ // Fail-closed: a component we cannot PROVE stopped (unattributable/unknown pidfile) leaves the
372
+ // cut partial - it must not be silently counted as gone, or `unknown` becomes a "successful cut".
373
+ const stillRunning = all.filter((component) => mayBeRunning(component, context));
374
+ if (stillRunning.length)
375
+ throw new Error(`preservation cut is partial; still running (or liveness unconfirmed): ${stillRunning.map((component) => component.name).join(", ")}`);
376
+ await waitForEndpointUnreachable(mesh.server);
377
+ // Step 7 and 8 of the cut. ONLY here: the manager has proven every child exited
378
+ // (`commitPreservation` above returned state "preserved" with no failures) and the whole stack
379
+ // is down, so nothing is writing to a working tree or a transcript. A capture any earlier races
380
+ // the harness by construction.
381
+ const captured = await captureSeatCheckpoints(root, mesh.space, resume, seatCheckpointDir(root, attemptId), sessionStores);
382
+ completeMaintenanceCut(lock, {
383
+ attemptId,
384
+ observedAt: new Date().toISOString(),
385
+ managerCommit: { operation: "commitPreservation", attemptId, state: "preserved" },
386
+ stopped: { manager: true, broker: true, localProcesses: true },
387
+ listener: { endpoint: mesh.server, unreachable: true },
388
+ });
389
+ console.log(c.green(`✓ preserved state for "${mesh.space}"`));
390
+ console.log(c.dim(` source: ${storeDir}`));
391
+ console.log(c.dim(` resume inventory: ${join(root, ".cotal", "maintenance", "v1", resume.file)}`));
392
+ for (const seat of captured)
393
+ console.log(c.dim(` checkpoint: ${seat.name} (${seat.session.continuity}, generation ${seat.generation}) -> ${join(seatCheckpointDir(root, attemptId), seat.name)}`));
394
+ console.log(c.dim(" stack remains stopped; create a backup or deliberately resume with `cotal up`"));
395
+ }
396
+ finally {
397
+ releaseMaintenanceLock(lock);
398
+ }
399
+ }
400
+ /**
401
+ * Refuse any seat the cut could not checkpoint, from the prepared inventory alone.
402
+ *
403
+ * Called at prepare time, before a single child is stopped. The capture itself must wait until the
404
+ * stack is proven down, but the DECISION about whether a capture is possible reads only the
405
+ * inventory, so it belongs where the operator still has a running mesh.
406
+ *
407
+ * A seat the manager would refuse to resume is refused here too, with the manager's own wording:
408
+ * `Manager.inventoryReferenceError` says `imperative launch options have no non-secret durable
409
+ * source`, and a checkpoint inherits that refusal rather than writing something that will not
410
+ * reproduce the seat.
411
+ */
412
+ export function assertSeatsCheckpointable(inventory) {
413
+ for (const entry of (inventory.agents ?? [])) {
414
+ const keys = entry.launch?.unresolvedLaunchOptionKeys ?? [];
415
+ if (keys.length)
416
+ throw new Error(`imperative launch options have no non-secret durable source (${keys.join(", ")}): seat ${entry.name} cannot be checkpointed`);
417
+ if (!entry.launch?.cwd)
418
+ throw new Error(`seat ${entry.name} has no launch cwd to capture`);
419
+ }
420
+ }
421
+ /** Capture one checkpoint per retained seat, after the cut has proven the whole stack down. */
422
+ export async function captureSeatCheckpoints(root, space, resume, destination, sessionStores) {
423
+ const document = readMaintenanceResumeDocument(root, resume);
424
+ const inventory = document.inventory;
425
+ const agents = inventory?.agents ?? [];
426
+ const sealed = [];
427
+ for (const entry of agents) {
428
+ // Re-asserted over the document that was actually written, not the plan read at prepare time.
429
+ assertSeatsCheckpointable({ agents: [entry] });
430
+ const cwd = entry.launch.cwd;
431
+ // The generation this cut is taken at, from what this host holds. A destination claims the
432
+ // successor by exclusive create before it launches anything.
433
+ const held = loadSeatWriterGeneration(root, space, entry.name);
434
+ const connector = await connectorCapabilities(entry.launch.connector);
435
+ // The store is applied to every CONTINUATION-CAPABLE seat and to no other. A connector that
436
+ // does not reopen a session has nothing to reopen it from, and carrying a transcript for it
437
+ // would put harness bytes in an artifact that can never use them.
438
+ const carriesSession = Boolean(connector?.supportsSessionContinuation);
439
+ sealed.push(captureSeatCheckpoint(join(destination, entry.name), entry, {
440
+ cwd,
441
+ space,
442
+ name: entry.name,
443
+ lifecycleUid: entry.identity.lifecycleUid,
444
+ generation: held?.generation ?? 0,
445
+ workspaceRoot: root,
446
+ profile: {
447
+ configSha256: entry.launch.source.configSha256,
448
+ ...(entry.launch.source.manifestSha256 ? { manifestSha256: entry.launch.source.manifestSha256 } : {}),
449
+ ...(entry.launch.source.hash ? { hash: entry.launch.source.hash } : {}),
450
+ },
451
+ connector,
452
+ ...(entry.launch.sessionId ? { sessionId: entry.launch.sessionId } : {}),
453
+ ...(carriesSession && entry.launch.sessionStatePath ? { sessionStatePath: entry.launch.sessionStatePath } : {}),
454
+ ...(carriesSession && sessionStores.length ? { sessionStorePaths: sessionStores } : {}),
455
+ }));
456
+ }
457
+ return sealed;
458
+ }
459
+ /** Resolve a connector's DECLARED capabilities. An unresolvable connector is `undefined`, which
460
+ * `sessionContinuityClass` reads as drain-only: unknown capabilities are default-deny and no
461
+ * continuation promise may be inferred from a package name or a host-local probe. */
462
+ async function connectorCapabilities(name) {
463
+ try {
464
+ return await materializeFromManifest({ kind: "connector", name });
465
+ }
466
+ catch {
467
+ return undefined;
468
+ }
469
+ }
470
+ function resolveStore(path) {
471
+ const resolved = path.startsWith("/") ? path : join(process.cwd(), path);
472
+ return resolved;
473
+ }
474
+ /** Wire-truth control-plane quiescence: a live manager/delivery daemon renews its lease
475
+ * continuously, so the cut publishes `ready` only once BOTH lease buckets hold no live value —
476
+ * a dead daemon's lease expires by TTL, a pidless live one keeps renewing and is refused here.
477
+ * Pidfiles are hints; leases are proof. */
478
+ export async function assertControlPlaneQuiesced(space, server) {
479
+ const resolved = await connectOrExit({ space, server }, "deployer");
480
+ const user = resolved.bearer ? await userViewAuthOrExit(resolved, "deployer") : undefined;
481
+ const nc = await dialerFor(server)({
482
+ servers: server,
483
+ ...standaloneConnectOpts({ ...(user ?? { creds: resolved.creds }), tls: resolved.tls }),
484
+ maxReconnectAttempts: 0,
485
+ });
486
+ try {
487
+ const jsm = await jetstreamManager(nc);
488
+ const liveKeys = async (bucket) => {
489
+ let subjects;
490
+ try {
491
+ const info = await jsm.streams.info(`KV_${bucket}`, { subjects_filter: `$KV.${bucket}.>` });
492
+ subjects = Object.keys(info.state.subjects ?? {});
493
+ }
494
+ catch (error) {
495
+ if (/stream not found/i.test(error.message))
496
+ return [];
497
+ throw error;
498
+ }
499
+ const live = [];
500
+ for (const subject of subjects) {
501
+ if (await directKvValue(nc, `KV_${bucket}`, subject, true) !== undefined)
502
+ live.push(subject);
503
+ }
504
+ return live;
505
+ };
506
+ const deadline = Date.now() + Math.max(LEASE_TTL_MS, MANAGER_LEASE_TTL_MS) + 5_000;
507
+ for (;;) {
508
+ const deliveryLive = await liveKeys(deliveryBucket(space));
509
+ const managerLive = await liveKeys(managerBucket(space));
510
+ if (deliveryLive.length === 0 && managerLive.length === 0)
511
+ return;
512
+ if (Date.now() >= deadline)
513
+ 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`);
514
+ await sleep(500);
515
+ }
516
+ }
517
+ finally {
518
+ await drainAndClose(nc).catch(() => { });
519
+ }
520
+ }
521
+ /** Read current KV subjects by Direct Get so the cut check leaves no ephemeral/native consumer.
522
+ *
523
+ * Exported for the gated tombstone cell. A regression test for the lease walk has to run through
524
+ * THIS function, not a transcription of it: a copy carries its own `allowEmpty` parameter, so it
525
+ * stays green when the argument at the real call site is removed and proves nothing about the fix. */
526
+ export async function readPresenceWithoutConsumer(space, server) {
527
+ const { roster, managerId } = await readPresenceAndLease(space, server);
528
+ if (managerId === undefined)
529
+ throw new Error("manager lease has no authoritative holder principal");
530
+ return { roster, managerId };
531
+ }
532
+ /** The roster and the principal holding the space's manager lease, or no holder when no manager
533
+ * serves the space. */
534
+ async function readPresenceAndLease(space, server) {
535
+ const resolved = await connectOrExit({ space, server }, "deployer");
536
+ const user = resolved.bearer ? await userViewAuthOrExit(resolved, "deployer") : undefined;
537
+ const nc = await dialerFor(server)({
538
+ servers: server,
539
+ ...standaloneConnectOpts({ ...(user ?? { creds: resolved.creds }), tls: resolved.tls }),
540
+ maxReconnectAttempts: 0,
541
+ });
542
+ try {
543
+ const directValue = async (stream, subject, allowEmpty = false) => directKvValue(nc, stream, subject, allowEmpty);
544
+ const bucket = presenceBucket(space);
545
+ const stream = `KV_${bucket}`;
546
+ const prefix = `$KV.${bucket}.`;
547
+ const info = await (await jetstreamManager(nc)).streams.info(stream, { subjects_filter: `${prefix}>` });
548
+ const roster = [];
549
+ for (const subject of Object.keys(info.state.subjects ?? {})) {
550
+ const presence = await directValue(stream, subject, true);
551
+ if (presence === undefined)
552
+ continue; // A positively identified KV tombstone has no value bytes.
553
+ if (!isPresenceRow(presence, subject.slice(prefix.length)))
554
+ throw new Error(`presence record ${subject} is malformed`);
555
+ roster.push(presence);
556
+ }
557
+ // ENUMERATE THE PER-INSTANCE LEASE KEYS. P2 item 3 demoted this bucket from a single `lease` key to
558
+ // one `lease.<instanceId>` per manager, and NOTHING WRITES THE BARE PREFIX ANY MORE — the supervisor's
559
+ // grant is `$KV.<bucket>.lease.*`, which does not even cover it, so no writer can legalise it. Reading
560
+ // the bare subject threw inside `directKvValue` on every preserve-state cut, which meant the holder
561
+ // guard on the next line was unreachable and the operator saw "maintenance inventory read failed"
562
+ // instead. Same STREAM.INFO + point-get shape as `liveKeys` above: no consumer, no new grant.
563
+ const leaseBucket = managerBucket(space);
564
+ const leaseStream = `KV_${leaseBucket}`;
565
+ // `lease.*`, not `lease.>`: `managerLeaseKey` is contractually ONE lowercase-alnum token, so `*`
566
+ // matches exactly the key space that can exist while `>` would additionally admit a malformed
567
+ // multi-token key. Matches `readManagerLease`'s filter — two probes of one bucket disagreeing on
568
+ // their wildcard is drift the next reader has to adjudicate from scratch.
569
+ const leaseInfo = await (await jetstreamManager(nc)).streams.info(leaseStream, { subjects_filter: `$KV.${leaseBucket}.${MANAGER_LEASE_KEY}.*` });
570
+ let lease;
571
+ for (const subject of Object.keys(leaseInfo.state.subjects ?? {})) {
572
+ // `allowEmpty` MUST be true here. STREAM.INFO lists tombstoned subjects, so a cleanly stopped
573
+ // manager's released key is in this walk; without it `directKvValue` THROWS on the tombstone
574
+ // instead of returning undefined, and the cut dies naming a dead manager's key before a live
575
+ // holder later in the list is ever examined. `Object.keys` order decides whether it fires, so
576
+ // it is a coin flip on exactly the clean-stop scenario. Both sibling walks in this function
577
+ // (`liveKeys`, the presence roster) already pass true; this one was copied from them without it.
578
+ const held = await directValue(leaseStream, subject, true);
579
+ if (held?.holder) {
580
+ lease = held;
581
+ break;
582
+ }
583
+ }
584
+ if (!lease?.holder)
585
+ return { roster };
586
+ return { roster, managerId: parsePrincipalKey(lease.holder) ? lease.holder : principalKey(DEV_OWNER, lease.holder).key };
587
+ }
588
+ finally {
589
+ await drainAndClose(nc).catch(() => { });
590
+ }
591
+ }
592
+ /** The one classifier of a pidfile, read through `readPidfile`, `parsePid` and `probeLiveness` in
593
+ * `@cotal-ai/workspace`: positive integers only, and `EPERM` means the process exists.
594
+ * `processAlive` and `mayBeRunning` are its two directions. */
595
+ export function pidfileState(path) {
596
+ const raw = readPidfile(path);
597
+ if (raw === undefined)
598
+ return { liveness: "dead", note: "no pidfile" };
599
+ if (raw.startsWith("removing:"))
600
+ return { liveness: "unknown", note: "extension removal in progress" };
601
+ const pid = parsePid(raw);
602
+ if (!pid)
603
+ return { liveness: raw ? "unknown" : "dead", note: "bad pidfile" };
604
+ const pin = verifyIdentityPin(path);
605
+ if (pin.kind === "mismatch")
606
+ return { pid, liveness: "dead", note: "foreign pid" };
607
+ if (pin.kind === "gone" || pin.kind === "no-pid")
608
+ return { pid, liveness: "dead", note: "stale pidfile" };
609
+ if (pin.kind !== "match" && pin.kind !== "legacy")
610
+ return { pid, liveness: "unknown", note: `identity ${pin.kind}` };
611
+ const liveness = probeLiveness(pid);
612
+ if (liveness === "alive" && process.platform === "linux") {
613
+ // kill(pid, 0) also succeeds after exit, until the parent reaps the process.
614
+ try {
615
+ const stat = readFileSync(`/proc/${pid}/stat`, "utf8");
616
+ const state = stat[stat.lastIndexOf(")") + 2];
617
+ if (state === "Z" || state === "X")
618
+ return { pid, liveness: "dead", note: "stale pidfile" };
619
+ }
620
+ catch { /* Keep the signal result when procfs cannot be read. */ }
621
+ }
622
+ if (liveness === "alive")
623
+ return { pid, liveness };
624
+ return { pid, liveness, note: liveness === "dead" ? "stale pidfile" : "liveness unknown" };
625
+ }
626
+ //# sourceMappingURL=down-preserve.js.map