@vrtmrz/livesync-commonlib 0.4.0 → 0.4.1

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 (58) hide show
  1. package/dist/common/models/fileaccess.definition.d.ts +35 -0
  2. package/dist/common/models/fileaccess.definition.js +11 -0
  3. package/dist/common/typeUtils.d.ts +27 -4
  4. package/dist/interfaces/FileHandler.d.ts +1 -1
  5. package/dist/managers/StorageEventManager/admission.d.ts +50 -0
  6. package/dist/managers/StorageEventManager/admission.js +129 -0
  7. package/dist/managers/StorageEventManager/batching.d.ts +93 -0
  8. package/dist/managers/StorageEventManager/batching.js +97 -0
  9. package/dist/managers/StorageEventManager/operations.d.ts +142 -0
  10. package/dist/managers/StorageEventManager/operations.js +69 -0
  11. package/dist/managers/StorageEventManager/processing.d.ts +63 -0
  12. package/dist/managers/StorageEventManager/processing.js +94 -0
  13. package/dist/managers/StorageEventManager/queue.d.ts +73 -0
  14. package/dist/managers/StorageEventManager/queue.js +113 -0
  15. package/dist/managers/StorageEventManager/retry.d.ts +33 -0
  16. package/dist/managers/StorageEventManager/retry.js +31 -0
  17. package/dist/managers/StorageEventManager/snapshot.d.ts +46 -0
  18. package/dist/managers/StorageEventManager/snapshot.js +53 -0
  19. package/dist/managers/StorageEventManager/state.d.ts +155 -0
  20. package/dist/managers/StorageEventManager/state.js +105 -0
  21. package/dist/managers/StorageEventManager/watching.d.ts +93 -0
  22. package/dist/managers/StorageEventManager/watching.js +36 -0
  23. package/dist/managers/StorageEventManager.d.ts +303 -83
  24. package/dist/managers/StorageEventManager.js +457 -547
  25. package/dist/serviceModules/ServiceFileHandlerBase/chunks.d.ts +10 -0
  26. package/dist/serviceModules/ServiceFileHandlerBase/chunks.js +51 -0
  27. package/dist/serviceModules/ServiceFileHandlerBase/context.d.ts +168 -0
  28. package/dist/serviceModules/ServiceFileHandlerBase/context.js +15 -0
  29. package/dist/serviceModules/ServiceFileHandlerBase/deletion.d.ts +40 -0
  30. package/dist/serviceModules/ServiceFileHandlerBase/deletion.js +142 -0
  31. package/dist/serviceModules/ServiceFileHandlerBase/events.d.ts +20 -0
  32. package/dist/serviceModules/ServiceFileHandlerBase/events.js +205 -0
  33. package/dist/serviceModules/ServiceFileHandlerBase/locking.d.ts +23 -0
  34. package/dist/serviceModules/ServiceFileHandlerBase/locking.js +51 -0
  35. package/dist/serviceModules/ServiceFileHandlerBase/protection.d.ts +26 -0
  36. package/dist/serviceModules/ServiceFileHandlerBase/protection.js +67 -0
  37. package/dist/serviceModules/ServiceFileHandlerBase/provenance.d.ts +174 -0
  38. package/dist/serviceModules/ServiceFileHandlerBase/provenance.js +182 -0
  39. package/dist/serviceModules/ServiceFileHandlerBase/reflection.d.ts +48 -0
  40. package/dist/serviceModules/ServiceFileHandlerBase/reflection.js +344 -0
  41. package/dist/serviceModules/ServiceFileHandlerBase/renaming.d.ts +23 -0
  42. package/dist/serviceModules/ServiceFileHandlerBase/renaming.js +77 -0
  43. package/dist/serviceModules/ServiceFileHandlerBase/saving.d.ts +40 -0
  44. package/dist/serviceModules/ServiceFileHandlerBase/saving.js +306 -0
  45. package/dist/serviceModules/ServiceFileHandlerBase/scanning.d.ts +22 -0
  46. package/dist/serviceModules/ServiceFileHandlerBase/scanning.js +93 -0
  47. package/dist/serviceModules/ServiceFileHandlerBase/selection.d.ts +58 -0
  48. package/dist/serviceModules/ServiceFileHandlerBase/selection.js +94 -0
  49. package/dist/serviceModules/ServiceFileHandlerBase/storage.d.ts +55 -0
  50. package/dist/serviceModules/ServiceFileHandlerBase/storage.js +37 -0
  51. package/dist/serviceModules/ServiceFileHandlerBase.d.ts +119 -182
  52. package/dist/serviceModules/ServiceFileHandlerBase.js +182 -1402
  53. package/docs/conflict-resolution.md +3 -1
  54. package/docs/development.md +36 -0
  55. package/docs/offline-scanner.md +5 -1
  56. package/docs/p2p-transport-lifecycle.md +8 -1
  57. package/docs/storage-events-and-reflection.md +203 -19
  58. package/package.json +1 -1
@@ -130,7 +130,9 @@ User-directed reconciliation may select any exact current live revision, includi
130
130
 
131
131
  `storeWithBaseRevision()` is the force-write primitive for deliberately preserving a branch below an exact revision, including a revision which is no longer a leaf. It must not be used when an operation means 'advance this revision only if it is still current'. For that compare-and-store boundary, `storeWithLiveBaseRevision()` uses PouchDB's ordinary revision check and returns `false` if the supplied base has already been advanced. Any current revision-tree leaf is eligible, including a non-winning conflict leaf or a logical-deletion leaf. The caller must refresh its state after refusal rather than silently falling back to the deterministic winner.
132
132
 
133
- `storeIndependentRevision()` explicitly preserves unknown-origin content through `putDBEntryAsIndependentRoot()`. Passing an undefined base to `storeWithBaseRevision()` retains its existing latest-revision behaviour and does not create an independent root. `findLiveContentRevisions()` compares only current non-deleted leaves using locally available chunks. Additional provenance comparisons also use local-only retrieval, so they do not introduce remote chunk requests or delivery waits; a missing body without matching saved content evidence leads to preservation rather than an inferred base.
133
+ `storeIndependentRevision()` explicitly preserves unknown-origin content through `putDBEntryAsIndependentRoot()`. Passing an undefined base to `storeWithBaseRevision()` retains its existing latest-revision behaviour and does not create an independent root. `findLiveContentRevisions()` compares only current non-deleted leaves using locally available chunks. Ordinary saves and incoming reflection keep their additional provenance comparisons local-only; a missing body without matching saved content evidence leads to preservation rather than an inferred base.
134
+
135
+ Strict scan reconciliation, including equal-time provenance reconstruction, reads the required current and recorded revisions through the ordinary Chunk retrieval policy. This permits content omitted from CouchDB replication to be fetched when the settings allow it. `useOnlyLocalChunk` still prohibits direct remote requests. If required content remains unavailable, the pair fails for retry instead of inferring a base or assuming equality. See the [offline scan contract](offline-scanner.md#files-in-the-same-timestamp-bucket).
134
136
 
135
137
  A successful non-deleted reconciliation records the exact selected or newly created revision as provenance. Applying a logical deletion removes the storage item and its provenance record. Deletion provenance is not retained indefinitely: an absent storage item and a current logical-deletion winner already agree and need no further reconciliation.
136
138
 
@@ -39,6 +39,42 @@ style for the rest of the basename. Corresponding test files use the same
39
39
  basename, such as `fastForward.unit.spec.ts`. Retain established names for
40
40
  unrelated files and separate conventions for components or other file types.
41
41
 
42
+ ## Ordinary file handler implementation
43
+
44
+ `src/serviceModules/ServiceFileHandlerBase.ts` retains the public file-handler
45
+ class and its existing import path. Its implementation lives in the sibling
46
+ `ServiceFileHandlerBase/` directory. These modules are package-private; they do
47
+ not add consumer entry points.
48
+
49
+ | Modules | Responsibility |
50
+ | --- | --- |
51
+ | `context.ts`, `storage.ts` | Capture injected services, own per-instance state, retain host method dispatch, and resolve file paths, stubs, and bodies. |
52
+ | `locking.ts` | Acquire sorted document locks and run deferred conflict hooks after releasing them. |
53
+ | `provenance.ts`, `scanning.ts` | Track the displayed revision and content evidence, classify storage, revalidate snapshots, and inspect scan hints. |
54
+ | `saving.ts` | Save ordinary or reconciled storage content and handle explicit base-revision selection. |
55
+ | `deletion.ts`, `renaming.ts` | Apply deletion, revision removal, and source-preserving rename operations. |
56
+ | `reflection.ts`, `protection.ts` | Reflect database revisions while protecting unsynchronised storage content. |
57
+ | `events.ts`, `selection.ts` | Interpret ordinary, restored, retried, and replicated events against current selection and storage. |
58
+ | `chunks.ts` | Repair chunks through the host's save method with bounded concurrency. |
59
+
60
+ The facade acquires document locks at public operation boundaries. Internal
61
+ operations reuse the caller's locks; routing them back through a public wrapper
62
+ would acquire the same lock again. The context captures the injected service
63
+ references at construction and resolves existing overridable getters and methods
64
+ when used. Its hash cache and deferred conflict checks belong to one handler
65
+ instance. It contains no additional persistent state.
66
+
67
+ Keep the final snapshot validation and the destructive storage operation in the
68
+ same reflection stage. A candidate snapshot is evidence to recheck, rather than
69
+ permission to write later. The [provenance contract](conflict-resolution.md#file-reflection-provenance)
70
+ owns branch selection and recovery policy. Function TSDoc records inputs, lock
71
+ ownership, effects, completion, and refusal conditions, including private helpers.
72
+
73
+ `src/managers/StorageEventManager.ts` likewise keeps its existing host-facing
74
+ class. Its extracted functions and their focused tests live in
75
+ `src/managers/StorageEventManager/`. These organise the event lifecycle separately
76
+ from the file handler's database and storage effects.
77
+
42
78
  ## Service composition and state ownership
43
79
 
44
80
  Commonlib uses four related forms of composition. Choose between them by ownership and dependency direction, not merely by whether an implementation has mutable state.
@@ -7,6 +7,8 @@ status: unreleased
7
7
 
8
8
  # Full offline scan
9
9
 
10
+ Implementation note: the settings-controlled strict comparison correction for [Self-hosted LiveSync #1329](https://github.com/vrtmrz/obsidian-livesync/issues/1329) is implemented but unreleased. The original reviewed-version fields above retain their historical baseline.
11
+
10
12
  This document defines the developer contract for `synchroniseAllFilesBetweenDBandStorage`. It describes how the scanner classifies each selected path, chooses an action, and records a database-to-storage reflection. Host-specific setup dialogue and recovery choices remain outside this contract.
11
13
 
12
14
  Before applying the host's target-file policy, the scanner validates each decoded Metadata document against its actual local document ID. Consistent internal, customisation, and plug-in storage namespaces remain owned by their dedicated features. A namespace disagreement, or a normal-file ID which does not match the ID derived from its recorded path, is quarantined.
@@ -148,7 +150,9 @@ Self-hosted LiveSync enables this policy only for ordinary Obsidian start-up, wh
148
150
 
149
151
  ## Files in the same timestamp bucket
150
152
 
151
- For a `both` pair which selects `NEWER_WINS` (`sync-newer`), the normal freshness comparison can reach `EVEN` for equal raw modification times or distinct times within the platform tolerance; those timestamps alone do not establish that the storage file is unchanged. Under the omitted-option strict path, the scanner asks the file handler to record provenance for the current database revision only when current storage and one unambiguous live revision have matching content. The handler checks the storage bytes and database revision under the document lock, then revalidates the storage snapshot, current revision, and absent provenance before writing the record. This check writes neither storage content nor a database revision. With explicit `strictContentCheck: false`, the scanner may request `canSkipUnchangedFile` only in the `EVEN` branch, and only when the raw mtime exactly matches the recorded provenance mtime; a value merely in the same tolerance bucket does not qualify. The `BASE_IS_NEW` and `TARGET_IS_NEW` branches retain their existing timestamp-directed reflection and last-seen bookkeeping. The existing selection, file-size, and conflict policies still apply, and the `DB_APPLY` action remains unchanged.
153
+ For a `both` pair which selects `NEWER_WINS` (`sync-newer`), the normal freshness comparison can reach `EVEN` for equal raw modification times or distinct times within the platform tolerance; those timestamps alone do not establish that the storage file is unchanged. Under the omitted-option strict path, the scanner asks the file handler to record provenance for the current database revision only when current storage and one unambiguous live revision have matching content. The handler checks the storage bytes and database revision under the document lock, then revalidates the storage snapshot, current revision, and absent provenance before writing the record. This check writes neither storage content nor a Metadata revision. With explicit `strictContentCheck: false`, the scanner may request `canSkipUnchangedFile` only in the `EVEN` branch, and only when the raw mtime exactly matches the recorded provenance mtime; a value merely in the same tolerance bucket does not qualify. The `BASE_IS_NEW` and `TARGET_IS_NEW` branches retain their existing timestamp-directed reflection and last-seen bookkeeping. The existing selection, file-size, and conflict policies still apply, and the `DB_APPLY` action remains unchanged.
154
+
155
+ Strict content comparisons use the ordinary, settings-controlled Chunk retrieval path for the current revision and any recorded base. This includes Chunks omitted from CouchDB pull replication by `readChunksOnline`. `useOnlyLocalChunk` continues to prohibit direct remote requests; existing local content or an already-active finite replication may still satisfy the comparison. If the required content remains unavailable, the pair fails for retry, and its diagnostic identifies the path and shortened revision. Ordinary saves retain their existing local-first comparison policy.
152
156
 
153
157
  The result of `tryRecordUntrackedFileRevision()` is not an edit predicate. Its `false` can mean that provenance already exists, content differs, history conflicts, required content or provenance is unavailable, or state changed during verification. When it returns `false`, the scanner uses the ordinary, non-forced `storeFileToDB` path with bounded storage revalidation; it does not force the Vault file into the current database winner. The file handler retains a known branch when readable provenance identifies it, applies newer database state when the storage bytes match that recorded older revision, and saves a genuine edit on its recorded branch.
154
158
 
@@ -2,13 +2,20 @@
2
2
  date: 2026-09-16
3
3
  commonlib-version: "0.1.25-dev.turn-credentials.6"
4
4
  self-hosted-livesync-version: "1.0.28"
5
- status: unreleased
5
+ status: published
6
+ published-in: "0.4.0"
7
+ publication-date: 2026-11-07
6
8
  ---
7
9
 
8
10
  # P2P service and transport lifecycle
9
11
 
10
12
  This design document records the implemented Commonlib Trystero P2P service. It defines the current resource owners, demand and automation lifecycles, replacement fences, and shutdown semantics. It is not a migration plan or a general Trystero API reference.
11
13
 
14
+ The per-peer transfer statistics and latest diagnostic observations described
15
+ here are available in [Commonlib 0.4.0](https://github.com/vrtmrz/livesync-commonlib/releases/tag/0.4.0).
16
+ The [release notes](../updates.md#040) describe the transport compatibility change.
17
+ Hosts choose when to adopt the package and expose these capabilities.
18
+
12
19
  ## Ownership layers
13
20
 
14
21
  The P2P composition deliberately separates stable host policy from one replaceable room membership:
@@ -14,6 +14,141 @@ present in storage, and the accepted local completion contract for queued file
14
14
  operations. The version fields identify the reviewed source versions; these
15
15
  changes remain unreleased.
16
16
 
17
+ ## Event-manager terminology
18
+
19
+ Hosts normally supply an adapter and, where necessary, override protected
20
+ `StorageEventManagerBase` hooks. The responsibility modules implement the shared
21
+ pipeline; hosts do not need to call every helper directly. Their TSDoc describes
22
+ inputs, completion boundaries, state changes, and persistence preconditions for
23
+ maintainers who extend or reuse them.
24
+
25
+ | Term | Meaning in this implementation |
26
+ | ------------------- | ------------------------------------------------------------------------------------------------------------------------------------ |
27
+ | Facade | The host-facing class which connects adapters and overridable hooks to the shared functions. |
28
+ | Watcher | The host integration which receives file or editor change notifications. |
29
+ | Admission | Filtering a received event and registering its operation. Its completion does not await the file handler. |
30
+ | Operation | The accepted event intent whose identity survives failed attempts until completion is durably acknowledged. |
31
+ | Attempt | One execution of an operation, with its own result and completion promise. |
32
+ | Ownership | The identity relationships which determine which operation and attempt may acknowledge retained work. |
33
+ | Batching | Delaying eligible content events so related updates can be processed together. |
34
+ | Gate | A promise deciding whether a waiting operation may proceed or has been covered by a successor. Opening it is not handler completion. |
35
+ | Coalescing | Combining pending intents by making an earlier operation depend on the result of a successor which covers it. |
36
+ | Prerequisite | A related operation whose captured attempt must succeed before the dependent handler can run. |
37
+ | Ordered predecessor | An earlier operation which must settle before an ordered event proceeds, even if the earlier result is a failure. |
38
+ | Boundary | The finite selection of operations, admissions, or observed failures relevant to one request. |
39
+ | Sentinel | A queue marker before deletion or rename which waits only for earlier operations. |
40
+ | Dispatch | Taking buffered events and starting their processing; it does not itself establish durable completion. |
41
+ | Flush | Releasing delays and waiting for the captured local completion boundary. It does not establish remote replication. |
42
+ | Snapshot | The saved pending event intents. It is not a backup of every intermediate file body. |
43
+ | Reconciliation | Re-evaluating intent against current storage, database state, and provenance before choosing an effect. |
44
+ | Retry | Starting a new eligible attempt while preserving the result already observed by an earlier caller. |
45
+ | Effects | Explicit callbacks for stateful work or I/O, separated from functions which only construct a plan. |
46
+ | Type guard | A runtime predicate which also narrows the value's TypeScript type before it is used. |
47
+
48
+ ## File-event structure and ownership
49
+
50
+ The pipeline uses several related types. Their declarations are the source of
51
+ truth; the following map explains which layer owns each value.
52
+
53
+ ```text
54
+ Host FileEvent
55
+ -> admission and selection -> FileEventItem
56
+ -> PendingFileEvent -> FileEventAttempt (one result per attempt)
57
+ -> handler(original event or transient ReconcileFileEvent)
58
+
59
+ Snapshot: original FileEventItem | FileEventItemSentinel
60
+ ```
61
+
62
+ ### Host notification: `FileEvent`
63
+
64
+ [`FileEvent`](../src/interfaces/StorageEventManager.ts) is the input to
65
+ `appendQueue()`. It contains `type`, `file`, and optional `oldPath`,
66
+ `cachedData`, `skipBatchWait`, and `cancelled` fields. Admission filters the
67
+ notification before creating a queue item; completion of `appendQueue()` means
68
+ admission has finished, not that its file effect has completed.
69
+
70
+ The event types are `CREATE`, `CHANGED`, `DELETE`, `RENAME`, and `INTERNAL`.
71
+ The ordinary file stub has `path`, `name`, and `stat` (`ctime`, `mtime`, `size`,
72
+ and `type`). An internal-file stub instead has `isInternal: true` and
73
+ `stat: undefined`; a path does not imply that storage statistics are available.
74
+ Neither stub contains the file body. A `UXFileInfo` additionally carries a
75
+ `Blob` body when content has actually been read.
76
+
77
+ ### Retained intent: `FileEventItem`
78
+
79
+ [`FileEventItem` and `FileEventArgs`](../src/common/models/fileaccess.type.ts)
80
+ are the queue and snapshot shapes:
81
+
82
+ | Field | Meaning |
83
+ | ------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
84
+ | `type` | The selected operation type, which can differ from the host notification after rename filtering. |
85
+ | `args.file` | The ordinary or internal-file observation. A rename uses the destination observation; a source-only selected rename becomes a deletion with a source-path observation. |
86
+ | `args.oldPath?` | The source path for a retained `RENAME`. |
87
+ | `args.renameTarget?` | The destination of a rename converted into source-only `DELETE`, retained for exclusion and preservation checks. |
88
+ | `args.cache?` | Optional cached text or `ArrayBuffer`; host `cachedData` is mapped here. It is not an authoritative historical file version. |
89
+ | `args.ctx?` | Opaque host context passed to `appendQueue()`, forwarded to the handler. Its durable representation depends on the host snapshot adapter. |
90
+ | `key` | A generated event label. Operation ownership and acknowledgement use event/attempt identity, not equality of this string or path. |
91
+ | `restoredFromPreviousRuntime?` | `true` on a replayed event; selects current-state revalidation. Restoration adds this marker and `skipBatchWait` to loaded file events. |
92
+ | `skipBatchWait?` | Bypass the intentional batch delay; processing and snapshot acknowledgement must still complete. |
93
+ | `cancelled?` | A queue-item cancellation marker. The handler rejects it rather than confirming an unperformed effect. It is not a successful completion result. |
94
+ | `batched?` | An optional field retained in the shared type for compatibility. The current manager owns batching through gates and attempt dependencies. |
95
+
96
+ Admission copies the selected type, file arguments, host context, cache, and
97
+ batch-wait policy. It does not copy the host `cancelled` field into the new
98
+ item. The declared host and queue shapes therefore must not be treated as
99
+ interchangeable objects.
100
+
101
+ For example, an ordinary rename retains these path relationships:
102
+
103
+ ```ts
104
+ {
105
+ type: 'RENAME',
106
+ key: 'generated-event-label',
107
+ args: {
108
+ file: { path: 'new.md', name: 'new.md', stat: currentStat },
109
+ oldPath: 'old.md',
110
+ },
111
+ }
112
+ ```
113
+
114
+ If only `old.md` is selected, admission emits `DELETE` with
115
+ `args.file.path: 'old.md'` and `args.renameTarget: 'new.md'` instead. This
116
+ preserves the relationship without treating the excluded destination as an
117
+ ordinary synchronisation target.
118
+
119
+ ### In-memory operation and attempts
120
+
121
+ [`PendingFileEvent` and `FileEventAttempt`](../src/managers/StorageEventManager/operations.ts)
122
+ are manager-local state. The operation retains its original `event`, insertion
123
+ `sequence`, admission time and failure boundary, path predecessors, related
124
+ prerequisites, ordering barrier, and current `attempt`. It survives a failed
125
+ attempt. The attempt owns its completion promise, result, start state, captured
126
+ dependency attempts, retry cutoff, and any admission failure. A retry replaces
127
+ the current attempt, leaving earlier callers attached to their original
128
+ result. These maps, promises, and counters are not the persisted event schema.
129
+
130
+ [`PendingSnapshotEntry`](../src/managers/StorageEventManager/state.ts) links an
131
+ event to its operation and provisional completion state. Its exact entry and
132
+ attempt identities must still match before acknowledgement. A
133
+ `FileEventItemSentinel` contains only `{ type: 'SENTINEL_FLUSH' }`; it has no
134
+ file body or operation and orders only preceding work. Snapshots contain the
135
+ original events and sentinels, with insertion and attempt state reconstructed
136
+ when a new manager restores them.
137
+
138
+ ### Transient reconciliation request
139
+
140
+ [`ReconcileFileEvent`](../src/common/models/fileaccess.definition.ts) is a
141
+ shallow copy of a valid `FileEventItem` branded by a private symbol. Construct
142
+ it with `createReconcileEvent()` and inspect it with `isReconcileEvent()`.
143
+ Its arguments are shared with the original event. It selects current-state
144
+ reconciliation for a running-session retry, while the manager continues to
145
+ persist the original event. The symbol is not a persisted format or a new
146
+ operation. Restart replay uses `restoredFromPreviousRuntime` separately.
147
+
148
+ An event records intent. Current storage, database effects, and revision
149
+ provenance determine what is still necessary when its handler executes; the
150
+ saved stub, cache, and event label cannot establish completion by themselves.
151
+
17
152
  ## Processing directions
18
153
 
19
154
  `StorageEventManager.appendQueue` receives watcher events, applies target and
@@ -30,7 +165,7 @@ current-storage check therefore suppresses that deletion, even when the
30
165
  current file's path would itself be excluded from synchronisation.
31
166
 
32
167
  `ServiceFileHandlerBase` serialises this work by the canonical document ID
33
- derived from each path. Before a watcher `DELETE` reaches `deleteFileFromDB`,
168
+ derived from each path. Before a watcher `DELETE` reaches the database deletion core,
34
169
  the handler rechecks current storage under that lock. Rename-derived deletions
35
170
  lock both source and destination document IDs. This direction updates database
36
171
  Metadata; it does not remove the physical file from storage.
@@ -43,11 +178,18 @@ snapshots without that field keep their conservative absence-only rule.
43
178
 
44
179
  Database-to-storage work follows the opposite direction. Replicated Metadata
45
180
  reaches `_anyProcessReplicatedDoc`, which applies target and size checks,
46
- obtains a storage stub, and calls `dbToStorage`. Logical deletion, conflicts,
181
+ obtains a storage stub, and enters the reflection core under the same lock. Logical deletion, conflicts,
47
182
  and unsynchronised storage content retain their existing reflection rules.
48
183
  The watcher guard does not intercept this path or general explicit database
49
184
  deletion operations.
50
185
 
186
+ The public `ServiceFileHandlerBase` import and operation signatures remain the
187
+ host integration boundary. Its responsibility functions live in the sibling
188
+ `ServiceFileHandlerBase/` implementation directory. Internal event processing
189
+ reuses already-held locks, so it does not call the public wrappers which acquire
190
+ those locks. The [developer guide](development.md#ordinary-file-handler-implementation)
191
+ records the module responsibilities and existing override boundaries.
192
+
51
193
  ## Startup scans and pending operations
52
194
 
53
195
  The full scanner's optional `strictContentCheck: false` path is gated by the host's file-operation state. Any related queued, running, or failed operation blocks the `canSkipUnchangedFile` hint. The host must provide an available query before the scanner can establish that no related work exists; without that query or other required evidence, strict content comparison remains active. The hint is considered only after normal freshness comparison reaches `EVEN`, and requires the raw mtime to exactly match the recorded provenance value; a match within the platform comparison bucket is insufficient. `BASE_IS_NEW` and `TARGET_IS_NEW` retain their timestamp-directed reflection and last-seen bookkeeping. A pair returned as `SKIPPED` by this hint does not acknowledge or remove a saved event. Event work continues to follow the snapshot and handler-completion contract below. This option affects only the full-scan same-stat check; ordinary watcher `CREATE` and `CHANGED` handling, replicated writes, and logical-deletion protection retain their existing rules. See [Full offline scan](offline-scanner.md#startup-content-checking) for the full option and eligibility conditions.
@@ -105,6 +247,48 @@ timers do not occupy a processing slot, and time spent waiting for a slot does
105
247
  not restart the maximum delay. Once due, the operation acquires a slot and reads
106
248
  current content for processing.
107
249
 
250
+ ## Retrying ordinary file operations
251
+
252
+ The following extension is unreleased. A failed ordinary `CREATE`, `CHANGED`,
253
+ `DELETE`, or `RENAME` remains pending, while its attempt has a completed failure
254
+ result. A later finite `commitPendingFileEvents()` request can start a new
255
+ attempt. A subsequent event for the same path or related rename paths can also
256
+ re-evaluate failed predecessors before proceeding. These paths share the event
257
+ manager's ownership and use the existing current-state reconciliation rules.
258
+
259
+ Each request captures a finite set of operations and attempts. It may retry an
260
+ existing failure once, shares an attempt already running, and reports failures
261
+ from its captured attempts without looping until success. Later edits do not
262
+ extend that boundary indefinitely. Independent paths can continue, and a new
263
+ file event only recovers its related dependency chain.
264
+
265
+ An earlier caller retains its failed result. Completion removes only the
266
+ operation which owns that result, after its ordered snapshot update succeeds;
267
+ it cannot remove a newer event. Reconciliation checks current file content,
268
+ database effects, and provenance instead of resending a saved body. An absent
269
+ temporary file can make its old content save unnecessary, but following
270
+ rename, deletion, and final-path save operations retain their own effects.
271
+
272
+ Already represented deletions and completed renames retain their replay rules.
273
+ Recreated files and later edits remain protected. A target's existence alone
274
+ does not prove ownership of a partially completed rename. If the displayed
275
+ source branch cannot be established, the existing conservative deletion and
276
+ rename fallback preserves the branches and requests conflict checking; the
277
+ requested deletion may remain unmet.
278
+
279
+ The database and provenance writes remain separate. Their known interruption
280
+ window may produce additional revisions or a preserved conflict under the
281
+ [provenance contract](conflict-resolution.md). An empty pending set is not proof
282
+ of preserved content or ancestry.
283
+
284
+ Start-up continues to restore the existing saved snapshot before watching.
285
+ Runtime retries reuse its file-reconciliation rules without replacing the
286
+ running manager through `restoreState()`. The saved format, handler return
287
+ contracts, and optional-provider retry policy remain unchanged. Hosts can use
288
+ their existing flush and lifecycle calls; no retry timer or new callback is
289
+ required. See the [retry decision](https://github.com/vrtmrz/obsidian-livesync/blob/main/docs/adr/2026_11_local_file_operation_retry.md)
290
+ for the operation matrix and considered alternatives.
291
+
108
292
  ## Optional file handlers
109
293
 
110
294
  `INTERNAL` events and files marked `isInternal` use their owning feature's
@@ -113,12 +297,12 @@ contract. Hosts can register `processOptionalFileEventWithResult` handlers with
113
297
  success value and a veto reason independently; a non-void payload is required
114
298
  in its branch. Dispatch follows priority and registration order:
115
299
 
116
- | Outcome | Dispatch and completion |
117
- | --- | --- |
118
- | `not-applicable` | Try the next provider. If none applies, complete the policy-approved skip. |
119
- | `completed` | Stop and complete the event after the provider's actual save or verified no-op. |
120
- | `veto` | Stop and retain the event with a reported refusal reason. |
121
- | Exception or rejection | Propagate the original error and retain the event. |
300
+ | Outcome | Dispatch and completion |
301
+ | ---------------------- | ------------------------------------------------------------------------------- |
302
+ | `not-applicable` | Try the next provider. If none applies, complete the policy-approved skip. |
303
+ | `completed` | Stop and complete the event after the provider's actual save or verified no-op. |
304
+ | `veto` | Stop and retain the event with a reported refusal reason. |
305
+ | Exception or rejection | Propagate the original error and retain the event. |
122
306
 
123
307
  A completed result stops dispatch immediately; a later provider cannot veto
124
308
  it. Empty registration returns `not-applicable`. False or zero payloads remain
@@ -149,17 +333,17 @@ does not introduce an automatic retry loop for a failed operation.
149
333
 
150
334
  ## Event intent and current storage state
151
335
 
152
- | Event intent | Current storage observation | Admitted operation |
153
- | --- | --- | --- |
154
- | Watcher `CREATE` or `CHANGED` | A selected regular file is present | Keep the existing storage-to-database write. |
155
- | Watcher `DELETE` without `renameTarget` | A current file resolves to the same canonical document ID, including at an excluded path, or a folder occupies the path | Suppress the database deletion; no rename destination is known. |
156
- | Watcher `DELETE` without `renameTarget` | The host lookup reports no current item, or a file belonging to a distinct document ID | Use the existing deletion operation. |
157
- | Watcher `DELETE` without `renameTarget` | Lookup fails | Leave the database unchanged; failure is unknown, not absence. |
158
- | `RENAME` converted to `DELETE` | The destination is still selected when case-collision rejection is omitted | Suppress the database deletion. |
159
- | `RENAME` converted to `DELETE` | The destination is deliberately excluded, and the source is absent | Apply the old document's deletion. |
160
- | Case-only `RENAME` converted to `DELETE` | Source lookup resolves to the exact deliberately excluded destination, not the original path | Apply the old document's deletion despite the shared ID. |
161
- | Restored `DELETE` without `renameTarget` | A current item occupies the saved path | Keep the existing restored-event suppression. |
162
- | Replicated logical deletion | Storage contains a file | Keep the existing database-to-storage conflict and preservation rules. |
336
+ | Event intent | Current storage observation | Admitted operation |
337
+ | ---------------------------------------- | ----------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------- |
338
+ | Watcher `CREATE` or `CHANGED` | A selected regular file is present | Keep the existing storage-to-database write. |
339
+ | Watcher `DELETE` without `renameTarget` | A current file resolves to the same canonical document ID, including at an excluded path, or a folder occupies the path | Suppress the database deletion; no rename destination is known. |
340
+ | Watcher `DELETE` without `renameTarget` | The host lookup reports no current item, or a file belonging to a distinct document ID | Use the existing deletion operation. |
341
+ | Watcher `DELETE` without `renameTarget` | Lookup fails | Leave the database unchanged; failure is unknown, not absence. |
342
+ | `RENAME` converted to `DELETE` | The destination is still selected when case-collision rejection is omitted | Suppress the database deletion. |
343
+ | `RENAME` converted to `DELETE` | The destination is deliberately excluded, and the source is absent | Apply the old document's deletion. |
344
+ | Case-only `RENAME` converted to `DELETE` | Source lookup resolves to the exact deliberately excluded destination, not the original path | Apply the old document's deletion despite the shared ID. |
345
+ | Restored `DELETE` without `renameTarget` | A current item occupies the saved path | Keep the existing restored-event suppression. |
346
+ | Replicated logical deletion | Storage contains a file | Keep the existing database-to-storage conflict and preservation rules. |
163
347
 
164
348
  ## Rename exclusion and preservation
165
349
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@vrtmrz/livesync-commonlib",
3
- "version": "0.4.0",
3
+ "version": "0.4.1",
4
4
  "description": "Shared data, storage, and replication primitives for Self-hosted LiveSync clients.",
5
5
  "type": "module",
6
6
  "types": "./dist/index.d.ts",