@cotal-ai/workspace 0.171.0 → 0.171.2

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.
@@ -1,1594 +1,13 @@
1
- import { closeSync, chmodSync, constants, existsSync, fstatSync, fsyncSync, lstatSync, mkdirSync, openSync, readdirSync, readFileSync, readSync, realpathSync, renameSync, rmdirSync, rmSync, statSync, unlinkSync, writeFileSync, } from "node:fs";
2
- import { hostname } from "node:os";
3
- import { basename, dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
1
+ import { closeSync, constants, existsSync, fsyncSync, lstatSync, mkdirSync, openSync, readdirSync, readFileSync, renameSync, rmdirSync, rmSync, statSync, unlinkSync, writeFileSync, } from "node:fs";
2
+ import { dirname, isAbsolute, join, resolve } from "node:path";
4
3
  import { createHash, randomUUID } from "node:crypto";
5
- import { hardenPrivate, wfjStreamName } from "@cotal-ai/core";
4
+ import { wfjStreamName } from "@cotal-ai/core";
6
5
  import { findCotalRoot } from "./auth-paths.js";
7
- import { recordOperationWarning } from "./output.js";
8
6
  import { foreignStoreEntries, STORE_ENTRY_NAMES, storeAccounts } from "./store-entries.js";
9
- /** Version 1 lives in `<project>/.cotal/maintenance/v1`; the lock is shared across versions. */
10
- export const MAINTENANCE_JOURNAL_VERSION = 1;
11
- export const MAINTENANCE_RESUME_DOCUMENT_VERSION = 1;
12
- export const MAX_MAINTENANCE_RESUME_BYTES = 1024 * 1024;
13
- const MAINTENANCE_ERROR = "cotal:workspace:maintenance-error";
14
- /** Stable code and structured recourse are the consumer contract; `message` is diagnostic text. */
15
- export class MaintenanceError extends Error {
16
- brand = MAINTENANCE_ERROR;
17
- code;
18
- details;
19
- constructor(code, message, details) {
20
- super(message);
21
- this.name = "MaintenanceError";
22
- this.code = code;
23
- this.details = details;
24
- }
25
- }
26
- export function isMaintenanceError(error) {
27
- return typeof error === "object" && error !== null &&
28
- error.brand === MAINTENANCE_ERROR;
29
- }
30
- const noRecourse = [];
31
- const STORE_ID_FILE = ".cotal-store-id";
32
- const ATTEMPT_ID = /^[A-Za-z0-9][A-Za-z0-9_-]{0,127}$/;
33
- const DURABLE_COMMIT_TOKEN = /^[a-f0-9]{64}$/;
34
- function maintenanceError(code, message, details = {}) {
35
- throw new MaintenanceError(code, message, { ...details, recourse: details.recourse ?? noRecourse });
36
- }
37
- function errno(error) {
38
- return error.code;
39
- }
40
- function canonicalRoot(root) {
41
- if (!root || !isAbsolute(root))
42
- maintenanceError("invalid-path", "maintenance root must be an absolute existing directory", {
43
- root,
44
- paths: [root],
45
- });
46
- let canonical;
47
- try {
48
- canonical = realpathSync.native(root);
49
- }
50
- catch {
51
- maintenanceError("invalid-path", "maintenance root does not exist", { root, paths: [root] });
52
- }
53
- if (!statSync(canonical).isDirectory())
54
- maintenanceError("invalid-path", "maintenance root is not a directory", { root, paths: [root] });
55
- return canonical;
56
- }
57
- export function maintenancePaths(root) {
58
- const canonical = canonicalRoot(root);
59
- const cotalDir = join(canonical, ".cotal");
60
- const maintenanceDir = join(cotalDir, "maintenance");
61
- const versionDir = join(maintenanceDir, `v${MAINTENANCE_JOURNAL_VERSION}`);
62
- return {
63
- root: canonical,
64
- cotalDir,
65
- maintenanceDir,
66
- versionDir,
67
- journal: join(versionDir, "journal.json"),
68
- resume: join(versionDir, "resume.json"),
69
- prepareIntent: join(versionDir, "prepare-intent.json"),
70
- commitIntent: join(versionDir, "commit-intent.json"),
71
- lock: join(maintenanceDir, "lock.json"),
72
- reaper: join(maintenanceDir, "lock-reaper.json"),
73
- handoff: join(versionDir, "handoff"),
74
- };
75
- }
76
- function fsyncDirectory(path) {
77
- let fd;
78
- try {
79
- fd = openSync(path, constants.O_RDONLY);
80
- fsyncSync(fd);
81
- }
82
- catch (error) {
83
- // Windows does not support opening/fsyncing a directory. POSIX errors are correctness failures.
84
- if (process.platform !== "win32")
85
- throw error;
86
- }
87
- finally {
88
- if (fd !== undefined)
89
- closeSync(fd);
90
- }
91
- }
92
- function ensureDirectory(path, harden) {
93
- if (!existsSync(path)) {
94
- // A concurrent first operation on this root can create it between the check and the mkdir; the
95
- // checks below verify what is there, and the lock then names that operation.
96
- try {
97
- mkdirSync(path, { mode: 0o700 });
98
- fsyncDirectory(dirname(path));
99
- }
100
- catch (error) {
101
- if (error.code !== "EEXIST")
102
- throw error;
103
- }
104
- }
105
- const stat = lstatSync(path);
106
- if (!stat.isDirectory() || stat.isSymbolicLink())
107
- maintenanceError("invalid-path", "maintenance path is not a real directory", { paths: [path] });
108
- if (harden) {
109
- if (process.platform !== "win32")
110
- chmodSync(path, 0o700);
111
- hardenPrivate(path, "dir");
112
- }
113
- }
114
- function ensureLayout(paths) {
115
- ensureDirectory(paths.cotalDir, false);
116
- ensureDirectory(paths.maintenanceDir, true);
117
- ensureDirectory(paths.versionDir, true);
118
- }
119
- function canonicalAbsentPath(path) {
120
- if (!path || !isAbsolute(path))
121
- maintenanceError("invalid-path", "store path must be absolute", { paths: [path] });
122
- const parent = dirname(resolve(path));
123
- let realParent;
124
- try {
125
- realParent = realpathSync.native(parent);
126
- }
127
- catch {
128
- maintenanceError("invalid-path", "store parent does not exist", { paths: [parent] });
129
- }
130
- const canonical = join(realParent, basename(path));
131
- if (pathExistsStrict(canonical))
132
- maintenanceError("path-exists", "store path must be absent", {
133
- paths: [canonical],
134
- recourse: [{ action: "inspect", description: "Inspect the unexpected path before retrying.", paths: [canonical] }],
135
- });
136
- return canonical;
137
- }
138
- function canonicalCandidatePath(path) {
139
- if (!path || !isAbsolute(path))
140
- maintenanceError("invalid-path", "store path must be absolute", { paths: [path] });
141
- if (pathExistsStrict(resolve(path))) {
142
- try {
143
- return realpathSync.native(resolve(path));
144
- }
145
- catch {
146
- maintenanceError("invalid-path", "store path cannot be resolved safely", { paths: [path] });
147
- }
148
- }
149
- return canonicalAbsentPath(path);
150
- }
151
- function pathContains(parent, child) {
152
- const fromParent = relative(parent, child);
153
- return fromParent === "" ||
154
- (fromParent !== ".." && !fromParent.startsWith(`..${sep}`) && !isAbsolute(fromParent));
155
- }
156
- function assertPathsDoNotOverlap(a, b, message) {
157
- if (pathContains(a, b) || pathContains(b, a))
158
- maintenanceError("invalid-path", message, {
159
- paths: [a, b],
160
- recourse: [{ action: "inspect", description: "Choose disjoint source and target directory trees.", paths: [a, b] }],
161
- });
162
- }
163
- function pathExistsStrict(path) {
164
- try {
165
- lstatSync(path);
166
- return true;
167
- }
168
- catch (error) {
169
- if (errno(error) === "ENOENT")
170
- return false;
171
- maintenanceError("invalid-path", "filesystem path cannot be inspected safely", { paths: [path] });
172
- }
173
- }
174
- function storeGeneration(path, create) {
175
- const marker = join(path, STORE_ID_FILE);
176
- if (!pathExistsStrict(marker)) {
177
- if (!create)
178
- maintenanceError("identity-mismatch", "store generation marker is missing", {
179
- paths: [path, marker],
180
- recourse: [{ action: "inspect", description: "Treat this path as a replacement until its provenance is proven.", paths: [path] }],
181
- });
182
- writePrivateExclusive(marker, `${randomUUID()}\n`);
183
- }
184
- let stat;
185
- try {
186
- stat = lstatSync(marker);
187
- }
188
- catch {
189
- maintenanceError("identity-mismatch", "store generation marker cannot be inspected", { paths: [path, marker] });
190
- }
191
- if (!stat.isFile() || stat.isSymbolicLink() || stat.size > 128)
192
- maintenanceError("identity-mismatch", "store generation marker is invalid", { paths: [path, marker] });
193
- const generation = readFileSync(marker, "utf8").trim();
194
- if (!/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(generation))
195
- maintenanceError("identity-mismatch", "store generation marker is corrupt", { paths: [path, marker] });
196
- return generation;
197
- }
198
- function storeIdentity(path, createGeneration) {
199
- if (!path || !isAbsolute(path))
200
- maintenanceError("invalid-path", "store path must be absolute", { paths: [path] });
201
- let canonical;
202
- try {
203
- canonical = realpathSync.native(path);
204
- }
205
- catch (error) {
206
- if (errno(error) === "ENOENT")
207
- maintenanceError("path-missing", "store path is missing", { paths: [path] });
208
- maintenanceError("invalid-path", "store path cannot be resolved safely", { paths: [path] });
209
- }
210
- const stat = lstatSync(canonical, { bigint: true });
211
- if (!stat.isDirectory() || stat.isSymbolicLink())
212
- maintenanceError("invalid-path", "store path must be a real directory", { paths: [canonical] });
213
- return {
214
- path: canonical, dev: stat.dev.toString(), ino: stat.ino.toString(),
215
- generation: storeGeneration(canonical, createGeneration),
216
- };
217
- }
218
- /** Read an already-bound store identity. Missing generation is a replacement ambiguity, not absence. */
219
- export function readStoreIdentity(path) {
220
- return storeIdentity(path, false);
221
- }
222
- /** Bind a stopped source or attempt-owned target to a non-reusable generation marker. */
223
- export function ensureStoreIdentity(path) {
224
- return storeIdentity(path, true);
225
- }
226
- export function sameStoreIdentity(a, b) {
227
- return a.path === b.path && a.dev === b.dev && a.ino === b.ino && a.generation === b.generation;
228
- }
229
- function identityAt(path) {
230
- try {
231
- return readStoreIdentity(path);
232
- }
233
- catch (error) {
234
- if (isMaintenanceError(error) && error.code === "path-missing")
235
- return undefined;
236
- throw error;
237
- }
238
- }
239
- export function assertStoreIdentity(expected) {
240
- const actual = identityAt(expected.path);
241
- if (!actual)
242
- maintenanceError("path-missing", "recorded store path is missing", {
243
- paths: [expected.path], expected,
244
- recourse: [{ action: "inspect", description: "Do not recreate the path; inspect maintenance state first.", paths: [expected.path] }],
245
- });
246
- if (!sameStoreIdentity(expected, actual))
247
- maintenanceError("identity-mismatch", "recorded store path has been replaced", {
248
- paths: [expected.path], expected, actual,
249
- recourse: [{ action: "inspect", description: "Preserve both stores and determine which inode is authoritative.", paths: [expected.path] }],
250
- });
251
- return actual;
252
- }
253
- function writePrivateExclusive(path, data) {
254
- let fd;
255
- let created = false;
256
- try {
257
- fd = openSync(path, constants.O_CREAT | constants.O_EXCL | constants.O_WRONLY, 0o600);
258
- created = true;
259
- writeFileSync(fd, data);
260
- fsyncSync(fd);
261
- closeSync(fd);
262
- fd = undefined;
263
- hardenPrivate(path, "file");
264
- fsyncDirectory(dirname(path));
265
- }
266
- catch (error) {
267
- if (fd !== undefined)
268
- closeSync(fd);
269
- if (created) {
270
- try {
271
- unlinkSync(path);
272
- }
273
- catch { /* remove only the path this exclusive create owned */ }
274
- }
275
- throw error;
276
- }
277
- }
278
- function atomicWrite(path, value) {
279
- const tmp = `${path}.${process.pid}.${randomUUID()}.tmp`;
280
- try {
281
- writePrivateExclusive(tmp, `${JSON.stringify(value, null, 2)}\n`);
282
- renameSync(tmp, path);
283
- fsyncDirectory(dirname(path));
284
- }
285
- catch (error) {
286
- try {
287
- unlinkSync(tmp);
288
- }
289
- catch { /* best effort for an exclusively-created temp */ }
290
- throw error;
291
- }
292
- }
293
- function defaultOwner() {
294
- return { pid: process.pid, host: hostname(), startedAt: new Date().toISOString(), id: randomUUID() };
295
- }
296
- export function localProcessOwnerStatus(owner) {
297
- if (owner.host !== hostname())
298
- return "unknown";
299
- try {
300
- process.kill(owner.pid, 0);
301
- return "alive";
302
- }
303
- catch (error) {
304
- if (errno(error) === "ESRCH")
305
- return "dead";
306
- if (errno(error) === "EPERM")
307
- return "alive";
308
- return "unknown";
309
- }
310
- }
311
- function parseOwner(value, label) {
312
- const o = value;
313
- if (!o || typeof o !== "object" || !Number.isInteger(o.pid) || o.pid <= 0 ||
314
- typeof o.host !== "string" || !o.host || typeof o.startedAt !== "string" || !Number.isFinite(Date.parse(o.startedAt)) ||
315
- typeof o.id !== "string" || !o.id)
316
- maintenanceError("journal-corrupt", `invalid ${label} owner record`);
317
- return o;
318
- }
319
- function readLockFile(path) {
320
- let parsed;
321
- try {
322
- const stat = lstatSync(path);
323
- if (!stat.isFile() || stat.isSymbolicLink() || stat.size > 64 * 1024)
324
- maintenanceError("journal-corrupt", "maintenance lock is not a bounded regular file", { paths: [path] });
325
- parsed = JSON.parse(readFileSync(path, "utf8"));
326
- }
327
- catch (error) {
328
- if (isMaintenanceError(error))
329
- throw error;
330
- if (errno(error) === "ENOENT")
331
- throw error;
332
- maintenanceError("journal-corrupt", "maintenance lock cannot be parsed", { paths: [path] });
333
- }
334
- const lock = parsed;
335
- if (!lock || typeof lock !== "object" || typeof lock.token !== "string" || !lock.token)
336
- maintenanceError("journal-corrupt", "maintenance lock has no token", { paths: [path] });
337
- const operation = typeof lock.operation === "string" && /^[a-z][a-z -]{0,63}$/.test(lock.operation) ? lock.operation : undefined;
338
- return { token: lock.token, owner: parseOwner(lock.owner, "lock"), ...(operation ? { operation } : {}) };
339
- }
340
- /** The process that holds this root's maintenance lock, and the operation it recorded, for a refused
341
- * contender to name. Undefined when no lock is held or it cannot be read. */
342
- export function readMaintenanceLockHolder(root) {
343
- try {
344
- const { owner, operation } = readLockFile(maintenancePaths(root).lock);
345
- return { owner, ...(operation ? { operation } : {}) };
346
- }
347
- catch {
348
- return undefined;
349
- }
350
- }
351
- function removeReaper(path, token) {
352
- try {
353
- const current = readLockFile(path);
354
- if (current.token === token) {
355
- unlinkSync(path);
356
- fsyncDirectory(dirname(path));
357
- }
358
- }
359
- catch (error) {
360
- if (errno(error) !== "ENOENT")
361
- throw error;
362
- }
363
- }
364
- /** Whether a live process holds `root`'s maintenance lock, read without taking it: the holder's
365
- * status as {@link acquireMaintenanceLock} would judge it, or `undefined` when no lock is held. */
366
- export function maintenanceLockHolder(root) {
367
- try {
368
- return localProcessOwnerStatus(readLockFile(maintenancePaths(root).lock).owner);
369
- }
370
- catch (error) {
371
- if (errno(error) === "ENOENT")
372
- return undefined;
373
- throw error;
374
- }
375
- }
376
- export function acquireMaintenanceLock(root, options = {}) {
377
- const paths = maintenancePaths(root);
378
- ensureLayout(paths);
379
- const owner = options.owner ?? defaultOwner();
380
- parseOwner(owner, "requested lock");
381
- const token = randomUUID();
382
- const body = `${JSON.stringify({ token, owner, ...(options.operation ? { operation: options.operation } : {}) }, null, 2)}\n`;
383
- try {
384
- writePrivateExclusive(paths.lock, body);
385
- return { root: paths.root, path: paths.lock, token, owner };
386
- }
387
- catch (error) {
388
- if (errno(error) !== "EEXIST")
389
- throw error;
390
- }
391
- // One exclusive reaper serializes stale-owner removal. Without it, two reclaimers could race
392
- // between checking the old inode and unlinking it, and one could unlink the other's new lock.
393
- const reaperToken = randomUUID();
394
- try {
395
- writePrivateExclusive(paths.reaper, `${JSON.stringify({ token: reaperToken, owner }, null, 2)}\n`);
396
- }
397
- catch (error) {
398
- if (errno(error) === "EEXIST") {
399
- const stale = readLockFile(paths.reaper);
400
- const status = (options.ownerStatus ?? localProcessOwnerStatus)(stale.owner);
401
- if (status === "alive")
402
- maintenanceError("lock-held", "maintenance lock recovery is already in progress", {
403
- root: paths.root,
404
- recourse: [{ action: "retry", description: "Retry after the current maintenance operation exits." }],
405
- });
406
- if (status === "unknown")
407
- maintenanceError("lock-owner-ambiguous", "maintenance lock reaper death cannot be proven", {
408
- root: paths.root,
409
- paths: [paths.reaper],
410
- recourse: [{ action: "inspect", description: "Prove the recorded reaper owner dead before retrying.", paths: [paths.reaper] }],
411
- });
412
- // There is no portable token-conditional unlink. Automatic recovery would let two contenders
413
- // both approve the stale token, then one unlink the other's fresh reaper. Fail closed and make
414
- // the deliberate single-operator recovery step explicit instead of weakening exclusion.
415
- maintenanceError("lock-owner-ambiguous", "maintenance lock reaper is stale and requires manual recovery", {
416
- root: paths.root,
417
- paths: [paths.lock, paths.reaper],
418
- recourse: [{
419
- action: "repair",
420
- description: "With all Cotal maintenance commands stopped, remove only the recorded stale reaper, then retry; the stale main lock will be recovered normally.",
421
- paths: [paths.reaper],
422
- }],
423
- });
424
- }
425
- throw error;
426
- }
427
- let takenOver;
428
- try {
429
- let existing;
430
- try {
431
- existing = readLockFile(paths.lock);
432
- }
433
- catch (error) {
434
- if (errno(error) !== "ENOENT")
435
- throw error;
436
- }
437
- if (existing) {
438
- const status = (options.ownerStatus ?? localProcessOwnerStatus)(existing.owner);
439
- if (status === "alive")
440
- maintenanceError("lock-held", "maintenance lock is held by a live owner", {
441
- root: paths.root,
442
- recourse: [{ action: "retry", description: "Wait for the current maintenance operation to finish." }],
443
- });
444
- if (status === "unknown")
445
- maintenanceError("lock-owner-ambiguous", "maintenance lock owner death cannot be proven", {
446
- root: paths.root,
447
- recourse: [{ action: "inspect", description: "Confirm the recorded host and process are dead before retrying.", paths: [paths.lock] }],
448
- });
449
- const again = readLockFile(paths.lock);
450
- if (again.token !== existing.token)
451
- maintenanceError("lock-held", "maintenance lock changed during stale-owner recovery", {
452
- root: paths.root,
453
- recourse: [{ action: "retry", description: "Retry after the current maintenance operation exits." }],
454
- });
455
- unlinkSync(paths.lock);
456
- fsyncDirectory(paths.maintenanceDir);
457
- takenOver = existing.owner;
458
- }
459
- }
460
- finally {
461
- removeReaper(paths.reaper, reaperToken);
462
- }
463
- // Another waiter may win after stale removal. Exclusive create remains the arbiter.
464
- try {
465
- writePrivateExclusive(paths.lock, body);
466
- }
467
- catch (error) {
468
- if (errno(error) === "EEXIST")
469
- maintenanceError("lock-held", "another maintenance operation acquired the recovered lock", {
470
- root: paths.root,
471
- recourse: [{ action: "retry", description: "Retry after the current maintenance operation exits." }],
472
- });
473
- throw error;
474
- }
475
- // A lock is taken over only from an owner proven dead, and the run that takes it says so.
476
- if (takenOver)
477
- recordOperationWarning({
478
- code: "MAINTENANCE_LOCK_TAKEN_OVER",
479
- target: { root: paths.root, path: paths.lock, owner: { pid: takenOver.pid, host: takenOver.host, startedAt: takenOver.startedAt } },
480
- message: `took over the maintenance lock in ${paths.root} that process ${takenOver.pid} (started ${takenOver.startedAt}) left; that process is no longer running, so the command it ran there ended without releasing it`,
481
- });
482
- return { root: paths.root, path: paths.lock, token, owner };
483
- }
484
- function assertLock(lock) {
485
- const paths = maintenancePaths(lock.root);
486
- if (paths.lock !== lock.path)
487
- maintenanceError("lock-lost", "maintenance lock belongs to a different root", { root: paths.root });
488
- let current;
489
- try {
490
- current = readLockFile(lock.path);
491
- }
492
- catch (error) {
493
- if (errno(error) === "ENOENT")
494
- maintenanceError("lock-lost", "maintenance lock disappeared", { root: paths.root });
495
- throw error;
496
- }
497
- if (current.token !== lock.token)
498
- maintenanceError("lock-lost", "maintenance lock ownership changed", { root: paths.root });
499
- }
500
- /** Verify a retained lock token at the expected root, without releasing it. */
501
- export function assertMaintenanceLock(lock, root = lock.root) {
502
- if (maintenancePaths(root).root !== lock.root)
503
- maintenanceError("lock-lost", "maintenance lock belongs to a different root", { root: maintenancePaths(root).root });
504
- assertLock(lock);
505
- }
506
- export function releaseMaintenanceLock(lock) {
507
- assertLock(lock);
508
- unlinkSync(lock.path);
509
- fsyncDirectory(dirname(lock.path));
510
- const onlyLockLayout = lock.createdDirectories !== undefined && readdirSync(join(lock.root, ".cotal")).every((entry) => entry === "maintenance");
511
- for (const dir of onlyLockLayout ? lock.createdDirectories ?? [] : []) {
512
- try {
513
- rmdirSync(dir);
514
- }
515
- catch {
516
- break;
517
- }
518
- }
519
- }
520
- export function withMaintenanceLock(root, operation, options = {}) {
521
- const lock = acquireMaintenanceLock(root, options);
522
- try {
523
- return operation(lock);
524
- }
525
- finally {
526
- releaseMaintenanceLock(lock);
527
- }
528
- }
529
- function validIdentity(value) {
530
- const identity = value;
531
- return Boolean(identity && typeof identity === "object" && isAbsolute(identity.path) &&
532
- typeof identity.dev === "string" && /^\d+$/.test(identity.dev) &&
533
- typeof identity.ino === "string" && /^\d+$/.test(identity.ino) &&
534
- typeof identity.generation === "string" &&
535
- /^[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));
536
- }
537
- function exactObjectKeys(value, expected) {
538
- const prototype = Object.getPrototypeOf(value);
539
- return (prototype === Object.prototype || prototype === null) &&
540
- Object.keys(value).sort().join(",") === [...expected].sort().join(",") &&
541
- Reflect.ownKeys(value).length === expected.length;
542
- }
543
- function canonicalListenerEndpoint(value) {
544
- if (!value || Buffer.byteLength(value) > 2048)
545
- return undefined;
546
- try {
547
- const endpoint = new URL(value);
548
- if (!["nats:", "tls:"].includes(endpoint.protocol) || !endpoint.hostname ||
549
- endpoint.username || endpoint.password || endpoint.search || endpoint.hash ||
550
- (endpoint.pathname && endpoint.pathname !== "/"))
551
- return undefined;
552
- const port = endpoint.port || "4222";
553
- const canonical = `${endpoint.protocol}//${endpoint.hostname.toLowerCase()}:${port}`;
554
- return value === canonical ? canonical : undefined;
555
- }
556
- catch {
557
- return undefined;
558
- }
559
- }
560
- function validProofOwner(value) {
561
- const owner = value;
562
- return Boolean(owner && typeof owner === "object" &&
563
- exactObjectKeys(owner, ["pid", "host", "startedAt", "id"]) &&
564
- Number.isInteger(owner.pid) && owner.pid > 0 &&
565
- typeof owner.host === "string" && Buffer.byteLength(owner.host) <= 255 &&
566
- /^[A-Za-z0-9][A-Za-z0-9._:-]*$/.test(owner.host) &&
567
- typeof owner.startedAt === "string" && owner.startedAt.length <= 64 &&
568
- Number.isFinite(Date.parse(owner.startedAt)) &&
569
- typeof owner.id === "string" && /^[A-Za-z0-9][A-Za-z0-9._:-]{0,255}$/.test(owner.id));
570
- }
571
- function validProofIdentity(value) {
572
- return Boolean(value && typeof value === "object" &&
573
- exactObjectKeys(value, ["path", "dev", "ino", "generation"]) && validIdentity(value));
574
- }
575
- const LISTENER_PROOF_KEYS = ["attemptId", "serverName", "serverNonce", "processOwner", "serverEndpoint", "target"];
576
- /** The service layer's full assigned id (`serviceOperationId`), repeated here because this module
577
- * reports through its own maintenance error and must not import the adapter layer. */
578
- 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}$/;
579
- function validControllerListenerInstance(value, owner) {
580
- const instance = value;
581
- const pinned = instance?.process;
582
- // The creation token is opaque (pid.ts): a macOS token carries spaces, so only its frame is checked.
583
- return Boolean(instance && typeof instance === "object" &&
584
- exactObjectKeys(instance, ["instanceId", "launchRequestId", "process"]) &&
585
- typeof instance.instanceId === "string" && SERVICE_ID.test(instance.instanceId) &&
586
- typeof instance.launchRequestId === "string" && SERVICE_ID.test(instance.launchRequestId) &&
587
- pinned && typeof pinned === "object" && exactObjectKeys(pinned, ["pid", "token"]) &&
588
- Number.isInteger(pinned.pid) && Number(pinned.pid) > 0 &&
589
- typeof pinned.token === "string" && pinned.token !== "" && pinned.token.trim() === pinned.token &&
590
- pinned.token.length <= 256 && !/[\u0000-\u001f\u007f]/u.test(pinned.token) &&
591
- owner.pid === pinned.pid && owner.id === `controller-broker-${instance.launchRequestId}`);
592
- }
593
- function validListenerProof(value) {
594
- const proof = value;
595
- const controller = Boolean(proof && typeof proof === "object" && proof.kind !== undefined);
596
- return Boolean(proof && typeof proof === "object" &&
597
- (controller
598
- ? exactObjectKeys(proof, ["kind", ...LISTENER_PROOF_KEYS, "instance"]) && proof.kind === "controller"
599
- : exactObjectKeys(proof, LISTENER_PROOF_KEYS)) &&
600
- typeof proof.attemptId === "string" && ATTEMPT_ID.test(proof.attemptId) &&
601
- typeof proof.serverName === "string" && /^[A-Za-z0-9][A-Za-z0-9._:-]{0,255}$/.test(proof.serverName) &&
602
- typeof proof.serverNonce === "string" && /^[A-Za-z0-9][A-Za-z0-9._:-]{0,255}$/.test(proof.serverNonce) &&
603
- validProofOwner(proof.processOwner) && typeof proof.serverEndpoint === "string" &&
604
- canonicalListenerEndpoint(proof.serverEndpoint) === proof.serverEndpoint && validProofIdentity(proof.target) &&
605
- (!controller || validControllerListenerInstance(proof.instance, proof.processOwner)) &&
606
- Buffer.byteLength(JSON.stringify(proof)) <= 16 * 1024);
607
- }
608
- function validTimestamp(value) {
609
- return typeof value === "string" && value.length <= 64 && Number.isFinite(Date.parse(value));
610
- }
611
- function validManagerCommitEvidence(value, attemptId) {
612
- const evidence = value;
613
- return Boolean(evidence && typeof evidence === "object" &&
614
- exactObjectKeys(evidence, ["attemptId", "state", "durableCommitToken"]) &&
615
- evidence.attemptId === attemptId && evidence.state === "awaitingFinalize" &&
616
- typeof evidence.durableCommitToken === "string" && DURABLE_COMMIT_TOKEN.test(evidence.durableCommitToken));
617
- }
618
- function validManagerFinalizeEvidence(value, attemptId, durableCommitToken) {
619
- const evidence = value;
620
- return Boolean(evidence && typeof evidence === "object" &&
621
- exactObjectKeys(evidence, ["attemptId", "state", "durableCommitToken"]) &&
622
- evidence.attemptId === attemptId && evidence.state === "active" &&
623
- evidence.durableCommitToken === durableCommitToken && DURABLE_COMMIT_TOKEN.test(evidence.durableCommitToken));
624
- }
625
- function sameManagerCommitEvidence(a, b) {
626
- return a.attemptId === b.attemptId && a.state === b.state &&
627
- a.durableCommitToken === b.durableCommitToken;
628
- }
629
- function sameManagerFinalizeEvidence(a, b) {
630
- return a.attemptId === b.attemptId && a.state === b.state &&
631
- a.durableCommitToken === b.durableCommitToken;
632
- }
633
- function validRestoreActivationEvidence(value, attemptId) {
634
- const evidence = value;
635
- return Boolean(evidence && typeof evidence === "object" &&
636
- exactObjectKeys(evidence, ["attemptId", "listenerReady", "observedAt", "managerCommit", "managerFinalize"]) &&
637
- evidence.attemptId === attemptId && evidence.listenerReady === true && validTimestamp(evidence.observedAt) &&
638
- validManagerCommitEvidence(evidence.managerCommit, attemptId) &&
639
- validManagerFinalizeEvidence(evidence.managerFinalize, attemptId, evidence.managerCommit.durableCommitToken));
640
- }
641
- function validOrdinaryResumeActivationEvidence(value, attemptId) {
642
- const evidence = value;
643
- return Boolean(evidence && typeof evidence === "object" &&
644
- exactObjectKeys(evidence, ["operation", "attemptId", "state", "observedAt"]) &&
645
- evidence.operation === "resumePreserved" && evidence.attemptId === attemptId &&
646
- evidence.state === "awaitingCommit" && validTimestamp(evidence.observedAt));
647
- }
648
- function validAttemptOwnedPath(value) {
649
- const owned = value;
650
- if (!owned || typeof owned !== "object")
651
- return false;
652
- const pending = exactObjectKeys(owned, ["label", "path"]);
653
- if (!pending && !exactObjectKeys(owned, ["label", "path", "dev", "ino"]))
654
- return false;
655
- if (!["clone", "destination", "staging", "quarantine", "sanitized", "config"].includes(owned.label) ||
656
- typeof owned.path !== "string" || !isAbsolute(owned.path))
657
- return false;
658
- if (pending)
659
- return true;
660
- return typeof owned.dev === "string" && /^\d+$/.test(owned.dev) &&
661
- typeof owned.ino === "string" && /^\d+$/.test(owned.ino);
662
- }
663
- function validOwnedPaths(value) {
664
- return Array.isArray(value) && value.length <= 64 && value.every(validAttemptOwnedPath) &&
665
- new Set(value.map((owned) => owned.path)).size === value.length;
666
- }
667
- function validRestoreClaim(value) {
668
- const claim = value;
669
- if (!claim || typeof claim !== "object" || !exactObjectKeys(claim, ["deadline", "coordinator", "owners"]))
670
- return false;
671
- if (typeof claim.deadline !== "string" || !Number.isFinite(Date.parse(claim.deadline)))
672
- return false;
673
- if (!validProofOwner(claim.coordinator))
674
- return false;
675
- return Array.isArray(claim.owners) && claim.owners.length <= 16 && claim.owners.every(validProofOwner);
676
- }
677
- function validCutContext(value) {
678
- const cut = value;
679
- return Boolean(cut && typeof cut === "object" && exactObjectKeys(cut, ["attemptId", "intentAt", "launch"]) &&
680
- typeof cut.attemptId === "string" && ATTEMPT_ID.test(cut.attemptId) && validTimestamp(cut.intentAt) &&
681
- validJsonObject(cut.launch) && typeof cut.launch.server === "string" &&
682
- canonicalListenerEndpoint(cut.launch.server) === cut.launch.server &&
683
- (cut.launch.custody === undefined ? cut.launch.controller === undefined
684
- : cut.launch.custody === "legacy" ? cut.launch.controller === undefined
685
- : cut.launch.custody === "controller" && validControllerCutBinding(cut.launch.controller)));
686
- }
687
- const CONTROLLER_ROLES = ["broker", "auth", "delivery", "manager"];
688
- const SHA256_HEX = /^[0-9a-f]{64}$/;
689
- /** A protected local record revision (protected-records.ts mints a UUID; older records are text). */
690
- const DEFINITION_REVISION = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,199}$/;
691
- const DEFINITION_NAME = /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/;
692
- function validPinnedProcess(value) {
693
- const pinned = value;
694
- return Boolean(pinned && typeof pinned === "object" && exactObjectKeys(pinned, ["pid", "token"]) &&
695
- Number.isInteger(pinned.pid) && Number(pinned.pid) > 0 &&
696
- typeof pinned.token === "string" && pinned.token !== "" && pinned.token.trim() === pinned.token &&
697
- pinned.token.length <= 256 && !/[\u0000-\u001f\u007f]/u.test(pinned.token));
698
- }
699
- function validControllerMember(value) {
700
- const member = value;
701
- return Boolean(member && typeof member === "object" &&
702
- exactObjectKeys(member, ["role", "definition", "definitionRevision", "instanceId", "launchRequestId", "process"]) &&
703
- CONTROLLER_ROLES.includes(member.role) &&
704
- typeof member.definition === "string" && DEFINITION_NAME.test(member.definition) &&
705
- typeof member.definitionRevision === "string" && DEFINITION_REVISION.test(member.definitionRevision) &&
706
- typeof member.instanceId === "string" && SERVICE_ID.test(member.instanceId) &&
707
- typeof member.launchRequestId === "string" && SERVICE_ID.test(member.launchRequestId) &&
708
- validPinnedProcess(member.process));
709
- }
710
- /** Members are unique by role and instance, and always include the broker and the manager. The
711
- * broker member keeps its cut-time revision; only `brokerDefinitionRevision` is rebound by a
712
- * restore rollback, so the two are not compared here. */
713
- function validControllerCutBinding(value) {
714
- const binding = value;
715
- const manager = binding?.manager;
716
- if (!binding || typeof binding !== "object" ||
717
- !exactObjectKeys(binding, ["stackOperationId", "brokerDefinitionRevision", "members", "manager"]) ||
718
- typeof binding.stackOperationId !== "string" || !SERVICE_ID.test(binding.stackOperationId) ||
719
- typeof binding.brokerDefinitionRevision !== "string" || !DEFINITION_REVISION.test(binding.brokerDefinitionRevision) ||
720
- !Array.isArray(binding.members) || binding.members.length < 2 || binding.members.length > CONTROLLER_ROLES.length ||
721
- !binding.members.every(validControllerMember) ||
722
- !manager || typeof manager !== "object" || !exactObjectKeys(manager, ["instanceId", "epoch", "lifecycleUid"]) ||
723
- typeof manager.instanceId !== "string" || !/^[A-Za-z0-9][A-Za-z0-9._:-]{0,255}$/.test(manager.instanceId) ||
724
- !Number.isSafeInteger(manager.epoch) || Number(manager.epoch) < 0 ||
725
- typeof manager.lifecycleUid !== "string" || !/^[A-Za-z0-9][A-Za-z0-9._:-]{0,255}$/.test(manager.lifecycleUid))
726
- return false;
727
- const roles = binding.members.map((member) => member.role);
728
- const broker = binding.members.find((member) => member.role === "broker");
729
- return new Set(roles).size === roles.length && roles.includes("manager") && Boolean(broker) &&
730
- new Set(binding.members.map((member) => member.instanceId)).size === binding.members.length;
731
- }
732
- /** The cut's controller binding, or undefined for a legacy cut. The journal reader has validated it. */
733
- export function cutController(cut) {
734
- return cut.launch.custody === "controller" ? cut.launch.controller : undefined;
735
- }
736
- function validControllerStop(value, members) {
737
- const stop = value;
738
- if (!stop || typeof stop !== "object" || !exactObjectKeys(stop, ["role", "instanceId", "launchRequestId", "receipt"]))
739
- return false;
740
- const member = members.find((row) => row.role === stop.role);
741
- if (!member || member.instanceId !== stop.instanceId || member.launchRequestId !== stop.launchRequestId)
742
- return false;
743
- const receipt = stop.receipt;
744
- const kind = stop.role === "manager" ? "preserved-exit" : stop.role === "broker" ? "kernel-exit" : "process-exit";
745
- const scoped = kind !== "process-exit";
746
- return Boolean(receipt && typeof receipt === "object" &&
747
- exactObjectKeys(receipt, scoped ? ["kind", "requestId", "scopeSha256", "observedAt"] : ["kind", "requestId", "observedAt"]) &&
748
- receipt.kind === kind && typeof receipt.requestId === "string" && SERVICE_ID.test(receipt.requestId) &&
749
- (!scoped || typeof receipt.scopeSha256 === "string" && SHA256_HEX.test(receipt.scopeSha256)) &&
750
- validTimestamp(receipt.observedAt));
751
- }
752
- /** One row per cut member, in any order, with the receipt kind its role requires. */
753
- function validControllerStops(value, binding) {
754
- return Array.isArray(value) && value.length === binding.members.length &&
755
- value.every((stop) => validControllerStop(stop, binding.members)) &&
756
- new Set(value.map((stop) => stop.role)).size === value.length;
757
- }
758
- function validPreservedStop(value, cut, binding) {
759
- const stop = value;
760
- const manager = binding.members.find((member) => member.role === "manager");
761
- if (!stop || typeof stop !== "object" || !exactObjectKeys(stop, ["instanceId", "launchRequestId", "attempts"]) ||
762
- stop.instanceId !== manager.instanceId || stop.launchRequestId !== manager.launchRequestId ||
763
- !Array.isArray(stop.attempts) || stop.attempts.length < 1 || stop.attempts.length > 16)
764
- return false;
765
- // An unpublished attempt at any position is prepublication history.
766
- return stop.attempts.every((attempt) => {
767
- const row = attempt;
768
- const published = exactObjectKeys(row, ["requestId", "target", "stopper", "withAgents", "scopeSha256", "preserved", "recordedAt", "published"]);
769
- return Boolean((published || exactObjectKeys(row, ["requestId", "target", "stopper", "withAgents", "scopeSha256", "preserved", "recordedAt"])) &&
770
- (!published || row.published === true) &&
771
- typeof row.requestId === "string" && SERVICE_ID.test(row.requestId) &&
772
- validPinnedProcess(row.target) && row.target.pid === manager.process.pid && row.target.token === manager.process.token &&
773
- validPinnedProcess(row.stopper) && row.withAgents === false &&
774
- typeof row.scopeSha256 === "string" && SHA256_HEX.test(row.scopeSha256) &&
775
- row.preserved && typeof row.preserved === "object" && exactObjectKeys(row.preserved, ["attemptId", "inventorySha256"]) &&
776
- row.preserved.attemptId === cut.attemptId &&
777
- typeof row.preserved.inventorySha256 === "string" && SHA256_HEX.test(row.preserved.inventorySha256) &&
778
- validTimestamp(row.recordedAt));
779
- }) && new Set(stop.attempts.map((attempt) => attempt.requestId)).size === stop.attempts.length;
780
- }
781
- /** A rollback rebound the broker revision away from the one the cut's broker record runs at, so that
782
- * record can never start again (`startProcessService` refuses a revision mismatch). */
783
- function cutBrokerRetired(cut) {
784
- return cut.members.find((member) => member.role === "broker").definitionRevision !== cut.brokerDefinitionRevision;
785
- }
786
- function validAttemptBroker(value, cut) {
787
- const broker = value;
788
- return Boolean(broker && typeof broker === "object" && exactObjectKeys(broker, ["instanceId", "launchRequestId"]) &&
789
- typeof broker.instanceId === "string" && SERVICE_ID.test(broker.instanceId) &&
790
- typeof broker.launchRequestId === "string" && SERVICE_ID.test(broker.launchRequestId) &&
791
- broker.instanceId !== cut.members.find((member) => member.role === "broker").instanceId);
792
- }
793
- function validControllerResumeBinding(value, cut) {
794
- const binding = value;
795
- if (!binding || typeof binding !== "object" ||
796
- !exactObjectKeys(binding, binding.broker === undefined ? ["stackOperationId", "started"] : ["stackOperationId", "started", "broker"]) ||
797
- binding.broker !== undefined && (!cutBrokerRetired(cut) || !validAttemptBroker(binding.broker, cut)) ||
798
- typeof binding.stackOperationId !== "string" || !SERVICE_ID.test(binding.stackOperationId) ||
799
- binding.stackOperationId === cut.stackOperationId ||
800
- !Array.isArray(binding.started) || binding.started.length > 64)
801
- return false;
802
- return binding.started.every((value) => {
803
- const row = value;
804
- const keys = ["role", "instanceId", "priorLaunchRequestId", "state"];
805
- const settled = row?.launchRequestId !== undefined || row?.outcome !== undefined;
806
- return Boolean(row && typeof row === "object" &&
807
- exactObjectKeys(row, settled ? [...keys, "launchRequestId", "outcome"] : keys) &&
808
- CONTROLLER_ROLES.includes(row.role) && row.state === "requested" &&
809
- typeof row.instanceId === "string" && SERVICE_ID.test(row.instanceId) &&
810
- typeof row.priorLaunchRequestId === "string" && SERVICE_ID.test(row.priorLaunchRequestId) &&
811
- (!settled || typeof row.launchRequestId === "string" && SERVICE_ID.test(row.launchRequestId) &&
812
- row.launchRequestId !== row.priorLaunchRequestId &&
813
- ["running", "refused-before-spawn", "unknown"].includes(String(row.outcome))));
814
- });
815
- }
816
- /** The resume's controller binding, or undefined for a legacy resume. The journal reader has validated it. */
817
- export function ordinaryResumeController(context) {
818
- return context.launch.custody === "controller" ? context.launch.controller : undefined;
819
- }
820
- function validTokenHandoff(value, handoffDir, attemptId) {
821
- const handoff = value;
822
- if (!handoff || typeof handoff !== "object")
823
- return false;
824
- const pinned = handoff.dev !== undefined || handoff.ino !== undefined || handoff.sha256 !== undefined;
825
- if (!exactObjectKeys(handoff, pinned ? ["path", "state", "dev", "ino", "sha256"] : ["path", "state"]))
826
- return false;
827
- if (typeof handoff.path !== "string" || dirname(handoff.path) !== handoffDir ||
828
- !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)))
829
- return false;
830
- // `intended` never has an inode; `written` always has one; consumed or swept keep it when it was written.
831
- if (handoff.state === "intended")
832
- return !pinned;
833
- if (!["written", "consumed", "swept"].includes(handoff.state))
834
- return false;
835
- if (handoff.state === "written" && !pinned)
836
- return false;
837
- return !pinned || (typeof handoff.dev === "string" && /^\d+$/.test(handoff.dev) &&
838
- typeof handoff.ino === "string" && /^\d+$/.test(handoff.ino) &&
839
- typeof handoff.sha256 === "string" && SHA256_HEX.test(handoff.sha256));
840
- }
841
- function validControllerReconfiguration(value, restore, binding) {
842
- const reconfiguration = value;
843
- if (!reconfiguration || typeof reconfiguration !== "object")
844
- return false;
845
- const keys = ["fromRevision", "fromOptionsSha256", "fromConfigPath", "fromConfigSha256", "toConfigPath", "toConfigSha256", "toStoreIdentity", "phase"];
846
- const phase = reconfiguration.phase;
847
- const expected = phase === "rendered" ? keys
848
- : phase === "definition-committed" || phase === "rolling-back" ? [...keys, "toRevision"]
849
- : phase === "rolled-back" ? [...keys, "toRevision", "rollbackRevision"] : undefined;
850
- return Boolean(expected && exactObjectKeys(reconfiguration, expected) &&
851
- typeof reconfiguration.fromRevision === "string" && DEFINITION_REVISION.test(reconfiguration.fromRevision) &&
852
- typeof reconfiguration.fromOptionsSha256 === "string" && SHA256_HEX.test(reconfiguration.fromOptionsSha256) &&
853
- typeof reconfiguration.fromConfigPath === "string" && isAbsolute(reconfiguration.fromConfigPath) &&
854
- reconfiguration.fromConfigPath !== reconfiguration.toConfigPath &&
855
- typeof reconfiguration.fromConfigSha256 === "string" && SHA256_HEX.test(reconfiguration.fromConfigSha256) &&
856
- typeof reconfiguration.toConfigPath === "string" && isAbsolute(reconfiguration.toConfigPath) &&
857
- restore.ownedPaths?.some((owned) => owned.label === "config" && owned.path === reconfiguration.toConfigPath) &&
858
- typeof reconfiguration.toConfigSha256 === "string" && SHA256_HEX.test(reconfiguration.toConfigSha256) &&
859
- validIdentity(reconfiguration.toStoreIdentity) && reconfiguration.toStoreIdentity.path === restore.targetPath &&
860
- (restore.target === undefined || sameStoreIdentity(reconfiguration.toStoreIdentity, restore.target)) &&
861
- (reconfiguration.toRevision === undefined ||
862
- typeof reconfiguration.toRevision === "string" && DEFINITION_REVISION.test(reconfiguration.toRevision) &&
863
- reconfiguration.toRevision !== reconfiguration.fromRevision) &&
864
- (reconfiguration.rollbackRevision === undefined ||
865
- typeof reconfiguration.rollbackRevision === "string" && DEFINITION_REVISION.test(reconfiguration.rollbackRevision) &&
866
- reconfiguration.rollbackRevision !== reconfiguration.fromRevision && reconfiguration.rollbackRevision !== reconfiguration.toRevision &&
867
- reconfiguration.rollbackRevision === binding.brokerDefinitionRevision) &&
868
- // Before a rollback the cut still expects the revision the rewrite started from.
869
- (phase === "rolled-back" || reconfiguration.fromRevision === binding.brokerDefinitionRevision));
870
- }
871
- /** A restore's proof scope: its context and the attempt broker its launch binding names. */
872
- function restoreProofScope(record) {
873
- const broker = record.launch.controller?.broker;
874
- return { restore: record.restore, ...(broker ? { broker } : {}) };
875
- }
876
- /** A controller listener proof fits the journal's own record of which broker it may name. A
877
- * resume names a settled `started` broker row. A restore names `reconfiguredBroker` or its
878
- * binding's attempt broker when present, otherwise the cut's broker instance at a new launch
879
- * request. An attempt broker of a resume must be that exact pair too. The caller still checks
880
- * that the instance record is running at that launch request with that process. */
881
- function controllerProofFits(proof, cut, scope) {
882
- const instance = proof.instance;
883
- if (proof.kind !== "controller" || !instance)
884
- return false;
885
- const exact = (pair) => pair.instanceId === instance.instanceId && pair.launchRequestId === instance.launchRequestId;
886
- if ("resume" in scope)
887
- return (!scope.resume.broker || exact(scope.resume.broker)) &&
888
- scope.resume.started.some((row) => row.role === "broker" && row.instanceId === instance.instanceId &&
889
- row.launchRequestId === instance.launchRequestId);
890
- const attempt = scope.restore.reconfiguredBroker ?? scope.broker;
891
- if (attempt)
892
- return exact(attempt);
893
- const broker = cut.members.find((member) => member.role === "broker");
894
- return broker.instanceId === instance.instanceId && broker.launchRequestId !== instance.launchRequestId;
895
- }
896
- /** The proof variant follows the cut's custody, and a controller proof fits its scope. */
897
- function listenerProofFitsCustody(proof, cut, scope) {
898
- const controller = cutController(cut);
899
- if (!controller)
900
- return proof.kind === undefined;
901
- return scope !== undefined && controllerProofFits(proof, controller, scope);
902
- }
903
- function validCutCompletionEvidence(value, cut) {
904
- const evidence = value;
905
- const controller = cutController(cut);
906
- return Boolean(evidence && typeof evidence === "object" &&
907
- exactObjectKeys(evidence, controller
908
- ? ["attemptId", "observedAt", "managerCommit", "stopped", "listener", "controllerStops"]
909
- : ["attemptId", "observedAt", "managerCommit", "stopped", "listener"]) &&
910
- (!controller || validControllerStops(evidence.controllerStops, controller)) &&
911
- evidence.attemptId === cut.attemptId && validTimestamp(evidence.observedAt) &&
912
- evidence.managerCommit && typeof evidence.managerCommit === "object" &&
913
- exactObjectKeys(evidence.managerCommit, ["operation", "attemptId", "state"]) &&
914
- evidence.managerCommit.operation === "commitPreservation" &&
915
- evidence.managerCommit.attemptId === cut.attemptId && evidence.managerCommit.state === "preserved" &&
916
- evidence.stopped && typeof evidence.stopped === "object" &&
917
- exactObjectKeys(evidence.stopped, ["manager", "broker", "localProcesses"]) &&
918
- evidence.stopped.manager === true && evidence.stopped.broker === true && evidence.stopped.localProcesses === true &&
919
- evidence.listener && typeof evidence.listener === "object" &&
920
- exactObjectKeys(evidence.listener, ["endpoint", "unreachable"]) &&
921
- evidence.listener.endpoint === cut.launch.server && evidence.listener.unreachable === true);
922
- }
923
- function normalizedListenerProof(value) {
924
- if (!validListenerProof(value))
925
- maintenanceError("listener-proof-invalid", "restore listener proof is invalid, non-canonical, or oversized");
926
- return {
927
- attemptId: value.attemptId,
928
- serverName: value.serverName,
929
- serverNonce: value.serverNonce,
930
- processOwner: {
931
- pid: value.processOwner.pid,
932
- host: value.processOwner.host,
933
- startedAt: value.processOwner.startedAt,
934
- id: value.processOwner.id,
935
- },
936
- serverEndpoint: value.serverEndpoint,
937
- target: {
938
- path: value.target.path,
939
- dev: value.target.dev,
940
- ino: value.target.ino,
941
- generation: value.target.generation,
942
- },
943
- ...(value.kind === "controller" && value.instance ? {
944
- kind: "controller",
945
- instance: {
946
- instanceId: value.instance.instanceId,
947
- launchRequestId: value.instance.launchRequestId,
948
- process: { pid: value.instance.process.pid, token: value.instance.process.token },
949
- },
950
- } : {}),
951
- };
952
- }
953
- function sameProcessOwner(a, b) {
954
- return a.pid === b.pid && a.host === b.host && a.startedAt === b.startedAt && a.id === b.id;
955
- }
956
- /** The proof variant must match the cut's custody, and a controller proof must fit the journal's
957
- * recorded broker. The workspace cannot read service instance records, so the caller passes the
958
- * live check that the named instance is running at that launch request with that process. A
959
- * controller proof without that check refuses. */
960
- function requireCustodyProof(proof, cut, scope, running, root, attemptId) {
961
- if (!listenerProofFitsCustody(proof, cut, scope))
962
- maintenanceError("listener-proof-mismatch", proof.kind === "controller"
963
- ? "the controller listener proof does not name this attempt's recorded broker instance"
964
- : "a legacy listener proof cannot bind a controller-custody attempt", { root, attemptId });
965
- if (proof.kind === "controller" && (!running || !running(proof.instance)))
966
- maintenanceError("listener-proof-mismatch", "the controller listener's broker instance is not proven running at that launch request and process", { root, attemptId });
967
- }
968
- function sameListenerProof(a, b) {
969
- return a.kind === b.kind && a.attemptId === b.attemptId && a.serverName === b.serverName &&
970
- a.serverNonce === b.serverNonce && sameProcessOwner(a.processOwner, b.processOwner) &&
971
- a.serverEndpoint === b.serverEndpoint && sameStoreIdentity(a.target, b.target) &&
972
- (a.kind !== "controller" || Boolean(a.instance && b.instance &&
973
- a.instance.instanceId === b.instance.instanceId && a.instance.launchRequestId === b.instance.launchRequestId &&
974
- a.instance.process.pid === b.instance.process.pid && a.instance.process.token === b.instance.process.token));
975
- }
976
- function reusesListenerIdentity(a, b) {
977
- return a.serverName === b.serverName || a.serverNonce === b.serverNonce ||
978
- sameProcessOwner(a.processOwner, b.processOwner) ||
979
- Boolean(a.instance && b.instance && a.instance.launchRequestId === b.instance.launchRequestId);
980
- }
981
- function validListenerReplacements(value) {
982
- if (!Array.isArray(value) || value.length === 0 || value.length > 1024)
983
- return false;
984
- const replacements = value;
985
- for (let index = 0; index < replacements.length; index++) {
986
- const replacement = replacements[index];
987
- if (!replacement || typeof replacement !== "object" ||
988
- !exactObjectKeys(replacement, ["generation", "replacedAt", "proof"]) ||
989
- replacement.generation !== index + 1 || typeof replacement.replacedAt !== "string" ||
990
- replacement.replacedAt.length > 64 || !Number.isFinite(Date.parse(replacement.replacedAt)) ||
991
- !validListenerProof(replacement.proof))
992
- return false;
993
- if (replacements.slice(0, index).some((prior) => reusesListenerIdentity(prior.proof, replacement.proof)))
994
- return false;
995
- }
996
- return Buffer.byteLength(JSON.stringify(replacements)) <= 512 * 1024;
997
- }
998
- function assertListenerOwnerAlive(proof) {
999
- const status = localProcessOwnerStatus(proof.processOwner);
1000
- if (status === "unknown")
1001
- maintenanceError("listener-owner-ambiguous", "restore listener process ownership cannot be proven locally", {
1002
- attemptId: proof.attemptId,
1003
- recourse: [{ action: "inspect", description: "Prove the recorded listener owner and server nonce before recovery." }],
1004
- });
1005
- if (status === "dead")
1006
- maintenanceError("listener-owner-dead", "recorded restore listener process is not alive", {
1007
- attemptId: proof.attemptId,
1008
- recourse: [{ action: "repair", description: "Preserve both stores and relaunch through an explicit restore recovery path." }],
1009
- });
1010
- }
1011
- function validJson(value) {
1012
- if (value === null || typeof value === "string" || typeof value === "boolean")
1013
- return true;
1014
- if (typeof value === "number")
1015
- return Number.isFinite(value);
1016
- if (Array.isArray(value))
1017
- return value.every(validJson);
1018
- if (!value || typeof value !== "object")
1019
- return false;
1020
- return Object.values(value).every(validJson);
1021
- }
1022
- function validJsonObject(value) {
1023
- if (!value || typeof value !== "object" || Array.isArray(value))
1024
- return false;
1025
- const prototype = Object.getPrototypeOf(value);
1026
- return (prototype === Object.prototype || prototype === null) && validJson(value);
1027
- }
1028
- function sameJsonValue(a, b) {
1029
- if (a === b)
1030
- return true;
1031
- if (Array.isArray(a) || Array.isArray(b)) {
1032
- if (!Array.isArray(a) || !Array.isArray(b))
1033
- return false;
1034
- return a.length === b.length && a.every((item, index) => sameJsonValue(item, b[index]));
1035
- }
1036
- if (!a || !b || typeof a !== "object" || typeof b !== "object")
1037
- return false;
1038
- const aObject = a;
1039
- const bObject = b;
1040
- const aKeys = Object.keys(aObject).sort();
1041
- const bKeys = Object.keys(bObject).sort();
1042
- return aKeys.length === bKeys.length && aKeys.every((key, index) => key === bKeys[index] && sameJsonValue(aObject[key], bObject[key]));
1043
- }
1044
- function cloneJsonValue(value, seen, depth = 0, budget = { nodes: 0 }) {
1045
- if (++budget.nodes > 100_000 || depth > 64)
1046
- maintenanceError("resume-too-large", "maintenance resume document is too deeply nested or complex");
1047
- if (value === null || typeof value === "boolean")
1048
- return value;
1049
- if (typeof value === "string") {
1050
- if (Buffer.byteLength(value) > MAX_MAINTENANCE_RESUME_BYTES)
1051
- maintenanceError("resume-too-large", "maintenance resume document contains an oversized string");
1052
- return value;
1053
- }
1054
- if (typeof value === "number") {
1055
- if (!Number.isFinite(value))
1056
- maintenanceError("resume-invalid", "maintenance resume document contains a non-finite number");
1057
- return value;
1058
- }
1059
- if (!value || typeof value !== "object")
1060
- maintenanceError("resume-invalid", "maintenance resume document must contain only JSON values");
1061
- if (seen.has(value))
1062
- maintenanceError("resume-invalid", "maintenance resume document contains a cycle");
1063
- seen.add(value);
1064
- try {
1065
- if (Array.isArray(value)) {
1066
- if (Reflect.ownKeys(value).length !== value.length + 1)
1067
- maintenanceError("resume-invalid", "maintenance resume arrays must be dense plain data");
1068
- return Array.from({ length: value.length }, (_, index) => {
1069
- const descriptor = Object.getOwnPropertyDescriptor(value, String(index));
1070
- if (!descriptor || !descriptor.enumerable || descriptor.get || descriptor.set)
1071
- maintenanceError("resume-invalid", "maintenance resume arrays must contain data properties only");
1072
- return cloneJsonValue(descriptor.value, seen, depth + 1, budget);
1073
- });
1074
- }
1075
- const prototype = Object.getPrototypeOf(value);
1076
- if (prototype !== Object.prototype && prototype !== null)
1077
- maintenanceError("resume-invalid", "maintenance resume document objects must be plain data");
1078
- const descriptors = Object.getOwnPropertyDescriptors(value);
1079
- const keys = Object.keys(descriptors).sort((a, b) => a < b ? -1 : a > b ? 1 : 0);
1080
- if (Reflect.ownKeys(value).length !== keys.length ||
1081
- keys.some((key) => !descriptors[key].enumerable || descriptors[key].get || descriptors[key].set))
1082
- maintenanceError("resume-invalid", "maintenance resume document objects must contain enumerable data properties only");
1083
- const output = Object.create(null);
1084
- for (const key of keys)
1085
- Object.defineProperty(output, key, {
1086
- value: cloneJsonValue(descriptors[key].value, seen, depth + 1, budget),
1087
- enumerable: true,
1088
- configurable: true,
1089
- writable: true,
1090
- });
1091
- return output;
1092
- }
1093
- finally {
1094
- seen.delete(value);
1095
- }
1096
- }
1097
- function resumeBytes(document) {
1098
- if (!document || typeof document !== "object" || Array.isArray(document))
1099
- maintenanceError("resume-invalid", "maintenance resume document must be exactly { version, inventory, launch }");
1100
- const prototype = Object.getPrototypeOf(document);
1101
- const descriptors = Object.getOwnPropertyDescriptors(document);
1102
- const keys = Object.keys(descriptors).sort();
1103
- if ((prototype !== Object.prototype && prototype !== null) || Reflect.ownKeys(document).length !== 3 ||
1104
- keys.join(",") !== "inventory,launch,version" ||
1105
- keys.some((key) => !descriptors[key].enumerable || descriptors[key].get || descriptors[key].set) ||
1106
- descriptors.version.value !== MAINTENANCE_RESUME_DOCUMENT_VERSION)
1107
- maintenanceError("resume-invalid", "maintenance resume document must be exactly { version, inventory, launch }");
1108
- const normalized = {
1109
- version: MAINTENANCE_RESUME_DOCUMENT_VERSION,
1110
- inventory: cloneJsonValue(descriptors.inventory.value, new Set()),
1111
- launch: cloneJsonValue(descriptors.launch.value, new Set()),
1112
- };
1113
- const data = `${JSON.stringify(normalized, null, 2)}\n`;
1114
- const bytes = Buffer.byteLength(data);
1115
- if (bytes > MAX_MAINTENANCE_RESUME_BYTES)
1116
- maintenanceError("resume-too-large", `maintenance resume document exceeds ${MAX_MAINTENANCE_RESUME_BYTES} bytes`);
1117
- return {
1118
- document: normalized,
1119
- data,
1120
- descriptor: {
1121
- version: MAINTENANCE_RESUME_DOCUMENT_VERSION,
1122
- file: "resume.json",
1123
- bytes,
1124
- sha256: createHash("sha256").update(data).digest("hex"),
1125
- },
1126
- };
1127
- }
1128
- function validResumeDescriptor(value) {
1129
- const descriptor = value;
1130
- return Boolean(descriptor && typeof descriptor === "object" &&
1131
- descriptor.version === MAINTENANCE_RESUME_DOCUMENT_VERSION && descriptor.file === "resume.json" &&
1132
- Number.isInteger(descriptor.bytes) && descriptor.bytes > 0 && descriptor.bytes <= MAX_MAINTENANCE_RESUME_BYTES &&
1133
- typeof descriptor.sha256 === "string" && /^[0-9a-f]{64}$/.test(descriptor.sha256));
1134
- }
1135
- function sameResumeDescriptor(a, b) {
1136
- return a.version === b.version && a.file === b.file && a.bytes === b.bytes && a.sha256 === b.sha256;
1137
- }
1138
- /** Atomically persist the bounded private resume inventory and launch provenance before publishing ready. */
1139
- export function writeMaintenanceResumeDocument(lock, document) {
1140
- assertLock(lock);
1141
- const paths = maintenancePaths(lock.root);
1142
- ensureLayout(paths);
1143
- const serialized = resumeBytes(document);
1144
- const journal = readMaintenanceJournal(lock.root);
1145
- if (journal) {
1146
- if (!sameResumeDescriptor(journal.resume, serialized.descriptor))
1147
- maintenanceError("invalid-transition", "cannot replace the resume document referenced by a maintenance journal", {
1148
- root: lock.root,
1149
- paths: [paths.resume, paths.journal],
1150
- recourse: [{ action: "repair", description: "Complete or explicitly repair the current maintenance state before writing another resume document.", paths: [paths.journal] }],
1151
- });
1152
- return journal.resume;
1153
- }
1154
- const tmp = `${paths.resume}.${process.pid}.${randomUUID()}.tmp`;
1155
- try {
1156
- writePrivateExclusive(tmp, serialized.data);
1157
- renameSync(tmp, paths.resume);
1158
- fsyncDirectory(paths.versionDir);
1159
- }
1160
- catch (error) {
1161
- try {
1162
- unlinkSync(tmp);
1163
- }
1164
- catch { /* best effort for an exclusively-created private temp */ }
1165
- throw error;
1166
- }
1167
- readMaintenanceResumeDocument(lock.root, serialized.descriptor);
1168
- return serialized.descriptor;
1169
- }
1170
- /** Read exactly the fixed resume file after size, mode, SHA-256, version, and JSON-shape verification. */
1171
- export function readMaintenanceResumeDocument(root, descriptor) {
1172
- const paths = maintenancePaths(root);
1173
- if (!validResumeDescriptor(descriptor))
1174
- maintenanceError("resume-invalid", "maintenance resume descriptor is invalid", { paths: [paths.journal] });
1175
- let fd;
1176
- try {
1177
- const noFollow = constants.O_NOFOLLOW ?? 0;
1178
- fd = openSync(paths.resume, constants.O_RDONLY | noFollow);
1179
- }
1180
- catch (error) {
1181
- if (errno(error) === "ENOENT")
1182
- maintenanceError("resume-missing", "maintenance resume document is missing", {
1183
- root: paths.root,
1184
- paths: [paths.resume],
1185
- recourse: [{ action: "repair", description: "Restore the exact resume document before using this maintenance cut.", paths: [paths.resume] }],
1186
- });
1187
- if (errno(error) === "ELOOP")
1188
- maintenanceError("resume-mismatch", "maintenance resume document must not be a symlink", { paths: [paths.resume] });
1189
- maintenanceError("resume-invalid", "maintenance resume document cannot be inspected", { paths: [paths.resume] });
1190
- }
1191
- let bytes;
1192
- try {
1193
- const before = fstatSync(fd, { bigint: true });
1194
- if (!before.isFile() || before.size !== BigInt(descriptor.bytes) ||
1195
- before.size > BigInt(MAX_MAINTENANCE_RESUME_BYTES) ||
1196
- (process.platform !== "win32" && (before.mode & 63n) !== 0n))
1197
- maintenanceError("resume-mismatch", "maintenance resume document metadata does not match its descriptor", {
1198
- root: paths.root,
1199
- paths: [paths.resume],
1200
- recourse: [{ action: "inspect", description: "Do not resume or restore from a missing, replaced, or non-private document.", paths: [paths.resume] }],
1201
- });
1202
- const bounded = Buffer.alloc(descriptor.bytes + 1);
1203
- let length = 0;
1204
- while (length < bounded.length) {
1205
- const count = readSync(fd, bounded, length, bounded.length - length, null);
1206
- if (count === 0)
1207
- break;
1208
- length += count;
1209
- }
1210
- const after = fstatSync(fd, { bigint: true });
1211
- if (length !== descriptor.bytes || before.dev !== after.dev || before.ino !== after.ino ||
1212
- before.size !== after.size || before.mtimeNs !== after.mtimeNs || before.ctimeNs !== after.ctimeNs)
1213
- maintenanceError("resume-mismatch", "maintenance resume document changed while it was being read", {
1214
- root: paths.root, paths: [paths.resume],
1215
- });
1216
- bytes = bounded.subarray(0, length);
1217
- }
1218
- finally {
1219
- closeSync(fd);
1220
- }
1221
- const digest = createHash("sha256").update(bytes).digest("hex");
1222
- if (digest !== descriptor.sha256)
1223
- maintenanceError("resume-mismatch", "maintenance resume document SHA-256 does not match its descriptor", {
1224
- root: paths.root,
1225
- paths: [paths.resume],
1226
- recourse: [{ action: "inspect", description: "Restore the exact content-addressed resume document before continuing.", paths: [paths.resume] }],
1227
- });
1228
- let parsed;
1229
- try {
1230
- parsed = JSON.parse(bytes.toString("utf8"));
1231
- }
1232
- catch {
1233
- maintenanceError("resume-invalid", "maintenance resume document is not valid JSON", { paths: [paths.resume] });
1234
- }
1235
- const normalized = resumeBytes(parsed).document;
1236
- return normalized;
1237
- }
1238
- function validRecourse(value) {
1239
- return Array.isArray(value) && value.every((item) => {
1240
- const r = item;
1241
- return Boolean(r && typeof r === "object" &&
1242
- ["retry", "inspect", "rollback", "repair", "cleanup"].includes(r.action) &&
1243
- typeof r.description === "string" &&
1244
- (r.command === undefined || typeof r.command === "string") &&
1245
- (r.paths === undefined || (Array.isArray(r.paths) && r.paths.every((p) => typeof p === "string" && isAbsolute(p)))));
1246
- });
1247
- }
1248
- function validateRestoreContext(record, path) {
1249
- const restore = record.restore;
1250
- if (!restore || typeof restore.attemptId !== "string" || !ATTEMPT_ID.test(restore.attemptId) ||
1251
- !["same-path", "alternate", "disaster"].includes(restore.method) ||
1252
- typeof restore.targetPath !== "string" || !isAbsolute(restore.targetPath) ||
1253
- (restore.selection !== undefined && !["full", "registry"].includes(restore.selection)))
1254
- maintenanceError("journal-corrupt", "restore context is invalid", { paths: [path] });
1255
- if (restore.target && (!validIdentity(restore.target) || restore.target.path !== restore.targetPath))
1256
- maintenanceError("journal-corrupt", "restore target identity is invalid", { paths: [path] });
1257
- if (restore.previousSource &&
1258
- (!["fallback", "retained"].includes(restore.previousSource.kind) || !validIdentity(restore.previousSource.identity)))
1259
- maintenanceError("journal-corrupt", "previous source identity is invalid", { paths: [path] });
1260
- if (restore.method === "same-path") {
1261
- if (restore.targetPath !== record.source.path || typeof restore.fallbackPath !== "string" ||
1262
- !isAbsolute(restore.fallbackPath) || dirname(restore.fallbackPath) !== dirname(record.source.path))
1263
- maintenanceError("journal-corrupt", "same-path restore paths are inconsistent", { paths: [path] });
1264
- if (record.state === "restore-ready" && !["move-pending", "source-moved"].includes(record.phase))
1265
- maintenanceError("journal-corrupt", "same-path restore phase is inconsistent", { paths: [path] });
1266
- if (record.state === "restore-ready" && record.phase === "move-pending" &&
1267
- (restore.previousSource || restore.target || restore.cleanup))
1268
- maintenanceError("journal-corrupt", "pending move unexpectedly records bound or owned paths", { paths: [path] });
1269
- if ((record.state !== "restore-ready" || record.phase === "source-moved") &&
1270
- (!restore.previousSource || restore.previousSource.kind !== "fallback" ||
1271
- restore.previousSource.identity.path !== restore.fallbackPath ||
1272
- restore.previousSource.identity.dev !== record.source.dev || restore.previousSource.identity.ino !== record.source.ino ||
1273
- restore.previousSource.identity.generation !== record.source.generation))
1274
- maintenanceError("journal-corrupt", "moved source identity is inconsistent", { paths: [path] });
1275
- }
1276
- else if (restore.method === "alternate") {
1277
- if (restore.targetPath === record.source.path || restore.fallbackPath !== undefined ||
1278
- !restore.previousSource || restore.previousSource.kind !== "retained" ||
1279
- !sameStoreIdentity(restore.previousSource.identity, record.source) ||
1280
- (record.state === "restore-ready" && record.phase !== "source-retained"))
1281
- maintenanceError("journal-corrupt", "alternate restore context is inconsistent", { paths: [path] });
1282
- if (pathContains(record.source.path, restore.targetPath) || pathContains(restore.targetPath, record.source.path))
1283
- maintenanceError("journal-corrupt", "alternate restore source and target trees overlap", {
1284
- paths: [path, record.source.path, restore.targetPath],
1285
- });
1286
- }
1287
- else if (restore.targetPath !== record.source.path || restore.fallbackPath !== undefined ||
1288
- restore.previousSource !== undefined ||
1289
- (record.state === "restore-ready" && record.phase !== "disaster-source-missing")) {
1290
- maintenanceError("journal-corrupt", "disaster restore context is inconsistent", { paths: [path] });
1291
- }
1292
- if (restore.ownedPaths !== undefined && !validOwnedPaths(restore.ownedPaths))
1293
- maintenanceError("journal-corrupt", "restore attempt-owned paths are invalid", { paths: [path] });
1294
- const controller = cutController(record.cut);
1295
- if (restore.controllerReconfiguration !== undefined &&
1296
- (!controller || restore.method !== "alternate" ||
1297
- !validControllerReconfiguration(restore.controllerReconfiguration, restore, controller)))
1298
- maintenanceError("journal-corrupt", "restore broker reconfiguration is invalid or outside a controller alternate restore", { paths: [path] });
1299
- const reconfiguredBroker = restore.reconfiguredBroker;
1300
- if (reconfiguredBroker !== undefined) {
1301
- const broker = controller?.members.find((member) => member.role === "broker");
1302
- if (!broker || restore.controllerReconfiguration?.phase !== "definition-committed" ||
1303
- !reconfiguredBroker || typeof reconfiguredBroker !== "object" ||
1304
- !exactObjectKeys(reconfiguredBroker, ["instanceId", "launchRequestId"]) ||
1305
- typeof reconfiguredBroker.instanceId !== "string" || !SERVICE_ID.test(reconfiguredBroker.instanceId) ||
1306
- typeof reconfiguredBroker.launchRequestId !== "string" || !SERVICE_ID.test(reconfiguredBroker.launchRequestId) ||
1307
- reconfiguredBroker.instanceId === broker.instanceId)
1308
- maintenanceError("journal-corrupt", "reconfigured broker instance is invalid", { paths: [path] });
1309
- }
1310
- const handoff = record.tokenHandoff;
1311
- if (handoff !== undefined &&
1312
- !validTokenHandoff(handoff, join(dirname(path), "handoff"), restore.attemptId))
1313
- maintenanceError("journal-corrupt", "restore commit-token handoff record is invalid", { paths: [path] });
1314
- if (restore.cleanup) {
1315
- const cleanup = restore.cleanup;
1316
- if (!["attempt-target", "previous-source"].includes(cleanup.kind) ||
1317
- !["pending", "complete"].includes(cleanup.status) || !validIdentity(cleanup.identity) ||
1318
- cleanup.originalPath !== cleanup.identity.path || !isAbsolute(cleanup.tombPath) ||
1319
- dirname(cleanup.tombPath) !== dirname(cleanup.originalPath) ||
1320
- (cleanup.kind === "attempt-target" && (!restore.target || !sameStoreIdentity(cleanup.identity, restore.target))) ||
1321
- (cleanup.kind === "previous-source" && (!restore.previousSource || !sameStoreIdentity(cleanup.identity, restore.previousSource.identity))))
1322
- maintenanceError("journal-corrupt", "restore cleanup record is inconsistent", { paths: [path] });
1323
- }
1324
- }
1325
- function validateOrdinaryResume(record, path) {
1326
- const context = record.ordinaryResume;
1327
- if (!context || typeof context !== "object" || typeof context.attemptId !== "string" ||
1328
- !ATTEMPT_ID.test(context.attemptId) || typeof context.intentAt !== "string" ||
1329
- !Number.isFinite(Date.parse(context.intentAt)) || !validJsonObject(context.launch))
1330
- maintenanceError("journal-corrupt", "ordinary resume intent is invalid", { paths: [path] });
1331
- const cut = cutController(record.cut);
1332
- const custody = context.launch.custody;
1333
- if (cut ? custody !== "controller" || !validControllerResumeBinding(context.launch.controller, cut)
1334
- : custody !== undefined || context.launch.controller !== undefined)
1335
- maintenanceError("journal-corrupt", "ordinary resume custody does not match the cut", { paths: [path] });
1336
- const resumeScope = cut ? { resume: ordinaryResumeController(context) } : undefined;
1337
- if (record.tokenHandoff !== undefined &&
1338
- !validTokenHandoff(record.tokenHandoff, join(dirname(path), "handoff"), context.attemptId))
1339
- maintenanceError("journal-corrupt", "resume commit-token handoff record is invalid", { paths: [path] });
1340
- if (record.listenerProof !== undefined &&
1341
- (!validListenerProof(record.listenerProof) ||
1342
- !listenerProofFitsCustody(record.listenerProof, record.cut, resumeScope) ||
1343
- record.listenerProof.attemptId !== context.attemptId ||
1344
- !sameStoreIdentity(record.listenerProof.target, record.source) ||
1345
- typeof context.launch.server !== "string" ||
1346
- canonicalListenerEndpoint(context.launch.server) !== record.listenerProof.serverEndpoint))
1347
- maintenanceError("journal-corrupt", "resume listener proof is invalid or belongs to another attempt", { paths: [path] });
1348
- if (record.listenerReplacements !== undefined &&
1349
- (!validListenerReplacements(record.listenerReplacements) ||
1350
- record.listenerReplacements.some((replacement) => !listenerProofFitsCustody(replacement.proof, record.cut, resumeScope) ||
1351
- replacement.proof.attemptId !== context.attemptId ||
1352
- !sameStoreIdentity(replacement.proof.target, record.source) ||
1353
- typeof context.launch.server !== "string" ||
1354
- canonicalListenerEndpoint(context.launch.server) !== replacement.proof.serverEndpoint)))
1355
- maintenanceError("journal-corrupt", "resume listener replacement history is invalid", { paths: [path] });
1356
- const currentResumeProof = record.listenerProof;
1357
- if (currentResumeProof && record.listenerReplacements?.some((replacement) => reusesListenerIdentity(replacement.proof, currentResumeProof)))
1358
- maintenanceError("journal-corrupt", "current resume listener reuses a retired identity", { paths: [path] });
1359
- if (record.state === "resume-intent") {
1360
- const extra = record;
1361
- if (extra.activeAt !== undefined || extra.activation !== undefined || extra.degradedAt !== undefined ||
1362
- extra.reason !== undefined || extra.recourse !== undefined || extra.managerCommittedAt !== undefined ||
1363
- extra.managerCommit !== undefined || extra.retiredAt !== undefined || extra.retirement !== undefined)
1364
- maintenanceError("journal-corrupt", "ordinary resume intent contains later-phase fields", { paths: [path] });
1365
- return;
1366
- }
1367
- if (record.state === "resume-active") {
1368
- if (typeof record.activeAt !== "string" || !Number.isFinite(Date.parse(record.activeAt)) ||
1369
- !validOrdinaryResumeActivationEvidence(record.activation, context.attemptId))
1370
- maintenanceError("journal-corrupt", "active ordinary resume is invalid", { paths: [path] });
1371
- return;
1372
- }
1373
- if (record.state === "resume-committed") {
1374
- if (typeof record.activeAt !== "string" || !Number.isFinite(Date.parse(record.activeAt)) ||
1375
- !validOrdinaryResumeActivationEvidence(record.activation, context.attemptId) ||
1376
- typeof record.managerCommittedAt !== "string" || !Number.isFinite(Date.parse(record.managerCommittedAt)) ||
1377
- !validManagerCommitEvidence(record.managerCommit, context.attemptId))
1378
- maintenanceError("journal-corrupt", "manager-committed ordinary resume is invalid", { paths: [path] });
1379
- return;
1380
- }
1381
- if (record.state === "resume-degraded") {
1382
- const hasActiveAt = record.activeAt !== undefined;
1383
- const hasActivation = record.activation !== undefined;
1384
- if (hasActiveAt !== hasActivation ||
1385
- (hasActiveAt && (typeof record.activeAt !== "string" || !Number.isFinite(Date.parse(record.activeAt)) ||
1386
- !validOrdinaryResumeActivationEvidence(record.activation, context.attemptId))) ||
1387
- ((record.managerCommittedAt === undefined) !== (record.managerCommit === undefined)) ||
1388
- (record.managerCommittedAt !== undefined &&
1389
- (!validTimestamp(record.managerCommittedAt) ||
1390
- !validManagerCommitEvidence(record.managerCommit, context.attemptId))) ||
1391
- typeof record.degradedAt !== "string" || !Number.isFinite(Date.parse(record.degradedAt)) ||
1392
- typeof record.reason !== "string" ||
1393
- !record.reason || !validRecourse(record.recourse))
1394
- maintenanceError("journal-corrupt", "degraded ordinary resume is invalid", { paths: [path] });
1395
- return;
1396
- }
1397
- if (typeof record.activeAt !== "string" || !Number.isFinite(Date.parse(record.activeAt)) ||
1398
- !validOrdinaryResumeActivationEvidence(record.activation, context.attemptId) ||
1399
- typeof record.managerCommittedAt !== "string" || !Number.isFinite(Date.parse(record.managerCommittedAt)) ||
1400
- !validManagerCommitEvidence(record.managerCommit, context.attemptId) ||
1401
- typeof record.retiredAt !== "string" || !Number.isFinite(Date.parse(record.retiredAt)) ||
1402
- !validManagerFinalizeEvidence(record.retirement, context.attemptId, record.managerCommit.durableCommitToken))
1403
- maintenanceError("journal-corrupt", "retired ordinary resume is invalid", { paths: [path] });
1404
- }
1405
- function validateJournal(value, path) {
1406
- const record = value;
1407
- if (!record || typeof record !== "object")
1408
- maintenanceError("journal-corrupt", "maintenance journal is not an object", { paths: [path] });
1409
- if (record.version !== MAINTENANCE_JOURNAL_VERSION)
1410
- maintenanceError("journal-version", "unsupported maintenance journal version", { paths: [path] });
1411
- if (!Number.isInteger(record.revision) || record.revision <= 0 || typeof record.updatedAt !== "string" ||
1412
- !Number.isFinite(Date.parse(record.updatedAt)) ||
1413
- typeof record.space !== "string" || !record.space || !["auth", "open", "user"].includes(record.mode) ||
1414
- !validIdentity(record.source) || !validResumeDescriptor(record.resume) || !validCutContext(record.cut))
1415
- maintenanceError("journal-corrupt", "maintenance journal base fields are invalid", { paths: [path] });
1416
- if (!["cut-intent", "cut-committed", "ready", "claimed", "restore-ready", "commit-intent", "manager-committed", "active", "degraded",
1417
- "resume-intent", "resume-active", "resume-committed", "resume-degraded", "resume-retired"].includes(record.state))
1418
- maintenanceError("journal-corrupt", "maintenance journal state is invalid", { paths: [path] });
1419
- const completion = record.cutCompletion;
1420
- if (record.state === "cut-intent" || record.state === "cut-committed") {
1421
- if (completion !== undefined)
1422
- maintenanceError("journal-corrupt", "an uncompleted cut cannot contain completion evidence", { paths: [path] });
1423
- }
1424
- else if (!validCutCompletionEvidence(completion, record.cut)) {
1425
- maintenanceError("journal-corrupt", "completed maintenance state has invalid cut evidence", { paths: [path] });
1426
- }
1427
- if (record.state === "cut-committed") {
1428
- const committed = record;
1429
- const manager = committed.managerCommit;
1430
- if (!validTimestamp(committed.managerCommittedAt) || !manager || typeof manager !== "object" ||
1431
- !exactObjectKeys(manager, ["operation", "attemptId", "state"]) ||
1432
- committed.managerCommit.operation !== "commitPreservation" ||
1433
- committed.managerCommit.attemptId !== record.cut.attemptId ||
1434
- committed.managerCommit.state !== "preserved")
1435
- maintenanceError("journal-corrupt", "cut-committed manager evidence is invalid", { paths: [path] });
1436
- const controller = cutController(record.cut);
1437
- if (committed.preservedStop !== undefined &&
1438
- (!controller || !validPreservedStop(committed.preservedStop, record.cut, controller)))
1439
- maintenanceError("journal-corrupt", "cut-committed preserved stop attempts are invalid", { paths: [path] });
1440
- }
1441
- else if (record.preservedStop !== undefined) {
1442
- maintenanceError("journal-corrupt", "only a cut-committed journal can record preserved stop attempts", { paths: [path] });
1443
- }
1444
- if (record.tokenHandoff !== undefined &&
1445
- !["manager-committed", "active", "degraded", "resume-committed", "resume-degraded", "resume-retired"].includes(record.state))
1446
- maintenanceError("journal-corrupt", "this maintenance state cannot record a commit-token handoff", { paths: [path] });
1447
- if (record.state === "claimed") {
1448
- const claim = record.claim;
1449
- if (!claim || typeof claim.attemptId !== "string" || !ATTEMPT_ID.test(claim.attemptId) ||
1450
- typeof claim.deadline !== "string" || !Number.isFinite(Date.parse(claim.deadline)) ||
1451
- !Array.isArray(claim.owners) || claim.owners.length > 16)
1452
- maintenanceError("journal-corrupt", "maintenance claim is invalid", { paths: [path] });
1453
- parseOwner(claim.coordinator, "claim coordinator");
1454
- for (const claimOwner of claim.owners)
1455
- parseOwner(claimOwner, "claim owner");
1456
- if (claim.ownedPaths !== undefined && !validOwnedPaths(claim.ownedPaths))
1457
- maintenanceError("journal-corrupt", "maintenance claim owned paths are invalid", { paths: [path] });
1458
- }
1459
- if (record.state === "restore-ready" && !validRestoreClaim(record.claim))
1460
- maintenanceError("journal-corrupt", "restore-ready record has no valid liveness claim", { paths: [path] });
1461
- if (["restore-ready", "commit-intent", "manager-committed", "active", "degraded"].includes(record.state)) {
1462
- const restoreRecord = record;
1463
- if (restoreRecord.state === "restore-ready" && !["move-pending", "source-moved", "source-retained", "disaster-source-missing"].includes(restoreRecord.phase))
1464
- maintenanceError("journal-corrupt", "restore phase is invalid", { paths: [path] });
1465
- if (restoreRecord.state !== "restore-ready" && !restoreRecord.restore.target)
1466
- maintenanceError("journal-corrupt", "committed restore has no target identity", { paths: [path] });
1467
- validateRestoreContext(restoreRecord, path);
1468
- if (restoreRecord.state !== "restore-ready" &&
1469
- !validJsonObject(restoreRecord.launch))
1470
- maintenanceError("journal-corrupt", "restore launch metadata is invalid", { paths: [path] });
1471
- // A controller restore journals its member starts in the launch, as a controller resume does.
1472
- if (restoreRecord.state !== "restore-ready") {
1473
- const launch = restoreRecord.launch;
1474
- const controller = cutController(record.cut);
1475
- if (controller ? launch.custody !== "controller" || !validControllerResumeBinding(launch.controller, controller) ||
1476
- // A rewritten broker definition names its new broker in reconfiguredBroker, never here.
1477
- launch.controller.broker !== undefined && restoreRecord.restore.controllerReconfiguration !== undefined
1478
- : launch.custody !== undefined || launch.controller !== undefined)
1479
- maintenanceError("journal-corrupt", "restore launch custody does not match the cut", { paths: [path] });
1480
- }
1481
- if (restoreRecord.state !== "restore-ready" && restoreRecord.listenerProof !== undefined &&
1482
- (!validListenerProof(restoreRecord.listenerProof) ||
1483
- !listenerProofFitsCustody(restoreRecord.listenerProof, record.cut, restoreProofScope(restoreRecord)) ||
1484
- restoreRecord.listenerProof.attemptId !== restoreRecord.restore.attemptId ||
1485
- !sameStoreIdentity(restoreRecord.listenerProof.target, restoreRecord.restore.target) ||
1486
- typeof restoreRecord.launch.server !== "string" ||
1487
- canonicalListenerEndpoint(restoreRecord.launch.server) !== restoreRecord.listenerProof.serverEndpoint))
1488
- maintenanceError("journal-corrupt", "restore listener proof is invalid or belongs to another attempt", { paths: [path] });
1489
- if (restoreRecord.state !== "restore-ready") {
1490
- const committed = restoreRecord;
1491
- if (committed.listenerReplacements !== undefined &&
1492
- (!validListenerReplacements(committed.listenerReplacements) ||
1493
- committed.listenerReplacements.some((replacement) => !listenerProofFitsCustody(replacement.proof, record.cut, restoreProofScope(committed)) ||
1494
- replacement.proof.attemptId !== committed.restore.attemptId ||
1495
- !sameStoreIdentity(replacement.proof.target, committed.restore.target) ||
1496
- typeof committed.launch.server !== "string" ||
1497
- canonicalListenerEndpoint(committed.launch.server) !== replacement.proof.serverEndpoint)))
1498
- maintenanceError("journal-corrupt", "restore listener replacement history is invalid", { paths: [path] });
1499
- const currentProof = committed.listenerProof;
1500
- if (currentProof && committed.listenerReplacements?.some((replacement) => reusesListenerIdentity(replacement.proof, currentProof)))
1501
- maintenanceError("journal-corrupt", "current restore listener reuses a retired identity", { paths: [path] });
1502
- }
1503
- if (restoreRecord.state === "manager-committed" &&
1504
- (!restoreRecord.listenerProof || !validTimestamp(restoreRecord.managerCommittedAt) ||
1505
- !validManagerCommitEvidence(restoreRecord.managerCommit, restoreRecord.restore.attemptId)))
1506
- maintenanceError("journal-corrupt", "manager-committed restore evidence is invalid", { paths: [path] });
1507
- if (restoreRecord.state === "active" &&
1508
- (!validTimestamp(restoreRecord.managerCommittedAt) ||
1509
- !validManagerCommitEvidence(restoreRecord.managerCommit, restoreRecord.restore.attemptId) ||
1510
- !Number.isFinite(Date.parse(restoreRecord.activeAt)) || !restoreRecord.listenerProof ||
1511
- !validRestoreActivationEvidence(restoreRecord.details, restoreRecord.restore.attemptId) ||
1512
- !sameManagerCommitEvidence(restoreRecord.managerCommit, restoreRecord.details.managerCommit)))
1513
- maintenanceError("journal-corrupt", "active restore details are invalid", { paths: [path] });
1514
- if (restoreRecord.state === "degraded" &&
1515
- (((restoreRecord.managerCommittedAt === undefined) !== (restoreRecord.managerCommit === undefined)) ||
1516
- (restoreRecord.managerCommittedAt !== undefined &&
1517
- (!restoreRecord.listenerProof || !validTimestamp(restoreRecord.managerCommittedAt) ||
1518
- !validManagerCommitEvidence(restoreRecord.managerCommit, restoreRecord.restore.attemptId))) ||
1519
- (restoreRecord.activeAt !== undefined && !Number.isFinite(Date.parse(restoreRecord.activeAt))) ||
1520
- (restoreRecord.activeAt !== undefined && (!restoreRecord.listenerProof ||
1521
- !validRestoreActivationEvidence(restoreRecord.details, restoreRecord.restore.attemptId))) ||
1522
- (restoreRecord.activeAt !== undefined &&
1523
- (restoreRecord.managerCommit === undefined ||
1524
- !sameManagerCommitEvidence(restoreRecord.managerCommit, restoreRecord.details.managerCommit))) ||
1525
- (restoreRecord.activeAt === undefined && restoreRecord.details !== undefined) ||
1526
- !Number.isFinite(Date.parse(restoreRecord.degradedAt)) ||
1527
- typeof restoreRecord.reason !== "string" || !validRecourse(restoreRecord.recourse)))
1528
- maintenanceError("journal-corrupt", "degraded restore recourse is invalid", { paths: [path] });
1529
- }
1530
- if (["resume-intent", "resume-active", "resume-committed", "resume-degraded", "resume-retired"].includes(record.state))
1531
- validateOrdinaryResume(record, path);
1532
- return record;
1533
- }
1534
- export function readMaintenanceJournal(root) {
1535
- const paths = maintenancePaths(root);
1536
- let raw;
1537
- try {
1538
- const stat = lstatSync(paths.journal);
1539
- if (!stat.isFile() || stat.isSymbolicLink() || stat.size > 1024 * 1024)
1540
- maintenanceError("journal-corrupt", "maintenance journal is not a bounded regular file", { paths: [paths.journal] });
1541
- raw = readFileSync(paths.journal, "utf8");
1542
- }
1543
- catch (error) {
1544
- if (errno(error) === "ENOENT")
1545
- return undefined;
1546
- if (isMaintenanceError(error))
1547
- throw error;
1548
- maintenanceError("journal-corrupt", "maintenance journal cannot be read", { paths: [paths.journal] });
1549
- }
1550
- try {
1551
- const record = validateJournal(JSON.parse(raw), paths.journal);
1552
- readMaintenanceResumeDocument(paths.root, record.resume);
1553
- return record;
1554
- }
1555
- catch (error) {
1556
- if (isMaintenanceError(error))
1557
- throw error;
1558
- maintenanceError("journal-corrupt", "maintenance journal cannot be parsed", { paths: [paths.journal] });
1559
- }
1560
- }
1561
- function currentJournal(lock) {
1562
- assertLock(lock);
1563
- const record = readMaintenanceJournal(lock.root);
1564
- if (!record)
1565
- maintenanceError("journal-missing", "maintenance journal does not exist", {
1566
- root: lock.root,
1567
- recourse: [{ action: "repair", description: "Complete a preserve-state cut before backup or restore." }],
1568
- });
1569
- return record;
1570
- }
1571
- function writeJournal(lock, previous, next) {
1572
- assertLock(lock);
1573
- const paths = maintenancePaths(lock.root);
1574
- ensureLayout(paths);
1575
- const record = {
1576
- ...next,
1577
- version: MAINTENANCE_JOURNAL_VERSION,
1578
- revision: (previous?.revision ?? 0) + 1,
1579
- updatedAt: new Date().toISOString(),
1580
- };
1581
- validateJournal(record, paths.journal);
1582
- readMaintenanceResumeDocument(lock.root, record.resume);
1583
- atomicWrite(paths.journal, record);
1584
- return record;
1585
- }
1586
- function readyFrom(record) {
1587
- return {
1588
- state: "ready", space: record.space, mode: record.mode, source: record.source, resume: record.resume,
1589
- cut: record.cut, cutCompletion: record.cutCompletion,
1590
- };
1591
- }
7
+ import { ATTEMPT_ID, STORE_ID_FILE, assertLock, assertPathsDoNotOverlap, assertStoreIdentity, atomicWrite, canonicalAbsentPath, canonicalCandidatePath, defaultOwner, ensureLayout, ensureStoreIdentity, errno, fsyncDirectory, identityAt, isMaintenanceError, localProcessOwnerStatus, maintenanceError, maintenancePaths, parseOwner, pathContains, pathExistsStrict, readStoreIdentity, sameStoreIdentity, } from "./maintenance-foundation.js";
8
+ export { MAINTENANCE_JOURNAL_VERSION, MAINTENANCE_RESUME_DOCUMENT_VERSION, MAX_MAINTENANCE_RESUME_BYTES, MaintenanceError, isMaintenanceError, maintenancePaths, readStoreIdentity, ensureStoreIdentity, sameStoreIdentity, assertStoreIdentity, localProcessOwnerStatus, readMaintenanceLockHolder, maintenanceLockHolder, acquireMaintenanceLock, assertMaintenanceLock, releaseMaintenanceLock, withMaintenanceLock, } from "./maintenance-foundation.js";
9
+ import { assertListenerOwnerAlive, canonicalListenerEndpoint, currentJournal, cutBrokerRetired, cutController, exactObjectKeys, normalizedListenerProof, ordinaryResumeController, readMaintenanceJournal, readMaintenanceResumeDocument, readyFrom, requireCustodyProof, restoreProofScope, reusesListenerIdentity, sameJsonValue, sameListenerProof, sameManagerCommitEvidence, sameManagerFinalizeEvidence, sameProcessOwner, sameResumeDescriptor, validAttemptBroker, validCutCompletionEvidence, validJsonObject, validManagerCommitEvidence, validManagerFinalizeEvidence, validOrdinaryResumeActivationEvidence, validOwnedPaths, validRecourse, validRestoreActivationEvidence, validRestoreClaim, writeJournal, } from "./maintenance-journal.js";
10
+ export { cutController, ordinaryResumeController, writeMaintenanceResumeDocument, readMaintenanceResumeDocument, readMaintenanceJournal, } from "./maintenance-journal.js";
1592
11
  function validCapability(value) {
1593
12
  const capability = value;
1594
13
  const text = (field) => typeof field === "string" && /^[A-Za-z0-9][A-Za-z0-9._:-]{0,255}$/.test(field);