@aeondave/pi-persona-mind 0.0.0-stage → 0.8.4

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 (43) hide show
  1. package/AGENTS.md +78 -0
  2. package/CHANGELOG.md +78 -0
  3. package/LICENSE +24 -0
  4. package/README.md +244 -2
  5. package/assets/banner.png +0 -0
  6. package/docs/DESIGN.md +282 -0
  7. package/docs/MEMORY-RESEARCH.md +112 -0
  8. package/package.json +93 -4
  9. package/src/core/auto-optimize.ts +239 -0
  10. package/src/core/backlog.ts +228 -0
  11. package/src/core/blocked.ts +38 -0
  12. package/src/core/capture.ts +146 -0
  13. package/src/core/context-budget.ts +74 -0
  14. package/src/core/host-compat.ts +13 -0
  15. package/src/core/ids.ts +59 -0
  16. package/src/core/inject.ts +247 -0
  17. package/src/core/memory-read.ts +34 -0
  18. package/src/core/memory.ts +308 -0
  19. package/src/core/migrate.ts +713 -0
  20. package/src/core/mind-settings.ts +54 -0
  21. package/src/core/optimize-history.ts +101 -0
  22. package/src/core/optimize-service.ts +182 -0
  23. package/src/core/optimize.ts +133 -0
  24. package/src/core/retrieval.ts +108 -0
  25. package/src/core/scanner.ts +146 -0
  26. package/src/core/scope.ts +205 -0
  27. package/src/core/service.ts +644 -0
  28. package/src/core/session-memory.ts +71 -0
  29. package/src/core/store.ts +948 -0
  30. package/src/extension/activity.ts +79 -0
  31. package/src/extension/auto-optimize-session.ts +118 -0
  32. package/src/extension/auto-optimize.ts +265 -0
  33. package/src/extension/mind-command.ts +335 -0
  34. package/src/extension/mind-worker.ts +32 -0
  35. package/src/extension/persona-dependency.ts +76 -0
  36. package/src/index.ts +1231 -0
  37. package/src/session-memory.ts +118 -0
  38. package/src/tools/backlog.ts +126 -0
  39. package/src/tools/memory-optimize.ts +133 -0
  40. package/src/tools/memory.ts +400 -0
  41. package/src/ui/mind-result-card.ts +15 -0
  42. package/src/ui/presentation.ts +97 -0
  43. package/src/ui/session-note-card.ts +50 -0
@@ -0,0 +1,948 @@
1
+ /**
2
+ * Durable, cross-OS, concurrency-safe JSON persistence for pi-persona-mind's stores.
3
+ *
4
+ * A store is one JSON file rewritten in full. Without care, a crash mid-write leaves a torn
5
+ * file that loads as a silent empty store (memory vanishes with no signal), and two writers
6
+ * race with last-writer-wins. These primitives prevent both, using only the Node stdlib — no
7
+ * native binding, no `flock`/`lockf` (so it works on Windows, unlike the POSIX-lock stores in
8
+ * the Pi memory ecosystem):
9
+ *
10
+ * 1. {@link atomicWriteFile} — temp-in-same-dir → fsync → atomic rename. A crash before the
11
+ * rename leaves the prior file intact; never a partially-written store.
12
+ * 2. {@link casUpdate} — the load→mutate→write runs inside a per-file advisory lockfile
13
+ * (`wx`/O_EXCL create, polled, with dead-local recovery for a crashed holder and an ownership
14
+ * token so a stolen hold is never wrongly released). No committed write is lost.
15
+ * 3. {@link quarantineCorrupt} — a file that fails validation is moved aside to `*.corrupt-N`
16
+ * (never silently replaced with empty, which would present absence as current fact).
17
+ *
18
+ * The pattern is adapted from OpenLore's `atomic-store.ts` (clay-good/openlore, MIT).
19
+ */
20
+
21
+ import { constants as fsConstants } from "node:fs";
22
+ import { createHash, randomBytes } from "node:crypto";
23
+ import { copyFile, link, lstat, mkdir, open, rename, rmdir, unlink } from "node:fs/promises";
24
+ import { hostname } from "node:os";
25
+ import { performance } from "node:perf_hooks";
26
+ import { basename, dirname, join } from "node:path";
27
+
28
+ /** Every persisted store carries the monotonic compare-and-swap counter. */
29
+ export interface StoreFile<E> {
30
+ version: number;
31
+ updatedAt: string;
32
+ /** Monotonic write counter: orders writes and lets an external reader detect change. */
33
+ sequence: number;
34
+ entries: E[];
35
+ }
36
+
37
+ export interface StoreSnapshot<E> {
38
+ store: StoreFile<E>;
39
+ /** Binds the exact live bytes and store path, including same-sequence replacements. */
40
+ fingerprint: string;
41
+ }
42
+
43
+ export class StoreConflictError extends Error {
44
+ constructor() { super("memory store changed since preview; inspect and preview again"); this.name = "StoreConflictError"; }
45
+ }
46
+
47
+ /** Defensive defaults for out-of-band/corrupt stores. Normal stores are far smaller than these. */
48
+ export const DEFAULT_STORE_MAX_BYTES = 4 * 1024 * 1024;
49
+ export const DEFAULT_STORE_MAX_ENTRIES = 10_000;
50
+
51
+ // Lock tokens are process-local sequence values. Temp names use cryptographic randomness and are
52
+ // still opened with O_EXCL so a pre-created symlink can never be followed by a writer.
53
+ let lockSeq = 0;
54
+
55
+ // Invalid raw entries are retained only inside an update's private state. They are never returned by
56
+ // JsonStore.load(), but the next atomic rewrite can put them back verbatim instead of silently
57
+ // erasing data that the current validator does not understand yet.
58
+ const PRESERVED_INVALID_ENTRIES: unique symbol = Symbol("preservedInvalidEntries");
59
+ type InternalStoreFile<E> = StoreFile<E> & { [PRESERVED_INVALID_ENTRIES]?: unknown[] };
60
+
61
+ export interface AtomicWriteOptions {
62
+ /** Refresh the `.bak` sidecar from the current live file only when this returns true for its
63
+ * bytes. Guards against copying a torn file — one that load() just recovered FROM `.bak` — over
64
+ * the only good backup, which would destroy the sole recoverable copy. Absent ⇒ always refresh. */
65
+ backupIf?: (currentRaw: string) => boolean;
66
+ /** Maximum live-file bytes read when evaluating `backupIf`; oversized files are not backed up. */
67
+ maxBackupBytes?: number;
68
+ }
69
+
70
+ export type BoundedReadFailureKind = "bytes" | "entries" | "path";
71
+
72
+ export class BoundedReadFailure extends Error {
73
+ readonly kind: BoundedReadFailureKind;
74
+
75
+ constructor(kind: BoundedReadFailureKind, message: string) {
76
+ super(message);
77
+ this.kind = kind;
78
+ this.name = "BoundedReadFailure";
79
+ }
80
+ }
81
+
82
+ /**
83
+ * Thrown when a store envelope carries a version this build does not implement. It is deliberately
84
+ * NOT a corruption signal: a store written by another version is intact, just unreadable here, so it
85
+ * must be left in place (never quarantined, never overwritten) until a build that understands it —
86
+ * or a migration — runs. Failing loudly is the only non-destructive answer available.
87
+ */
88
+ export class StoreVersionError extends Error {
89
+ readonly found: number;
90
+ readonly expected: number;
91
+
92
+ constructor(found: number, expected: number) {
93
+ super(`mind store version ${found} was written by a different pi-persona-mind build (this one reads version ${expected}); the file is left untouched`);
94
+ this.found = found;
95
+ this.expected = expected;
96
+ this.name = "StoreVersionError";
97
+ }
98
+ }
99
+
100
+ /** Thrown before an update writes a store that the next bounded load would reject. */
101
+ export class StoreCapacityError extends Error {
102
+ readonly kind: "bytes" | "entries";
103
+ readonly actual: number;
104
+ readonly limit: number;
105
+
106
+ constructor(kind: "bytes" | "entries", actual: number, limit: number) {
107
+ super(`mind store capacity: ${kind} ${actual} exceeds limit ${limit}`);
108
+ this.kind = kind;
109
+ this.actual = actual;
110
+ this.limit = limit;
111
+ this.name = "StoreCapacityError";
112
+ }
113
+ }
114
+
115
+ const noFollow = (fsConstants as { O_NOFOLLOW?: number }).O_NOFOLLOW;
116
+ const readFlags: string | number = noFollow === undefined ? "r" : fsConstants.O_RDONLY | noFollow;
117
+
118
+ function sameFile(a: { dev: number; ino: number }, b: { dev: number; ino: number }): boolean {
119
+ return a.dev === b.dev && a.ino === b.ino;
120
+ }
121
+
122
+ const LOCK_POLL_MS = 25;
123
+ const LOCK_MAX_WAIT_MS = 30_000;
124
+ const REPLACE_MAX_WAIT_MS = 30_000;
125
+ const sleep = (ms: number): Promise<void> => new Promise((r) => setTimeout(r, ms));
126
+
127
+ type LockStats = { dev: number; ino: number };
128
+
129
+ export interface FileLockOptions {
130
+ /** Internal seam used to prove cleanup when closing a newly-created lock handle fails. */
131
+ close?: (handle: Awaited<ReturnType<typeof open>>) => Promise<void>;
132
+ }
133
+
134
+ async function unlinkIfSameFile(path: string, expected: LockStats): Promise<void> {
135
+ try {
136
+ const current = await lstat(path);
137
+ if (sameFile(expected, current)) await unlink(path).catch(() => {});
138
+ } catch {
139
+ /* the failed acquisition may already have been cleaned up */
140
+ }
141
+ }
142
+
143
+ /** Create a lockfile and clean up its inode if writing or closing the handle fails. */
144
+ async function createLockFile(
145
+ lockPath: string,
146
+ token: string,
147
+ closeHandle: (handle: Awaited<ReturnType<typeof open>>) => Promise<void> = (handle) => handle.close(),
148
+ ): Promise<void> {
149
+ const fh = await open(lockPath, "wx");
150
+ let created: LockStats | undefined;
151
+ try {
152
+ created = await fh.stat();
153
+ await fh.writeFile(token);
154
+ await closeHandle(fh);
155
+ } catch (err) {
156
+ // A failed write can leave an empty/partial lock that no waiter can safely attribute. Close
157
+ // the descriptor when possible, then remove only the inode this acquisition created.
158
+ await fh.close().catch(() => {});
159
+ if (created) await unlinkIfSameFile(lockPath, created);
160
+ throw err;
161
+ }
162
+ }
163
+
164
+ /** Read at most one byte beyond the fstat-observed size, rejecting symlinks, replacements, and floods. */
165
+ export async function readTextFileBounded(path: string, maxBytes: number): Promise<string> {
166
+ if (!Number.isSafeInteger(maxBytes) || maxBytes <= 0) throw new RangeError("store maxBytes must be a positive safe integer");
167
+ let listed;
168
+ try {
169
+ listed = await lstat(path);
170
+ } catch (err) {
171
+ throw err;
172
+ }
173
+ if (listed.isSymbolicLink()) throw new BoundedReadFailure("path", "store path is a symbolic link");
174
+ if (!listed.isFile()) throw new BoundedReadFailure("path", "store path is not a regular file");
175
+
176
+ let fh;
177
+ try {
178
+ fh = await open(path, readFlags);
179
+ } catch (err) {
180
+ if ((err as NodeJS.ErrnoException).code === "ELOOP") {
181
+ throw new BoundedReadFailure("path", "store path is a symbolic link");
182
+ }
183
+ throw err;
184
+ }
185
+ try {
186
+ const opened = await fh.stat();
187
+ if (!opened.isFile() || !sameFile(listed, opened)) {
188
+ throw new BoundedReadFailure("path", "store path changed or is not a regular file");
189
+ }
190
+ const observedSize = opened.size;
191
+ if (!Number.isSafeInteger(observedSize) || observedSize > maxBytes) {
192
+ throw new BoundedReadFailure("bytes", `store file exceeds the ${maxBytes}-byte limit`);
193
+ }
194
+ const bytes = Buffer.allocUnsafe(observedSize + 1);
195
+ let offset = 0;
196
+ while (offset < bytes.length) {
197
+ const result = await fh.read(bytes, offset, bytes.length - offset, offset);
198
+ if (result.bytesRead === 0) break;
199
+ offset += result.bytesRead;
200
+ }
201
+ if (offset > observedSize) throw new BoundedReadFailure("bytes", "store file grew while it was being read");
202
+ const finalOpened = await fh.stat();
203
+ if (!finalOpened.isFile() || !sameFile(opened, finalOpened) || finalOpened.size !== observedSize || offset !== observedSize) {
204
+ throw new BoundedReadFailure("path", "store file changed or was truncated while it was being read");
205
+ }
206
+ const current = await lstat(path);
207
+ if (current.isSymbolicLink() || !current.isFile() || !sameFile(opened, current) || current.size !== observedSize) {
208
+ throw new BoundedReadFailure("path", "store path changed while it was being read");
209
+ }
210
+ return bytes.subarray(0, offset).toString("utf8");
211
+ } finally {
212
+ await fh.close();
213
+ }
214
+ }
215
+
216
+ const MAX_LOCK_TOKEN_BYTES = 1024;
217
+
218
+ async function openRandomTemp(dir: string, base: string): Promise<{ path: string; handle: Awaited<ReturnType<typeof open>> }> {
219
+ for (let attempt = 0; attempt < 16; attempt++) {
220
+ const path = join(dir, `.${base}.tmp-${randomBytes(16).toString("hex")}`);
221
+ try {
222
+ return { path, handle: await open(path, "wx") };
223
+ } catch (err) {
224
+ if ((err as NodeJS.ErrnoException).code !== "EEXIST") throw err;
225
+ }
226
+ }
227
+ throw new Error(`mind store: could not allocate a unique temporary file beside ${base}`);
228
+ }
229
+
230
+ async function copyToRandomTemp(source: string, dir: string, base: string): Promise<string> {
231
+ for (let attempt = 0; attempt < 16; attempt++) {
232
+ const path = join(dir, `.${base}.tmp-${randomBytes(16).toString("hex")}`);
233
+ try {
234
+ await copyFile(source, path, fsConstants.COPYFILE_EXCL);
235
+ return path;
236
+ } catch (err) {
237
+ if ((err as NodeJS.ErrnoException).code !== "EEXIST") throw err;
238
+ }
239
+ }
240
+ throw new Error(`mind store: could not allocate a unique backup temporary file beside ${base}`);
241
+ }
242
+
243
+ /** Replace a destination path without ever opening/following an existing destination symlink. */
244
+ async function replacePath(staged: string, destination: string): Promise<void> {
245
+ const started = performance.now();
246
+ try {
247
+ await rename(staged, destination);
248
+ return;
249
+ } catch (err) {
250
+ const code = (err as NodeJS.ErrnoException).code;
251
+ if (code !== "EEXIST" && code !== "EPERM" && code !== "ENOTEMPTY") throw err;
252
+ }
253
+ // Windows may reject rename over a live destination while another process still has an open
254
+ // handle. Keep the staged bytes in place and retry the remove/rename sequence until that handle
255
+ // closes. The destination identity is checked before unlinking so a concurrent replacement is
256
+ // never removed by a stale retry.
257
+ for (;;) {
258
+ let observed;
259
+ try {
260
+ observed = await lstat(destination);
261
+ } catch (err) {
262
+ if ((err as NodeJS.ErrnoException).code !== "ENOENT") throw err;
263
+ }
264
+ if (observed) {
265
+ let current;
266
+ try {
267
+ current = await lstat(destination);
268
+ } catch (err) {
269
+ if ((err as NodeJS.ErrnoException).code === "ENOENT") continue;
270
+ throw err;
271
+ }
272
+ if (!sameFile(observed, current)) continue;
273
+ try {
274
+ await unlink(destination);
275
+ } catch (err) {
276
+ const code = (err as NodeJS.ErrnoException).code;
277
+ if (code !== "EPERM" && code !== "EACCES" && code !== "EBUSY") throw err;
278
+ if (performance.now() - started > REPLACE_MAX_WAIT_MS) throw err;
279
+ await sleep(LOCK_POLL_MS);
280
+ continue;
281
+ }
282
+ }
283
+ try {
284
+ await rename(staged, destination);
285
+ return;
286
+ } catch (err) {
287
+ const code = (err as NodeJS.ErrnoException).code;
288
+ if (code !== "EEXIST" && code !== "EPERM" && code !== "ENOTEMPTY") throw err;
289
+ if (performance.now() - started > REPLACE_MAX_WAIT_MS) throw err;
290
+ await sleep(LOCK_POLL_MS);
291
+ }
292
+ }
293
+ }
294
+
295
+ /**
296
+ * Replace the live store atomically. Windows rejects rename-over-destination while a reader still
297
+ * holds the destination open; retry the SAME rename (without unlinking the committed file) until
298
+ * that short-lived reader closes. The old or new file is therefore always present.
299
+ */
300
+ async function replaceLivePath(staged: string, destination: string): Promise<void> {
301
+ const started = performance.now();
302
+ for (;;) {
303
+ try {
304
+ await rename(staged, destination);
305
+ return;
306
+ } catch (err) {
307
+ const code = (err as NodeJS.ErrnoException).code;
308
+ if (code !== "EPERM" && code !== "EACCES" && code !== "EBUSY") throw err;
309
+ if (performance.now() - started > REPLACE_MAX_WAIT_MS) throw err;
310
+ await sleep(LOCK_POLL_MS);
311
+ }
312
+ }
313
+ }
314
+
315
+ async function refreshBackup(source: string, destination: string): Promise<void> {
316
+ const listed = await lstat(source);
317
+ if (!listed.isFile()) return;
318
+ const staged = await copyToRandomTemp(source, dirname(destination), basename(destination));
319
+ let replaced = false;
320
+ try {
321
+ const current = await lstat(source);
322
+ if (!current.isFile() || !sameFile(listed, current)) return;
323
+ await replacePath(staged, destination);
324
+ replaced = true;
325
+ } finally {
326
+ if (!replaced) await unlink(staged).catch(() => {});
327
+ }
328
+ }
329
+
330
+ /** Lock metadata is trusted only when it is a tiny regular file; never read an attacker-sized token. */
331
+ async function readLockToken(lockPath: string): Promise<string | null> {
332
+ let listed;
333
+ try {
334
+ listed = await lstat(lockPath);
335
+ if (!listed.isFile()) return null;
336
+ const fh = await open(lockPath, readFlags);
337
+ try {
338
+ const opened = await fh.stat();
339
+ if (!opened.isFile() || !sameFile(listed, opened) || opened.size > MAX_LOCK_TOKEN_BYTES) return null;
340
+ const bytes = Buffer.alloc(MAX_LOCK_TOKEN_BYTES);
341
+ const result = await fh.read(bytes, 0, MAX_LOCK_TOKEN_BYTES, 0);
342
+ if (result.bytesRead !== opened.size) return null;
343
+ const current = await lstat(lockPath);
344
+ if (!current.isFile() || !sameFile(opened, current) || current.size !== opened.size) return null;
345
+ return bytes.subarray(0, result.bytesRead).toString("utf8");
346
+ } finally {
347
+ await fh.close();
348
+ }
349
+ } catch {
350
+ return null;
351
+ }
352
+ }
353
+
354
+ /**
355
+ * Write `data` to `path` atomically: to a sibling temp file, flushed to disk (`fsync`), then
356
+ * moved into place with a single atomic `rename`. A crash before the rename leaves the previous
357
+ * file untouched. The directory fsync is best-effort — Windows rejects it, and the data fsync
358
+ * already bounds the loss.
359
+ */
360
+ export async function atomicWriteFile(path: string, data: string, opts: AtomicWriteOptions = {}): Promise<void> {
361
+ const dir = dirname(path);
362
+ await mkdir(dir, { recursive: true });
363
+ const temp = await openRandomTemp(dir, basename(path));
364
+ const tmp = temp.path;
365
+ let renamed = false;
366
+ try {
367
+ const fh = temp.handle;
368
+ try {
369
+ await fh.writeFile(data, "utf-8");
370
+ await fh.sync();
371
+ } finally {
372
+ await fh.close();
373
+ }
374
+ // Preserve the current (known-good) file as a last-known-good sidecar BEFORE we overwrite it,
375
+ // so a later torn/truncated live file can be rolled back to it (JsonStore.load consults .bak
376
+ // before quarantining). But never clobber a good .bak with a live file that isn't itself good
377
+ // (a torn file we just recovered FROM .bak): that would destroy the only recoverable copy.
378
+ try {
379
+ if (!opts.backupIf) {
380
+ await refreshBackup(path, `${path}.bak`);
381
+ } else {
382
+ const current = await readTextFileBounded(path, opts.maxBackupBytes ?? DEFAULT_STORE_MAX_BYTES);
383
+ if (opts.backupIf(current)) await refreshBackup(path, `${path}.bak`);
384
+ }
385
+ } catch {
386
+ /* no current file, unsafe path, or oversized current file — nothing to preserve */
387
+ }
388
+ await replaceLivePath(tmp, path);
389
+ renamed = true;
390
+ } finally {
391
+ if (!renamed) await unlink(tmp).catch(() => {});
392
+ }
393
+ try {
394
+ const dh = await open(dir, "r");
395
+ try {
396
+ await dh.sync();
397
+ } finally {
398
+ await dh.close();
399
+ }
400
+ } catch {
401
+ /* directory fsync unsupported (e.g. Windows) — skip */
402
+ }
403
+ }
404
+
405
+ // Dead-lock recovery is itself a critical section. The directory gate is process-wide (not merely
406
+ // an in-memory promise), and contenders check it before every acquisition attempt. A recovering
407
+ // process keeps the gate until it has installed its replacement token, so another process can never
408
+ // observe the old dead lock removed and enter the callback during the hand-off window.
409
+ const recoveryTails = new Map<string, Promise<void>>();
410
+ async function withRecoveryGate<T>(lockPath: string, fn: () => Promise<T>): Promise<T> {
411
+ const previous = recoveryTails.get(lockPath) ?? Promise.resolve();
412
+ let release!: () => void;
413
+ const current = new Promise<void>((resolve) => {
414
+ release = resolve;
415
+ });
416
+ recoveryTails.set(lockPath, current);
417
+ await previous;
418
+ try {
419
+ return await fn();
420
+ } finally {
421
+ release();
422
+ if (recoveryTails.get(lockPath) === current) recoveryTails.delete(lockPath);
423
+ }
424
+ }
425
+
426
+ function recoveryGatePath(lockPath: string): string {
427
+ return `${lockPath}.recovery`;
428
+ }
429
+
430
+ async function recoveryGateExists(lockPath: string): Promise<boolean> {
431
+ try {
432
+ await lstat(recoveryGatePath(lockPath));
433
+ return true;
434
+ } catch (err) {
435
+ if ((err as NodeJS.ErrnoException).code === "ENOENT") return false;
436
+ return true; // an unreadable gate is treated as held: fail closed, never race recovery
437
+ }
438
+ }
439
+
440
+ /**
441
+ * Is the lock held by a LOCAL process that is already dead? The lock token is `host:pid-seq`; only
442
+ * when the host matches ours can we probe the pid (`process.kill(pid, 0)`: ESRCH ⇒ gone). A token
443
+ * from another machine (network FS) or an unparseable/legacy one returns false and is never
444
+ * stealable by age: without a trustworthy owner identity, time alone cannot distinguish a crashed
445
+ * process from a slow-but-alive one.
446
+ */
447
+ function tokenHolderIsDeadLocal(content: string): boolean {
448
+ const match = /^([^:\r\n]+):([0-9]+)-([0-9]+)$/.exec(content);
449
+ if (!match || match[1] !== hostname()) return false;
450
+ const pid = Number(match[2]);
451
+ if (!Number.isSafeInteger(pid) || pid <= 0 || !Number.isSafeInteger(Number(match[3]))) return false;
452
+ try {
453
+ process.kill(pid, 0);
454
+ return false; // exists (alive)
455
+ } catch (err) {
456
+ return (err as NodeJS.ErrnoException).code === "ESRCH"; // ESRCH ⇒ dead; EPERM ⇒ alive
457
+ }
458
+ }
459
+
460
+ /**
461
+ * Recover a dead lock while holding a cross-process gate. The replacement lock is created before
462
+ * the gate is released; this is the key ordering that prevents a second process from deleting a
463
+ * fresh lock after observing the same old dead token. A recovery process that itself crashes leaves
464
+ * the gate behind; waiters fail closed after the normal bounded wait instead of guessing that a
465
+ * potentially live recovery owner is dead.
466
+ */
467
+ async function recoverDeadLocalLock(
468
+ lockPath: string,
469
+ token: string,
470
+ closeHandle: (handle: Awaited<ReturnType<typeof open>>) => Promise<void>,
471
+ ): Promise<boolean> {
472
+ return withRecoveryGate(lockPath, async () => {
473
+ const gate = recoveryGatePath(lockPath);
474
+ try {
475
+ await mkdir(gate);
476
+ } catch (err) {
477
+ if ((err as NodeJS.ErrnoException).code === "EEXIST") return false;
478
+ throw err;
479
+ }
480
+ try {
481
+ const observed = await readLockToken(lockPath);
482
+ if (observed === null || !tokenHolderIsDeadLocal(observed)) return false;
483
+ // Re-read immediately before removal while every other contender is required to honor `gate`.
484
+ if ((await readLockToken(lockPath)) !== observed) return false;
485
+ await unlink(lockPath);
486
+ // Acquire the canonical lock before releasing the recovery gate. If this fails, the caller
487
+ // will continue polling; importantly, no other contender can enter during this hand-off.
488
+ await createLockFile(lockPath, token, closeHandle);
489
+ return true;
490
+ } finally {
491
+ await rmdir(gate).catch(() => {});
492
+ }
493
+ });
494
+ }
495
+
496
+ /** Thrown internally when the commit lock was stolen mid-critical-section; {@link casUpdate} re-acquires. */
497
+ class LockLostError extends Error {}
498
+
499
+ /**
500
+ * Run `fn` while holding a per-file advisory lock (exclusive-create lockfile, polled, with dead-local
501
+ * recovery for a crashed holder). The lock carries an ownership token — passed to `fn` so it can
502
+ * re-verify ownership before committing — and is released only if still ours, so a hold stolen after
503
+ * proving its local owner is dead is never wrongly deleted. Foreign, malformed, or otherwise
504
+ * unprobeable locks fail closed after the bounded wait instead of being stolen by age.
505
+ */
506
+ export async function withFileLock<T>(lockPath: string, fn: (token: string) => Promise<T>, options: FileLockOptions = {}): Promise<T> {
507
+ await mkdir(dirname(lockPath), { recursive: true });
508
+ const token = `${hostname()}:${process.pid}-${lockSeq++}`;
509
+ const start = performance.now();
510
+ const closeHandle = options.close ?? ((handle: Awaited<ReturnType<typeof open>>) => handle.close());
511
+ for (;;) {
512
+ if (await recoveryGateExists(lockPath)) {
513
+ if (performance.now() - start > LOCK_MAX_WAIT_MS) {
514
+ throw new Error(
515
+ `mind store lock: timed out after ${LOCK_MAX_WAIT_MS}ms waiting for ${lockPath} ` +
516
+ `(recovery gate is held; retry the operation)`,
517
+ );
518
+ }
519
+ await sleep(LOCK_POLL_MS);
520
+ continue;
521
+ }
522
+ try {
523
+ await createLockFile(lockPath, token, closeHandle);
524
+ break;
525
+ } catch (err) {
526
+ const code = (err as NodeJS.ErrnoException).code;
527
+ if (code !== "EEXIST") {
528
+ // Windows can report EPERM, rather than EEXIST, when another process has the
529
+ // lockfile open. Treat it as contention only when the path can be observed; a
530
+ // genuine permission failure on an absent/inaccessible path must still surface.
531
+ if (code !== "EPERM") throw err;
532
+ try {
533
+ await lstat(lockPath);
534
+ } catch (probeErr) {
535
+ // On Windows an open racing with a concurrent unlink can report EPERM even
536
+ // though the path has already vanished. Retry the acquisition; surfacing that
537
+ // transient error would strand otherwise live writers.
538
+ if ((probeErr as NodeJS.ErrnoException).code === "ENOENT") continue;
539
+ throw err;
540
+ }
541
+ }
542
+ // A crashed LOCAL holder is stolen at once (no 10s wait).
543
+ if (await recoverDeadLocalLock(lockPath, token, closeHandle)) {
544
+ break;
545
+ }
546
+ // A LIVE local holder is genuinely mid-critical-section, while a foreign or malformed
547
+ // token is unprobeable. Never time-steal either case: age cannot prove that the owner is
548
+ // dead, and stealing could let both writers pass their ownership checks and lose a commit.
549
+ if (performance.now() - start > LOCK_MAX_WAIT_MS) {
550
+ throw new Error(
551
+ `mind store lock: timed out after ${LOCK_MAX_WAIT_MS}ms waiting for ${lockPath} ` +
552
+ `(sustained write contention) — retry the operation`,
553
+ );
554
+ }
555
+ await sleep(LOCK_POLL_MS);
556
+ }
557
+ }
558
+ try {
559
+ return await fn(token);
560
+ } finally {
561
+ try {
562
+ if ((await readLockToken(lockPath)) === token) await unlink(lockPath).catch(() => {});
563
+ } catch {
564
+ /* lock already gone */
565
+ }
566
+ }
567
+ }
568
+
569
+ /**
570
+ * Atomically read-modify-write a sequenced JSON store. The load→mutate→write runs inside the
571
+ * per-store lock, so the lock (not an optimistic sequence guard) is the serialization point:
572
+ * `mutate` always runs against the freshest on-disk store and a competing write cannot interleave.
573
+ * `mutate` MUST be a pure merge over the loaded store; every writer MUST go through this function.
574
+ */
575
+ export async function casUpdate<T extends { sequence: number }>(opts: {
576
+ storePath: string;
577
+ load: (token?: string) => Promise<T>;
578
+ mutate: (current: T) => T;
579
+ serialize: (next: T) => string;
580
+ /** Forwarded to atomicWriteFile: gate the `.bak` refresh on the current live file being valid. */
581
+ backupIf?: (currentRaw: string) => boolean;
582
+ /** Forwarded to atomicWriteFile: bound the live bytes inspected for `.bak` refresh. */
583
+ maxBackupBytes?: number;
584
+ }): Promise<T> {
585
+ const lockPath = `${opts.storePath}.lock`;
586
+ for (let attempt = 0; ; attempt++) {
587
+ try {
588
+ return await withFileLock(lockPath, async (token) => {
589
+ const current = await opts.load(token);
590
+ const merged = opts.mutate(current);
591
+ const next: T = { ...merged, sequence: current.sequence + 1 };
592
+ // Re-verify ownership before committing: recovery or a post-crash dual-steal could have
593
+ // handed the lock to another writer while we loaded/mutated — writing now would overwrite
594
+ // their committed entry with our stale snapshot. If we no longer own the lock, re-acquire.
595
+ const owner = await readLockToken(lockPath);
596
+ if (owner !== token) throw new LockLostError();
597
+ const writeOptions: AtomicWriteOptions = {};
598
+ if (opts.backupIf) writeOptions.backupIf = opts.backupIf;
599
+ if (opts.maxBackupBytes !== undefined) writeOptions.maxBackupBytes = opts.maxBackupBytes;
600
+ await atomicWriteFile(opts.storePath, opts.serialize(next), writeOptions);
601
+ return next;
602
+ });
603
+ } catch (err) {
604
+ if (err instanceof LockLostError && attempt < 5) continue; // re-acquire and retry
605
+ throw err;
606
+ }
607
+ }
608
+ }
609
+
610
+ export interface QuarantineOptions {
611
+ /** Existing store-lock ownership, used internally when the caller already holds the lock. */
612
+ lockToken?: string;
613
+ /** Test seam executed after the hard-link claim and before the source is removed. */
614
+ beforeRemove?: () => Promise<void>;
615
+ }
616
+
617
+ async function quarantineUnderLock(path: string, opts: QuarantineOptions): Promise<string | null> {
618
+ const lockPath = `${path}.lock`;
619
+ for (let n = 0; ; n++) {
620
+ const dest = `${path}.corrupt-${n}`;
621
+ let original;
622
+ try {
623
+ original = await lstat(path);
624
+ } catch (err) {
625
+ if ((err as NodeJS.ErrnoException).code === "ENOENT") return null;
626
+ throw err;
627
+ }
628
+ try {
629
+ await link(path, dest);
630
+ } catch (err) {
631
+ const code = (err as NodeJS.ErrnoException).code;
632
+ if (code === "EEXIST") continue;
633
+ if (code === "ENOENT") return null; // already moved by a concurrent loader
634
+ if (code !== "EPERM" && code !== "ENOSYS" && code !== "EXDEV" && code !== "EMLINK") throw err;
635
+ // Filesystems without hard links use rename, but still revalidate the source and lock first.
636
+ if (opts.beforeRemove) await opts.beforeRemove();
637
+ const current = await lstat(path);
638
+ if (!sameFile(original, current) || (opts.lockToken !== undefined && (await readLockToken(lockPath)) !== opts.lockToken)) return null;
639
+ let claimed = false;
640
+ try {
641
+ await rename(path, dest);
642
+ claimed = true;
643
+ return dest;
644
+ } finally {
645
+ if (!claimed) await unlink(dest).catch(() => {});
646
+ }
647
+ }
648
+ try {
649
+ if (opts.beforeRemove) await opts.beforeRemove();
650
+ const current = await lstat(path);
651
+ const claim = await lstat(dest);
652
+ const ownsLock = opts.lockToken === undefined || (await readLockToken(lockPath)) === opts.lockToken;
653
+ if (!sameFile(original, current) || !sameFile(original, claim) || !ownsLock) {
654
+ await unlink(dest).catch(() => {});
655
+ return null;
656
+ }
657
+ await unlink(path);
658
+ return dest;
659
+ } catch (err) {
660
+ await unlink(dest).catch(() => {});
661
+ if ((err as NodeJS.ErrnoException).code === "ENOENT") return null;
662
+ throw err;
663
+ }
664
+ }
665
+ }
666
+
667
+ /**
668
+ * Move a store that failed validation aside to `${path}.corrupt-<n>` (first free suffix, derived
669
+ * from disk not wall-clock so recovery is reproducible), instead of silently substituting empty.
670
+ * Quarantine is serialized by the same per-store lock used by updates, and the hard-link claim is
671
+ * revalidated before removal so a concurrent atomic replacement can never be unlinked.
672
+ */
673
+ export async function quarantineCorrupt(path: string, reason: string, opts: QuarantineOptions = {}): Promise<string | null> {
674
+ void reason;
675
+ if (opts.lockToken !== undefined) {
676
+ try {
677
+ return await quarantineUnderLock(path, opts);
678
+ } catch {
679
+ return null;
680
+ }
681
+ }
682
+ try {
683
+ return await withFileLock(`${path}.lock`, async (token) => quarantineUnderLock(path, { ...opts, lockToken: token }));
684
+ } catch {
685
+ return null; // could not move it aside — caller degrades to empty, loudly
686
+ }
687
+ }
688
+
689
+ export interface JsonStoreOptions<E> {
690
+ version: number;
691
+ /** Validate one raw entry; return the typed entry, or null to drop it (schema drift). */
692
+ validateEntry: (raw: unknown) => E | null;
693
+ /** Maximum bytes read from or written to a live or backup store. Defaults to {@link DEFAULT_STORE_MAX_BYTES}. */
694
+ maxBytes?: number;
695
+ /** Maximum entries accepted from a store wrapper. Defaults to {@link DEFAULT_STORE_MAX_ENTRIES}. */
696
+ maxEntries?: number;
697
+ /** Wall clock for `updatedAt` (injectable for tests). Default Date.now. */
698
+ now?: () => number;
699
+ /** Surfacing for recovery events (quarantine). Default: none. */
700
+ onWarn?: (message: string) => void;
701
+ }
702
+
703
+ /**
704
+ * A typed, durable store of entries in one JSON file. Load degrades safely (missing → empty;
705
+ * torn/invalid shape → quarantine + empty; individual invalid entries → hidden and preserved).
706
+ * Update is serialized and atomic. The generic `E` is the entry type; the file wraps `E[]` with
707
+ * version and the CAS sequence.
708
+ */
709
+ export class JsonStore<E> {
710
+ readonly filePath: string;
711
+ private readonly opts: JsonStoreOptions<E>;
712
+ private readonly now: () => number;
713
+ private readonly onWarn: (message: string) => void;
714
+ private readonly maxBytes: number;
715
+ private readonly maxEntries: number;
716
+
717
+ constructor(
718
+ filePath: string,
719
+ opts: JsonStoreOptions<E>,
720
+ ) {
721
+ this.filePath = filePath;
722
+ this.opts = opts;
723
+ this.now = opts.now ?? Date.now;
724
+ this.onWarn = opts.onWarn ?? (() => {});
725
+ this.maxBytes = opts.maxBytes ?? DEFAULT_STORE_MAX_BYTES;
726
+ this.maxEntries = opts.maxEntries ?? DEFAULT_STORE_MAX_ENTRIES;
727
+ if (!Number.isSafeInteger(this.maxBytes) || this.maxBytes <= 0) throw new RangeError("mind store maxBytes must be a positive safe integer");
728
+ if (!Number.isSafeInteger(this.maxEntries) || this.maxEntries <= 0) throw new RangeError("mind store maxEntries must be a positive safe integer");
729
+ }
730
+
731
+ private empty(): StoreFile<E> {
732
+ return { version: this.opts.version, updatedAt: new Date(this.now()).toISOString(), sequence: 0, entries: [] };
733
+ }
734
+
735
+ /** Parse + validate raw store bytes into a StoreFile, or null on unparseable JSON / wrong shape. */
736
+ private parseStore(raw: string): InternalStoreFile<E> | null {
737
+ let parsed: unknown;
738
+ try {
739
+ parsed = JSON.parse(raw);
740
+ } catch {
741
+ return null;
742
+ }
743
+ if (!parsed || typeof parsed !== "object" || !Array.isArray((parsed as { entries?: unknown }).entries)) return null;
744
+ const obj = parsed as Partial<StoreFile<unknown>>;
745
+ if (obj.version !== this.opts.version) {
746
+ // A well-formed envelope naming another version is a different build's store, not corruption:
747
+ // surface it and leave the file alone. An absent/garbage version is envelope corruption.
748
+ if (typeof obj.version === "number" && Number.isSafeInteger(obj.version) && obj.version > 0) throw new StoreVersionError(obj.version, this.opts.version);
749
+ return null;
750
+ }
751
+ if (typeof obj.updatedAt !== "string" || !Number.isFinite(Date.parse(obj.updatedAt))) return null;
752
+ if (typeof obj.sequence !== "number" || !Number.isSafeInteger(obj.sequence) || obj.sequence < 0) return null;
753
+ const rawEntries = obj.entries as unknown[];
754
+ if (rawEntries.length > this.maxEntries) {
755
+ throw new BoundedReadFailure("entries", `store file exceeds the ${this.maxEntries}-entry limit`);
756
+ }
757
+ const entries: E[] = [];
758
+ const invalidEntries: unknown[] = [];
759
+ for (const rawEntry of rawEntries) {
760
+ const e = this.opts.validateEntry(rawEntry);
761
+ if (e !== null) entries.push(e);
762
+ else invalidEntries.push(rawEntry);
763
+ }
764
+ const store: InternalStoreFile<E> = {
765
+ version: obj.version,
766
+ updatedAt: obj.updatedAt,
767
+ sequence: obj.sequence,
768
+ entries,
769
+ };
770
+ if (invalidEntries.length > 0) store[PRESERVED_INVALID_ENTRIES] = invalidEntries;
771
+ return store;
772
+ }
773
+
774
+ private async restoreLive(store: InternalStoreFile<E>): Promise<void> {
775
+ const invalidEntries = store[PRESERVED_INVALID_ENTRIES] ?? [];
776
+ const persisted = invalidEntries.length > 0 ? { ...store, entries: [...store.entries, ...invalidEntries] } : store;
777
+ await atomicWriteFile(this.filePath, `${JSON.stringify(persisted, null, 2)}\n`, {
778
+ backupIf: () => false,
779
+ maxBackupBytes: this.maxBytes,
780
+ });
781
+ }
782
+
783
+ private async recoverFromBak(reason: string, lockToken?: string): Promise<InternalStoreFile<E> | null> {
784
+ if (lockToken === undefined) {
785
+ const peek = await this.tryBak();
786
+ if (!peek) return null;
787
+ return withFileLock(`${this.filePath}.lock`, async (token) => this.recoverFromBak(reason, token));
788
+ }
789
+ const bak = await this.tryBak();
790
+ if (!bak) return null;
791
+ this.onWarn(`mind store: ${this.filePath} ${reason}; recovered from ${this.filePath}.bak`);
792
+ this.warnInvalidEntries(bak);
793
+ await this.restoreLive(bak);
794
+ return bak;
795
+ }
796
+
797
+ /** Try to recover the last-known-good `.bak` sidecar. Returns null if it is absent or also bad. */
798
+ private async tryBak(): Promise<InternalStoreFile<E> | null> {
799
+ try {
800
+ return this.parseStore(await readTextFileBounded(`${this.filePath}.bak`, this.maxBytes));
801
+ } catch (err) {
802
+ if (err instanceof BoundedReadFailure) {
803
+ this.onWarn(`mind store: ${this.filePath}.bak rejected — ${err.message}`);
804
+ }
805
+ return null;
806
+ }
807
+ }
808
+
809
+ private warnInvalidEntries(store: InternalStoreFile<E>): void {
810
+ const count = store[PRESERVED_INVALID_ENTRIES]?.length ?? 0;
811
+ if (count === 0) return;
812
+ this.onWarn(
813
+ `mind store: ${this.filePath} contained ${count} invalid entr${count === 1 ? "y" : "ies"}; ` +
814
+ "preserved raw and hidden from consumers",
815
+ );
816
+ }
817
+
818
+ private async recoverBoundedFailure(failure: BoundedReadFailure, lockToken?: string): Promise<InternalStoreFile<E>> {
819
+ if (lockToken === undefined) {
820
+ // Keep healthy/missing reads non-blocking. A bounded failure is re-read under the same
821
+ // store lock before quarantine so a writer that repaired the path wins the race safely.
822
+ return withFileLock(`${this.filePath}.lock`, async (token) => this.loadInternal(token));
823
+ }
824
+ const bak = await this.recoverFromBak(`rejected — ${failure.message}`, lockToken);
825
+ if (bak) return bak;
826
+ const quarantineOptions: QuarantineOptions = {};
827
+ if (lockToken !== undefined) quarantineOptions.lockToken = lockToken;
828
+ const dest = await quarantineCorrupt(this.filePath, failure.message, quarantineOptions);
829
+ this.onWarn(`mind store: ${this.filePath} rejected — ${failure.message}; no usable backup, quarantined to ${dest ?? "(nowhere)"}, starting empty`);
830
+ return this.empty();
831
+ }
832
+
833
+ private async loadInternal(lockToken?: string): Promise<InternalStoreFile<E>> {
834
+ let raw: string;
835
+ try {
836
+ raw = await readTextFileBounded(this.filePath, this.maxBytes);
837
+ } catch (err) {
838
+ if ((err as NodeJS.ErrnoException).code === "ENOENT") {
839
+ const bak = await this.recoverFromBak("missing", lockToken);
840
+ return bak ?? this.empty();
841
+ }
842
+ if (err instanceof BoundedReadFailure) return this.recoverBoundedFailure(err, lockToken);
843
+ throw err;
844
+ }
845
+ let parsed: InternalStoreFile<E> | null;
846
+ try {
847
+ parsed = this.parseStore(raw);
848
+ } catch (err) {
849
+ if (err instanceof BoundedReadFailure) return this.recoverBoundedFailure(err, lockToken);
850
+ throw err;
851
+ }
852
+ if (parsed) {
853
+ this.warnInvalidEntries(parsed);
854
+ return parsed;
855
+ }
856
+ if (lockToken === undefined) {
857
+ // The first read was only an optimistic check. Re-read while holding the update lock before
858
+ // deciding whether the path is still corrupt and may be quarantined.
859
+ return withFileLock(`${this.filePath}.lock`, async (token) => this.loadInternal(token));
860
+ }
861
+ // Live file is torn/invalid — roll back to the last-known-good backup before giving up.
862
+ const bak = await this.recoverFromBak("was corrupt — the last committed write may be lost", lockToken);
863
+ if (bak) return bak;
864
+ const quarantineOptions: QuarantineOptions = {};
865
+ if (lockToken !== undefined) quarantineOptions.lockToken = lockToken;
866
+ const dest = await quarantineCorrupt(this.filePath, "unparseable / unexpected shape", quarantineOptions);
867
+ this.onWarn(`mind store: ${this.filePath} was corrupt and had no usable backup — quarantined to ${dest ?? "(nowhere)"}, starting empty`);
868
+ return this.empty();
869
+ }
870
+
871
+ async load(): Promise<StoreFile<E>> {
872
+ const store = await this.loadInternal();
873
+ return { version: store.version, updatedAt: store.updatedAt, sequence: store.sequence, entries: [...store.entries] };
874
+ }
875
+
876
+ /** Read without recovery, quarantine, warnings or writes; invalid rows make editing unsafe. */
877
+ async inspectStrict(): Promise<StoreSnapshot<E>> {
878
+ let raw: string | undefined;
879
+ try {
880
+ raw = await readTextFileBounded(this.filePath, this.maxBytes);
881
+ } catch (err) {
882
+ if ((err as NodeJS.ErrnoException).code !== "ENOENT") throw err;
883
+ try {
884
+ await lstat(`${this.filePath}.bak`);
885
+ throw new Error("memory store is missing with a recoverable backup; repair before optimizing");
886
+ } catch (backupError) {
887
+ if ((backupError as NodeJS.ErrnoException).code !== "ENOENT") throw backupError;
888
+ }
889
+ }
890
+ const store: InternalStoreFile<E> | null = raw === undefined ? this.empty() : this.parseStore(raw);
891
+ if (!store || (store[PRESERVED_INVALID_ENTRIES]?.length ?? 0) > 0) {
892
+ throw new Error("memory store is corrupt or contains invalid entries; repair before optimizing");
893
+ }
894
+ const fingerprint = createHash("sha256").update(JSON.stringify([this.filePath, raw ?? null])).digest("hex");
895
+ return { store: { version: store.version, updatedAt: store.updatedAt, sequence: store.sequence, entries: [...store.entries] }, fingerprint };
896
+ }
897
+
898
+ /** Strict one-file CAS. A stale preview and a no-op leave live bytes and backups untouched. */
899
+ async compareAndUpdate(fingerprint: string, mutate: (entries: E[]) => E[]): Promise<StoreFile<E>> {
900
+ return withFileLock(`${this.filePath}.lock`, async (token) => {
901
+ const current = await this.inspectStrict();
902
+ if (current.fingerprint !== fingerprint) throw new StoreConflictError();
903
+ const previousEntries = JSON.stringify(current.store.entries);
904
+ const entries = mutate(current.store.entries);
905
+ if (JSON.stringify(entries) === previousEntries) return current.store;
906
+ if (!Number.isSafeInteger(current.store.sequence + 1)) throw new Error("memory store sequence exhausted");
907
+ const next = { ...current.store, entries, sequence: current.store.sequence + 1, updatedAt: new Date(this.now()).toISOString() };
908
+ const serialized = this.serializeStore(next);
909
+ const validated = this.parseStore(serialized);
910
+ if (!validated || (validated[PRESERVED_INVALID_ENTRIES]?.length ?? 0) > 0) throw new Error("invalid memory store update");
911
+ if ((await readLockToken(`${this.filePath}.lock`)) !== token) throw new StoreConflictError();
912
+ await atomicWriteFile(this.filePath, serialized, { backupIf: () => true, maxBackupBytes: this.maxBytes });
913
+ return next;
914
+ });
915
+ }
916
+
917
+ private serializeStore(next: InternalStoreFile<E>): string {
918
+ const invalidEntries = next[PRESERVED_INVALID_ENTRIES] ?? [];
919
+ const count = next.entries.length + invalidEntries.length;
920
+ if (count > this.maxEntries) throw new StoreCapacityError("entries", count, this.maxEntries);
921
+ const persisted = invalidEntries.length > 0 ? { ...next, entries: [...next.entries, ...invalidEntries] } : next;
922
+ const serialized = `${JSON.stringify(persisted, null, 2)}\n`;
923
+ const bytes = Buffer.byteLength(serialized, "utf8");
924
+ if (bytes > this.maxBytes) throw new StoreCapacityError("bytes", bytes, this.maxBytes);
925
+ return serialized;
926
+ }
927
+
928
+ /** Atomically apply `mutate` to the current entries and persist. Returns the committed store. */
929
+ async update(mutate: (entries: E[]) => E[]): Promise<StoreFile<E>> {
930
+ const next = await casUpdate<InternalStoreFile<E>>({
931
+ storePath: this.filePath,
932
+ load: (token) => this.loadInternal(token),
933
+ mutate: (current) => ({ ...current, updatedAt: new Date(this.now()).toISOString(), entries: mutate(current.entries) }),
934
+ serialize: (next) => this.serializeStore(next),
935
+ // Only refresh the .bak from a live file that still parses — never let a torn file we just
936
+ // recovered from .bak overwrite that good backup.
937
+ backupIf: (raw) => {
938
+ try {
939
+ return this.parseStore(raw) !== null;
940
+ } catch {
941
+ return false;
942
+ }
943
+ },
944
+ maxBackupBytes: this.maxBytes,
945
+ });
946
+ return { version: next.version, updatedAt: next.updatedAt, sequence: next.sequence, entries: [...next.entries] };
947
+ }
948
+ }