@cotal-ai/workspace 0.171.1 → 0.171.3

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 (50) hide show
  1. package/dist/agent-grants.d.ts.map +1 -1
  2. package/dist/agent-grants.js +4 -2
  3. package/dist/agent-grants.js.map +1 -1
  4. package/dist/connect.d.ts +9 -4
  5. package/dist/connect.d.ts.map +1 -1
  6. package/dist/connect.js +56 -47
  7. package/dist/connect.js.map +1 -1
  8. package/dist/connector-retention.d.ts +1 -1
  9. package/dist/connector-retention.d.ts.map +1 -1
  10. package/dist/connector-retention.js +54 -19
  11. package/dist/connector-retention.js.map +1 -1
  12. package/dist/extension-mutation.d.ts +1 -0
  13. package/dist/extension-mutation.d.ts.map +1 -1
  14. package/dist/extension-mutation.js +1 -0
  15. package/dist/extension-mutation.js.map +1 -1
  16. package/dist/maintenance-foundation.d.ts +568 -0
  17. package/dist/maintenance-foundation.d.ts.map +1 -0
  18. package/dist/maintenance-foundation.js +531 -0
  19. package/dist/maintenance-foundation.js.map +1 -0
  20. package/dist/maintenance-journal.d.ts +59 -0
  21. package/dist/maintenance-journal.d.ts.map +1 -0
  22. package/dist/maintenance-journal.js +1072 -0
  23. package/dist/maintenance-journal.js.map +1 -0
  24. package/dist/maintenance.d.ts +3 -556
  25. package/dist/maintenance.d.ts.map +1 -1
  26. package/dist/maintenance.js +7 -1588
  27. package/dist/maintenance.js.map +1 -1
  28. package/dist/mesh-registry.d.ts +2 -0
  29. package/dist/mesh-registry.d.ts.map +1 -1
  30. package/dist/mesh-registry.js.map +1 -1
  31. package/dist/mesh-target.d.ts +2 -2
  32. package/dist/mesh-target.d.ts.map +1 -1
  33. package/dist/mesh-target.js +30 -2
  34. package/dist/mesh-target.js.map +1 -1
  35. package/dist/protected-records.d.ts +3 -0
  36. package/dist/protected-records.d.ts.map +1 -1
  37. package/dist/protected-records.js +41 -5
  38. package/dist/protected-records.js.map +1 -1
  39. package/dist/render.js +2 -0
  40. package/dist/render.js.map +1 -1
  41. package/dist/service-adapter.d.ts +3 -0
  42. package/dist/service-adapter.d.ts.map +1 -1
  43. package/dist/service-adapter.js.map +1 -1
  44. package/dist/update-check.d.ts.map +1 -1
  45. package/dist/update-check.js +4 -2
  46. package/dist/update-check.js.map +1 -1
  47. package/dist/update-recovery.d.ts.map +1 -1
  48. package/dist/update-recovery.js +13 -11
  49. package/dist/update-recovery.js.map +1 -1
  50. package/package.json +2 -2
@@ -0,0 +1,1072 @@
1
+ /** The maintenance journal: the shape validators for every persisted journal record and its evidence,
2
+ * listener custody proofs, the resume document, and the journal read/validate/write path that the
3
+ * maintenance operations in `maintenance.ts` drive. `maintenance.ts` re-exports every public name
4
+ * here, so importers keep their path. */
5
+ import { closeSync, constants, fstatSync, lstatSync, openSync, readFileSync, readSync, renameSync, unlinkSync, } from "node:fs";
6
+ import { basename, dirname, isAbsolute, join } from "node:path";
7
+ import { createHash, randomUUID } from "node:crypto";
8
+ import { ATTEMPT_ID, DURABLE_COMMIT_TOKEN, MAINTENANCE_JOURNAL_VERSION, MAINTENANCE_RESUME_DOCUMENT_VERSION, MAX_MAINTENANCE_RESUME_BYTES, assertLock, atomicWrite, ensureLayout, errno, fsyncDirectory, isMaintenanceError, localProcessOwnerStatus, maintenanceError, maintenancePaths, parseOwner, pathContains, sameStoreIdentity, writePrivateExclusive, } from "./maintenance-foundation.js";
9
+ function validIdentity(value) {
10
+ const identity = value;
11
+ return Boolean(identity && typeof identity === "object" && isAbsolute(identity.path) &&
12
+ typeof identity.dev === "string" && /^\d+$/.test(identity.dev) &&
13
+ typeof identity.ino === "string" && /^\d+$/.test(identity.ino) &&
14
+ typeof identity.generation === "string" &&
15
+ /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(identity.generation));
16
+ }
17
+ export function exactObjectKeys(value, expected) {
18
+ const prototype = Object.getPrototypeOf(value);
19
+ return (prototype === Object.prototype || prototype === null) &&
20
+ Object.keys(value).sort().join(",") === [...expected].sort().join(",") &&
21
+ Reflect.ownKeys(value).length === expected.length;
22
+ }
23
+ export function canonicalListenerEndpoint(value) {
24
+ if (!value || Buffer.byteLength(value) > 2048)
25
+ return undefined;
26
+ try {
27
+ const endpoint = new URL(value);
28
+ if (!["nats:", "tls:"].includes(endpoint.protocol) || !endpoint.hostname ||
29
+ endpoint.username || endpoint.password || endpoint.search || endpoint.hash ||
30
+ (endpoint.pathname && endpoint.pathname !== "/"))
31
+ return undefined;
32
+ const port = endpoint.port || "4222";
33
+ const canonical = `${endpoint.protocol}//${endpoint.hostname.toLowerCase()}:${port}`;
34
+ return value === canonical ? canonical : undefined;
35
+ }
36
+ catch {
37
+ return undefined;
38
+ }
39
+ }
40
+ function validProofOwner(value) {
41
+ const owner = value;
42
+ return Boolean(owner && typeof owner === "object" &&
43
+ exactObjectKeys(owner, ["pid", "host", "startedAt", "id"]) &&
44
+ Number.isInteger(owner.pid) && owner.pid > 0 &&
45
+ typeof owner.host === "string" && Buffer.byteLength(owner.host) <= 255 &&
46
+ /^[A-Za-z0-9][A-Za-z0-9._:-]*$/.test(owner.host) &&
47
+ typeof owner.startedAt === "string" && owner.startedAt.length <= 64 &&
48
+ Number.isFinite(Date.parse(owner.startedAt)) &&
49
+ typeof owner.id === "string" && /^[A-Za-z0-9][A-Za-z0-9._:-]{0,255}$/.test(owner.id));
50
+ }
51
+ function validProofIdentity(value) {
52
+ return Boolean(value && typeof value === "object" &&
53
+ exactObjectKeys(value, ["path", "dev", "ino", "generation"]) && validIdentity(value));
54
+ }
55
+ const LISTENER_PROOF_KEYS = ["attemptId", "serverName", "serverNonce", "processOwner", "serverEndpoint", "target"];
56
+ /** The service layer's full assigned id (`serviceOperationId`), repeated here because this module
57
+ * reports through its own maintenance error and must not import the adapter layer. */
58
+ const SERVICE_ID = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/;
59
+ function validControllerListenerInstance(value, owner) {
60
+ const instance = value;
61
+ const pinned = instance?.process;
62
+ // The creation token is opaque (pid.ts): a macOS token carries spaces, so only its frame is checked.
63
+ return Boolean(instance && typeof instance === "object" &&
64
+ exactObjectKeys(instance, ["instanceId", "launchRequestId", "process"]) &&
65
+ typeof instance.instanceId === "string" && SERVICE_ID.test(instance.instanceId) &&
66
+ typeof instance.launchRequestId === "string" && SERVICE_ID.test(instance.launchRequestId) &&
67
+ pinned && typeof pinned === "object" && exactObjectKeys(pinned, ["pid", "token"]) &&
68
+ Number.isInteger(pinned.pid) && Number(pinned.pid) > 0 &&
69
+ typeof pinned.token === "string" && pinned.token !== "" && pinned.token.trim() === pinned.token &&
70
+ pinned.token.length <= 256 && !/[\u0000-\u001f\u007f]/u.test(pinned.token) &&
71
+ owner.pid === pinned.pid && owner.id === `controller-broker-${instance.launchRequestId}`);
72
+ }
73
+ function validListenerProof(value) {
74
+ const proof = value;
75
+ const controller = Boolean(proof && typeof proof === "object" && proof.kind !== undefined);
76
+ return Boolean(proof && typeof proof === "object" &&
77
+ (controller
78
+ ? exactObjectKeys(proof, ["kind", ...LISTENER_PROOF_KEYS, "instance"]) && proof.kind === "controller"
79
+ : exactObjectKeys(proof, LISTENER_PROOF_KEYS)) &&
80
+ typeof proof.attemptId === "string" && ATTEMPT_ID.test(proof.attemptId) &&
81
+ typeof proof.serverName === "string" && /^[A-Za-z0-9][A-Za-z0-9._:-]{0,255}$/.test(proof.serverName) &&
82
+ typeof proof.serverNonce === "string" && /^[A-Za-z0-9][A-Za-z0-9._:-]{0,255}$/.test(proof.serverNonce) &&
83
+ validProofOwner(proof.processOwner) && typeof proof.serverEndpoint === "string" &&
84
+ canonicalListenerEndpoint(proof.serverEndpoint) === proof.serverEndpoint && validProofIdentity(proof.target) &&
85
+ (!controller || validControllerListenerInstance(proof.instance, proof.processOwner)) &&
86
+ Buffer.byteLength(JSON.stringify(proof)) <= 16 * 1024);
87
+ }
88
+ function validTimestamp(value) {
89
+ return typeof value === "string" && value.length <= 64 && Number.isFinite(Date.parse(value));
90
+ }
91
+ export function validManagerCommitEvidence(value, attemptId) {
92
+ const evidence = value;
93
+ return Boolean(evidence && typeof evidence === "object" &&
94
+ exactObjectKeys(evidence, ["attemptId", "state", "durableCommitToken"]) &&
95
+ evidence.attemptId === attemptId && evidence.state === "awaitingFinalize" &&
96
+ typeof evidence.durableCommitToken === "string" && DURABLE_COMMIT_TOKEN.test(evidence.durableCommitToken));
97
+ }
98
+ export function validManagerFinalizeEvidence(value, attemptId, durableCommitToken) {
99
+ const evidence = value;
100
+ return Boolean(evidence && typeof evidence === "object" &&
101
+ exactObjectKeys(evidence, ["attemptId", "state", "durableCommitToken"]) &&
102
+ evidence.attemptId === attemptId && evidence.state === "active" &&
103
+ evidence.durableCommitToken === durableCommitToken && DURABLE_COMMIT_TOKEN.test(evidence.durableCommitToken));
104
+ }
105
+ export function sameManagerCommitEvidence(a, b) {
106
+ return a.attemptId === b.attemptId && a.state === b.state &&
107
+ a.durableCommitToken === b.durableCommitToken;
108
+ }
109
+ export function sameManagerFinalizeEvidence(a, b) {
110
+ return a.attemptId === b.attemptId && a.state === b.state &&
111
+ a.durableCommitToken === b.durableCommitToken;
112
+ }
113
+ export function validRestoreActivationEvidence(value, attemptId) {
114
+ const evidence = value;
115
+ return Boolean(evidence && typeof evidence === "object" &&
116
+ exactObjectKeys(evidence, ["attemptId", "listenerReady", "observedAt", "managerCommit", "managerFinalize"]) &&
117
+ evidence.attemptId === attemptId && evidence.listenerReady === true && validTimestamp(evidence.observedAt) &&
118
+ validManagerCommitEvidence(evidence.managerCommit, attemptId) &&
119
+ validManagerFinalizeEvidence(evidence.managerFinalize, attemptId, evidence.managerCommit.durableCommitToken));
120
+ }
121
+ export function validOrdinaryResumeActivationEvidence(value, attemptId) {
122
+ const evidence = value;
123
+ return Boolean(evidence && typeof evidence === "object" &&
124
+ exactObjectKeys(evidence, ["operation", "attemptId", "state", "observedAt"]) &&
125
+ evidence.operation === "resumePreserved" && evidence.attemptId === attemptId &&
126
+ evidence.state === "awaitingCommit" && validTimestamp(evidence.observedAt));
127
+ }
128
+ function validAttemptOwnedPath(value) {
129
+ const owned = value;
130
+ if (!owned || typeof owned !== "object")
131
+ return false;
132
+ const pending = exactObjectKeys(owned, ["label", "path"]);
133
+ if (!pending && !exactObjectKeys(owned, ["label", "path", "dev", "ino"]))
134
+ return false;
135
+ if (!["clone", "destination", "staging", "quarantine", "sanitized", "config"].includes(owned.label) ||
136
+ typeof owned.path !== "string" || !isAbsolute(owned.path))
137
+ return false;
138
+ if (pending)
139
+ return true;
140
+ return typeof owned.dev === "string" && /^\d+$/.test(owned.dev) &&
141
+ typeof owned.ino === "string" && /^\d+$/.test(owned.ino);
142
+ }
143
+ export function validOwnedPaths(value) {
144
+ return Array.isArray(value) && value.length <= 64 && value.every(validAttemptOwnedPath) &&
145
+ new Set(value.map((owned) => owned.path)).size === value.length;
146
+ }
147
+ export function validRestoreClaim(value) {
148
+ const claim = value;
149
+ if (!claim || typeof claim !== "object" || !exactObjectKeys(claim, ["deadline", "coordinator", "owners"]))
150
+ return false;
151
+ if (typeof claim.deadline !== "string" || !Number.isFinite(Date.parse(claim.deadline)))
152
+ return false;
153
+ if (!validProofOwner(claim.coordinator))
154
+ return false;
155
+ return Array.isArray(claim.owners) && claim.owners.length <= 16 && claim.owners.every(validProofOwner);
156
+ }
157
+ function validCutContext(value) {
158
+ const cut = value;
159
+ return Boolean(cut && typeof cut === "object" && exactObjectKeys(cut, ["attemptId", "intentAt", "launch"]) &&
160
+ typeof cut.attemptId === "string" && ATTEMPT_ID.test(cut.attemptId) && validTimestamp(cut.intentAt) &&
161
+ validJsonObject(cut.launch) && typeof cut.launch.server === "string" &&
162
+ canonicalListenerEndpoint(cut.launch.server) === cut.launch.server &&
163
+ (cut.launch.custody === undefined ? cut.launch.controller === undefined
164
+ : cut.launch.custody === "legacy" ? cut.launch.controller === undefined
165
+ : cut.launch.custody === "controller" && validControllerCutBinding(cut.launch.controller)));
166
+ }
167
+ const CONTROLLER_ROLES = ["broker", "auth", "delivery", "manager"];
168
+ const SHA256_HEX = /^[0-9a-f]{64}$/;
169
+ /** A protected local record revision (protected-records.ts mints a UUID; older records are text). */
170
+ const DEFINITION_REVISION = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,199}$/;
171
+ const DEFINITION_NAME = /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/;
172
+ function validPinnedProcess(value) {
173
+ const pinned = value;
174
+ return Boolean(pinned && typeof pinned === "object" && exactObjectKeys(pinned, ["pid", "token"]) &&
175
+ Number.isInteger(pinned.pid) && Number(pinned.pid) > 0 &&
176
+ typeof pinned.token === "string" && pinned.token !== "" && pinned.token.trim() === pinned.token &&
177
+ pinned.token.length <= 256 && !/[\u0000-\u001f\u007f]/u.test(pinned.token));
178
+ }
179
+ function validControllerMember(value) {
180
+ const member = value;
181
+ return Boolean(member && typeof member === "object" &&
182
+ exactObjectKeys(member, ["role", "definition", "definitionRevision", "instanceId", "launchRequestId", "process"]) &&
183
+ CONTROLLER_ROLES.includes(member.role) &&
184
+ typeof member.definition === "string" && DEFINITION_NAME.test(member.definition) &&
185
+ typeof member.definitionRevision === "string" && DEFINITION_REVISION.test(member.definitionRevision) &&
186
+ typeof member.instanceId === "string" && SERVICE_ID.test(member.instanceId) &&
187
+ typeof member.launchRequestId === "string" && SERVICE_ID.test(member.launchRequestId) &&
188
+ validPinnedProcess(member.process));
189
+ }
190
+ /** Members are unique by role and instance, and always include the broker and the manager. The
191
+ * broker member keeps its cut-time revision; only `brokerDefinitionRevision` is rebound by a
192
+ * restore rollback, so the two are not compared here. */
193
+ function validControllerCutBinding(value) {
194
+ const binding = value;
195
+ const manager = binding?.manager;
196
+ if (!binding || typeof binding !== "object" ||
197
+ !exactObjectKeys(binding, ["stackOperationId", "brokerDefinitionRevision", "members", "manager"]) ||
198
+ typeof binding.stackOperationId !== "string" || !SERVICE_ID.test(binding.stackOperationId) ||
199
+ typeof binding.brokerDefinitionRevision !== "string" || !DEFINITION_REVISION.test(binding.brokerDefinitionRevision) ||
200
+ !Array.isArray(binding.members) || binding.members.length < 2 || binding.members.length > CONTROLLER_ROLES.length ||
201
+ !binding.members.every(validControllerMember) ||
202
+ !manager || typeof manager !== "object" || !exactObjectKeys(manager, ["instanceId", "epoch", "lifecycleUid"]) ||
203
+ typeof manager.instanceId !== "string" || !/^[A-Za-z0-9][A-Za-z0-9._:-]{0,255}$/.test(manager.instanceId) ||
204
+ !Number.isSafeInteger(manager.epoch) || Number(manager.epoch) < 0 ||
205
+ typeof manager.lifecycleUid !== "string" || !/^[A-Za-z0-9][A-Za-z0-9._:-]{0,255}$/.test(manager.lifecycleUid))
206
+ return false;
207
+ const roles = binding.members.map((member) => member.role);
208
+ const broker = binding.members.find((member) => member.role === "broker");
209
+ return new Set(roles).size === roles.length && roles.includes("manager") && Boolean(broker) &&
210
+ new Set(binding.members.map((member) => member.instanceId)).size === binding.members.length;
211
+ }
212
+ /** The cut's controller binding, or undefined for a legacy cut. The journal reader has validated it. */
213
+ export function cutController(cut) {
214
+ return cut.launch.custody === "controller" ? cut.launch.controller : undefined;
215
+ }
216
+ function validControllerStop(value, members) {
217
+ const stop = value;
218
+ if (!stop || typeof stop !== "object" || !exactObjectKeys(stop, ["role", "instanceId", "launchRequestId", "receipt"]))
219
+ return false;
220
+ const member = members.find((row) => row.role === stop.role);
221
+ if (!member || member.instanceId !== stop.instanceId || member.launchRequestId !== stop.launchRequestId)
222
+ return false;
223
+ const receipt = stop.receipt;
224
+ const kind = stop.role === "manager" ? "preserved-exit" : stop.role === "broker" ? "kernel-exit" : "process-exit";
225
+ const scoped = kind !== "process-exit";
226
+ return Boolean(receipt && typeof receipt === "object" &&
227
+ exactObjectKeys(receipt, scoped ? ["kind", "requestId", "scopeSha256", "observedAt"] : ["kind", "requestId", "observedAt"]) &&
228
+ receipt.kind === kind && typeof receipt.requestId === "string" && SERVICE_ID.test(receipt.requestId) &&
229
+ (!scoped || typeof receipt.scopeSha256 === "string" && SHA256_HEX.test(receipt.scopeSha256)) &&
230
+ validTimestamp(receipt.observedAt));
231
+ }
232
+ /** One row per cut member, in any order, with the receipt kind its role requires. */
233
+ function validControllerStops(value, binding) {
234
+ return Array.isArray(value) && value.length === binding.members.length &&
235
+ value.every((stop) => validControllerStop(stop, binding.members)) &&
236
+ new Set(value.map((stop) => stop.role)).size === value.length;
237
+ }
238
+ function validPreservedStop(value, cut, binding) {
239
+ const stop = value;
240
+ const manager = binding.members.find((member) => member.role === "manager");
241
+ if (!stop || typeof stop !== "object" || !exactObjectKeys(stop, ["instanceId", "launchRequestId", "attempts"]) ||
242
+ stop.instanceId !== manager.instanceId || stop.launchRequestId !== manager.launchRequestId ||
243
+ !Array.isArray(stop.attempts) || stop.attempts.length < 1 || stop.attempts.length > 16)
244
+ return false;
245
+ // An unpublished attempt at any position is prepublication history.
246
+ return stop.attempts.every((attempt) => {
247
+ const row = attempt;
248
+ const published = exactObjectKeys(row, ["requestId", "target", "stopper", "withAgents", "scopeSha256", "preserved", "recordedAt", "published"]);
249
+ return Boolean((published || exactObjectKeys(row, ["requestId", "target", "stopper", "withAgents", "scopeSha256", "preserved", "recordedAt"])) &&
250
+ (!published || row.published === true) &&
251
+ typeof row.requestId === "string" && SERVICE_ID.test(row.requestId) &&
252
+ validPinnedProcess(row.target) && row.target.pid === manager.process.pid && row.target.token === manager.process.token &&
253
+ validPinnedProcess(row.stopper) && row.withAgents === false &&
254
+ typeof row.scopeSha256 === "string" && SHA256_HEX.test(row.scopeSha256) &&
255
+ row.preserved && typeof row.preserved === "object" && exactObjectKeys(row.preserved, ["attemptId", "inventorySha256"]) &&
256
+ row.preserved.attemptId === cut.attemptId &&
257
+ typeof row.preserved.inventorySha256 === "string" && SHA256_HEX.test(row.preserved.inventorySha256) &&
258
+ validTimestamp(row.recordedAt));
259
+ }) && new Set(stop.attempts.map((attempt) => attempt.requestId)).size === stop.attempts.length;
260
+ }
261
+ /** A rollback rebound the broker revision away from the one the cut's broker record runs at, so that
262
+ * record can never start again (`startProcessService` refuses a revision mismatch). */
263
+ export function cutBrokerRetired(cut) {
264
+ return cut.members.find((member) => member.role === "broker").definitionRevision !== cut.brokerDefinitionRevision;
265
+ }
266
+ export function validAttemptBroker(value, cut) {
267
+ const broker = value;
268
+ return Boolean(broker && typeof broker === "object" && exactObjectKeys(broker, ["instanceId", "launchRequestId"]) &&
269
+ typeof broker.instanceId === "string" && SERVICE_ID.test(broker.instanceId) &&
270
+ typeof broker.launchRequestId === "string" && SERVICE_ID.test(broker.launchRequestId) &&
271
+ broker.instanceId !== cut.members.find((member) => member.role === "broker").instanceId);
272
+ }
273
+ function validControllerResumeBinding(value, cut) {
274
+ const binding = value;
275
+ if (!binding || typeof binding !== "object" ||
276
+ !exactObjectKeys(binding, binding.broker === undefined ? ["stackOperationId", "started"] : ["stackOperationId", "started", "broker"]) ||
277
+ binding.broker !== undefined && (!cutBrokerRetired(cut) || !validAttemptBroker(binding.broker, cut)) ||
278
+ typeof binding.stackOperationId !== "string" || !SERVICE_ID.test(binding.stackOperationId) ||
279
+ binding.stackOperationId === cut.stackOperationId ||
280
+ !Array.isArray(binding.started) || binding.started.length > 64)
281
+ return false;
282
+ return binding.started.every((value) => {
283
+ const row = value;
284
+ const keys = ["role", "instanceId", "priorLaunchRequestId", "state"];
285
+ const settled = row?.launchRequestId !== undefined || row?.outcome !== undefined;
286
+ return Boolean(row && typeof row === "object" &&
287
+ exactObjectKeys(row, settled ? [...keys, "launchRequestId", "outcome"] : keys) &&
288
+ CONTROLLER_ROLES.includes(row.role) && row.state === "requested" &&
289
+ typeof row.instanceId === "string" && SERVICE_ID.test(row.instanceId) &&
290
+ typeof row.priorLaunchRequestId === "string" && SERVICE_ID.test(row.priorLaunchRequestId) &&
291
+ (!settled || typeof row.launchRequestId === "string" && SERVICE_ID.test(row.launchRequestId) &&
292
+ row.launchRequestId !== row.priorLaunchRequestId &&
293
+ ["running", "refused-before-spawn", "unknown"].includes(String(row.outcome))));
294
+ });
295
+ }
296
+ /** The resume's controller binding, or undefined for a legacy resume. The journal reader has validated it. */
297
+ export function ordinaryResumeController(context) {
298
+ return context.launch.custody === "controller" ? context.launch.controller : undefined;
299
+ }
300
+ function validTokenHandoff(value, handoffDir, attemptId) {
301
+ const handoff = value;
302
+ if (!handoff || typeof handoff !== "object")
303
+ return false;
304
+ const pinned = handoff.dev !== undefined || handoff.ino !== undefined || handoff.sha256 !== undefined;
305
+ if (!exactObjectKeys(handoff, pinned ? ["path", "state", "dev", "ino", "sha256"] : ["path", "state"]))
306
+ return false;
307
+ if (typeof handoff.path !== "string" || dirname(handoff.path) !== handoffDir ||
308
+ !new RegExp(`^resume-commit\\.${attemptId}\\.[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$`).test(basename(handoff.path)))
309
+ return false;
310
+ // `intended` never has an inode; `written` always has one; consumed or swept keep it when it was written.
311
+ if (handoff.state === "intended")
312
+ return !pinned;
313
+ if (!["written", "consumed", "swept"].includes(handoff.state))
314
+ return false;
315
+ if (handoff.state === "written" && !pinned)
316
+ return false;
317
+ return !pinned || (typeof handoff.dev === "string" && /^\d+$/.test(handoff.dev) &&
318
+ typeof handoff.ino === "string" && /^\d+$/.test(handoff.ino) &&
319
+ typeof handoff.sha256 === "string" && SHA256_HEX.test(handoff.sha256));
320
+ }
321
+ function validControllerReconfiguration(value, restore, binding) {
322
+ const reconfiguration = value;
323
+ if (!reconfiguration || typeof reconfiguration !== "object")
324
+ return false;
325
+ const keys = ["fromRevision", "fromOptionsSha256", "fromConfigPath", "fromConfigSha256", "toConfigPath", "toConfigSha256", "toStoreIdentity", "phase"];
326
+ const phase = reconfiguration.phase;
327
+ const expected = phase === "rendered" ? keys
328
+ : phase === "definition-committed" || phase === "rolling-back" ? [...keys, "toRevision"]
329
+ : phase === "rolled-back" ? [...keys, "toRevision", "rollbackRevision"] : undefined;
330
+ return Boolean(expected && exactObjectKeys(reconfiguration, expected) &&
331
+ typeof reconfiguration.fromRevision === "string" && DEFINITION_REVISION.test(reconfiguration.fromRevision) &&
332
+ typeof reconfiguration.fromOptionsSha256 === "string" && SHA256_HEX.test(reconfiguration.fromOptionsSha256) &&
333
+ typeof reconfiguration.fromConfigPath === "string" && isAbsolute(reconfiguration.fromConfigPath) &&
334
+ reconfiguration.fromConfigPath !== reconfiguration.toConfigPath &&
335
+ typeof reconfiguration.fromConfigSha256 === "string" && SHA256_HEX.test(reconfiguration.fromConfigSha256) &&
336
+ typeof reconfiguration.toConfigPath === "string" && isAbsolute(reconfiguration.toConfigPath) &&
337
+ restore.ownedPaths?.some((owned) => owned.label === "config" && owned.path === reconfiguration.toConfigPath) &&
338
+ typeof reconfiguration.toConfigSha256 === "string" && SHA256_HEX.test(reconfiguration.toConfigSha256) &&
339
+ validIdentity(reconfiguration.toStoreIdentity) && reconfiguration.toStoreIdentity.path === restore.targetPath &&
340
+ (restore.target === undefined || sameStoreIdentity(reconfiguration.toStoreIdentity, restore.target)) &&
341
+ (reconfiguration.toRevision === undefined ||
342
+ typeof reconfiguration.toRevision === "string" && DEFINITION_REVISION.test(reconfiguration.toRevision) &&
343
+ reconfiguration.toRevision !== reconfiguration.fromRevision) &&
344
+ (reconfiguration.rollbackRevision === undefined ||
345
+ typeof reconfiguration.rollbackRevision === "string" && DEFINITION_REVISION.test(reconfiguration.rollbackRevision) &&
346
+ reconfiguration.rollbackRevision !== reconfiguration.fromRevision && reconfiguration.rollbackRevision !== reconfiguration.toRevision &&
347
+ reconfiguration.rollbackRevision === binding.brokerDefinitionRevision) &&
348
+ // Before a rollback the cut still expects the revision the rewrite started from.
349
+ (phase === "rolled-back" || reconfiguration.fromRevision === binding.brokerDefinitionRevision));
350
+ }
351
+ /** A restore's proof scope: its context and the attempt broker its launch binding names. */
352
+ export function restoreProofScope(record) {
353
+ const broker = record.launch.controller?.broker;
354
+ return { restore: record.restore, ...(broker ? { broker } : {}) };
355
+ }
356
+ /** A controller listener proof fits the journal's own record of which broker it may name. A
357
+ * resume names a settled `started` broker row. A restore names `reconfiguredBroker` or its
358
+ * binding's attempt broker when present, otherwise the cut's broker instance at a new launch
359
+ * request. An attempt broker of a resume must be that exact pair too. The caller still checks
360
+ * that the instance record is running at that launch request with that process. */
361
+ function controllerProofFits(proof, cut, scope) {
362
+ const instance = proof.instance;
363
+ if (proof.kind !== "controller" || !instance)
364
+ return false;
365
+ const exact = (pair) => pair.instanceId === instance.instanceId && pair.launchRequestId === instance.launchRequestId;
366
+ if ("resume" in scope)
367
+ return (!scope.resume.broker || exact(scope.resume.broker)) &&
368
+ scope.resume.started.some((row) => row.role === "broker" && row.instanceId === instance.instanceId &&
369
+ row.launchRequestId === instance.launchRequestId);
370
+ const attempt = scope.restore.reconfiguredBroker ?? scope.broker;
371
+ if (attempt)
372
+ return exact(attempt);
373
+ const broker = cut.members.find((member) => member.role === "broker");
374
+ return broker.instanceId === instance.instanceId && broker.launchRequestId !== instance.launchRequestId;
375
+ }
376
+ /** The proof variant follows the cut's custody, and a controller proof fits its scope. */
377
+ function listenerProofFitsCustody(proof, cut, scope) {
378
+ const controller = cutController(cut);
379
+ if (!controller)
380
+ return proof.kind === undefined;
381
+ return scope !== undefined && controllerProofFits(proof, controller, scope);
382
+ }
383
+ export function validCutCompletionEvidence(value, cut) {
384
+ const evidence = value;
385
+ const controller = cutController(cut);
386
+ return Boolean(evidence && typeof evidence === "object" &&
387
+ exactObjectKeys(evidence, controller
388
+ ? ["attemptId", "observedAt", "managerCommit", "stopped", "listener", "controllerStops"]
389
+ : ["attemptId", "observedAt", "managerCommit", "stopped", "listener"]) &&
390
+ (!controller || validControllerStops(evidence.controllerStops, controller)) &&
391
+ evidence.attemptId === cut.attemptId && validTimestamp(evidence.observedAt) &&
392
+ evidence.managerCommit && typeof evidence.managerCommit === "object" &&
393
+ exactObjectKeys(evidence.managerCommit, ["operation", "attemptId", "state"]) &&
394
+ evidence.managerCommit.operation === "commitPreservation" &&
395
+ evidence.managerCommit.attemptId === cut.attemptId && evidence.managerCommit.state === "preserved" &&
396
+ evidence.stopped && typeof evidence.stopped === "object" &&
397
+ exactObjectKeys(evidence.stopped, ["manager", "broker", "localProcesses"]) &&
398
+ evidence.stopped.manager === true && evidence.stopped.broker === true && evidence.stopped.localProcesses === true &&
399
+ evidence.listener && typeof evidence.listener === "object" &&
400
+ exactObjectKeys(evidence.listener, ["endpoint", "unreachable"]) &&
401
+ evidence.listener.endpoint === cut.launch.server && evidence.listener.unreachable === true);
402
+ }
403
+ export function normalizedListenerProof(value) {
404
+ if (!validListenerProof(value))
405
+ maintenanceError("listener-proof-invalid", "restore listener proof is invalid, non-canonical, or oversized");
406
+ return {
407
+ attemptId: value.attemptId,
408
+ serverName: value.serverName,
409
+ serverNonce: value.serverNonce,
410
+ processOwner: {
411
+ pid: value.processOwner.pid,
412
+ host: value.processOwner.host,
413
+ startedAt: value.processOwner.startedAt,
414
+ id: value.processOwner.id,
415
+ },
416
+ serverEndpoint: value.serverEndpoint,
417
+ target: {
418
+ path: value.target.path,
419
+ dev: value.target.dev,
420
+ ino: value.target.ino,
421
+ generation: value.target.generation,
422
+ },
423
+ ...(value.kind === "controller" && value.instance ? {
424
+ kind: "controller",
425
+ instance: {
426
+ instanceId: value.instance.instanceId,
427
+ launchRequestId: value.instance.launchRequestId,
428
+ process: { pid: value.instance.process.pid, token: value.instance.process.token },
429
+ },
430
+ } : {}),
431
+ };
432
+ }
433
+ export function sameProcessOwner(a, b) {
434
+ return a.pid === b.pid && a.host === b.host && a.startedAt === b.startedAt && a.id === b.id;
435
+ }
436
+ /** The proof variant must match the cut's custody, and a controller proof must fit the journal's
437
+ * recorded broker. The workspace cannot read service instance records, so the caller passes the
438
+ * live check that the named instance is running at that launch request with that process. A
439
+ * controller proof without that check refuses. */
440
+ export function requireCustodyProof(proof, cut, scope, running, root, attemptId) {
441
+ if (!listenerProofFitsCustody(proof, cut, scope))
442
+ maintenanceError("listener-proof-mismatch", proof.kind === "controller"
443
+ ? "the controller listener proof does not name this attempt's recorded broker instance"
444
+ : "a legacy listener proof cannot bind a controller-custody attempt", { root, attemptId });
445
+ if (proof.kind === "controller" && (!running || !running(proof.instance)))
446
+ maintenanceError("listener-proof-mismatch", "the controller listener's broker instance is not proven running at that launch request and process", { root, attemptId });
447
+ }
448
+ export function sameListenerProof(a, b) {
449
+ return a.kind === b.kind && a.attemptId === b.attemptId && a.serverName === b.serverName &&
450
+ a.serverNonce === b.serverNonce && sameProcessOwner(a.processOwner, b.processOwner) &&
451
+ a.serverEndpoint === b.serverEndpoint && sameStoreIdentity(a.target, b.target) &&
452
+ (a.kind !== "controller" || Boolean(a.instance && b.instance &&
453
+ a.instance.instanceId === b.instance.instanceId && a.instance.launchRequestId === b.instance.launchRequestId &&
454
+ a.instance.process.pid === b.instance.process.pid && a.instance.process.token === b.instance.process.token));
455
+ }
456
+ export function reusesListenerIdentity(a, b) {
457
+ return a.serverName === b.serverName || a.serverNonce === b.serverNonce ||
458
+ sameProcessOwner(a.processOwner, b.processOwner) ||
459
+ Boolean(a.instance && b.instance && a.instance.launchRequestId === b.instance.launchRequestId);
460
+ }
461
+ function validListenerReplacements(value) {
462
+ if (!Array.isArray(value) || value.length === 0 || value.length > 1024)
463
+ return false;
464
+ const replacements = value;
465
+ for (let index = 0; index < replacements.length; index++) {
466
+ const replacement = replacements[index];
467
+ if (!replacement || typeof replacement !== "object" ||
468
+ !exactObjectKeys(replacement, ["generation", "replacedAt", "proof"]) ||
469
+ replacement.generation !== index + 1 || typeof replacement.replacedAt !== "string" ||
470
+ replacement.replacedAt.length > 64 || !Number.isFinite(Date.parse(replacement.replacedAt)) ||
471
+ !validListenerProof(replacement.proof))
472
+ return false;
473
+ if (replacements.slice(0, index).some((prior) => reusesListenerIdentity(prior.proof, replacement.proof)))
474
+ return false;
475
+ }
476
+ return Buffer.byteLength(JSON.stringify(replacements)) <= 512 * 1024;
477
+ }
478
+ export function assertListenerOwnerAlive(proof) {
479
+ const status = localProcessOwnerStatus(proof.processOwner);
480
+ if (status === "unknown")
481
+ maintenanceError("listener-owner-ambiguous", "restore listener process ownership cannot be proven locally", {
482
+ attemptId: proof.attemptId,
483
+ recourse: [{ action: "inspect", description: "Prove the recorded listener owner and server nonce before recovery." }],
484
+ });
485
+ if (status === "dead")
486
+ maintenanceError("listener-owner-dead", "recorded restore listener process is not alive", {
487
+ attemptId: proof.attemptId,
488
+ recourse: [{ action: "repair", description: "Preserve both stores and relaunch through an explicit restore recovery path." }],
489
+ });
490
+ }
491
+ function validJson(value) {
492
+ if (value === null || typeof value === "string" || typeof value === "boolean")
493
+ return true;
494
+ if (typeof value === "number")
495
+ return Number.isFinite(value);
496
+ if (Array.isArray(value))
497
+ return value.every(validJson);
498
+ if (!value || typeof value !== "object")
499
+ return false;
500
+ return Object.values(value).every(validJson);
501
+ }
502
+ export function validJsonObject(value) {
503
+ if (!value || typeof value !== "object" || Array.isArray(value))
504
+ return false;
505
+ const prototype = Object.getPrototypeOf(value);
506
+ return (prototype === Object.prototype || prototype === null) && validJson(value);
507
+ }
508
+ export function sameJsonValue(a, b) {
509
+ if (a === b)
510
+ return true;
511
+ if (Array.isArray(a) || Array.isArray(b)) {
512
+ if (!Array.isArray(a) || !Array.isArray(b))
513
+ return false;
514
+ return a.length === b.length && a.every((item, index) => sameJsonValue(item, b[index]));
515
+ }
516
+ if (!a || !b || typeof a !== "object" || typeof b !== "object")
517
+ return false;
518
+ const aObject = a;
519
+ const bObject = b;
520
+ const aKeys = Object.keys(aObject).sort();
521
+ const bKeys = Object.keys(bObject).sort();
522
+ return aKeys.length === bKeys.length && aKeys.every((key, index) => key === bKeys[index] && sameJsonValue(aObject[key], bObject[key]));
523
+ }
524
+ function cloneJsonValue(value, seen, depth = 0, budget = { nodes: 0 }) {
525
+ if (++budget.nodes > 100_000 || depth > 64)
526
+ maintenanceError("resume-too-large", "maintenance resume document is too deeply nested or complex");
527
+ if (value === null || typeof value === "boolean")
528
+ return value;
529
+ if (typeof value === "string") {
530
+ if (Buffer.byteLength(value) > MAX_MAINTENANCE_RESUME_BYTES)
531
+ maintenanceError("resume-too-large", "maintenance resume document contains an oversized string");
532
+ return value;
533
+ }
534
+ if (typeof value === "number") {
535
+ if (!Number.isFinite(value))
536
+ maintenanceError("resume-invalid", "maintenance resume document contains a non-finite number");
537
+ return value;
538
+ }
539
+ if (!value || typeof value !== "object")
540
+ maintenanceError("resume-invalid", "maintenance resume document must contain only JSON values");
541
+ if (seen.has(value))
542
+ maintenanceError("resume-invalid", "maintenance resume document contains a cycle");
543
+ seen.add(value);
544
+ try {
545
+ if (Array.isArray(value)) {
546
+ if (Reflect.ownKeys(value).length !== value.length + 1)
547
+ maintenanceError("resume-invalid", "maintenance resume arrays must be dense plain data");
548
+ return Array.from({ length: value.length }, (_, index) => {
549
+ const descriptor = Object.getOwnPropertyDescriptor(value, String(index));
550
+ if (!descriptor || !descriptor.enumerable || descriptor.get || descriptor.set)
551
+ maintenanceError("resume-invalid", "maintenance resume arrays must contain data properties only");
552
+ return cloneJsonValue(descriptor.value, seen, depth + 1, budget);
553
+ });
554
+ }
555
+ const prototype = Object.getPrototypeOf(value);
556
+ if (prototype !== Object.prototype && prototype !== null)
557
+ maintenanceError("resume-invalid", "maintenance resume document objects must be plain data");
558
+ const descriptors = Object.getOwnPropertyDescriptors(value);
559
+ const keys = Object.keys(descriptors).sort((a, b) => a < b ? -1 : a > b ? 1 : 0);
560
+ if (Reflect.ownKeys(value).length !== keys.length ||
561
+ keys.some((key) => !descriptors[key].enumerable || descriptors[key].get || descriptors[key].set))
562
+ maintenanceError("resume-invalid", "maintenance resume document objects must contain enumerable data properties only");
563
+ const output = Object.create(null);
564
+ for (const key of keys)
565
+ Object.defineProperty(output, key, {
566
+ value: cloneJsonValue(descriptors[key].value, seen, depth + 1, budget),
567
+ enumerable: true,
568
+ configurable: true,
569
+ writable: true,
570
+ });
571
+ return output;
572
+ }
573
+ finally {
574
+ seen.delete(value);
575
+ }
576
+ }
577
+ function resumeBytes(document) {
578
+ if (!document || typeof document !== "object" || Array.isArray(document))
579
+ maintenanceError("resume-invalid", "maintenance resume document must be exactly { version, inventory, launch }");
580
+ const prototype = Object.getPrototypeOf(document);
581
+ const descriptors = Object.getOwnPropertyDescriptors(document);
582
+ const keys = Object.keys(descriptors).sort();
583
+ if ((prototype !== Object.prototype && prototype !== null) || Reflect.ownKeys(document).length !== 3 ||
584
+ keys.join(",") !== "inventory,launch,version" ||
585
+ keys.some((key) => !descriptors[key].enumerable || descriptors[key].get || descriptors[key].set) ||
586
+ descriptors.version.value !== MAINTENANCE_RESUME_DOCUMENT_VERSION)
587
+ maintenanceError("resume-invalid", "maintenance resume document must be exactly { version, inventory, launch }");
588
+ const normalized = {
589
+ version: MAINTENANCE_RESUME_DOCUMENT_VERSION,
590
+ inventory: cloneJsonValue(descriptors.inventory.value, new Set()),
591
+ launch: cloneJsonValue(descriptors.launch.value, new Set()),
592
+ };
593
+ const data = `${JSON.stringify(normalized, null, 2)}\n`;
594
+ const bytes = Buffer.byteLength(data);
595
+ if (bytes > MAX_MAINTENANCE_RESUME_BYTES)
596
+ maintenanceError("resume-too-large", `maintenance resume document exceeds ${MAX_MAINTENANCE_RESUME_BYTES} bytes`);
597
+ return {
598
+ document: normalized,
599
+ data,
600
+ descriptor: {
601
+ version: MAINTENANCE_RESUME_DOCUMENT_VERSION,
602
+ file: "resume.json",
603
+ bytes,
604
+ sha256: createHash("sha256").update(data).digest("hex"),
605
+ },
606
+ };
607
+ }
608
+ function validResumeDescriptor(value) {
609
+ const descriptor = value;
610
+ return Boolean(descriptor && typeof descriptor === "object" &&
611
+ descriptor.version === MAINTENANCE_RESUME_DOCUMENT_VERSION && descriptor.file === "resume.json" &&
612
+ Number.isInteger(descriptor.bytes) && descriptor.bytes > 0 && descriptor.bytes <= MAX_MAINTENANCE_RESUME_BYTES &&
613
+ typeof descriptor.sha256 === "string" && /^[0-9a-f]{64}$/.test(descriptor.sha256));
614
+ }
615
+ export function sameResumeDescriptor(a, b) {
616
+ return a.version === b.version && a.file === b.file && a.bytes === b.bytes && a.sha256 === b.sha256;
617
+ }
618
+ /** Atomically persist the bounded private resume inventory and launch provenance before publishing ready. */
619
+ export function writeMaintenanceResumeDocument(lock, document) {
620
+ assertLock(lock);
621
+ const paths = maintenancePaths(lock.root);
622
+ ensureLayout(paths);
623
+ const serialized = resumeBytes(document);
624
+ const journal = readMaintenanceJournal(lock.root);
625
+ if (journal) {
626
+ if (!sameResumeDescriptor(journal.resume, serialized.descriptor))
627
+ maintenanceError("invalid-transition", "cannot replace the resume document referenced by a maintenance journal", {
628
+ root: lock.root,
629
+ paths: [paths.resume, paths.journal],
630
+ recourse: [{ action: "repair", description: "Complete or explicitly repair the current maintenance state before writing another resume document.", paths: [paths.journal] }],
631
+ });
632
+ return journal.resume;
633
+ }
634
+ const tmp = `${paths.resume}.${process.pid}.${randomUUID()}.tmp`;
635
+ try {
636
+ writePrivateExclusive(tmp, serialized.data);
637
+ renameSync(tmp, paths.resume);
638
+ fsyncDirectory(paths.versionDir);
639
+ }
640
+ catch (error) {
641
+ try {
642
+ unlinkSync(tmp);
643
+ }
644
+ catch { /* best effort for an exclusively-created private temp */ }
645
+ throw error;
646
+ }
647
+ readMaintenanceResumeDocument(lock.root, serialized.descriptor);
648
+ return serialized.descriptor;
649
+ }
650
+ /** Read exactly the fixed resume file after size, mode, SHA-256, version, and JSON-shape verification. */
651
+ export function readMaintenanceResumeDocument(root, descriptor) {
652
+ const paths = maintenancePaths(root);
653
+ if (!validResumeDescriptor(descriptor))
654
+ maintenanceError("resume-invalid", "maintenance resume descriptor is invalid", { paths: [paths.journal] });
655
+ let fd;
656
+ try {
657
+ const noFollow = constants.O_NOFOLLOW ?? 0;
658
+ fd = openSync(paths.resume, constants.O_RDONLY | noFollow);
659
+ }
660
+ catch (error) {
661
+ if (errno(error) === "ENOENT")
662
+ maintenanceError("resume-missing", "maintenance resume document is missing", {
663
+ root: paths.root,
664
+ paths: [paths.resume],
665
+ recourse: [{ action: "repair", description: "Restore the exact resume document before using this maintenance cut.", paths: [paths.resume] }],
666
+ });
667
+ if (errno(error) === "ELOOP")
668
+ maintenanceError("resume-mismatch", "maintenance resume document must not be a symlink", { paths: [paths.resume] });
669
+ maintenanceError("resume-invalid", "maintenance resume document cannot be inspected", { paths: [paths.resume] });
670
+ }
671
+ let bytes;
672
+ try {
673
+ const before = fstatSync(fd, { bigint: true });
674
+ if (!before.isFile() || before.size !== BigInt(descriptor.bytes) ||
675
+ before.size > BigInt(MAX_MAINTENANCE_RESUME_BYTES) ||
676
+ (process.platform !== "win32" && (before.mode & 63n) !== 0n))
677
+ maintenanceError("resume-mismatch", "maintenance resume document metadata does not match its descriptor", {
678
+ root: paths.root,
679
+ paths: [paths.resume],
680
+ recourse: [{ action: "inspect", description: "Do not resume or restore from a missing, replaced, or non-private document.", paths: [paths.resume] }],
681
+ });
682
+ const bounded = Buffer.alloc(descriptor.bytes + 1);
683
+ let length = 0;
684
+ while (length < bounded.length) {
685
+ const count = readSync(fd, bounded, length, bounded.length - length, null);
686
+ if (count === 0)
687
+ break;
688
+ length += count;
689
+ }
690
+ const after = fstatSync(fd, { bigint: true });
691
+ if (length !== descriptor.bytes || before.dev !== after.dev || before.ino !== after.ino ||
692
+ before.size !== after.size || before.mtimeNs !== after.mtimeNs || before.ctimeNs !== after.ctimeNs)
693
+ maintenanceError("resume-mismatch", "maintenance resume document changed while it was being read", {
694
+ root: paths.root, paths: [paths.resume],
695
+ });
696
+ bytes = bounded.subarray(0, length);
697
+ }
698
+ finally {
699
+ closeSync(fd);
700
+ }
701
+ const digest = createHash("sha256").update(bytes).digest("hex");
702
+ if (digest !== descriptor.sha256)
703
+ maintenanceError("resume-mismatch", "maintenance resume document SHA-256 does not match its descriptor", {
704
+ root: paths.root,
705
+ paths: [paths.resume],
706
+ recourse: [{ action: "inspect", description: "Restore the exact content-addressed resume document before continuing.", paths: [paths.resume] }],
707
+ });
708
+ let parsed;
709
+ try {
710
+ parsed = JSON.parse(bytes.toString("utf8"));
711
+ }
712
+ catch {
713
+ maintenanceError("resume-invalid", "maintenance resume document is not valid JSON", { paths: [paths.resume] });
714
+ }
715
+ const normalized = resumeBytes(parsed).document;
716
+ return normalized;
717
+ }
718
+ export function validRecourse(value) {
719
+ return Array.isArray(value) && value.every((item) => {
720
+ const r = item;
721
+ return Boolean(r && typeof r === "object" &&
722
+ ["retry", "inspect", "rollback", "repair", "cleanup"].includes(r.action) &&
723
+ typeof r.description === "string" &&
724
+ (r.command === undefined || typeof r.command === "string") &&
725
+ (r.paths === undefined || (Array.isArray(r.paths) && r.paths.every((p) => typeof p === "string" && isAbsolute(p)))));
726
+ });
727
+ }
728
+ function validateRestoreContext(record, path) {
729
+ const restore = record.restore;
730
+ if (!restore || typeof restore.attemptId !== "string" || !ATTEMPT_ID.test(restore.attemptId) ||
731
+ !["same-path", "alternate", "disaster"].includes(restore.method) ||
732
+ typeof restore.targetPath !== "string" || !isAbsolute(restore.targetPath) ||
733
+ (restore.selection !== undefined && !["full", "registry"].includes(restore.selection)))
734
+ maintenanceError("journal-corrupt", "restore context is invalid", { paths: [path] });
735
+ if (restore.target && (!validIdentity(restore.target) || restore.target.path !== restore.targetPath))
736
+ maintenanceError("journal-corrupt", "restore target identity is invalid", { paths: [path] });
737
+ if (restore.previousSource &&
738
+ (!["fallback", "retained"].includes(restore.previousSource.kind) || !validIdentity(restore.previousSource.identity)))
739
+ maintenanceError("journal-corrupt", "previous source identity is invalid", { paths: [path] });
740
+ if (restore.method === "same-path") {
741
+ if (restore.targetPath !== record.source.path || typeof restore.fallbackPath !== "string" ||
742
+ !isAbsolute(restore.fallbackPath) || dirname(restore.fallbackPath) !== dirname(record.source.path))
743
+ maintenanceError("journal-corrupt", "same-path restore paths are inconsistent", { paths: [path] });
744
+ if (record.state === "restore-ready" && !["move-pending", "source-moved"].includes(record.phase))
745
+ maintenanceError("journal-corrupt", "same-path restore phase is inconsistent", { paths: [path] });
746
+ if (record.state === "restore-ready" && record.phase === "move-pending" &&
747
+ (restore.previousSource || restore.target || restore.cleanup))
748
+ maintenanceError("journal-corrupt", "pending move unexpectedly records bound or owned paths", { paths: [path] });
749
+ if ((record.state !== "restore-ready" || record.phase === "source-moved") &&
750
+ (!restore.previousSource || restore.previousSource.kind !== "fallback" ||
751
+ restore.previousSource.identity.path !== restore.fallbackPath ||
752
+ restore.previousSource.identity.dev !== record.source.dev || restore.previousSource.identity.ino !== record.source.ino ||
753
+ restore.previousSource.identity.generation !== record.source.generation))
754
+ maintenanceError("journal-corrupt", "moved source identity is inconsistent", { paths: [path] });
755
+ }
756
+ else if (restore.method === "alternate") {
757
+ if (restore.targetPath === record.source.path || restore.fallbackPath !== undefined ||
758
+ !restore.previousSource || restore.previousSource.kind !== "retained" ||
759
+ !sameStoreIdentity(restore.previousSource.identity, record.source) ||
760
+ (record.state === "restore-ready" && record.phase !== "source-retained"))
761
+ maintenanceError("journal-corrupt", "alternate restore context is inconsistent", { paths: [path] });
762
+ if (pathContains(record.source.path, restore.targetPath) || pathContains(restore.targetPath, record.source.path))
763
+ maintenanceError("journal-corrupt", "alternate restore source and target trees overlap", {
764
+ paths: [path, record.source.path, restore.targetPath],
765
+ });
766
+ }
767
+ else if (restore.targetPath !== record.source.path || restore.fallbackPath !== undefined ||
768
+ restore.previousSource !== undefined ||
769
+ (record.state === "restore-ready" && record.phase !== "disaster-source-missing")) {
770
+ maintenanceError("journal-corrupt", "disaster restore context is inconsistent", { paths: [path] });
771
+ }
772
+ if (restore.ownedPaths !== undefined && !validOwnedPaths(restore.ownedPaths))
773
+ maintenanceError("journal-corrupt", "restore attempt-owned paths are invalid", { paths: [path] });
774
+ const controller = cutController(record.cut);
775
+ if (restore.controllerReconfiguration !== undefined &&
776
+ (!controller || restore.method !== "alternate" ||
777
+ !validControllerReconfiguration(restore.controllerReconfiguration, restore, controller)))
778
+ maintenanceError("journal-corrupt", "restore broker reconfiguration is invalid or outside a controller alternate restore", { paths: [path] });
779
+ const reconfiguredBroker = restore.reconfiguredBroker;
780
+ if (reconfiguredBroker !== undefined) {
781
+ const broker = controller?.members.find((member) => member.role === "broker");
782
+ if (!broker || restore.controllerReconfiguration?.phase !== "definition-committed" ||
783
+ !reconfiguredBroker || typeof reconfiguredBroker !== "object" ||
784
+ !exactObjectKeys(reconfiguredBroker, ["instanceId", "launchRequestId"]) ||
785
+ typeof reconfiguredBroker.instanceId !== "string" || !SERVICE_ID.test(reconfiguredBroker.instanceId) ||
786
+ typeof reconfiguredBroker.launchRequestId !== "string" || !SERVICE_ID.test(reconfiguredBroker.launchRequestId) ||
787
+ reconfiguredBroker.instanceId === broker.instanceId)
788
+ maintenanceError("journal-corrupt", "reconfigured broker instance is invalid", { paths: [path] });
789
+ }
790
+ const handoff = record.tokenHandoff;
791
+ if (handoff !== undefined &&
792
+ !validTokenHandoff(handoff, join(dirname(path), "handoff"), restore.attemptId))
793
+ maintenanceError("journal-corrupt", "restore commit-token handoff record is invalid", { paths: [path] });
794
+ if (restore.cleanup) {
795
+ const cleanup = restore.cleanup;
796
+ if (!["attempt-target", "previous-source"].includes(cleanup.kind) ||
797
+ !["pending", "complete"].includes(cleanup.status) || !validIdentity(cleanup.identity) ||
798
+ cleanup.originalPath !== cleanup.identity.path || !isAbsolute(cleanup.tombPath) ||
799
+ dirname(cleanup.tombPath) !== dirname(cleanup.originalPath) ||
800
+ (cleanup.kind === "attempt-target" && (!restore.target || !sameStoreIdentity(cleanup.identity, restore.target))) ||
801
+ (cleanup.kind === "previous-source" && (!restore.previousSource || !sameStoreIdentity(cleanup.identity, restore.previousSource.identity))))
802
+ maintenanceError("journal-corrupt", "restore cleanup record is inconsistent", { paths: [path] });
803
+ }
804
+ }
805
+ function validateOrdinaryResume(record, path) {
806
+ const context = record.ordinaryResume;
807
+ if (!context || typeof context !== "object" || typeof context.attemptId !== "string" ||
808
+ !ATTEMPT_ID.test(context.attemptId) || typeof context.intentAt !== "string" ||
809
+ !Number.isFinite(Date.parse(context.intentAt)) || !validJsonObject(context.launch))
810
+ maintenanceError("journal-corrupt", "ordinary resume intent is invalid", { paths: [path] });
811
+ const cut = cutController(record.cut);
812
+ const custody = context.launch.custody;
813
+ if (cut ? custody !== "controller" || !validControllerResumeBinding(context.launch.controller, cut)
814
+ : custody !== undefined || context.launch.controller !== undefined)
815
+ maintenanceError("journal-corrupt", "ordinary resume custody does not match the cut", { paths: [path] });
816
+ const resumeScope = cut ? { resume: ordinaryResumeController(context) } : undefined;
817
+ if (record.tokenHandoff !== undefined &&
818
+ !validTokenHandoff(record.tokenHandoff, join(dirname(path), "handoff"), context.attemptId))
819
+ maintenanceError("journal-corrupt", "resume commit-token handoff record is invalid", { paths: [path] });
820
+ if (record.listenerProof !== undefined &&
821
+ (!validListenerProof(record.listenerProof) ||
822
+ !listenerProofFitsCustody(record.listenerProof, record.cut, resumeScope) ||
823
+ record.listenerProof.attemptId !== context.attemptId ||
824
+ !sameStoreIdentity(record.listenerProof.target, record.source) ||
825
+ typeof context.launch.server !== "string" ||
826
+ canonicalListenerEndpoint(context.launch.server) !== record.listenerProof.serverEndpoint))
827
+ maintenanceError("journal-corrupt", "resume listener proof is invalid or belongs to another attempt", { paths: [path] });
828
+ if (record.listenerReplacements !== undefined &&
829
+ (!validListenerReplacements(record.listenerReplacements) ||
830
+ record.listenerReplacements.some((replacement) => !listenerProofFitsCustody(replacement.proof, record.cut, resumeScope) ||
831
+ replacement.proof.attemptId !== context.attemptId ||
832
+ !sameStoreIdentity(replacement.proof.target, record.source) ||
833
+ typeof context.launch.server !== "string" ||
834
+ canonicalListenerEndpoint(context.launch.server) !== replacement.proof.serverEndpoint)))
835
+ maintenanceError("journal-corrupt", "resume listener replacement history is invalid", { paths: [path] });
836
+ const currentResumeProof = record.listenerProof;
837
+ if (currentResumeProof && record.listenerReplacements?.some((replacement) => reusesListenerIdentity(replacement.proof, currentResumeProof)))
838
+ maintenanceError("journal-corrupt", "current resume listener reuses a retired identity", { paths: [path] });
839
+ if (record.state === "resume-intent") {
840
+ const extra = record;
841
+ if (extra.activeAt !== undefined || extra.activation !== undefined || extra.degradedAt !== undefined ||
842
+ extra.reason !== undefined || extra.recourse !== undefined || extra.managerCommittedAt !== undefined ||
843
+ extra.managerCommit !== undefined || extra.retiredAt !== undefined || extra.retirement !== undefined)
844
+ maintenanceError("journal-corrupt", "ordinary resume intent contains later-phase fields", { paths: [path] });
845
+ return;
846
+ }
847
+ if (record.state === "resume-active") {
848
+ if (typeof record.activeAt !== "string" || !Number.isFinite(Date.parse(record.activeAt)) ||
849
+ !validOrdinaryResumeActivationEvidence(record.activation, context.attemptId))
850
+ maintenanceError("journal-corrupt", "active ordinary resume is invalid", { paths: [path] });
851
+ return;
852
+ }
853
+ if (record.state === "resume-committed") {
854
+ if (typeof record.activeAt !== "string" || !Number.isFinite(Date.parse(record.activeAt)) ||
855
+ !validOrdinaryResumeActivationEvidence(record.activation, context.attemptId) ||
856
+ typeof record.managerCommittedAt !== "string" || !Number.isFinite(Date.parse(record.managerCommittedAt)) ||
857
+ !validManagerCommitEvidence(record.managerCommit, context.attemptId))
858
+ maintenanceError("journal-corrupt", "manager-committed ordinary resume is invalid", { paths: [path] });
859
+ return;
860
+ }
861
+ if (record.state === "resume-degraded") {
862
+ const hasActiveAt = record.activeAt !== undefined;
863
+ const hasActivation = record.activation !== undefined;
864
+ if (hasActiveAt !== hasActivation ||
865
+ (hasActiveAt && (typeof record.activeAt !== "string" || !Number.isFinite(Date.parse(record.activeAt)) ||
866
+ !validOrdinaryResumeActivationEvidence(record.activation, context.attemptId))) ||
867
+ ((record.managerCommittedAt === undefined) !== (record.managerCommit === undefined)) ||
868
+ (record.managerCommittedAt !== undefined &&
869
+ (!validTimestamp(record.managerCommittedAt) ||
870
+ !validManagerCommitEvidence(record.managerCommit, context.attemptId))) ||
871
+ typeof record.degradedAt !== "string" || !Number.isFinite(Date.parse(record.degradedAt)) ||
872
+ typeof record.reason !== "string" ||
873
+ !record.reason || !validRecourse(record.recourse))
874
+ maintenanceError("journal-corrupt", "degraded ordinary resume is invalid", { paths: [path] });
875
+ return;
876
+ }
877
+ if (typeof record.activeAt !== "string" || !Number.isFinite(Date.parse(record.activeAt)) ||
878
+ !validOrdinaryResumeActivationEvidence(record.activation, context.attemptId) ||
879
+ typeof record.managerCommittedAt !== "string" || !Number.isFinite(Date.parse(record.managerCommittedAt)) ||
880
+ !validManagerCommitEvidence(record.managerCommit, context.attemptId) ||
881
+ typeof record.retiredAt !== "string" || !Number.isFinite(Date.parse(record.retiredAt)) ||
882
+ !validManagerFinalizeEvidence(record.retirement, context.attemptId, record.managerCommit.durableCommitToken))
883
+ maintenanceError("journal-corrupt", "retired ordinary resume is invalid", { paths: [path] });
884
+ }
885
+ function validateJournal(value, path) {
886
+ const record = value;
887
+ if (!record || typeof record !== "object")
888
+ maintenanceError("journal-corrupt", "maintenance journal is not an object", { paths: [path] });
889
+ if (record.version !== MAINTENANCE_JOURNAL_VERSION)
890
+ maintenanceError("journal-version", "unsupported maintenance journal version", { paths: [path] });
891
+ if (!Number.isInteger(record.revision) || record.revision <= 0 || typeof record.updatedAt !== "string" ||
892
+ !Number.isFinite(Date.parse(record.updatedAt)) ||
893
+ typeof record.space !== "string" || !record.space || !["auth", "open", "user"].includes(record.mode) ||
894
+ !validIdentity(record.source) || !validResumeDescriptor(record.resume) || !validCutContext(record.cut))
895
+ maintenanceError("journal-corrupt", "maintenance journal base fields are invalid", { paths: [path] });
896
+ if (!["cut-intent", "cut-committed", "ready", "claimed", "restore-ready", "commit-intent", "manager-committed", "active", "degraded",
897
+ "resume-intent", "resume-active", "resume-committed", "resume-degraded", "resume-retired"].includes(record.state))
898
+ maintenanceError("journal-corrupt", "maintenance journal state is invalid", { paths: [path] });
899
+ const completion = record.cutCompletion;
900
+ if (record.state === "cut-intent" || record.state === "cut-committed") {
901
+ if (completion !== undefined)
902
+ maintenanceError("journal-corrupt", "an uncompleted cut cannot contain completion evidence", { paths: [path] });
903
+ }
904
+ else if (!validCutCompletionEvidence(completion, record.cut)) {
905
+ maintenanceError("journal-corrupt", "completed maintenance state has invalid cut evidence", { paths: [path] });
906
+ }
907
+ if (record.state === "cut-committed") {
908
+ const committed = record;
909
+ const manager = committed.managerCommit;
910
+ if (!validTimestamp(committed.managerCommittedAt) || !manager || typeof manager !== "object" ||
911
+ !exactObjectKeys(manager, ["operation", "attemptId", "state"]) ||
912
+ committed.managerCommit.operation !== "commitPreservation" ||
913
+ committed.managerCommit.attemptId !== record.cut.attemptId ||
914
+ committed.managerCommit.state !== "preserved")
915
+ maintenanceError("journal-corrupt", "cut-committed manager evidence is invalid", { paths: [path] });
916
+ const controller = cutController(record.cut);
917
+ if (committed.preservedStop !== undefined &&
918
+ (!controller || !validPreservedStop(committed.preservedStop, record.cut, controller)))
919
+ maintenanceError("journal-corrupt", "cut-committed preserved stop attempts are invalid", { paths: [path] });
920
+ }
921
+ else if (record.preservedStop !== undefined) {
922
+ maintenanceError("journal-corrupt", "only a cut-committed journal can record preserved stop attempts", { paths: [path] });
923
+ }
924
+ if (record.tokenHandoff !== undefined &&
925
+ !["manager-committed", "active", "degraded", "resume-committed", "resume-degraded", "resume-retired"].includes(record.state))
926
+ maintenanceError("journal-corrupt", "this maintenance state cannot record a commit-token handoff", { paths: [path] });
927
+ if (record.state === "claimed") {
928
+ const claim = record.claim;
929
+ if (!claim || typeof claim.attemptId !== "string" || !ATTEMPT_ID.test(claim.attemptId) ||
930
+ typeof claim.deadline !== "string" || !Number.isFinite(Date.parse(claim.deadline)) ||
931
+ !Array.isArray(claim.owners) || claim.owners.length > 16)
932
+ maintenanceError("journal-corrupt", "maintenance claim is invalid", { paths: [path] });
933
+ parseOwner(claim.coordinator, "claim coordinator");
934
+ for (const claimOwner of claim.owners)
935
+ parseOwner(claimOwner, "claim owner");
936
+ if (claim.ownedPaths !== undefined && !validOwnedPaths(claim.ownedPaths))
937
+ maintenanceError("journal-corrupt", "maintenance claim owned paths are invalid", { paths: [path] });
938
+ }
939
+ if (record.state === "restore-ready" && !validRestoreClaim(record.claim))
940
+ maintenanceError("journal-corrupt", "restore-ready record has no valid liveness claim", { paths: [path] });
941
+ if (["restore-ready", "commit-intent", "manager-committed", "active", "degraded"].includes(record.state)) {
942
+ const restoreRecord = record;
943
+ if (restoreRecord.state === "restore-ready" && !["move-pending", "source-moved", "source-retained", "disaster-source-missing"].includes(restoreRecord.phase))
944
+ maintenanceError("journal-corrupt", "restore phase is invalid", { paths: [path] });
945
+ if (restoreRecord.state !== "restore-ready" && !restoreRecord.restore.target)
946
+ maintenanceError("journal-corrupt", "committed restore has no target identity", { paths: [path] });
947
+ validateRestoreContext(restoreRecord, path);
948
+ if (restoreRecord.state !== "restore-ready" &&
949
+ !validJsonObject(restoreRecord.launch))
950
+ maintenanceError("journal-corrupt", "restore launch metadata is invalid", { paths: [path] });
951
+ // A controller restore journals its member starts in the launch, as a controller resume does.
952
+ if (restoreRecord.state !== "restore-ready") {
953
+ const launch = restoreRecord.launch;
954
+ const controller = cutController(record.cut);
955
+ if (controller ? launch.custody !== "controller" || !validControllerResumeBinding(launch.controller, controller) ||
956
+ // A rewritten broker definition names its new broker in reconfiguredBroker, never here.
957
+ launch.controller.broker !== undefined && restoreRecord.restore.controllerReconfiguration !== undefined
958
+ : launch.custody !== undefined || launch.controller !== undefined)
959
+ maintenanceError("journal-corrupt", "restore launch custody does not match the cut", { paths: [path] });
960
+ }
961
+ if (restoreRecord.state !== "restore-ready" && restoreRecord.listenerProof !== undefined &&
962
+ (!validListenerProof(restoreRecord.listenerProof) ||
963
+ !listenerProofFitsCustody(restoreRecord.listenerProof, record.cut, restoreProofScope(restoreRecord)) ||
964
+ restoreRecord.listenerProof.attemptId !== restoreRecord.restore.attemptId ||
965
+ !sameStoreIdentity(restoreRecord.listenerProof.target, restoreRecord.restore.target) ||
966
+ typeof restoreRecord.launch.server !== "string" ||
967
+ canonicalListenerEndpoint(restoreRecord.launch.server) !== restoreRecord.listenerProof.serverEndpoint))
968
+ maintenanceError("journal-corrupt", "restore listener proof is invalid or belongs to another attempt", { paths: [path] });
969
+ if (restoreRecord.state !== "restore-ready") {
970
+ const committed = restoreRecord;
971
+ if (committed.listenerReplacements !== undefined &&
972
+ (!validListenerReplacements(committed.listenerReplacements) ||
973
+ committed.listenerReplacements.some((replacement) => !listenerProofFitsCustody(replacement.proof, record.cut, restoreProofScope(committed)) ||
974
+ replacement.proof.attemptId !== committed.restore.attemptId ||
975
+ !sameStoreIdentity(replacement.proof.target, committed.restore.target) ||
976
+ typeof committed.launch.server !== "string" ||
977
+ canonicalListenerEndpoint(committed.launch.server) !== replacement.proof.serverEndpoint)))
978
+ maintenanceError("journal-corrupt", "restore listener replacement history is invalid", { paths: [path] });
979
+ const currentProof = committed.listenerProof;
980
+ if (currentProof && committed.listenerReplacements?.some((replacement) => reusesListenerIdentity(replacement.proof, currentProof)))
981
+ maintenanceError("journal-corrupt", "current restore listener reuses a retired identity", { paths: [path] });
982
+ }
983
+ if (restoreRecord.state === "manager-committed" &&
984
+ (!restoreRecord.listenerProof || !validTimestamp(restoreRecord.managerCommittedAt) ||
985
+ !validManagerCommitEvidence(restoreRecord.managerCommit, restoreRecord.restore.attemptId)))
986
+ maintenanceError("journal-corrupt", "manager-committed restore evidence is invalid", { paths: [path] });
987
+ if (restoreRecord.state === "active" &&
988
+ (!validTimestamp(restoreRecord.managerCommittedAt) ||
989
+ !validManagerCommitEvidence(restoreRecord.managerCommit, restoreRecord.restore.attemptId) ||
990
+ !Number.isFinite(Date.parse(restoreRecord.activeAt)) || !restoreRecord.listenerProof ||
991
+ !validRestoreActivationEvidence(restoreRecord.details, restoreRecord.restore.attemptId) ||
992
+ !sameManagerCommitEvidence(restoreRecord.managerCommit, restoreRecord.details.managerCommit)))
993
+ maintenanceError("journal-corrupt", "active restore details are invalid", { paths: [path] });
994
+ if (restoreRecord.state === "degraded" &&
995
+ (((restoreRecord.managerCommittedAt === undefined) !== (restoreRecord.managerCommit === undefined)) ||
996
+ (restoreRecord.managerCommittedAt !== undefined &&
997
+ (!restoreRecord.listenerProof || !validTimestamp(restoreRecord.managerCommittedAt) ||
998
+ !validManagerCommitEvidence(restoreRecord.managerCommit, restoreRecord.restore.attemptId))) ||
999
+ (restoreRecord.activeAt !== undefined && !Number.isFinite(Date.parse(restoreRecord.activeAt))) ||
1000
+ (restoreRecord.activeAt !== undefined && (!restoreRecord.listenerProof ||
1001
+ !validRestoreActivationEvidence(restoreRecord.details, restoreRecord.restore.attemptId))) ||
1002
+ (restoreRecord.activeAt !== undefined &&
1003
+ (restoreRecord.managerCommit === undefined ||
1004
+ !sameManagerCommitEvidence(restoreRecord.managerCommit, restoreRecord.details.managerCommit))) ||
1005
+ (restoreRecord.activeAt === undefined && restoreRecord.details !== undefined) ||
1006
+ !Number.isFinite(Date.parse(restoreRecord.degradedAt)) ||
1007
+ typeof restoreRecord.reason !== "string" || !validRecourse(restoreRecord.recourse)))
1008
+ maintenanceError("journal-corrupt", "degraded restore recourse is invalid", { paths: [path] });
1009
+ }
1010
+ if (["resume-intent", "resume-active", "resume-committed", "resume-degraded", "resume-retired"].includes(record.state))
1011
+ validateOrdinaryResume(record, path);
1012
+ return record;
1013
+ }
1014
+ export function readMaintenanceJournal(root) {
1015
+ const paths = maintenancePaths(root);
1016
+ let raw;
1017
+ try {
1018
+ const stat = lstatSync(paths.journal);
1019
+ if (!stat.isFile() || stat.isSymbolicLink() || stat.size > 1024 * 1024)
1020
+ maintenanceError("journal-corrupt", "maintenance journal is not a bounded regular file", { paths: [paths.journal] });
1021
+ raw = readFileSync(paths.journal, "utf8");
1022
+ }
1023
+ catch (error) {
1024
+ if (errno(error) === "ENOENT")
1025
+ return undefined;
1026
+ if (isMaintenanceError(error))
1027
+ throw error;
1028
+ maintenanceError("journal-corrupt", "maintenance journal cannot be read", { paths: [paths.journal] });
1029
+ }
1030
+ try {
1031
+ const record = validateJournal(JSON.parse(raw), paths.journal);
1032
+ readMaintenanceResumeDocument(paths.root, record.resume);
1033
+ return record;
1034
+ }
1035
+ catch (error) {
1036
+ if (isMaintenanceError(error))
1037
+ throw error;
1038
+ maintenanceError("journal-corrupt", "maintenance journal cannot be parsed", { paths: [paths.journal] });
1039
+ }
1040
+ }
1041
+ export function currentJournal(lock) {
1042
+ assertLock(lock);
1043
+ const record = readMaintenanceJournal(lock.root);
1044
+ if (!record)
1045
+ maintenanceError("journal-missing", "maintenance journal does not exist", {
1046
+ root: lock.root,
1047
+ recourse: [{ action: "repair", description: "Complete a preserve-state cut before backup or restore." }],
1048
+ });
1049
+ return record;
1050
+ }
1051
+ export function writeJournal(lock, previous, next) {
1052
+ assertLock(lock);
1053
+ const paths = maintenancePaths(lock.root);
1054
+ ensureLayout(paths);
1055
+ const record = {
1056
+ ...next,
1057
+ version: MAINTENANCE_JOURNAL_VERSION,
1058
+ revision: (previous?.revision ?? 0) + 1,
1059
+ updatedAt: new Date().toISOString(),
1060
+ };
1061
+ validateJournal(record, paths.journal);
1062
+ readMaintenanceResumeDocument(lock.root, record.resume);
1063
+ atomicWrite(paths.journal, record);
1064
+ return record;
1065
+ }
1066
+ export function readyFrom(record) {
1067
+ return {
1068
+ state: "ready", space: record.space, mode: record.mode, source: record.source, resume: record.resume,
1069
+ cut: record.cut, cutCompletion: record.cutCompletion,
1070
+ };
1071
+ }
1072
+ //# sourceMappingURL=maintenance-journal.js.map