@vrtmrz/livesync-commonlib 0.7.0 → 0.8.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 (62) hide show
  1. package/dist/interfaces/FileReflectionProvenance.js +1 -0
  2. package/dist/interfaces/KeyValueDatabase.d.ts +1 -1
  3. package/dist/managers/EntryManager/EntryManagerImpls.js +76 -4
  4. package/dist/managers/StorageEventManager/admission.d.ts +15 -3
  5. package/dist/managers/StorageEventManager/admission.js +13 -3
  6. package/dist/managers/StorageEventManager/processing.d.ts +2 -2
  7. package/dist/managers/StorageEventManager/processing.js +3 -3
  8. package/dist/managers/StorageEventManager/queue.d.ts +23 -14
  9. package/dist/managers/StorageEventManager/queue.js +70 -30
  10. package/dist/managers/StorageEventManager/snapshot.d.ts +12 -1
  11. package/dist/managers/StorageEventManager/snapshot.js +74 -0
  12. package/dist/managers/StorageEventManager/state.d.ts +27 -5
  13. package/dist/managers/StorageEventManager/state.js +9 -7
  14. package/dist/managers/StorageEventManager.d.ts +6 -0
  15. package/dist/managers/StorageEventManager.js +135 -18
  16. package/dist/managers/adapters/IStorageEventManagerAdapter.d.ts +3 -1
  17. package/dist/managers/adapters/IStorageEventPersistenceAdapter.d.ts +16 -0
  18. package/dist/managers/adapters/index.d.ts +1 -1
  19. package/dist/serviceModules/ServiceFileHandlerBase/protection.d.ts +5 -2
  20. package/dist/serviceModules/ServiceFileHandlerBase/protection.js +24 -4
  21. package/dist/serviceModules/ServiceFileHandlerBase/provenance.d.ts +28 -0
  22. package/dist/serviceModules/ServiceFileHandlerBase/provenance.js +53 -0
  23. package/dist/serviceModules/ServiceFileHandlerBase/reflection.js +59 -3
  24. package/dist/services/base/KeyValueDBService.d.ts +6 -6
  25. package/dist/worker/WorkerPushStreamProducer.d.ts +45 -0
  26. package/dist/worker/WorkerPushStreamProducer.js +299 -0
  27. package/dist/worker/WorkerPushStreamReader.d.ts +28 -0
  28. package/dist/worker/WorkerPushStreamReader.js +179 -0
  29. package/dist/worker/backgroundWorkerRpcContract.d.ts +18 -0
  30. package/dist/worker/backgroundWorkerRpcContract.js +24 -0
  31. package/dist/worker/bg.worker.js +2 -16
  32. package/dist/worker/bg.worker.splitting.d.ts +3 -7
  33. package/dist/worker/bg.worker.splitting.js +46 -47
  34. package/dist/worker/bgWorker.d.ts +8 -14
  35. package/dist/worker/bgWorker.direct.d.ts +5 -28
  36. package/dist/worker/bgWorker.direct.js +32 -2
  37. package/dist/worker/bgWorker.errors.d.ts +1 -0
  38. package/dist/worker/bgWorker.errors.js +12 -0
  39. package/dist/worker/bgWorker.js +716 -296
  40. package/dist/worker/bgWorker.splitting.d.ts +12 -26
  41. package/dist/worker/bgWorker.splitting.js +115 -107
  42. package/dist/worker/outOfBandCancelIterator.d.ts +2 -0
  43. package/dist/worker/outOfBandCancelIterator.js +8 -0
  44. package/dist/worker/serveBackgroundWorker.d.ts +3 -0
  45. package/dist/worker/serveBackgroundWorker.js +35 -0
  46. package/dist/worker/splitConnectionTracker.d.ts +25 -0
  47. package/dist/worker/splitConnectionTracker.js +73 -0
  48. package/dist/worker/splitGate.d.ts +19 -0
  49. package/dist/worker/splitGate.js +71 -0
  50. package/dist/worker/universalTypes.d.ts +0 -30
  51. package/dist/worker/universalTypes.js +0 -4
  52. package/dist/worker/workerPushStreamProtocol.d.ts +68 -0
  53. package/dist/worker/workerPushStreamProtocol.js +143 -0
  54. package/docs/development.md +6 -0
  55. package/docs/storage-events-and-reflection.md +30 -2
  56. package/package.json +1 -1
  57. package/dist/worker/bg.common.d.ts +0 -2
  58. package/dist/worker/bg.common.js +0 -6
  59. package/dist/worker/bg.worker.encryption.d.ts +0 -7
  60. package/dist/worker/bg.worker.encryption.js +0 -30
  61. package/dist/worker/bgWorker.encryption.d.ts +0 -22
  62. package/dist/worker/bgWorker.encryption.js +0 -40
@@ -3,6 +3,7 @@
3
3
  * Snapshot writes are delegated to the snapshot module; these state transitions do not commit them.
4
4
  */
5
5
  import type { FileEventItem, FilePath } from "../../common/types.js";
6
+ import type { PendingStorageEventStore } from "../adapters/index.js";
6
7
  import { type FileEventAttempt, type PendingFileEvent } from "./operations.js";
7
8
  /** Queue marker which closes the ordered boundary before a delete or rename. */
8
9
  export declare const TYPE_SENTINEL_FLUSH = "SENTINEL_FLUSH";
@@ -25,12 +26,19 @@ export type EventAdmission = {
25
26
  /** Whether a flush has captured this admission, including operations it registers later. */
26
27
  flushRequested: boolean;
27
28
  };
29
+ /** Completion ownership shared by entries from one durable buffer. */
30
+ export type SavedEventBuffer = {
31
+ key: string;
32
+ remaining: number;
33
+ };
28
34
  /** Queue and persistence view of one event, optionally linked to its durable operation. */
29
35
  export type PendingSnapshotEntry = {
30
36
  /** Event intent written to or restored from the existing snapshot format. */
31
37
  event: QueuedFileEvent;
32
38
  /** Stable insertion order within this manager's pending snapshot. */
33
39
  sequence: number;
40
+ /** Buffer that durably holds this entry, once its append has committed. */
41
+ savedBuffer?: SavedEventBuffer;
34
42
  /** Provisional completion within a serial snapshot step; a failed save rolls it back. */
35
43
  completed: boolean;
36
44
  /** Durable operation for file events; sentinels have no operation. */
@@ -47,6 +55,15 @@ export type SnapshotCompletion = {
47
55
  export type RunQueuedEventsOptions = {
48
56
  waitForProcessing?: boolean;
49
57
  };
58
+ /** State for the ordered buffer store's append writer. */
59
+ export interface OrderedStorageEventState {
60
+ readonly store: PendingStorageEventStore;
61
+ nextBuffer: PendingSnapshotEntry[];
62
+ nextWrite?: Promise<void>;
63
+ appendTail?: Promise<void>;
64
+ appendFinishedAt?: number;
65
+ pendingOperations: number;
66
+ }
50
67
  /** Mutable ownership, admission, and persistence state for one manager. */
51
68
  export interface StorageEventState {
52
69
  /** Ordered intents still requiring durable acknowledgement. */
@@ -63,7 +80,9 @@ export interface StorageEventState {
63
80
  acceptingEvents: boolean;
64
81
  /** Admissions in progress which a finite flush must account for. */
65
82
  admissions: Set<EventAdmission>;
66
- /** Serial tail for completion marking, snapshot saving, and rollback. */
83
+ /** Ordered buffer persistence, when supplied by this host. */
84
+ readonly ordered?: OrderedStorageEventState;
85
+ /** Serial tail for persistence mutations and completion bookkeeping. */
67
86
  snapshotTail: Promise<void>;
68
87
  /** Stable key so concurrent dispatch calls for this manager share one run. */
69
88
  readonly dispatchKey: symbol;
@@ -76,8 +95,10 @@ export interface StorageEventBuffer {
76
95
  replace(events: QueuedFileEvent[]): void;
77
96
  /** Append one event or sentinel at the current tail. */
78
97
  append(event: QueuedFileEvent): void;
79
- /** Remove and return the next queued item. */
80
- shift(): QueuedFileEvent | undefined;
98
+ /** Return the current head, if any, without removing it. */
99
+ peek(): QueuedFileEvent | undefined;
100
+ /** Remove the expected item only if it is still the head. */
101
+ takeHead(expected: QueuedFileEvent): boolean;
81
102
  }
82
103
  /** Host notifications kept outside the state owner. */
83
104
  export interface StorageEventNotifications {
@@ -91,19 +112,20 @@ export interface StorageEventNotifications {
91
112
  * @returns Fresh maps, counters, admission tracking, and a resolved initial snapshot tail.
92
113
  * @remarks The state is isolated to one manager; no host callbacks or persistence are invoked here.
93
114
  */
94
- export declare function createStorageEventState(): StorageEventState;
115
+ export declare function createStorageEventState(store?: PendingStorageEventStore): StorageEventState;
95
116
  /**
96
117
  * Retain an event once and reuse its durable operation when the same event is encountered again.
97
118
  * @param state - The manager state which owns the snapshot entry and event-to-operation identity map.
98
119
  * @param event - A file event or ordering sentinel to retain.
99
120
  * @param register - Whether a file operation should also enter the per-path ordering index.
121
+ * @param savedBuffer - The existing durable buffer when this event was restored.
100
122
  * @returns The existing entry for this event object, or the newly created entry.
101
123
  * @remarks Snapshot collection passes register as false for events surfaced by batch gates, so persistence
102
124
  * discovery cannot become their first path-indexing moment and change path ownership or ordering. The registered
103
125
  * flag independently prevents later duplicate indexing. Retention does not write a snapshot or start a handler;
104
126
  * a new operation captures the current failure sequence as its boundary.
105
127
  */
106
- export declare function retainFileEvent(state: StorageEventState, event: QueuedFileEvent, register?: boolean): PendingSnapshotEntry;
128
+ export declare function retainFileEvent(state: StorageEventState, event: QueuedFileEvent, register?: boolean, savedBuffer?: SavedEventBuffer): PendingSnapshotEntry;
107
129
  /**
108
130
  * Retain buffered events in order and attach an adjacent sentinel to its delete or rename.
109
131
  * @param state - The manager state receiving entries and ordering barriers.
@@ -1,11 +1,9 @@
1
- import {
2
- createFileEventAttempt,
3
- getFileEventPaths
4
- } from "./operations.js";
1
+ import { createFileEventAttempt, getFileEventPaths } from "./operations.js";
5
2
  const TYPE_SENTINEL_FLUSH = "SENTINEL_FLUSH";
6
- function createStorageEventState() {
3
+ function createStorageEventState(store) {
7
4
  return {
8
5
  pendingSnapshot: /* @__PURE__ */ new Map(),
6
+ ordered: store ? { store, nextBuffer: [], pendingOperations: 0 } : void 0,
9
7
  operations: /* @__PURE__ */ new WeakMap(),
10
8
  latestByPath: /* @__PURE__ */ new Map(),
11
9
  nextSequence: 0,
@@ -25,13 +23,13 @@ function registerOperation(state, operation) {
25
23
  state.latestByPath.set(path, operation);
26
24
  }
27
25
  }
28
- function retainFileEvent(state, event, register = true) {
26
+ function retainFileEvent(state, event, register = true, savedBuffer) {
29
27
  const existing = state.pendingSnapshot.get(event);
30
28
  if (existing) {
31
29
  if (register && existing.operation) registerOperation(state, existing.operation);
32
30
  return existing;
33
31
  }
34
- const entry = { event, sequence: ++state.nextSequence, completed: false };
32
+ const entry = { event, sequence: ++state.nextSequence, completed: false, savedBuffer };
35
33
  if (event.type !== TYPE_SENTINEL_FLUSH) {
36
34
  const operation = state.operations.get(event) ?? {
37
35
  event,
@@ -50,6 +48,10 @@ function retainFileEvent(state, event, register = true) {
50
48
  state.operations.set(event, operation);
51
49
  }
52
50
  state.pendingSnapshot.set(event, entry);
51
+ if (state.ordered) {
52
+ if (entry.operation) state.ordered.pendingOperations++;
53
+ if (!savedBuffer) state.ordered.nextBuffer.push(entry);
54
+ }
53
55
  return entry;
54
56
  }
55
57
  function retainBufferedFileEvents(state, events) {
@@ -59,6 +59,8 @@ export declare abstract class StorageEventManagerBase<TAdapter extends IStorageE
59
59
  protected _waitingMap: Map<string, WaitInfo>;
60
60
  protected processingCount: number;
61
61
  private readonly eventState;
62
+ private orderedStoreLoaded;
63
+ private orderedStoreLoad?;
62
64
  private dispatchPaused;
63
65
  private dispatchResumeSignal;
64
66
  private readonly activeDispatches;
@@ -69,6 +71,7 @@ export declare abstract class StorageEventManagerBase<TAdapter extends IStorageE
69
71
  private readonly retry;
70
72
  private readonly snapshotIO;
71
73
  private readonly queue;
74
+ private readonly orderedAppend;
72
75
  private readonly admission;
73
76
  private readonly attempts;
74
77
  private readonly handler;
@@ -153,6 +156,7 @@ export declare abstract class StorageEventManagerBase<TAdapter extends IStorageE
153
156
  * Add an already selected event to the buffer and start background snapshotting and dispatch.
154
157
  * @param event - The event which has already passed host admission checks.
155
158
  * @returns Nothing; processing and persistence failures are reported through manager effects.
159
+ * @remarks Ordered stores must have completed their initial load. Append watcher events through `appendQueue`.
156
160
  */
157
161
  enqueue(event: FileEventItem): void;
158
162
  /**
@@ -293,6 +297,8 @@ export declare abstract class StorageEventManagerBase<TAdapter extends IStorageE
293
297
  * @returns A promise for restoration; storage or dispatch errors reject it, while failed attempt results are reported and retained.
294
298
  */
295
299
  _restoreFromSnapshot(): Promise<void>;
300
+ /** Join the initial load without waiting for restored handlers. */
301
+ private loadOrderedEvents;
296
302
  /**
297
303
  * Dispatch events in the buffer and optionally wait for captured processing attempts.
298
304
  * @param options - Queue-run options, including whether to wait for processing.
@@ -8,7 +8,14 @@ import { Semaphore } from "octagonal-wheels/concurrency/semaphore";
8
8
  import { promiseWithResolvers } from "octagonal-wheels/promises";
9
9
  import { StorageEventManager } from "../interfaces/StorageEventManager.js";
10
10
  import { createInstanceLogFunction } from "../services/lib/logUtils.js";
11
- import { admitStorageEvents } from "./StorageEventManager/admission.js";
11
+ import {
12
+ assertSuccessfulFileEvents
13
+ } from "./StorageEventManager/operations.js";
14
+ import {
15
+ admitStorageEvents,
16
+ registerAdmission,
17
+ trackStorageEventAdmission
18
+ } from "./StorageEventManager/admission.js";
12
19
  import {
13
20
  forwardVaultEvent,
14
21
  hasEditorChangePath,
@@ -23,6 +30,8 @@ import {
23
30
  import {
24
31
  enqueueStorageEvent,
25
32
  flushStorageEvents,
33
+ publishCommittedStorageEvents,
34
+ restoreOrderedStorageEvents,
26
35
  restoreStorageEvents,
27
36
  runBufferedStorageEvents
28
37
  } from "./StorageEventManager/queue.js";
@@ -30,7 +39,12 @@ import {
30
39
  captureFileEventAttempts,
31
40
  waitForFileEventAttempts
32
41
  } from "./StorageEventManager/retry.js";
33
- import { persistFileEventSnapshot } from "./StorageEventManager/snapshot.js";
42
+ import {
43
+ acknowledgeEmptyOrderedBuffer,
44
+ acknowledgeOrderedEntry,
45
+ appendPendingEventBuffer,
46
+ persistFileEventSnapshot
47
+ } from "./StorageEventManager/snapshot.js";
34
48
  import {
35
49
  handleStorageFileEvent,
36
50
  processStorageEventAttempt
@@ -52,7 +66,9 @@ class StorageEventManagerBase extends StorageEventManager {
52
66
  concurrentProcessing = Semaphore(5);
53
67
  _waitingMap = /* @__PURE__ */ new Map();
54
68
  processingCount = 0;
55
- eventState = createStorageEventState();
69
+ eventState;
70
+ orderedStoreLoaded = false;
71
+ orderedStoreLoad;
56
72
  dispatchPaused = false;
57
73
  dispatchResumeSignal;
58
74
  activeDispatches = /* @__PURE__ */ new Set();
@@ -64,7 +80,14 @@ class StorageEventManagerBase extends StorageEventManager {
64
80
  append: (event) => {
65
81
  this.bufferedQueuedItems.push(event);
66
82
  },
67
- shift: () => this.bufferedQueuedItems.shift()
83
+ peek: () => this.bufferedQueuedItems[0],
84
+ takeHead: (expected) => {
85
+ if (this.bufferedQueuedItems[0] !== expected) {
86
+ return false;
87
+ }
88
+ this.bufferedQueuedItems.shift();
89
+ return true;
90
+ }
68
91
  };
69
92
  notifications = {
70
93
  updateStatus: () => this.updateStatus(),
@@ -107,6 +130,17 @@ class StorageEventManagerBase extends StorageEventManager {
107
130
  wait: (attempts) => this.waitForAttempts(attempts),
108
131
  fail: (operation, error, attempt) => this.failOperation(operation, error, attempt)
109
132
  };
133
+ orderedAppend = {
134
+ publish: (events) => publishCommittedStorageEvents(this.eventState, events, this.queue),
135
+ reportAppendFailure: (error) => {
136
+ this._log(
137
+ "Some local file changes could not be queued for sync. Once file activity settles, rescan the Vault to check the current files.",
138
+ LOG_LEVEL_NOTICE
139
+ );
140
+ this._log(error, LOG_LEVEL_VERBOSE);
141
+ this.updateStatus();
142
+ }
143
+ };
110
144
  admission = {
111
145
  settings: () => this.settings,
112
146
  isFolder: (file) => this.isFolder(file),
@@ -155,6 +189,11 @@ class StorageEventManagerBase extends StorageEventManager {
155
189
  constructor(adapter, dependencies) {
156
190
  super();
157
191
  this.adapter = adapter;
192
+ this.eventState = createStorageEventState(adapter.pendingEventStore);
193
+ const ordered = this.eventState.ordered;
194
+ if (ordered) {
195
+ this.queue.acknowledgeSentinel = (entry) => acknowledgeOrderedEntry(this.eventState, ordered, entry, this.notifications.updateStatus);
196
+ }
158
197
  this.setting = dependencies.setting;
159
198
  this.vaultService = dependencies.vaultService;
160
199
  this.admission.isTargetInternal = dependencies.isTargetInternalFile?.bind(dependencies);
@@ -238,9 +277,7 @@ class StorageEventManagerBase extends StorageEventManager {
238
277
  this.adapter.status.updateStatus({
239
278
  batched: this._waitingMap.size,
240
279
  processing: this.processingCount,
241
- totalQueued: [...this.eventState.pendingSnapshot.values()].filter(
242
- (entry) => entry.operation && !entry.completed
243
- ).length
280
+ totalQueued: this.eventState.ordered?.pendingOperations ?? [...this.eventState.pendingSnapshot.values()].filter((entry) => entry.operation && !entry.completed).length
244
281
  });
245
282
  }
246
283
  /** Completes restored operations before the host starts watching. */
@@ -250,8 +287,16 @@ class StorageEventManagerBase extends StorageEventManager {
250
287
  * @returns A promise fulfilled after restoration and replay attempts settle; snapshot or dispatch errors reject it, while failed operation results are reported and retained.
251
288
  */
252
289
  restoreState() {
253
- this.snapShotRestored = this._restoreFromSnapshot();
254
- return this.snapShotRestored;
290
+ if (this.eventState.ordered && this.snapShotRestored) return this.snapShotRestored;
291
+ const restore = this._restoreFromSnapshot();
292
+ this.snapShotRestored = restore;
293
+ if (this.eventState.ordered) {
294
+ const clear = () => {
295
+ this.snapShotRestored = null;
296
+ };
297
+ void restore.then(clear, clear);
298
+ }
299
+ return restore;
255
300
  }
256
301
  /**
257
302
  * Filter and admit host watcher events into the operation queue.
@@ -261,14 +306,18 @@ class StorageEventManagerBase extends StorageEventManager {
261
306
  * @remarks The promise may resolve while admitted handlers are still pending. Use `waitForIdle` for the captured processing boundary.
262
307
  */
263
308
  appendQueue(params, ctx) {
264
- return admitStorageEvents(this.eventState, params, ctx, this.admission);
309
+ return admitStorageEvents(this.eventState, params, ctx, this.admission, () => this.loadOrderedEvents());
265
310
  }
266
311
  /**
267
312
  * Add an already selected event to the buffer and start background snapshotting and dispatch.
268
313
  * @param event - The event which has already passed host admission checks.
269
314
  * @returns Nothing; processing and persistence failures are reported through manager effects.
315
+ * @remarks Ordered stores must have completed their initial load. Append watcher events through `appendQueue`.
270
316
  */
271
317
  enqueue(event) {
318
+ if (this.eventState.ordered && !this.orderedStoreLoaded) {
319
+ throw new Error("Load the pending storage events before enqueueing an event");
320
+ }
272
321
  enqueueStorageEvent(this.eventState, event, this.queue);
273
322
  }
274
323
  /**
@@ -277,7 +326,7 @@ class StorageEventManagerBase extends StorageEventManager {
277
326
  * @remarks Later admissions are outside this flush boundary. Batch gates in the captured work are released before waiting.
278
327
  */
279
328
  async waitForIdle() {
280
- await flushStorageEvents(this.eventState, this.queue);
329
+ await flushStorageEvents(this.eventState, this.queue, this.orderedStoreLoad);
281
330
  }
282
331
  /**
283
332
  * Pause new file-handler dispatch and wait for dispatches already in progress.
@@ -311,8 +360,13 @@ class StorageEventManagerBase extends StorageEventManager {
311
360
  try {
312
361
  await this.waitForIdle();
313
362
  } catch (error) {
314
- this.reportOperationFailure(error);
363
+ if (!this.eventState.ordered) {
364
+ this.reportOperationFailure(error);
365
+ } else {
366
+ this._log(error, LOG_LEVEL_VERBOSE);
367
+ }
315
368
  }
369
+ if (this.eventState.ordered) await this.runQueuedEvents().catch(this.notifications.reportFailure);
316
370
  await this._takeSnapshot();
317
371
  }
318
372
  /**
@@ -456,8 +510,22 @@ class StorageEventManagerBase extends StorageEventManager {
456
510
  * @returns A promise fulfilled when the attempt completes; a failed attempt rejects it.
457
511
  */
458
512
  async processFileEvent(event) {
459
- const operation = this.retainEvent(event).operation;
460
- await this.processOperation(operation, operation.attempt);
513
+ if (!this.eventState.ordered) {
514
+ const operation = this.retainEvent(event).operation;
515
+ await this.processOperation(operation, operation.attempt);
516
+ return;
517
+ }
518
+ const existing = this.operations.get(event);
519
+ if (existing) {
520
+ await this.processOperation(existing, existing.attempt);
521
+ return;
522
+ }
523
+ let attempt;
524
+ await trackStorageEventAdmission(this.eventState, this.admission, async (admission) => {
525
+ await this.loadOrderedEvents();
526
+ attempt = this.operations.get(event)?.attempt ?? registerAdmission(this.eventState, admission, event, this.admission);
527
+ });
528
+ if (attempt) assertSuccessfulFileEvents([await attempt.completion.promise]);
461
529
  }
462
530
  /**
463
531
  * Persist the manager snapshot and optionally acknowledge one attempt in that snapshot.
@@ -465,7 +533,16 @@ class StorageEventManagerBase extends StorageEventManager {
465
533
  * @returns A promise for the serialised save; snapshot I/O failures reject it.
466
534
  */
467
535
  persistSnapshot(completion) {
468
- return persistFileEventSnapshot(this.eventState, this.buffer, this.snapshotIO, completion);
536
+ const ordered = this.eventState.ordered;
537
+ if (!ordered) return persistFileEventSnapshot(this.eventState, this.buffer, this.snapshotIO, completion);
538
+ if (!completion) return appendPendingEventBuffer(this.eventState, ordered, this.orderedAppend);
539
+ return acknowledgeOrderedEntry(
540
+ this.eventState,
541
+ ordered,
542
+ completion.entry,
543
+ this.notifications.updateStatus,
544
+ completion
545
+ );
469
546
  }
470
547
  /**
471
548
  * Wait for the next serialised snapshot write.
@@ -479,7 +556,41 @@ class StorageEventManagerBase extends StorageEventManager {
479
556
  * @returns A promise for restoration; storage or dispatch errors reject it, while failed attempt results are reported and retained.
480
557
  */
481
558
  async _restoreFromSnapshot() {
482
- await restoreStorageEvents(this.queue);
559
+ if (!this.eventState.ordered) {
560
+ await restoreStorageEvents(this.queue);
561
+ return;
562
+ }
563
+ if (!this.eventState.acceptingEvents) return;
564
+ await this.loadOrderedEvents();
565
+ await this.runQueuedEvents({ waitForProcessing: true });
566
+ }
567
+ /** Join the initial load without waiting for restored handlers. */
568
+ loadOrderedEvents() {
569
+ const ordered = this.eventState.ordered;
570
+ if (!ordered || this.orderedStoreLoaded) return;
571
+ if (this.orderedStoreLoad) return this.orderedStoreLoad;
572
+ const load = Promise.resolve().then(async () => {
573
+ const buffers = await ordered.store.load();
574
+ for (const { key, events } of buffers) {
575
+ if (events.length === 0) {
576
+ await acknowledgeEmptyOrderedBuffer(this.eventState, ordered, key).catch(
577
+ this.notifications.reportFailure
578
+ );
579
+ }
580
+ }
581
+ const operations = restoreOrderedStorageEvents(this.eventState, this.queue, buffers);
582
+ this.orderedStoreLoaded = true;
583
+ if (this.eventState.acceptingEvents) {
584
+ fireAndForget(this.runQueuedEvents().catch(this.notifications.reportFailure));
585
+ }
586
+ return operations;
587
+ });
588
+ this.orderedStoreLoad = load;
589
+ const clear = () => {
590
+ this.orderedStoreLoad = void 0;
591
+ };
592
+ void load.then(clear, clear);
593
+ return load;
483
594
  }
484
595
  /**
485
596
  * Dispatch events in the buffer and optionally wait for captured processing attempts.
@@ -494,7 +605,8 @@ class StorageEventManagerBase extends StorageEventManager {
494
605
  * @returns Nothing; the write is deliberately not awaited by the caller.
495
606
  */
496
607
  _triggerTakeSnapshot() {
497
- fireAndForget(() => this._takeSnapshot().catch((error) => this.reportOperationFailure(error)));
608
+ const snapshot = this._takeSnapshot();
609
+ fireAndForget(this.eventState.ordered ? snapshot : snapshot.catch(this.notifications.reportFailure));
498
610
  }
499
611
  /**
500
612
  * Throttled callback for requesting a background snapshot write.
@@ -538,7 +650,12 @@ class StorageEventManagerBase extends StorageEventManager {
538
650
  * @returns A promise fulfilled when watcher registration finishes; a restoration failure prevents registration and rejects it.
539
651
  */
540
652
  async beginWatch() {
541
- await this.snapShotRestored;
653
+ if (this.eventState.ordered) {
654
+ await this.restoreState();
655
+ } else {
656
+ await this.snapShotRestored;
657
+ }
658
+ if (this.eventState.ordered && !this.eventState.acceptingEvents) return;
542
659
  await this.adapter.watch.beginWatch({
543
660
  onCreate: (file, ctx) => this.watchVaultCreate(file, ctx),
544
661
  onChange: (file, ctx) => this.watchVaultChange(file, ctx),
@@ -1,5 +1,5 @@
1
1
  import type { IStorageEventTypeGuardAdapter } from "./IStorageEventTypeGuardAdapter.js";
2
- import type { IStorageEventPersistenceAdapter } from "./IStorageEventPersistenceAdapter.js";
2
+ import type { IStorageEventPersistenceAdapter, PendingStorageEventStore } from "./IStorageEventPersistenceAdapter.js";
3
3
  import type { IStorageEventWatchAdapter } from "./IStorageEventWatchAdapter.js";
4
4
  import type { IStorageEventStatusAdapter } from "./IStorageEventStatusAdapter.js";
5
5
  import type { IStorageEventConverterAdapter } from "./IStorageEventConverterAdapter.js";
@@ -12,6 +12,8 @@ import type { IStorageEventConverterAdapter } from "./IStorageEventConverterAdap
12
12
  export interface IStorageEventManagerAdapter<TFile, TFolder> {
13
13
  readonly typeGuard: IStorageEventTypeGuardAdapter<TFile, TFolder>;
14
14
  readonly persistence: IStorageEventPersistenceAdapter;
15
+ /** Select the ordered store when the host can persist separate event buffers. */
16
+ readonly pendingEventStore?: PendingStorageEventStore;
15
17
  readonly watch: IStorageEventWatchAdapter<TFile, unknown>;
16
18
  readonly status: IStorageEventStatusAdapter;
17
19
  readonly converter: IStorageEventConverterAdapter<TFile>;
@@ -1,5 +1,21 @@
1
1
  import type { FileEventItem } from "../../common/types.js";
2
2
  import type { FileEventItemSentinel } from "../StorageEventManager.js";
3
+ export interface PendingStorageEventBuffer {
4
+ readonly key: string;
5
+ readonly events: readonly (FileEventItem | FileEventItemSentinel)[];
6
+ }
7
+ /** Store immutable buffers of pending event intents. */
8
+ export interface PendingStorageEventStore {
9
+ /** Load buffers in replay order, with any legacy snapshot first. */
10
+ load(): Promise<readonly PendingStorageEventBuffer[]>;
11
+ /**
12
+ * Save the whole buffer atomically and return its unique key after the write commits.
13
+ * A rejected append leaves the store unchanged.
14
+ */
15
+ append(events: PendingStorageEventBuffer["events"]): Promise<string>;
16
+ /** Remove the buffer under the supplied key after all of its entries have completed. */
17
+ remove(key: string): Promise<void>;
18
+ }
3
19
  /**
4
20
  * Adapter interface for snapshot persistence operations
5
21
  */
@@ -1,5 +1,5 @@
1
1
  export type { IStorageEventTypeGuardAdapter } from "./IStorageEventTypeGuardAdapter.js";
2
- export type { IStorageEventPersistenceAdapter } from "./IStorageEventPersistenceAdapter.js";
2
+ export type { IStorageEventPersistenceAdapter, PendingStorageEventBuffer, PendingStorageEventStore, } from "./IStorageEventPersistenceAdapter.js";
3
3
  export type { IStorageEventWatchAdapter, IStorageEventWatchHandlers } from "./IStorageEventWatchAdapter.js";
4
4
  export type { IStorageEventStatusAdapter } from "./IStorageEventStatusAdapter.js";
5
5
  export type { IStorageEventConverterAdapter } from "./IStorageEventConverterAdapter.js";
@@ -1,5 +1,7 @@
1
1
  import type { FilePathWithPrefix, MetaEntry, UXFileInfoStub } from "../../common/types.js";
2
2
  import type { FileHandlerContext, PreservationResult } from "./context.js";
3
+ /** Decoded incoming file body supplied for live-write protection (absent for deletions). */
4
+ type IncomingContent = string | string[] | Blob | ArrayBuffer;
3
5
  /**
4
6
  * Preserve changed storage before an incoming write can replace its bytes.
5
7
  *
@@ -11,7 +13,7 @@ import type { FileHandlerContext, PreservationResult } from "./context.js";
11
13
  * @returns A PreservationResult: preserved:true stops the incoming effect; preserved:false without a snapshot means no safe candidate was established.
12
14
  * @remarks The caller holds the document lock. preserved:true also covers a refused preservation write that must still stop overwrite; any returned snapshot requires later revalidation.
13
15
  */
14
- export declare function preserveUnsyncedStorageAsConflict(ctx: FileHandlerContext, path: FilePathWithPrefix, existDoc: UXFileInfoStub, incomingEntry: MetaEntry, incomingContent?: string | string[] | Blob | ArrayBuffer): Promise<PreservationResult>;
16
+ export declare function preserveUnsyncedStorageAsConflict(ctx: FileHandlerContext, path: FilePathWithPrefix, existDoc: UXFileInfoStub, incomingEntry: MetaEntry, incomingContent?: IncomingContent): Promise<PreservationResult>;
15
17
  /**
16
18
  * Repeat overwrite protection after a previous storage observation became stale.
17
19
  *
@@ -23,4 +25,5 @@ export declare function preserveUnsyncedStorageAsConflict(ctx: FileHandlerContex
23
25
  * @returns A PreservationResult that either stops the incoming effect or supplies a candidate; missing evidence can leave preserved:false without a snapshot.
24
26
  * @remarks The caller holds the document lock. This does not authorise overwrite; callers must validate any candidate at the established final check.
25
27
  */
26
- export declare function recheckIncomingStorage(ctx: FileHandlerContext, path: FilePathWithPrefix, incomingEntry: MetaEntry, incomingContent: string | string[] | Blob | ArrayBuffer | undefined, allowExistingConflicts: boolean): Promise<PreservationResult>;
28
+ export declare function recheckIncomingStorage(ctx: FileHandlerContext, path: FilePathWithPrefix, incomingEntry: MetaEntry, incomingContent: IncomingContent | undefined, allowExistingConflicts: boolean): Promise<PreservationResult>;
29
+ export {};
@@ -1,5 +1,6 @@
1
1
  import { ContentReadError } from "../../common/LSError.js";
2
2
  import {
3
+ getProvenancePath,
3
4
  readProvenanceSnapshot,
4
5
  currentStorageSnapshotMatches,
5
6
  classifyStorageContent,
@@ -10,11 +11,18 @@ import { queueConflictCheckFor } from "./locking.js";
10
11
  import { isFolderInfo } from "./storage.js";
11
12
  import { LOG_LEVEL_NOTICE } from "octagonal-wheels/common/logger";
12
13
  import { isDocContentSame } from "../../common/utils.js";
14
+ function hasIncomingContent(content) {
15
+ return content !== void 0;
16
+ }
13
17
  async function preserveUnsyncedStorageAsConflict(ctx, path, existDoc, incomingEntry, incomingContent) {
14
- const observedProvenance = await readProvenanceSnapshot(ctx, path);
18
+ const observedPath = existDoc.path;
19
+ const observedProvenance = await readProvenanceSnapshot(ctx, observedPath);
15
20
  const readFile = await ctx.host.readFileFromStub(existDoc);
21
+ if (readFile.path !== observedPath) {
22
+ return { preserved: false };
23
+ }
16
24
  const snapshot = { file: readFile, revision: observedProvenance };
17
- if (incomingContent && await isDocContentSame(incomingContent, readFile.body)) {
25
+ if (hasIncomingContent(incomingContent) && await isDocContentSame(incomingContent, readFile.body)) {
18
26
  return await currentStorageSnapshotMatches(ctx, readFile, observedProvenance) ? { preserved: false, snapshot } : { preserved: false };
19
27
  }
20
28
  if (!incomingEntry._rev) {
@@ -29,7 +37,7 @@ async function preserveUnsyncedStorageAsConflict(ctx, path, existDoc, incomingEn
29
37
  incomingEntry,
30
38
  void 0,
31
39
  observedProvenance,
32
- incomingContent ? { _rev: incomingEntry._rev, data: incomingContent } : void 0,
40
+ hasIncomingContent(incomingContent) ? { _rev: incomingEntry._rev, data: incomingContent } : void 0,
33
41
  false
34
42
  );
35
43
  } catch (error) {
@@ -46,7 +54,7 @@ async function preserveUnsyncedStorageAsConflict(ctx, path, existDoc, incomingEn
46
54
  return { preserved: false, snapshot };
47
55
  }
48
56
  if (classification.kind === "matching-leaf") {
49
- await rememberMatchingLeaf(ctx, path, classification.revision, readFile.stat.mtime, readFile.body);
57
+ await rememberMatchingLeaf(ctx, observedPath, classification.revision, readFile.stat.mtime, readFile.body);
50
58
  await queueConflictCheckFor(ctx, path);
51
59
  return { preserved: true };
52
60
  }
@@ -68,6 +76,18 @@ async function preserveUnsyncedStorageAsConflict(ctx, path, existDoc, incomingEn
68
76
  async function recheckIncomingStorage(ctx, path, incomingEntry, incomingContent, allowExistingConflicts) {
69
77
  const current = await ctx.host.storage().getStub(path);
70
78
  if (!current || isFolderInfo(current)) return { preserved: false };
79
+ if (current.path !== path) {
80
+ const [currentDocumentId, targetDocumentId] = await Promise.all([
81
+ ctx.path.path2id(current.path),
82
+ ctx.path.path2id(path)
83
+ ]);
84
+ if (currentDocumentId !== targetDocumentId) {
85
+ return { preserved: false };
86
+ }
87
+ if (hasIncomingContent(incomingContent) && getProvenancePath(ctx, current.path) !== getProvenancePath(ctx, path)) {
88
+ return { preserved: false };
89
+ }
90
+ }
71
91
  const protection = await preserveUnsyncedStorageAsConflict(ctx, path, current, incomingEntry, incomingContent);
72
92
  if (protection.preserved || !protection.snapshot) return protection;
73
93
  if (!allowExistingConflicts && !ctx.setting.currentSettings().writeDocumentsIfConflicted && (await ctx.host.db().readConflictedRevs(path)).length > 0) {
@@ -50,6 +50,34 @@ export declare function setProvenance(ctx: FileHandlerContext, path: FilePathWit
50
50
  * @remarks No document lock is acquired here. The caller's database or storage effect is not rolled back if device-local cleanup fails.
51
51
  */
52
52
  export declare function deleteProvenance(ctx: FileHandlerContext, path: FilePathWithPrefix): Promise<void>;
53
+ /** Pre-rename provenance snapshot for source and target spellings under the same document lock. */
54
+ export interface RenameProvenanceSnapshot {
55
+ readonly oldPath: FilePathWithPrefix;
56
+ readonly oldKey: FilePathWithPrefix;
57
+ readonly expectedNewKey: FilePathWithPrefix;
58
+ readonly sourceRecord: FileReflectionProvenanceRecord | undefined;
59
+ readonly destinationBefore: FileReflectionProvenanceRecord | undefined;
60
+ }
61
+ /**
62
+ * Capture source and destination provenance strictly before a physical case-only rename.
63
+ *
64
+ * @param ctx - The captured services, per-instance state, and dynamic host seams.
65
+ * @param oldPath - The physical path observed before renaming.
66
+ * @param targetPath - The incoming canonical path requested for the rename.
67
+ * @returns The captured snapshot, or undefined when provenance is disabled or keys already match; returns false on a read or pre-rename stale-destination cleanup failure.
68
+ * @remarks When the source has no provenance and a stale record already occupies the destination key, that stale record is removed before mutating storage so a post-rename retry cannot inherit it.
69
+ */
70
+ export declare function captureRenameProvenance(ctx: FileHandlerContext, oldPath: FilePathWithPrefix, targetPath: FilePathWithPrefix): Promise<RenameProvenanceSnapshot | undefined | false>;
71
+ /**
72
+ * Transfer or reconcile destination provenance after a verified physical case-only rename.
73
+ *
74
+ * @param ctx - The captured services, per-instance state, and dynamic host seams.
75
+ * @param snapshot - The pre-rename source and destination provenance observations.
76
+ * @param newPath - The physical path returned by the storage rename.
77
+ * @returns True if provenance is now consistent with the renamed file; false if an intervening host update or store error prevents safe continuation.
78
+ * @remarks Performs an optimistic check against the pre-rename destination snapshot (read and write are separate operations) to preserve concurrent out-of-lock destination updates. Deletes the old key best-effort only after the new key write succeeds.
79
+ */
80
+ export declare function commitRenamedProvenance(ctx: FileHandlerContext, snapshot: RenameProvenanceSnapshot, newPath: FilePathWithPrefix): Promise<boolean>;
53
81
  /**
54
82
  * Find one unambiguous database revision containing the observed storage bytes.
55
83
  *