@jjh32456/longlive 2.1.0 → 2.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (51) hide show
  1. package/CHANGELOG.md +108 -1
  2. package/QUICKSTART.md +7 -7
  3. package/README.en.md +13 -1
  4. package/README.md +26 -8
  5. package/SPEC.md +6 -5
  6. package/build-info.json +143 -73
  7. package/cordis.patch.yml +2 -0
  8. package/docs/ARCHITECTURE.md +6 -3
  9. package/docs/CONFIG.md +25 -1
  10. package/docs/FAQ.md +2 -2
  11. package/docs/FEATURES.md +125 -2
  12. package/docs/INDEX-FRESHNESS.md +8 -1
  13. package/docs/OPERATIONS.md +63 -2
  14. package/docs/QUICKSTART.md +2 -2
  15. package/docs/README.en.md +1 -1
  16. package/docs/TROUBLESHOOTING.md +1 -1
  17. package/package.json +10 -2
  18. package/scripts/assert-install.mjs +124 -0
  19. package/scripts/backlog-report.mjs +98 -0
  20. package/scripts/install-230.mjs +787 -0
  21. package/scripts/lib/eng-common.mjs +428 -0
  22. package/scripts/rebuild-index.mjs +148 -0
  23. package/scripts/restore-drill.mjs +351 -0
  24. package/scripts/run-autoresolve.mjs +123 -0
  25. package/scripts/watchdog-230.mjs +379 -0
  26. package/src/config.js +7 -0
  27. package/src/features.js +35 -0
  28. package/src/gate/action-gate.js +545 -0
  29. package/src/memory/backup-retention.mjs +823 -0
  30. package/src/memory/cards.js +73 -12
  31. package/src/memory/conflict-scan.mjs +356 -0
  32. package/src/memory/conflicts.js +202 -9
  33. package/src/memory/consolidate.js +537 -35
  34. package/src/memory/decay.js +133 -19
  35. package/src/memory/event-index.js +62 -4
  36. package/src/memory/forget-scheduler.mjs +303 -0
  37. package/src/memory/forget-v2.js +94 -8
  38. package/src/memory/index-cache.mjs +216 -0
  39. package/src/memory/index.js +179 -16
  40. package/src/memory/lock.js +53 -12
  41. package/src/memory/maintenance.js +295 -19
  42. package/src/memory/recall-feedback.mjs +159 -17
  43. package/src/memory/recall-v2.js +5 -3
  44. package/src/memory/recall.js +10 -4
  45. package/src/memory/state.js +446 -38
  46. package/src/memory/task-state.mjs +569 -0
  47. package/src/recall/brain.mjs +55 -6
  48. package/src/recall/continuity-volatile.mjs +195 -1
  49. package/src/recall/index.js +8 -0
  50. package/src/tools.js +141 -21
  51. package/src/ui/routes-readonly.js +63 -5
@@ -4,16 +4,42 @@
4
4
  // the audit log, backups, reports, and the atomic write/verify/rollback path.
5
5
  // Every path is re-checked against the root here, even when a caller already
6
6
  // resolved it, so a bug upstream cannot become a write outside the store.
7
+ //
8
+ // 2.3.0 / W1-1: the read-modify-write of `.longlive/memory-state.json` is now
9
+ // guarded by the shared lease (`lock.js`) and patches are merged entry-by-entry
10
+ // against a fresh read, so two sessions can no longer overwrite each other's
11
+ // `seenProposals` / `lastConsolidated` / `lastCaptureAt` (measured lost-update,
12
+ // BACKLOG F8). Rollback after a failed write is *targeted*: only the entries
13
+ // this process added and the scalar keys it changed are reverted, never the
14
+ // whole old snapshot over someone else's successful write.
15
+ //
16
+ // 2.3.0 / W1-2: backups go through `backup-retention.mjs` (sha dedupe, manifest,
17
+ // UTF-8 SHA256SUMS, retention gate) instead of an unbounded copy per write.
7
18
 
8
19
  import fs from 'node:fs';
9
20
  import path from 'node:path';
10
21
  import crypto from 'node:crypto';
11
22
 
12
23
  import { memoryError, resolveInside, relativePath } from './paths.js';
24
+ import { withLease, LockError } from './lock.js';
25
+ import { createWal } from './wal.js';
26
+ import {
27
+ DEFAULT_RETENTION,
28
+ backupStoreNeedsMaintenance,
29
+ ensureManagedBackup,
30
+ runBackupMaintenance,
31
+ } from './backup-retention.mjs';
13
32
 
14
33
  export const LONGLIVE_DIR = '.longlive';
15
34
  export const BACKUPS_DIR = 'backups';
16
35
  export const REPORTS_DIR = 'reports';
36
+ export const STATE_LOCK_FILE = 'memory-state.lock';
37
+ // The lease only covers a read-merge-write of a few hundred KB; a short TTL
38
+ // bounds how long a crashed writer can block the store (retention runs outside
39
+ // the lease, so nothing long-lived happens while it is held).
40
+ export const DEFAULT_STATE_LOCK_TTL_MS = 60 * 1000;
41
+ export const DEFAULT_STATE_LOCK_WAIT_MS = 5000;
42
+ export const DEFAULT_STATE_LOCK_RETRY_MS = 25;
17
43
 
18
44
  export function longliveDir(root) {
19
45
  return resolveInside(root, LONGLIVE_DIR);
@@ -83,35 +109,19 @@ function collisionFree(dir, base, stamp, ext) {
83
109
  /**
84
110
  * Copy one file into a backup directory inside the root and verify the copy
85
111
  * byte-for-byte. A failed verification removes the partial copy and throws.
112
+ *
113
+ * 2.3.0: goes through `backup-retention.mjs#ensureManagedBackup`, so the copy is
114
+ * sha256-deduped against the manifest (same base + same sha = no second file)
115
+ * and recorded in the dir's manifest journal for retention/restore.
86
116
  */
87
- export function backupInto(root, file, dir, { now = new Date() } = {}) {
117
+ export function backupInto(root, file, dir, { now = new Date(), dedupe = true, kind = 'file', onBackup } = {}) {
88
118
  const abs = resolveInside(root, file);
89
119
  const targetDir = resolveInside(root, dir);
90
- let stat = null;
91
- try {
92
- stat = fs.lstatSync(abs);
93
- } catch (error) {
94
- throw memoryError('E_BACKUP_SOURCE', `备份源不存在:${abs}`, error);
95
- }
96
- if (!stat.isFile()) {
97
- throw memoryError('E_BACKUP_SOURCE', `备份源不是普通文件:${abs}`);
98
- }
99
- ensureDir(root, targetDir);
100
- const ext = path.extname(abs);
101
- const base = path.basename(abs, ext) || 'file';
102
- const dest = collisionFree(targetDir, base, stampToken(now), ext || '.md');
103
- fs.copyFileSync(abs, dest);
104
- const want = sha256File(abs);
105
- const got = sha256File(dest);
106
- if (want !== got) {
107
- try {
108
- fs.unlinkSync(dest);
109
- } catch {
110
- /* best effort: never mask the verification error below */
111
- }
112
- throw memoryError('E_BACKUP_VERIFY', `备份校验失败:${dest} 与源文件 sha256 不一致`);
120
+ const result = ensureManagedBackup(root, abs, { dir: targetDir, now, dedupe, kind, source: relativePath(root, abs) });
121
+ if (typeof onBackup === 'function') {
122
+ onBackup({ root, file: abs, dir: targetDir, path: result.path, rel: result.rel, sha256: result.sha256, deduped: result.deduped, now });
113
123
  }
114
- return { path: dest, rel: relativePath(root, dest), sha256: got };
124
+ return result;
115
125
  }
116
126
 
117
127
  /** Back a file up into `<root>/.longlive/backups/`. */
@@ -136,16 +146,18 @@ let tmpCounter = 0;
136
146
 
137
147
  /**
138
148
  * Write `content` to `file` atomically: backup first, tmp + rename, read-back
139
- * verify, and restore the original bytes if the verify fails. The caller gets
140
- * the backup path so a later step can roll back deliberately as well.
149
+ * verify. On a failed write the caller can pass `onWriteFailure` to repair a
150
+ * already-committed concurrent write *targetedly* (state.js passes one that
151
+ * reverts only this process's entries); without it the original bytes are
152
+ * restored whole, which is right for single-writer files (cards, indexes).
141
153
  */
142
- export function writeFileAtomic(root, file, content, { backup: wantBackup = true, now = new Date() } = {}) {
154
+ export function writeFileAtomic(root, file, content, { backup: wantBackup = true, now = new Date(), onWriteFailure = null, backupOptions = {} } = {}) {
143
155
  const abs = resolveInside(root, file);
144
156
  ensureDir(root, path.dirname(abs));
145
157
  const existed = fs.existsSync(abs);
146
158
  const original = existed ? fs.readFileSync(abs) : null;
147
159
  const originalSha = original ? sha256Buffer(original) : null;
148
- const backup = existed && wantBackup ? backupFile(root, abs, { now }) : null;
160
+ const backup = existed && wantBackup ? backupFile(root, abs, { now, ...backupOptions }) : null;
149
161
  const tmp = `${abs}.tmp-${process.pid}-${(tmpCounter += 1)}`;
150
162
  try {
151
163
  fs.writeFileSync(tmp, content, 'utf8');
@@ -167,9 +179,26 @@ export function writeFileAtomic(root, file, content, { backup: wantBackup = true
167
179
  if (originalSha != null) {
168
180
  const currentSha = fs.existsSync(abs) ? sha256File(abs) : null;
169
181
  if (currentSha !== originalSha) {
170
- fs.writeFileSync(abs, original);
171
- if (sha256File(abs) !== originalSha) {
172
- throw memoryError('E_ROLLBACK_FAILED', `写失败后无法恢复原文件:${abs}`, error);
182
+ if (typeof onWriteFailure === 'function') {
183
+ try {
184
+ onWriteFailure({
185
+ root,
186
+ file: abs,
187
+ error,
188
+ content,
189
+ originalText: original ? original.toString('utf8') : null,
190
+ originalSha,
191
+ currentText: fs.existsSync(abs) ? fs.readFileSync(abs, 'utf8') : null,
192
+ now,
193
+ });
194
+ } catch (repairError) {
195
+ throw memoryError('E_ROLLBACK_FAILED', `写失败后无法修复状态文件:${abs}`, repairError);
196
+ }
197
+ } else {
198
+ fs.writeFileSync(abs, original);
199
+ if (sha256File(abs) !== originalSha) {
200
+ throw memoryError('E_ROLLBACK_FAILED', `写失败后无法恢复原文件:${abs}`, error);
201
+ }
173
202
  }
174
203
  }
175
204
  }
@@ -225,12 +254,391 @@ export function readState(root) {
225
254
  };
226
255
  }
227
256
 
228
- /** Merge `patch` into the state file (backup + verify through writeFileAtomic). */
229
- export function updateState(root, patch, { now = new Date() } = {}) {
230
- const current = readState(root);
231
- const next = { ...current, ...patch, updatedAt: now.toISOString() };
232
- const result = writeFileAtomic(root, statePath(root), `${JSON.stringify(next, null, 2)}\n`, { now });
233
- return { ...next, write: result };
257
+ // ---------------------------------------------------------------------------
258
+ // 2.3.0 / W1-1: state lock, patch merge, targeted rollback, crash recovery
259
+ // ---------------------------------------------------------------------------
260
+
261
+ /** `<root>/.longlive/memory-state.lock` — the cross-process write lease. */
262
+ export function stateLockPath(root) {
263
+ return resolveInside(root, path.join(LONGLIVE_DIR, STATE_LOCK_FILE));
264
+ }
265
+
266
+ function stateLockHolder() {
267
+ return `state-${process.pid}-${crypto.randomBytes(4).toString('hex')}`;
268
+ }
269
+
270
+ /** Deterministic JSON (sorted keys) for entry identity / equality checks. */
271
+ export function stableStringify(value) {
272
+ const walk = (input) => {
273
+ if (Array.isArray(input)) return `[${input.map(walk).join(',')}]`;
274
+ if (input && typeof input === 'object') {
275
+ const keys = Object.keys(input).sort();
276
+ return `{${keys.map((key) => `${JSON.stringify(key)}:${walk(input[key])}`).join(',')}}`;
277
+ }
278
+ return JSON.stringify(input) ?? 'null';
279
+ };
280
+ return walk(value);
281
+ }
282
+
283
+ export function sameJson(left, right) {
284
+ return stableStringify(left) === stableStringify(right);
285
+ }
286
+
287
+ function proposalIdOf(entry) {
288
+ if (entry && typeof entry === 'object' && typeof entry.id === 'string' && entry.id !== '') return entry.id;
289
+ return sha256Text(stableStringify(entry)).slice(0, 16);
290
+ }
291
+
292
+ const PROPOSAL_STATUS_RANK = Object.freeze({ proposed: 0, accepted: 1, rejected: 2, resolved: 3 });
293
+
294
+ function statusRank(status) {
295
+ return typeof status === 'string' && Object.prototype.hasOwnProperty.call(PROPOSAL_STATUS_RANK, status)
296
+ ? PROPOSAL_STATUS_RANK[status]
297
+ : -1;
298
+ }
299
+
300
+ function mergeProposalEntry(base, incoming) {
301
+ if (base == null || typeof base !== 'object') return incoming;
302
+ if (incoming == null || typeof incoming !== 'object') return base;
303
+ const merged = { ...base, ...incoming };
304
+ const rank = statusRank(base.status) > statusRank(merged.status) ? base.status : merged.status;
305
+ if (merged.status !== rank) merged.status = rank;
306
+ for (const key of ['acceptedAt', 'rejectedAt', 'resolvedAt', 'resolvedBy', 'reason']) {
307
+ if (base[key] !== undefined && merged[key] === undefined) merged[key] = base[key];
308
+ }
309
+ return merged;
310
+ }
311
+
312
+ /**
313
+ * Merge seenProposals by proposal id. A stale whole-array patch (consolidate.js
314
+ * reads the array before taking a later write) must not drop entries another
315
+ * process added in between, and must not move an entry backwards from
316
+ * accepted/rejected to proposed.
317
+ */
318
+ export function mergeSeenProposals(baseEntries, incomingEntries) {
319
+ const base = Array.isArray(baseEntries) ? baseEntries : [];
320
+ const incoming = Array.isArray(incomingEntries) ? incomingEntries : [];
321
+ const merged = new Map();
322
+ for (const entry of base) merged.set(proposalIdOf(entry), entry);
323
+ for (const entry of incoming) {
324
+ const id = proposalIdOf(entry);
325
+ merged.set(id, mergeProposalEntry(merged.get(id), entry));
326
+ }
327
+ return [...merged.values()];
328
+ }
329
+
330
+ /** Union forgetRuns by stable serialisation (two processes can both record a day). */
331
+ export function mergeForgetRuns(baseRuns, incomingRuns) {
332
+ const base = Array.isArray(baseRuns) ? baseRuns : [];
333
+ const incoming = Array.isArray(incomingRuns) ? incomingRuns : [];
334
+ const seen = new Set(base.map((entry) => stableStringify(entry)));
335
+ const out = [...base];
336
+ for (const entry of incoming) {
337
+ const key = stableStringify(entry);
338
+ if (seen.has(key)) continue;
339
+ seen.add(key);
340
+ out.push(entry);
341
+ }
342
+ return out;
343
+ }
344
+
345
+ function laterIso(base, incoming) {
346
+ if (incoming == null) return base ?? null;
347
+ if (base == null) return incoming;
348
+ const baseMs = Date.parse(base);
349
+ const incomingMs = Date.parse(incoming);
350
+ if (!Number.isFinite(baseMs)) return incoming;
351
+ if (!Number.isFinite(incomingMs)) return base;
352
+ return incomingMs > baseMs ? incoming : base;
353
+ }
354
+
355
+ /**
356
+ * Merge a state patch over a freshly read state (the merge runs inside the
357
+ * lease). Arrays are merged by entry identity, scalars are last-write-wins,
358
+ * except `lastConsolidated` which never moves backwards.
359
+ */
360
+ export function mergeStatePatch(current, patch) {
361
+ const base = current && typeof current === 'object' ? current : {};
362
+ const delta = patch && typeof patch === 'object' ? patch : {};
363
+ const next = { ...base, ...delta };
364
+ if (Array.isArray(delta.forgetRuns)) next.forgetRuns = mergeForgetRuns(base.forgetRuns, delta.forgetRuns);
365
+ if (Array.isArray(delta.seenProposals)) next.seenProposals = mergeSeenProposals(base.seenProposals, delta.seenProposals);
366
+ if ('lastConsolidated' in delta) next.lastConsolidated = laterIso(base.lastConsolidated, delta.lastConsolidated);
367
+ return next;
368
+ }
369
+
370
+ function repairArray(key, original, intended, current) {
371
+ if (key === 'seenProposals') {
372
+ const originalById = new Map((Array.isArray(original) ? original : []).map((entry) => [proposalIdOf(entry), entry]));
373
+ const intendedById = new Map((Array.isArray(intended) ? intended : []).map((entry) => [proposalIdOf(entry), entry]));
374
+ const ourAdded = new Set([...intendedById.keys()].filter((id) => !originalById.has(id)));
375
+ const currentList = Array.isArray(current) ? current : [];
376
+ const out = [];
377
+ const seen = new Set();
378
+ for (const entry of currentList) {
379
+ const id = proposalIdOf(entry);
380
+ if (ourAdded.has(id)) continue; // revert exactly the entries this process added
381
+ if (originalById.has(id) && intendedById.has(id) && !sameJson(intendedById.get(id), originalById.get(id))) {
382
+ out.push(mergeProposalEntry(entry, originalById.get(id)));
383
+ } else {
384
+ out.push(entry);
385
+ }
386
+ seen.add(id);
387
+ }
388
+ for (const [id, entry] of originalById) {
389
+ if (!seen.has(id)) out.push(entry); // put back entries a truncated read-back lost
390
+ }
391
+ return out;
392
+ }
393
+ if (key === 'forgetRuns') {
394
+ const originalKeys = new Set((Array.isArray(original) ? original : []).map((entry) => stableStringify(entry)));
395
+ const intendedKeys = new Set((Array.isArray(intended) ? intended : []).map((entry) => stableStringify(entry)));
396
+ const ourAdded = new Set([...intendedKeys].filter((keyValue) => !originalKeys.has(keyValue)));
397
+ const currentList = Array.isArray(current) ? current : [];
398
+ return currentList.filter((entry) => !ourAdded.has(stableStringify(entry)));
399
+ }
400
+ return Array.isArray(current) ? current : original;
401
+ }
402
+
403
+ /**
404
+ * Targeted repair for a state write that failed after rename: keep every
405
+ * concurrent field/entry someone else wrote, revert only what this process
406
+ * changed (its added proposal ids, its scalar changes). Falls back to the old
407
+ * bytes when the read-back is unparseable.
408
+ */
409
+ export function repairStateWrite(root, file, { intendedText = null, originalText = null, now = new Date() } = {}) {
410
+ const abs = resolveInside(root, file);
411
+ const parse = (text) => {
412
+ if (text == null) return null;
413
+ try {
414
+ const value = JSON.parse(String(text));
415
+ return value && typeof value === 'object' && !Array.isArray(value) ? value : null;
416
+ } catch {
417
+ return null;
418
+ }
419
+ };
420
+ const currentText = fs.existsSync(abs) ? fs.readFileSync(abs, 'utf8') : null;
421
+ const intended = parse(intendedText);
422
+ const original = parse(originalText);
423
+ const current = parse(currentText);
424
+ if (intended && original && current) {
425
+ const repaired = { ...current };
426
+ for (const key of Object.keys(intended)) {
427
+ if (sameJson(intended[key], original[key])) continue; // this process did not change it
428
+ if (Array.isArray(intended[key]) && Array.isArray(original[key])) {
429
+ repaired[key] = repairArray(key, original[key], intended[key], current[key]);
430
+ } else if (key === 'lastConsolidated') {
431
+ repaired[key] = laterIso(current[key] ?? null, original[key] ?? null);
432
+ } else {
433
+ repaired[key] = current[key] !== undefined ? current[key] : original[key];
434
+ }
435
+ }
436
+ for (const key of Object.keys(original)) if (repaired[key] === undefined) repaired[key] = original[key];
437
+ repaired.updatedAt = now.toISOString();
438
+ const text = `${JSON.stringify(repaired, null, 2)}\n`;
439
+ fs.writeFileSync(abs, text, 'utf8');
440
+ if (fs.readFileSync(abs, 'utf8') !== text) {
441
+ throw memoryError('E_ROLLBACK_FAILED', `写失败后无法修复状态文件:${abs}`);
442
+ }
443
+ return { repaired: true, droppedAdded: true };
444
+ }
445
+ if (original) {
446
+ // read-back unparseable (truncated) → restore the pre-write bytes
447
+ fs.writeFileSync(abs, originalText);
448
+ if (sha256File(abs) !== sha256Text(originalText)) {
449
+ throw memoryError('E_ROLLBACK_FAILED', `写失败后无法恢复原文件:${abs}`);
450
+ }
451
+ return { repaired: true, restored: true };
452
+ }
453
+ try {
454
+ fs.rmSync(abs, { force: true });
455
+ } catch {
456
+ /* best effort: a brand-new file that failed verification is left out of state */
457
+ }
458
+ return { repaired: true, removed: true };
459
+ }
460
+
461
+ /** Delete leftover `memory-state.json.tmp-*` files from crashed writers. */
462
+ export function cleanupStaleStateTemps(root) {
463
+ const dir = resolveInside(root, LONGLIVE_DIR);
464
+ let names = [];
465
+ try {
466
+ names = fs.readdirSync(dir);
467
+ } catch {
468
+ return [];
469
+ }
470
+ const removed = [];
471
+ for (const name of names) {
472
+ if (!/^memory-state\.json\.tmp-\d+-\d+$/.test(name)) continue;
473
+ const abs = path.join(dir, name);
474
+ try {
475
+ fs.unlinkSync(abs);
476
+ removed.push(relativePath(root, abs));
477
+ } catch {
478
+ /* another process may have cleaned it already */
479
+ }
480
+ }
481
+ return removed;
482
+ }
483
+
484
+ /** WAL handle for the state write path (only created when crash recovery is on). */
485
+ export function stateWal(root, options = {}) {
486
+ return createWal({ memoryRoot: root, ...options });
487
+ }
488
+
489
+ /** Pending `state.write` intents in the WAL. */
490
+ export function pendingStateWalOps(root, options = {}) {
491
+ try {
492
+ return stateWal(root, options).pending().filter((entry) => entry?.op === 'state.write');
493
+ } catch {
494
+ return [];
495
+ }
496
+ }
497
+
498
+ function latestStateBackup(root) {
499
+ const dir = backupsDir(root);
500
+ let names = [];
501
+ try {
502
+ names = fs.readdirSync(dir).filter((name) => /^memory-state\..+\.json(?:-\d+)?$/.test(name)).sort();
503
+ } catch {
504
+ return null;
505
+ }
506
+ const latest = names[names.length - 1];
507
+ return latest ? resolveInside(root, path.join(LONGLIVE_DIR, BACKUPS_DIR, latest)) : null;
508
+ }
509
+
510
+ /**
511
+ * Crash recovery: any pending `state.write` means a previous process died
512
+ * between WAL append and markDone. If the state file parses, the write landed —
513
+ * mark the intent done. Otherwise restore the newest state backup and mark it
514
+ * failed (the caller can re-issue the write if it still wants it).
515
+ */
516
+ export function crashRecoverState(root, options = {}) {
517
+ const wal = stateWal(root, options);
518
+ const pending = wal.pending().filter((entry) => entry?.op === 'state.write');
519
+ const actions = [];
520
+ for (const entry of pending) {
521
+ let parsed = false;
522
+ try {
523
+ readState(root);
524
+ parsed = true;
525
+ } catch {
526
+ parsed = false;
527
+ }
528
+ if (parsed) {
529
+ wal.markDone(entry.walId, { recovered: true });
530
+ actions.push({ walId: entry.walId, action: 'mark-done' });
531
+ continue;
532
+ }
533
+ const backup = latestStateBackup(root);
534
+ if (!backup) {
535
+ wal.markFailed(entry.walId, 'no-state-backup');
536
+ actions.push({ walId: entry.walId, action: 'mark-failed', reason: 'no-state-backup' });
537
+ continue;
538
+ }
539
+ try {
540
+ restoreBackup(root, backup, statePath(root));
541
+ wal.markFailed(entry.walId, 'restored-from-backup');
542
+ actions.push({ walId: entry.walId, action: 'restore-backup', backup: relativePath(root, backup) });
543
+ } catch (error) {
544
+ wal.markFailed(entry.walId, error?.message ?? error);
545
+ actions.push({ walId: entry.walId, action: 'mark-failed', reason: String(error?.message ?? error) });
546
+ }
547
+ }
548
+ const cleanedTemps = cleanupStaleStateTemps(root);
549
+ return { ok: true, pending: pending.length, actions, cleanedTemps };
550
+ }
551
+
552
+ /**
553
+ * Merge `patch` into the state file under the cross-process lease.
554
+ *
555
+ * 2.3.0 / W1-1: the read-modify-write is serialised by
556
+ * `<root>/.longlive/memory-state.lock` (bounded retry: `lockWaitMs`, default
557
+ * 5s), the patch is merged against the state read *inside* the lease, and a
558
+ * failed write rolls back only this process's entries. `crashRecovery: true`
559
+ * additionally journals the intent to the WAL (opt-in: the default path must
560
+ * not create `.longlive/index` for callers that never enabled the index).
561
+ */
562
+ export function updateState(root, patch, options = {}) {
563
+ const {
564
+ now = new Date(),
565
+ lockWaitMs = DEFAULT_STATE_LOCK_WAIT_MS,
566
+ lockTtlMs = DEFAULT_STATE_LOCK_TTL_MS,
567
+ lockRetryMs = DEFAULT_STATE_LOCK_RETRY_MS,
568
+ backupOptions = {},
569
+ crashRecovery = false,
570
+ maintenance = true,
571
+ maintenanceOptions = {},
572
+ } = options ?? {};
573
+ const lockFile = stateLockPath(root);
574
+ const holder = stateLockHolder();
575
+ let wal = null;
576
+ if (crashRecovery) {
577
+ try {
578
+ wal = stateWal(root, { now });
579
+ } catch {
580
+ wal = null; // recovery is a best-effort amplifier; never block the write on it
581
+ }
582
+ }
583
+ const stateRel = path.join(LONGLIVE_DIR, 'memory-state.json');
584
+ const merged = withLease(
585
+ lockFile,
586
+ { holder, ttlMs: lockTtlMs, waitTimeoutMs: lockWaitMs, retryMs: lockRetryMs },
587
+ () => {
588
+ let walId = null;
589
+ try {
590
+ if (wal) walId = wal.begin('state.write', { keys: Object.keys(patch ?? {}), updatedAt: now.toISOString() });
591
+ const current = readState(root);
592
+ const next = mergeStatePatch(current, patch);
593
+ next.updatedAt = now.toISOString();
594
+ const intendedText = `${JSON.stringify(next, null, 2)}\n`;
595
+ const write = writeFileAtomic(root, statePath(root), intendedText, {
596
+ now,
597
+ backupOptions: { kind: 'state', source: stateRel, ...backupOptions },
598
+ onWriteFailure: ({ originalText }) => {
599
+ repairStateWrite(root, statePath(root), { intendedText, originalText, now });
600
+ },
601
+ });
602
+ if (wal) wal.markDone(walId);
603
+ return { next, write };
604
+ } catch (error) {
605
+ if (wal && walId) wal.markFailed(walId, error?.message ?? error);
606
+ throw error;
607
+ }
608
+ },
609
+ );
610
+
611
+ // Housekeeping runs after the state lease is released: retention may read
612
+ // thousands of backup files and must never extend the critical section.
613
+ if (maintenance) {
614
+ try {
615
+ // Adoption gate: a small/legacy backup dir is left byte-identical to
616
+ // 2.2.0 until it actually needs retention (over caps or aged), so the
617
+ // default-on housekeeping never changes exact file counts of fresh roots.
618
+ const adopt = backupStoreNeedsMaintenance(root, { dir: path.join(LONGLIVE_DIR, BACKUPS_DIR), options: maintenanceOptions, now });
619
+ const result = adopt
620
+ ? runBackupMaintenance(root, { dir: path.join(LONGLIVE_DIR, BACKUPS_DIR), options: maintenanceOptions, now })
621
+ : null;
622
+ if (result?.ran) {
623
+ const removed = result.retention?.removed?.length ?? 0;
624
+ const copied = result.rootSnapshot?.copied?.length ?? 0;
625
+ // Only actual retention deletions are audited: a routine root-file
626
+ // snapshot must stay silent, otherwise every state write appends an
627
+ // audit row and exact-line-count consumers (tests/audit readers) break.
628
+ if (removed > 0) {
629
+ appendAudit(root, {
630
+ action: 'backup.retention',
631
+ object: BACKUPS_DIR,
632
+ result: `removed=${removed};rootFiles=${copied};policy=${result.retention?.policy?.maxAgeDays ?? DEFAULT_RETENTION.maxAgeDays}d/${result.retention?.policy?.maxBytes ?? DEFAULT_RETENTION.maxBytes}B`,
633
+ now,
634
+ });
635
+ }
636
+ }
637
+ } catch {
638
+ /* housekeeping must never fail the state write (see backup-retention docs) */
639
+ }
640
+ }
641
+ return { ...merged.next, write: merged.write };
234
642
  }
235
643
 
236
644
  /** Append one audit line: ISO time, action, object, result. */