@cotal-ai/cli 0.99.3 → 0.100.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (241) hide show
  1. package/dist/chat/chat-view.d.ts.map +1 -1
  2. package/dist/chat/chat-view.js +9 -1
  3. package/dist/chat/chat-view.js.map +1 -1
  4. package/dist/chat/controller.d.ts.map +1 -1
  5. package/dist/chat/controller.js +6 -2
  6. package/dist/chat/controller.js.map +1 -1
  7. package/dist/chat/native-session.d.ts +8 -0
  8. package/dist/chat/native-session.d.ts.map +1 -1
  9. package/dist/chat/native-session.js +31 -6
  10. package/dist/chat/native-session.js.map +1 -1
  11. package/dist/chat/plain.d.ts.map +1 -1
  12. package/dist/chat/plain.js +33 -7
  13. package/dist/chat/plain.js.map +1 -1
  14. package/dist/chat/session.d.ts +3 -0
  15. package/dist/chat/session.d.ts.map +1 -1
  16. package/dist/chat/static-session.d.ts.map +1 -1
  17. package/dist/chat/static-session.js +2 -1
  18. package/dist/chat/static-session.js.map +1 -1
  19. package/dist/chat/stdio-io.js +2 -2
  20. package/dist/chat/stdio-io.js.map +1 -1
  21. package/dist/chat/stdio.d.ts +9 -2
  22. package/dist/chat/stdio.d.ts.map +1 -1
  23. package/dist/chat/stdio.js +33 -13
  24. package/dist/chat/stdio.js.map +1 -1
  25. package/dist/chat/view.d.ts +16 -4
  26. package/dist/chat/view.d.ts.map +1 -1
  27. package/dist/chat/view.js +21 -8
  28. package/dist/chat/view.js.map +1 -1
  29. package/dist/command.d.ts.map +1 -1
  30. package/dist/command.js +51 -8
  31. package/dist/command.js.map +1 -1
  32. package/dist/commands/agents.d.ts.map +1 -1
  33. package/dist/commands/agents.js +3 -2
  34. package/dist/commands/agents.js.map +1 -1
  35. package/dist/commands/backup-maintenance.d.ts.map +1 -1
  36. package/dist/commands/backup-maintenance.js +75 -16
  37. package/dist/commands/backup-maintenance.js.map +1 -1
  38. package/dist/commands/backup-read.d.ts.map +1 -1
  39. package/dist/commands/backup-read.js +14 -1
  40. package/dist/commands/backup-read.js.map +1 -1
  41. package/dist/commands/backup-restore.d.ts.map +1 -1
  42. package/dist/commands/backup-restore.js +4 -1
  43. package/dist/commands/backup-restore.js.map +1 -1
  44. package/dist/commands/backup.d.ts.map +1 -1
  45. package/dist/commands/backup.js +51 -11
  46. package/dist/commands/backup.js.map +1 -1
  47. package/dist/commands/channel-members.d.ts.map +1 -1
  48. package/dist/commands/channel-members.js +6 -3
  49. package/dist/commands/channel-members.js.map +1 -1
  50. package/dist/commands/channels.d.ts.map +1 -1
  51. package/dist/commands/channels.js +12 -9
  52. package/dist/commands/channels.js.map +1 -1
  53. package/dist/commands/chat.d.ts +4 -3
  54. package/dist/commands/chat.d.ts.map +1 -1
  55. package/dist/commands/chat.js +6 -3
  56. package/dist/commands/chat.js.map +1 -1
  57. package/dist/commands/clean.d.ts +4 -3
  58. package/dist/commands/clean.d.ts.map +1 -1
  59. package/dist/commands/clean.js +24 -14
  60. package/dist/commands/clean.js.map +1 -1
  61. package/dist/commands/completion.d.ts.map +1 -1
  62. package/dist/commands/completion.js +3 -1
  63. package/dist/commands/completion.js.map +1 -1
  64. package/dist/commands/config.d.ts +7 -0
  65. package/dist/commands/config.d.ts.map +1 -1
  66. package/dist/commands/config.js +42 -7
  67. package/dist/commands/config.js.map +1 -1
  68. package/dist/commands/console.js +1 -1
  69. package/dist/commands/console.js.map +1 -1
  70. package/dist/commands/doctor.d.ts.map +1 -1
  71. package/dist/commands/doctor.js +27 -7
  72. package/dist/commands/doctor.js.map +1 -1
  73. package/dist/commands/down.d.ts +3 -2
  74. package/dist/commands/down.d.ts.map +1 -1
  75. package/dist/commands/down.js +97 -19
  76. package/dist/commands/down.js.map +1 -1
  77. package/dist/commands/endpoints.js +4 -2
  78. package/dist/commands/endpoints.js.map +1 -1
  79. package/dist/commands/ext.js +1 -1
  80. package/dist/commands/ext.js.map +1 -1
  81. package/dist/commands/join.d.ts.map +1 -1
  82. package/dist/commands/join.js +17 -7
  83. package/dist/commands/join.js.map +1 -1
  84. package/dist/commands/meshes-add.d.ts.map +1 -1
  85. package/dist/commands/meshes-add.js +12 -6
  86. package/dist/commands/meshes-add.js.map +1 -1
  87. package/dist/commands/models.d.ts.map +1 -1
  88. package/dist/commands/models.js +3 -1
  89. package/dist/commands/models.js.map +1 -1
  90. package/dist/commands/persona.d.ts.map +1 -1
  91. package/dist/commands/persona.js +8 -1
  92. package/dist/commands/persona.js.map +1 -1
  93. package/dist/commands/personas.d.ts.map +1 -1
  94. package/dist/commands/personas.js +20 -9
  95. package/dist/commands/personas.js.map +1 -1
  96. package/dist/commands/reset-store-apply.d.ts.map +1 -1
  97. package/dist/commands/reset-store-apply.js +22 -7
  98. package/dist/commands/reset-store-apply.js.map +1 -1
  99. package/dist/commands/reset.js +1 -1
  100. package/dist/commands/reset.js.map +1 -1
  101. package/dist/commands/send.d.ts +1 -1
  102. package/dist/commands/send.d.ts.map +1 -1
  103. package/dist/commands/send.js +28 -11
  104. package/dist/commands/send.js.map +1 -1
  105. package/dist/commands/setup.js +3 -3
  106. package/dist/commands/setup.js.map +1 -1
  107. package/dist/commands/space-delete.d.ts.map +1 -1
  108. package/dist/commands/space-delete.js +31 -6
  109. package/dist/commands/space-delete.js.map +1 -1
  110. package/dist/commands/space-registration.d.ts +3 -1
  111. package/dist/commands/space-registration.d.ts.map +1 -1
  112. package/dist/commands/space-registration.js +85 -16
  113. package/dist/commands/space-registration.js.map +1 -1
  114. package/dist/commands/space.d.ts +1 -1
  115. package/dist/commands/space.js +1 -1
  116. package/dist/commands/space.js.map +1 -1
  117. package/dist/commands/stack-down.d.ts +3 -2
  118. package/dist/commands/stack-down.d.ts.map +1 -1
  119. package/dist/commands/stack-down.js +19 -10
  120. package/dist/commands/stack-down.js.map +1 -1
  121. package/dist/commands/stack-up.d.ts.map +1 -1
  122. package/dist/commands/stack-up.js +68 -20
  123. package/dist/commands/stack-up.js.map +1 -1
  124. package/dist/commands/status.d.ts +5 -1
  125. package/dist/commands/status.d.ts.map +1 -1
  126. package/dist/commands/status.js +134 -46
  127. package/dist/commands/status.js.map +1 -1
  128. package/dist/commands/team-boot-controller.d.ts.map +1 -1
  129. package/dist/commands/team-boot-controller.js +3 -1
  130. package/dist/commands/team-boot-controller.js.map +1 -1
  131. package/dist/commands/team.d.ts.map +1 -1
  132. package/dist/commands/team.js +28 -6
  133. package/dist/commands/team.js.map +1 -1
  134. package/dist/commands/telemetry.d.ts +3 -1
  135. package/dist/commands/telemetry.d.ts.map +1 -1
  136. package/dist/commands/telemetry.js +9 -3
  137. package/dist/commands/telemetry.js.map +1 -1
  138. package/dist/commands/up.d.ts +6 -3
  139. package/dist/commands/up.d.ts.map +1 -1
  140. package/dist/commands/up.js +230 -40
  141. package/dist/commands/up.js.map +1 -1
  142. package/dist/commands/use.d.ts.map +1 -1
  143. package/dist/commands/use.js +4 -1
  144. package/dist/commands/use.js.map +1 -1
  145. package/dist/commands/watch.d.ts.map +1 -1
  146. package/dist/commands/watch.js +11 -5
  147. package/dist/commands/watch.js.map +1 -1
  148. package/dist/console/mesh.d.ts +6 -1
  149. package/dist/console/mesh.d.ts.map +1 -1
  150. package/dist/console/mesh.js +18 -2
  151. package/dist/console/mesh.js.map +1 -1
  152. package/dist/help.d.ts.map +1 -1
  153. package/dist/help.js +14 -6
  154. package/dist/help.js.map +1 -1
  155. package/dist/index.d.ts.map +1 -1
  156. package/dist/index.js +9 -2
  157. package/dist/index.js.map +1 -1
  158. package/dist/lib/completion-install.d.ts.map +1 -1
  159. package/dist/lib/completion-install.js +78 -11
  160. package/dist/lib/completion-install.js.map +1 -1
  161. package/dist/lib/control.d.ts +6 -0
  162. package/dist/lib/control.d.ts.map +1 -1
  163. package/dist/lib/control.js +16 -1
  164. package/dist/lib/control.js.map +1 -1
  165. package/dist/lib/default-persona.js +1 -1
  166. package/dist/lib/default-persona.js.map +1 -1
  167. package/dist/lib/endpoint-errors.d.ts +2 -0
  168. package/dist/lib/endpoint-errors.d.ts.map +1 -1
  169. package/dist/lib/endpoint-errors.js +13 -7
  170. package/dist/lib/endpoint-errors.js.map +1 -1
  171. package/dist/lib/interrupt-notice.d.ts +5 -0
  172. package/dist/lib/interrupt-notice.d.ts.map +1 -0
  173. package/dist/lib/interrupt-notice.js +23 -0
  174. package/dist/lib/interrupt-notice.js.map +1 -0
  175. package/dist/lib/isolated-broker.d.ts +5 -0
  176. package/dist/lib/isolated-broker.d.ts.map +1 -1
  177. package/dist/lib/isolated-broker.js +36 -0
  178. package/dist/lib/isolated-broker.js.map +1 -1
  179. package/dist/lib/legacy-start.d.ts +17 -0
  180. package/dist/lib/legacy-start.d.ts.map +1 -0
  181. package/dist/lib/legacy-start.js +66 -0
  182. package/dist/lib/legacy-start.js.map +1 -0
  183. package/dist/lib/manager-choice.d.ts +21 -0
  184. package/dist/lib/manager-choice.d.ts.map +1 -0
  185. package/dist/lib/manager-choice.js +57 -0
  186. package/dist/lib/manager-choice.js.map +1 -0
  187. package/dist/lib/manifest/resolve.d.ts.map +1 -1
  188. package/dist/lib/manifest/resolve.js +9 -1
  189. package/dist/lib/manifest/resolve.js.map +1 -1
  190. package/dist/lib/missing-flags.d.ts +1 -1
  191. package/dist/lib/missing-flags.d.ts.map +1 -1
  192. package/dist/lib/missing-flags.js +2 -2
  193. package/dist/lib/missing-flags.js.map +1 -1
  194. package/dist/lib/persona-files.d.ts +2 -0
  195. package/dist/lib/persona-files.d.ts.map +1 -1
  196. package/dist/lib/persona-files.js +81 -23
  197. package/dist/lib/persona-files.js.map +1 -1
  198. package/dist/lib/restore.d.ts +27 -1
  199. package/dist/lib/restore.d.ts.map +1 -1
  200. package/dist/lib/restore.js +106 -14
  201. package/dist/lib/restore.js.map +1 -1
  202. package/dist/lib/service-process.d.ts +12 -2
  203. package/dist/lib/service-process.d.ts.map +1 -1
  204. package/dist/lib/service-process.js +25 -2
  205. package/dist/lib/service-process.js.map +1 -1
  206. package/dist/lib/setup-log.js +1 -1
  207. package/dist/lib/setup-log.js.map +1 -1
  208. package/dist/lib/stack-journal.d.ts +22 -1
  209. package/dist/lib/stack-journal.d.ts.map +1 -1
  210. package/dist/lib/stack-journal.js +104 -23
  211. package/dist/lib/stack-journal.js.map +1 -1
  212. package/dist/lib/stdout-owner.d.ts +7 -3
  213. package/dist/lib/stdout-owner.d.ts.map +1 -1
  214. package/dist/lib/stdout-owner.js +17 -4
  215. package/dist/lib/stdout-owner.js.map +1 -1
  216. package/dist/lib/store-dir.d.ts +8 -0
  217. package/dist/lib/store-dir.d.ts.map +1 -0
  218. package/dist/lib/store-dir.js +50 -0
  219. package/dist/lib/store-dir.js.map +1 -0
  220. package/dist/lib/team-additive-attempt.d.ts +1 -1
  221. package/dist/lib/team-fresh.d.ts +11 -1
  222. package/dist/lib/team-fresh.d.ts.map +1 -1
  223. package/dist/lib/team-fresh.js +24 -9
  224. package/dist/lib/team-fresh.js.map +1 -1
  225. package/dist/lib/transient.d.ts +2 -1
  226. package/dist/lib/transient.d.ts.map +1 -1
  227. package/dist/lib/transient.js +9 -3
  228. package/dist/lib/transient.js.map +1 -1
  229. package/dist/render.d.ts +4 -2
  230. package/dist/render.d.ts.map +1 -1
  231. package/dist/render.js +23 -16
  232. package/dist/render.js.map +1 -1
  233. package/dist/ui.d.ts +4 -2
  234. package/dist/ui.d.ts.map +1 -1
  235. package/dist/ui.js +13 -8
  236. package/dist/ui.js.map +1 -1
  237. package/dist/view/mesh-view.d.ts +3 -0
  238. package/dist/view/mesh-view.d.ts.map +1 -1
  239. package/dist/view/mesh-view.js +10 -0
  240. package/dist/view/mesh-view.js.map +1 -1
  241. package/package.json +4 -4
@@ -1,25 +1,33 @@
1
1
  import { spawnSync } from "node:child_process";
2
- import { lstatSync, mkdtempSync, readFileSync, realpathSync, rmSync, statSync, unlinkSync } from "node:fs";
2
+ import { accessSync, constants, existsSync, lstatSync, mkdtempSync, readFileSync, realpathSync, rmSync, statSync, unlinkSync } from "node:fs";
3
3
  import { tmpdir } from "node:os";
4
4
  import { basename, dirname, join } from "node:path";
5
- import { acquireLock, agentFilePath, assertValidName, hardenPrivate, mkSecretDir, parseAgentFileSource, saveAgentFile, writeSecretFile, writeSecretFileAtomic, } from "@cotal-ai/core";
6
- import { cachedPreferences, CommandFailure, inputDisabledByFlag, isWorkspaceTargetError, resolveMeshTarget, resolvePreference, targetErrorCode, workspaceErrorParts, } from "@cotal-ai/workspace";
5
+ import { acquireLock, agentFilePath, assertValidName, hardenPrivate, MAX_NAME_LENGTH, mkSecretDir, parseAgentFileSource, saveAgentFile, writeSecretFile, writeSecretFileAtomic, } from "@cotal-ai/core";
6
+ import { cachedPreferences, CommandFailure, inputDisabledByFlag, isCommandFailure, isGenuineSpace, isWorkspaceTargetError, loadMeshes, resolveMeshTarget, resolvePreference, targetErrorCode, workspaceErrorParts, } from "@cotal-ai/workspace";
7
7
  /** Resolve once, without inventing a broker for a prepared space or falling back to the cwd. */
8
8
  export function personaCatalog(values) {
9
9
  try {
10
10
  const target = resolveMeshTarget(process.cwd(), { ...values, readOnly: true });
11
+ // A `--server` that no registration names resolves to this folder's project, as launch does.
12
+ // Outside a project there is no catalog there, and the folder is not made into one.
13
+ if (values.server !== undefined && values.space === undefined && !loadMeshes().some((m) => m.server === values.server) && !isGenuineSpace(target.root))
14
+ throw new CommandFailure("refused", "TARGET_NOT_FOUND", `no space registered here is at ${values.server}, and this folder is not a space's project`, {
15
+ remedy: "name a prepared or registered space with `--space <name>`, or run this in its project folder", target: { server: values.server },
16
+ });
11
17
  return catalogAt(target.root, target.space);
12
18
  }
13
19
  catch (error) {
14
20
  if (!isWorkspaceTargetError(error))
15
21
  throw error;
16
- if (error.code === "not-started" && !values.server && error.details.root && error.details.space)
22
+ if (error.code === "not-started" && !values.server && error.details.root && error.details.space && !error.details.rootMissing)
17
23
  return catalogAt(error.details.root, error.details.space);
18
24
  const { message, remedy } = workspaceErrorParts({ kind: "target", error });
19
25
  // Every caller selects with --space, and some take no --server, so the shared remedy's
20
26
  // `--server` would name a flag the command refuses. A prepared space is selectable by name.
21
- const next = error.code === "no-meshes" ? "run `cotal up` in a project, or name a prepared or registered space with `--space <name>`" : remedy;
22
- throw new CommandFailure("refused", targetErrorCode(error.code), message, next ? { remedy: next } : {});
27
+ // The catalog is read offline, so no running mesh is not the reason: nothing selects a space.
28
+ const none = error.code === "no-meshes";
29
+ const next = none ? "run `cotal up` in a project, or name a prepared or registered space with `--space <name>`" : remedy;
30
+ throw new CommandFailure("refused", targetErrorCode(error.code), none ? "no space is selected, and this folder is not a space's project" : message, next ? { remedy: next } : {});
23
31
  }
24
32
  }
25
33
  function catalogAt(root, space) {
@@ -32,15 +40,24 @@ function catalogAt(root, space) {
32
40
  throw new CommandFailure("refused", "TARGET_UNAVAILABLE", "the selected persona catalog root is unavailable");
33
41
  }
34
42
  }
35
- export function personaPath(root, name) {
43
+ /** Why `name` cannot name a persona, or undefined when it can. */
44
+ export function personaNameProblem(name) {
36
45
  if (!/^[A-Za-z0-9_-]+$/.test(name))
37
- throw new CommandFailure("refused", "USAGE_INVALID", "persona names use letters, digits, '_' or '-'");
46
+ return `persona names use letters, digits, '_' or '-', up to ${MAX_NAME_LENGTH} characters`;
47
+ if (name.length > MAX_NAME_LENGTH)
48
+ return `persona names are at most ${MAX_NAME_LENGTH} characters; this one has ${name.length}`;
38
49
  try {
39
50
  assertValidName(name);
40
51
  }
41
- catch {
42
- throw new CommandFailure("refused", "USAGE_INVALID", "invalid persona name");
52
+ catch (error) {
53
+ return error.message;
43
54
  }
55
+ return undefined;
56
+ }
57
+ export function personaPath(root, name) {
58
+ const problem = personaNameProblem(name);
59
+ if (problem)
60
+ throw new CommandFailure("refused", "USAGE_INVALID", problem);
44
61
  return agentFilePath(root, name);
45
62
  }
46
63
  /** Only absence is absent. Unreadable and non-regular sources refuse rather than becoming empty. */
@@ -83,15 +100,28 @@ export function validatePersona(bytes, path, name) {
83
100
  function sameSource(a, b) {
84
101
  return a === undefined ? b === undefined : b !== undefined && a.ino === b.ino && a.dev === b.dev && a.mtimeMs === b.mtimeMs && a.bytes.equals(b.bytes);
85
102
  }
103
+ /** A catalog folder its owner made read-only is refused as it is: hardening it would undo the lock. */
104
+ function assertCatalogWritable(dir) {
105
+ if (!existsSync(dir))
106
+ return;
107
+ try {
108
+ accessSync(dir, constants.W_OK);
109
+ }
110
+ catch {
111
+ throw new CommandFailure("refused", "PERMISSION_DENIED", `the persona catalog ${dir} is not writable; nothing was changed`, { remedy: `make it writable with \`chmod u+w ${dir}\` to change its personas` });
112
+ }
113
+ }
86
114
  /** Shared by canonical and legacy CLI writes only. Manager and external writers do not take this lock. */
87
115
  export function commitPersona(path, expected, bytes) {
88
- mkSecretDir(dirname(path));
116
+ const dir = dirname(path);
117
+ assertCatalogWritable(dir);
118
+ mkSecretDir(dir);
89
119
  const lockPath = join(realpathSync(dirname(path)), `.${basename(path)}.lock`);
90
120
  const lock = acquireLock(lockPath, { label: "local persona write", onTimeout: () => new CommandFailure("refused", "CONFLICT", "another local persona write holds the catalog lock") });
91
121
  try {
92
122
  const current = readPersonaSource(path);
93
123
  if (!sameSource(expected, current))
94
- throw new CommandFailure("refused", "CONFLICT", `persona changed while the operation was open: ${path}`, { remedy: "read the current definition and retry" });
124
+ throw new CommandFailure("refused", "CONFLICT", `persona ${current === undefined ? "was removed" : "changed"} while the operation was open: ${path}`, { remedy: current === undefined ? "list the catalog with `cotal persona` and retry" : "read the current definition and retry" });
95
125
  if (bytes === undefined)
96
126
  unlinkSync(path);
97
127
  else
@@ -101,24 +131,35 @@ export function commitPersona(path, expected, bytes) {
101
131
  lock.release();
102
132
  }
103
133
  }
104
- /** Own a private draft and remove only that draft. A cleanup failure is not a successful operation. */
105
- function withDraft(name, action) {
134
+ /** Own a private draft and remove only that draft. A cleanup failure is not a successful operation.
135
+ * A failure that `keep` accepts leaves the draft in place, because it holds work that was not saved. */
136
+ function withDraft(name, action, keep) {
106
137
  const dir = mkdtempSync(join(tmpdir(), "cotal-persona-"));
138
+ let kept = false;
107
139
  try {
108
140
  hardenPrivate(dir, "dir");
109
141
  return action(join(dir, `${name}.md`));
110
142
  }
143
+ catch (error) {
144
+ kept = keep?.(error) === true;
145
+ throw error;
146
+ }
111
147
  finally {
112
- try {
113
- rmSync(dir, { recursive: true });
114
- }
115
- catch {
116
- throw new CommandFailure("partial", "OPERATION_PARTIAL", `cannot remove private persona draft: ${dir}`, { changed: [{ kind: "private-draft", path: dir }], remedy: "remove the private draft after reviewing the operation outcome" });
148
+ if (!kept) {
149
+ try {
150
+ rmSync(dir, { recursive: true });
151
+ }
152
+ catch {
153
+ throw new CommandFailure("partial", "OPERATION_PARTIAL", `cannot remove private persona draft: ${dir}`, { changed: [{ kind: "private-draft", path: dir }], remedy: "remove the private draft after reviewing the operation outcome" });
154
+ }
117
155
  }
118
156
  }
119
157
  }
120
158
  /** Use the existing serializer for flag-built definitions; file inputs keep their original bytes. */
121
159
  export function serializePersona(def) {
160
+ for (const [flag, value] of [["--role", def.role], ["--model", def.model]])
161
+ if (value !== undefined && /[\u0000-\u001f\u007f]/u.test(value))
162
+ throw new CommandFailure("refused", "USAGE_INVALID", `${flag} takes a label without control characters`);
122
163
  return withDraft(def.name, path => {
123
164
  try {
124
165
  writeSecretFile(path, "");
@@ -138,19 +179,36 @@ export function editPersona(path, name, catalog, json = false) {
138
179
  throw new CommandFailure("refused", "USAGE_INVALID", "persona edit opens an editor, --no-input forbids one, as does --json", { remedy: "edit interactively without --json or --no-input" });
139
180
  const source = requirePersonaSource(path);
140
181
  validatePersona(source.bytes, path);
182
+ assertCatalogWritable(dirname(path));
141
183
  const editor = resolvePreference("editor", { preferences: cachedPreferences(), space: catalog.space }).value;
142
184
  if (!editor)
143
185
  throw new CommandFailure("refused", "DEPENDENCY_UNAVAILABLE", "no editor is set", { remedy: "set VISUAL or EDITOR, or run `cotal config set editor vim`" });
144
- const edited = withDraft(name, draft => {
186
+ withDraft(name, draft => {
145
187
  writeSecretFile(draft, source.bytes);
146
188
  const quoted = process.platform === "win32" ? `"${draft.replaceAll('"', '""')}"` : `'${draft.replaceAll("'", "'\\''")}'`;
147
189
  const result = spawnSync(`${editor} ${quoted}`, { shell: true, stdio: "inherit" });
190
+ // A POSIX shell exits 127 when it finds no such command and 126 when it cannot run it: the editor
191
+ // is missing, as it is when none is set, and nothing was edited.
192
+ if (process.platform !== "win32" && !result.error && (result.status === 127 || result.status === 126))
193
+ throw new CommandFailure("refused", "DEPENDENCY_UNAVAILABLE", `the editor ${JSON.stringify(editor)} ${result.status === 127 ? "was not found" : "could not be run"} - not saved`, {
194
+ remedy: "set VISUAL or EDITOR to an installed editor, or run `cotal config set editor vim`; the value runs as a shell command, so quote a path that holds spaces",
195
+ });
148
196
  if (result.error || result.status !== 0)
149
197
  throw new CommandFailure("failed", "OPERATION_FAILED", `editor ${result.signal ? `ended on ${result.signal}` : `exited with status ${result.status}`} - not saved`);
150
198
  const edited = requirePersonaSource(draft).bytes;
151
199
  validatePersona(edited, path);
152
- return edited;
153
- });
154
- commitPersona(path, source, edited);
200
+ try {
201
+ commitPersona(path, source, edited);
202
+ }
203
+ catch (error) {
204
+ if (!isCommandFailure(error) || error.code !== "CONFLICT")
205
+ throw error;
206
+ // The edit was not saved, so the draft stays and the refusal says where it is.
207
+ const removed = readPersonaSource(path) === undefined;
208
+ throw new CommandFailure("refused", "CONFLICT", error.message, {
209
+ remedy: `your edit is kept in ${draft}; ${removed ? `restore it with \`cotal persona create ${name} --file ${draft}\`` : `compare it with \`cotal persona show ${name}\`, then edit again`}, and remove ${dirname(draft)} when you are done`,
210
+ });
211
+ }
212
+ }, (error) => isCommandFailure(error) && error.code === "CONFLICT");
155
213
  }
156
214
  //# sourceMappingURL=persona-files.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"persona-files.js","sourceRoot":"","sources":["../../src/lib/persona-files.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,MAAM,oBAAoB,CAAC;AAC/C,OAAO,EAAE,SAAS,EAAE,WAAW,EAAE,YAAY,EAAE,YAAY,EAAE,MAAM,EA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CAAC,MAAM,KAAK,CAAC;YACrC,MAAM,IAAI,cAAc,CAAC,QAAQ,EAAE,kBAAkB,EAAE,UAAU,MAAM,CAAC,MAAM,CAAC,CAAC,CAAC,YAAY,MAAM,CAAC,MAAM,EAAE,CAAC,CAAC,CAAC,sBAAsB,MAAM,CAAC,MAAM,EAAE,cAAc,CAAC,CAAC;QACtK,MAAM,MAAM,GAAG,oBAAoB,CAAC,KAAK,CAAC,CAAC,KAAK,CAAC;QACjD,eAAe,CAAC,MAAM,EAAE,IAAI,CAAC,CAAC;QAC9B,IAAI,CAAC;YAAC,aAAa,CAAC,IAAI,EAAE,MAAM,EAAE,MAAM,CAAC,CAAC;QAAC,CAAC;QAC5C,OAAO,KAAK,EAAE,CAAC;YACb,IAAI,CAAC,gBAAgB,CAAC,KAAK,CAAC,IAAI,KAAK,CAAC,IAAI,KAAK,UAAU;gBAAE,MAAM,KAAK,CAAC;YACvE,+EAA+E;YAC/E,MAAM,OAAO,GAAG,iBAAiB,CAAC,IAAI,CAAC,KAAK,SAAS,CAAC;YACtD,MAAM,IAAI,cAAc,CAAC,SAAS,EAAE,UAAU,EAAE,KAAK,CAAC,OAAO,EAAE;gBAC7D,MAAM,EAAE,wBAAwB,KAAK,KAAK,OAAO,CAAC,CAAC,CAAC,0CAA0C,IAAI,WAAW,KAAK,IAAI,CAAC,CAAC,CAAC,wCAAwC,IAAI,qBAAqB,gBAAgB,OAAO,CAAC,KAAK,CAAC,oBAAoB;aAC7O,CAAC,CAAC;QACL,CAAC;IACH,CAAC,EAAE,CAAC,KAAK,EAAE,EAAE,CAAC,gBAAgB,CAAC,KAAK,CAAC,IAAI,KAAK,CAAC,IAAI,KAAK,UAAU,CAAC,CAAC;AACtE,CAAC"}
@@ -1,4 +1,4 @@
1
- import { type CommitIntentRecord, type JsonValue, type ManagerCommitEvidence, type ManagerFinalizeEvidence, type MaintenanceLock, type MaintenanceReadyRecord, type ProcessOwner, type RestoreActiveRecord, type RestoreDegradedRecord, type RestoreListenerProof, type RestoreManagerCommittedRecord } from "@cotal-ai/workspace";
1
+ import { CommandFailure, type CommitIntentRecord, type JsonValue, type ManagerCommitEvidence, type ManagerFinalizeEvidence, type MaintenanceLock, type MaintenanceReadyRecord, type ProcessOwner, type RestoreActiveRecord, type RestoreDegradedRecord, type RestoreListenerProof, type RestoreManagerCommittedRecord, type StoreIdentity } from "@cotal-ai/workspace";
2
2
  export interface RestoreFlags {
3
3
  restore: string;
4
4
  "restore-only"?: string;
@@ -47,9 +47,35 @@ export declare function isManagerFinalizeResult(value: unknown, attemptId: strin
47
47
  attemptId: string;
48
48
  state: "active";
49
49
  };
50
+ /** Where a preserved store is relative to the path its journal recorded. `moved` means that path is
51
+ * gone and this root's own `.cotal/nats` is the same store, by device, inode and generation, so the
52
+ * folder was moved after the cut and `recordedRoot` is where it was. Resume and restore use the
53
+ * recorded path, so moving the folder back is what lets them run. */
54
+ export declare function preservedSourceState(root: string, source: StoreIdentity): {
55
+ state: "present";
56
+ } | {
57
+ state: "missing";
58
+ } | {
59
+ state: "moved";
60
+ recordedRoot: string;
61
+ store: string;
62
+ };
63
+ /** The refusal for a folder moved after its state was preserved: where the journal recorded the
64
+ * store, where it is now, and the folder to move back to before `then` runs there. */
65
+ export declare function movedFolderRefusal(root: string, space: string, recordedStore: string, moved: {
66
+ recordedRoot: string;
67
+ store: string;
68
+ }, then: string): CommandFailure;
50
69
  /** The step that moves a full restore attempt on from `state`, for a refusal to name. A committed or
51
70
  * degraded attempt goes forward through bare `up`, which continues it. */
52
71
  export declare function restoreNextStep(state: string, attemptId: string): string;
72
+ /** The refusal while a restore's or backup's claim is not provably stale: what holds it, until
73
+ * when, and when `backup recover` can release it. The refusing command changed nothing. */
74
+ export declare function heldClaim(root: string, attemptId: string, claim: {
75
+ readonly deadline: string;
76
+ readonly coordinator: ProcessOwner;
77
+ readonly owners: readonly ProcessOwner[];
78
+ }, command: string, assessment: "live" | "ambiguous"): CommandFailure;
53
79
  /** The restore attempt the root's journal holds, with the step that moves it on, so a failure can
54
80
  * name the full attempt a recovery command needs. An unreadable journal names none. */
55
81
  export declare function heldRestoreAttempt(root: string): {
@@ -1 +1 @@
1
- {"version":3,"file":"restore.d.ts","sourceRoot":"","sources":["../../src/lib/restore.ts"],"names":[],"mappings":"AA6CA,OAAO,EAyBL,KAAK,kBAAkB,EACvB,KAAK,SAAS,EACd,KAAK,qBAAqB,EAC1B,KAAK,uBAAuB,EAC5B,KAAK,eAAe,EACpB,KAAK,sBAAsB,EAC3B,KAAK,YAAY,EACjB,KAAK,mBAAmB,EACxB,KAAK,qBAAqB,EAC1B,KAAK,oBAAoB,EACzB,KAAK,6BAA6B,EACnC,MAAM,qBAAqB,CAAC;AAW7B,MAAM,WAAW,YAAY;IAC3B,OAAO,EAAE,MAAM,CAAC;IAChB,cAAc,CAAC,EAAE,MAAM,CAAC;IACxB,uBAAuB,CAAC,EAAE,OAAO,CAAC;IAClC,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,MAAM,CAAC,EAAE,OAAO,CAAC;IACjB,IAAI,CAAC,EAAE,OAAO,CAAC;IACf,WAAW,CAAC,EAAE,OAAO,CAAC;IACtB,GAAG,CAAC,EAAE,MAAM,CAAC;IACb;wFACoF;IACpF,yBAAyB,CAAC,EAAE,OAAO,CAAC;CACrC;AAED,MAAM,WAAW,eAAe;IAC9B,IAAI,EAAE,MAAM,CAAC;IACb,SAAS,EAAE,MAAM,CAAC;IAClB,UAAU,EAAE,MAAM,CAAC;IACnB,KAAK,EAAE,MAAM,CAAC;IACd,IAAI,EAAE,sBAAsB,CAAC,MAAM,CAAC,CAAC;IACrC,MAAM,EAAE,MAAM,CAAC;IACf,IAAI,EAAE,MAAM,CAAC;IACb,OAAO,EAAE,MAAM,CAAC;IAChB,QAA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C,IAAI,EAAE,MAAM,EAAE,SAAS,EAAE,MAAM,EAAE,KAAK,EAAE;IAAE,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAC;IAAC,QAAQ,CAAC,WAAW,EAAE,YAAY,CAAC;IAAC,QAAQ,CAAC,MAAM,EAAE,SAAS,YAAY,EAAE,CAAA;CAAE,EAAE,OAAO,EAAE,MAAM,EAAE,UAAU,EAAE,MAAM,GAAG,WAAW,GAAG,cAAc,CAahP;AAED;wFACwF;AACxF,wBAAgB,kBAAkB,CAAC,IAAI,EAAE,MAAM,GAAG;IAAE,SAAS,EAAE,MAAM,CAAC;IAAC,YAAY,EAAE,MAAM,CAAC;IAAC,MAAM,EAAE,MAAM,CAAA;CAAE,GAAG,SAAS,CAKxH;AAUD;2EAC2E;AAC3E,wBAAsB,cAAc,CAAC,IAAI,EAAE,MAAM,EAAE,KAAK,EAAE,YAAY,EAAE,QAAQ,CAAC,EAAE,CAAC,IAAI,EAAE,MAAM,KAAK,IAAI,GAAG,OAAO,CAAC,eAAe,CAAC,CAsUnI;AAYD,wBAAgB,yBAAyB,CACvC,QAAQ,EAAE,eAAe,EACzB,aAAa,EAAE,uBAAuB,EACtC,QAAQ,CAAC,EAAE,eAAe,GACzB,IAAI,CAgCN;AAED,wBAAgB,kCAAkC,CAChD,QAAQ,EAAE,eAAe,EACzB,QAAQ,EAAE,qBAAqB,EAC/B,QAAQ,CAAC,EAAE,eAAe,GACzB,IAAI,CAaN;AAED,wBAAgB,2BAA2B,CACzC,IAAI,EAAE,MAAM,EACZ,SAAS,EAAE,MAAM,EACjB,MAAM,EAAE,MAAM,EACd,QAAQ,CAAC,EAAE,eAAe,GACzB,IAAI,CAaN"}
@@ -5,10 +5,12 @@ import { basename, dirname, isAbsolute, join, relative, resolve } from "node:pat
5
5
  import { jetstreamManager } from "@nats-io/jetstream";
6
6
  import { Kvm } from "@nats-io/kv";
7
7
  import { canonicalBackupStreamConfig, consumerConfigFromCheckpoint, deliveryBucket, downloadStreamSnapshot, finalizeStreamRestore, hardenPrivate, initiateStreamRestore, LEASE_TTL_MS, managerBucket, MANAGER_LEASE_TTL_MS, membershipBucket, MEMBERSHIP_MAX_BYTES, PRESENCE_STORAGE, presenceBucket, recordsBucket, recreateConsumerCheckpoint, spaceBackupInventory, uploadStreamRestoreChunk, validateSpaceAuth, validateSpaceBackupInventory, validateBackupStreamState, validateCanonicalBackupStreamConfig, createEndpointStreams, ensureArtifactStore, hardenedAuthorityStreamNames, } from "@cotal-ai/core";
8
- import { CommandFailure, acquireMaintenanceLock, assessRestoreClaim, bindRestoreListener, bindRestoreTarget, cutController, getSpaceAuth, markRestoreActive, settleTokenHandoff, markRestoreDegraded, moveSamePathRestoreSource, prepareAlternateRestore, prepareMissingSourceRestore, prepareSamePathRestore, readMaintenanceJournal, readMaintenanceResumeDocument, recordRestoreAttemptResources, recordRestoreManagerCommit, replaceDeadRestoreListener, repairRestoreDegradedToActive, releaseMaintenanceLock, workspaceSecretStore, writeRestoreCommitIntent, } from "@cotal-ai/workspace";
8
+ import { CommandFailure, acquireMaintenanceLock, assessRestoreClaim, bindRestoreListener, bindRestoreTarget, cutController, getSpaceAuth, markRestoreActive, settleTokenHandoff, markRestoreDegraded, moveSamePathRestoreSource, prepareAlternateRestore, prepareMissingSourceRestore, prepareSamePathRestore, localProcessOwnerStatus, readMaintenanceJournal, readMaintenanceResumeDocument, recordRestoreAttemptResources, recordRestoreManagerCommit, replaceDeadRestoreListener, repairRestoreDegradedToActive, releaseMaintenanceLock, workspaceSecretStore, writeRestoreCommitIntent, readStoreIdentity, } from "@cotal-ai/workspace";
9
9
  import { readStagedCheckpoints, stageArtifact } from "./backup-artifact.js";
10
10
  import { authorityFingerprint } from "./maintenance-files.js";
11
- import { connectIsolatedBroker, ensurePrivateAttemptsDir, startIsolatedBroker, sweepAttemptResidue } from "./isolated-broker.js";
11
+ import { attemptProcessesGone, connectIsolatedBroker, ensurePrivateAttemptsDir, startIsolatedBroker, sweepAttemptResidue } from "./isolated-broker.js";
12
+ import { noticeOnInterrupt } from "./interrupt-notice.js";
13
+ import { acquireStackOperationLock } from "./stack-journal.js";
12
14
  import { admitAndRestoreSeatCheckpoints } from "./seat-resume.js";
13
15
  import { assertControllerRestorable, reconfigureControllerBroker, rollbackRestoreWithBroker } from "./controller-restore.js";
14
16
  import { assertControllerCoupling, newControllerAttemptLaunch } from "./controller-resume.js";
@@ -167,6 +169,27 @@ function contains(parent, child) {
167
169
  const separator = process.platform === "win32" ? "\\" : "/";
168
170
  return path === "" || (path !== ".." && !path.startsWith(`..${separator}`) && !isAbsolute(path));
169
171
  }
172
+ /** An explicit `--store-dir` names the directory a restore creates and owns for its rollback, so it
173
+ * must not exist yet and its parent must. Either mistake is a usage refusal before anything is
174
+ * staged. The preserved source itself is the same-path restore. */
175
+ function assertNewStorePath(target, source) {
176
+ const present = (path) => {
177
+ try {
178
+ lstatSync(path);
179
+ return true;
180
+ }
181
+ catch (error) {
182
+ if (error.code === "ENOENT")
183
+ return false;
184
+ throw error;
185
+ }
186
+ };
187
+ const remedy = "name a --store-dir path that does not exist yet, inside an existing directory; the restore creates it";
188
+ if (!present(dirname(target)))
189
+ throw new CommandFailure("refused", "USAGE_INVALID", `the --store-dir parent ${dirname(target)} does not exist; nothing was restored`, { target: { storeDir: target }, remedy });
190
+ if (target !== source && present(target))
191
+ throw new CommandFailure("refused", "USAGE_INVALID", `the --store-dir path ${target} already exists, and a restore creates its store directory itself; nothing was restored`, { target: { storeDir: target }, remedy });
192
+ }
170
193
  function assertRestoreTargetPath(source, artifact, attempts, target) {
171
194
  const canonicalTarget = canonicalFuturePath(target);
172
195
  if (canonicalTarget !== source && (contains(source, canonicalTarget) || contains(canonicalTarget, source)))
@@ -197,8 +220,9 @@ async function validateManifest(manifest, flags, ready, currentAuthority) {
197
220
  if (flags["restore-only"] === "registry" && manifest.selection !== "registry" &&
198
221
  !manifest.streams.some((entry) => entry.stream === spaceBackupInventory(manifest.space).registry[0]))
199
222
  throw new Error("artifact does not contain the registry component");
223
+ // Checked before any transition, so the preserved cut is unchanged: a refusal, not an unknown outcome.
200
224
  if (manifest.space !== ready.space)
201
- throw new Error(`backup belongs to space ${JSON.stringify(manifest.space)}, not ${JSON.stringify(ready.space)}`);
225
+ throw new CommandFailure("refused", "CONFLICT", `backup belongs to space ${JSON.stringify(manifest.space)}, not ${JSON.stringify(ready.space)}; the preserved cut was not changed`, { target: { space: ready.space, backupSpace: manifest.space }, remedy: `restore it on the root that preserved ${JSON.stringify(manifest.space)}, or use a backup of ${JSON.stringify(ready.space)}` });
202
226
  if (manifest.mode !== ready.mode)
203
227
  throw new Error(`backup auth mode ${manifest.mode} does not match preserved source mode ${ready.mode}`);
204
228
  if (flags.space && flags.space !== manifest.space)
@@ -453,15 +477,62 @@ function removeOwnedDirectory(path, identity) {
453
477
  }
454
478
  catch { /* absent or identity cannot be proven */ }
455
479
  }
480
+ /** Where a preserved store is relative to the path its journal recorded. `moved` means that path is
481
+ * gone and this root's own `.cotal/nats` is the same store, by device, inode and generation, so the
482
+ * folder was moved after the cut and `recordedRoot` is where it was. Resume and restore use the
483
+ * recorded path, so moving the folder back is what lets them run. */
484
+ export function preservedSourceState(root, source) {
485
+ // Only a confirmed absence is classified here; any other lstat failure is left to the store checks.
486
+ try {
487
+ lstatSync(source.path);
488
+ return { state: "present" };
489
+ }
490
+ catch (error) {
491
+ if (error.code !== "ENOENT")
492
+ return { state: "present" };
493
+ }
494
+ if (basename(source.path) !== "nats" || basename(dirname(source.path)) !== ".cotal")
495
+ return { state: "missing" };
496
+ const recordedRoot = dirname(dirname(source.path));
497
+ let here;
498
+ try {
499
+ here = readStoreIdentity(join(root, ".cotal", "nats"));
500
+ }
501
+ catch {
502
+ return { state: "missing" };
503
+ }
504
+ return here.dev === source.dev && here.ino === source.ino && here.generation === source.generation ? { state: "moved", recordedRoot, store: here.path } : { state: "missing" };
505
+ }
506
+ /** The refusal for a folder moved after its state was preserved: where the journal recorded the
507
+ * store, where it is now, and the folder to move back to before `then` runs there. */
508
+ export function movedFolderRefusal(root, space, recordedStore, moved, then) {
509
+ return new CommandFailure("refused", "CONFLICT", `this folder was moved from ${moved.recordedRoot} after its state was preserved: the maintenance journal records the preserved store at ${recordedStore}, and that store is now ${moved.store}`, { target: { root, space, recordedRoot: moved.recordedRoot, recordedStore, store: moved.store }, remedy: `move this folder back to ${moved.recordedRoot}, then ${then} there` });
510
+ }
456
511
  /** The step that moves a full restore attempt on from `state`, for a refusal to name. A committed or
457
512
  * degraded attempt goes forward through bare `up`, which continues it. */
458
513
  export function restoreNextStep(state, attemptId) {
459
514
  if (state === "restore-ready")
460
- return `roll the pre-commit attempt back: review cotal backup recover ${attemptId} --dry-run, then run it without --dry-run`;
515
+ return `roll the pre-commit attempt back with cotal backup recover ${attemptId} --yes; preview it first with --dry-run`;
461
516
  if (state === "active")
462
- return `the restore completed: review cotal backup cleanup-fallback ${attemptId} --dry-run, then run it without --dry-run to retire its journal`;
517
+ return `the restore completed: retire its journal with cotal backup cleanup-fallback ${attemptId} --yes; preview it first with --dry-run`;
463
518
  return `recover forward with bare cotal up from this root, which continues attempt ${attemptId}; fallback cleanup follows once it is active`;
464
519
  }
520
+ /** The refusal while a restore's or backup's claim is not provably stale: what holds it, until
521
+ * when, and when `backup recover` can release it. The refusing command changed nothing. */
522
+ export function heldClaim(root, attemptId, claim, command, assessment) {
523
+ const { coordinator, owners, deadline } = claim, kind = attemptId.startsWith("backup-") ? "backup" : "restore";
524
+ const running = owners.filter((owner) => localProcessOwnerStatus(owner) === "alive").map((owner) => owner.pid);
525
+ const coordinatorRuns = localProcessOwnerStatus(coordinator) === "alive";
526
+ const recover = `cotal backup recover ${attemptId} --yes`;
527
+ const [holder, remedy] = assessment === "ambiguous"
528
+ ? [`its processes on host ${coordinator.host} cannot be proven gone from this host`, `prove its ${kind} process and brokers on ${coordinator.host} have exited, then run ${recover}`]
529
+ : coordinatorRuns
530
+ ? [`its ${kind} process ${coordinator.pid} is still running`, `wait for that ${kind} to finish; if it was stopped, run ${recover} once process ${coordinator.pid} has exited`]
531
+ : running.length
532
+ ? [`its ${kind} process ${coordinator.pid} has exited, and its brokers (pid ${running.join(", ")}) are still stopping`, `run ${recover} again once they have exited`]
533
+ : [`its ${kind} process ${coordinator.pid} has exited, but a broker it started cannot be proven gone`, `run ${recover} after ${deadline}`];
534
+ return new CommandFailure("refused", "LIFECYCLE_BLOCKED", `${command} is refused: ${kind} attempt ${attemptId} holds this root until ${deadline}, and ${holder}; nothing was changed`, { target: { root, attemptId, deadline, holderPid: coordinator.pid }, remedy });
535
+ }
465
536
  /** The restore attempt the root's journal holds, with the step that moves it on, so a failure can
466
537
  * name the full attempt a recovery command needs. An unreadable journal names none. */
467
538
  export function heldRestoreAttempt(root) {
@@ -497,7 +568,7 @@ export async function prepareRestore(root, flags, progress) {
497
568
  // directory, so a refused restore leaves the folder as it found it and `up` there sees no state.
498
569
  if (!readMaintenanceJournal(root))
499
570
  throw notRestorable(root, undefined);
500
- let lock = acquireMaintenanceLock(root);
571
+ let lock = acquireStackOperationLock(root);
501
572
  let staged;
502
573
  let transitioned = false;
503
574
  let targetBound = false;
@@ -516,20 +587,28 @@ export async function prepareRestore(root, flags, progress) {
516
587
  releaseMaintenanceLock(resourceLock);
517
588
  }
518
589
  };
590
+ // From here an interrupt leaves whatever this attempt journaled; the notice names it and its recovery.
591
+ const releaseNotice = noticeOnInterrupt(() => restoreInterruptNotice(root, attemptId));
519
592
  try {
520
593
  let journal = readMaintenanceJournal(root);
521
594
  if (journal?.state === "restore-ready") {
522
595
  // Never touch a live attempt: recover by rollback only once the recorded claim is provably
523
- // stale (deadline elapsed, coordinator/watchdogs/brokers all dead).
524
- const assessment = assessRestoreClaim(journal);
525
- if (assessment === "live")
526
- throw new Error(`restore attempt ${journal.restore.attemptId} is in progress (claim live until ${journal.claim.deadline}); retry after it completes or becomes provably stale`);
527
- if (assessment === "ambiguous")
528
- throw new Error(`restore attempt ${journal.restore.attemptId} owners cannot be proven dead; inspect the recorded coordinator, watchdog, and broker processes before recovery`);
529
- journal = rollbackRestoreWithBroker(lock);
596
+ // stale (every owner dead, and the deadline elapsed or every broker it started gone).
597
+ const unrecordedOwnersDead = attemptProcessesGone(root);
598
+ const assessment = assessRestoreClaim(journal, { unrecordedOwnersDead });
599
+ if (assessment !== "stale")
600
+ throw heldClaim(root, journal.restore.attemptId, journal.claim, "this restore", assessment);
601
+ journal = rollbackRestoreWithBroker(lock, { unrecordedOwnersDead });
530
602
  }
531
603
  if (!journal || journal.state !== "ready")
532
604
  throw notRestorable(root, journal);
605
+ // A preserved store gone from its recorded path either moved with this folder, which no restore
606
+ // here may replace, or is lost, which only --accept-missing-source restores over.
607
+ const source = preservedSourceState(root, journal.source);
608
+ if (source.state === "moved")
609
+ throw movedFolderRefusal(root, journal.space, journal.source.path, source, "run the restore");
610
+ if (source.state === "missing" && !flags["accept-missing-source"])
611
+ throw new CommandFailure("refused", "TARGET_NOT_FOUND", `the preserved store recorded at ${journal.source.path} is missing; the restore did not start`, { target: { root, space: journal.space, recordedStore: journal.source.path }, remedy: "if this folder was moved, move it back so that path exists again; pass --accept-missing-source only after verifying disaster recovery intent" });
533
612
  // A controller cut restores only through its recorded members,
534
613
  // checked here before staging, a claim or any store move. Its broker address is the cut's.
535
614
  const controller = cutController(journal.cut);
@@ -554,6 +633,8 @@ export async function prepareRestore(root, flags, progress) {
554
633
  if (contains(stageParent, artifactPath) || contains(artifactPath, stageParent))
555
634
  throw new Error("restore artifact must not overlap the maintenance attempt directory");
556
635
  targetPath = resolve(flags["store-dir"] ?? (controller ? journal.source.path : join(root, ".cotal", "nats")));
636
+ if (flags["store-dir"] !== undefined)
637
+ assertNewStorePath(targetPath, journal.source.path);
557
638
  assertRestoreTargetPath(journal.source.path, artifactPath, stageParent, targetPath);
558
639
  // The journal is ready with no live claim, and the artifact/target are proven disjoint from
559
640
  // the attempts directory: any attempts-dir content is dead-attempt residue.
@@ -619,7 +700,7 @@ export async function prepareRestore(root, flags, progress) {
619
700
  };
620
701
  if (!sourceExists) {
621
702
  if (!flags["accept-missing-source"])
622
- throw new Error("preserved source is missing; pass --accept-missing-source only after verifying disaster recovery intent");
703
+ throw new CommandFailure("refused", "TARGET_NOT_FOUND", `the preserved source ${journal.source.path} is missing; nothing was changed`, { target: { root, space: journal.space, source: journal.source.path }, remedy: "put the preserved store back at that path, or, once you have verified it is lost, repeat the restore with --accept-missing-source to rebuild it from this backup" });
623
704
  prepareMissingSourceRestore(lock, { attemptId, targetPath, claim });
624
705
  }
625
706
  else if (targetPath === journal.source.path) {
@@ -841,10 +922,21 @@ export async function prepareRestore(root, flags, progress) {
841
922
  throw error;
842
923
  }
843
924
  finally {
925
+ releaseNotice();
844
926
  if (lock)
845
927
  releaseMaintenanceLock(lock);
846
928
  }
847
929
  }
930
+ /** What an interrupted restore left, read from the journal at the moment of the signal. */
931
+ function restoreInterruptNotice(root, attemptId) {
932
+ const journal = readMaintenanceJournal(root);
933
+ const ours = journal !== undefined && "restore" in journal && journal.restore.attemptId === attemptId;
934
+ if (ours && journal.state === "restore-ready")
935
+ return `Interrupted: restore attempt ${attemptId} stopped before it committed, and nothing was restored.\nRoll it back with cotal backup recover ${attemptId} --yes, or run the restore again, which rolls it back first.`;
936
+ if (ours)
937
+ return `Interrupted: restore attempt ${attemptId} committed before it stopped. Continue it with bare cotal up from ${root}.`;
938
+ return `Interrupted: restore attempt ${attemptId} stopped before it claimed this root; nothing was restored.`;
939
+ }
848
940
  export function markPreparedRestoreActive(prepared, managerResult, heldLock) {
849
941
  if (!isManagerFinalizeEvidence(managerResult, prepared.attemptId, prepared.managerCommit?.durableCommitToken ?? ""))
850
942
  throw new Error(`restore attempt ${prepared.attemptId} has invalid manager finalize evidence`);