@vrtmrz/livesync-commonlib 0.4.0 → 0.4.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (79) hide show
  1. package/README.md +14 -2
  2. package/dist/common/models/fileaccess.definition.d.ts +35 -0
  3. package/dist/common/models/fileaccess.definition.js +11 -0
  4. package/dist/common/typeUtils.d.ts +27 -4
  5. package/dist/interfaces/FileHandler.d.ts +60 -1
  6. package/dist/interfaces/FileReflectionProvenance.d.ts +15 -1
  7. package/dist/interfaces/FileReflectionProvenance.js +11 -1
  8. package/dist/managers/StorageEventManager/admission.d.ts +50 -0
  9. package/dist/managers/StorageEventManager/admission.js +129 -0
  10. package/dist/managers/StorageEventManager/batching.d.ts +93 -0
  11. package/dist/managers/StorageEventManager/batching.js +97 -0
  12. package/dist/managers/StorageEventManager/operations.d.ts +142 -0
  13. package/dist/managers/StorageEventManager/operations.js +69 -0
  14. package/dist/managers/StorageEventManager/processing.d.ts +63 -0
  15. package/dist/managers/StorageEventManager/processing.js +94 -0
  16. package/dist/managers/StorageEventManager/queue.d.ts +73 -0
  17. package/dist/managers/StorageEventManager/queue.js +113 -0
  18. package/dist/managers/StorageEventManager/retry.d.ts +33 -0
  19. package/dist/managers/StorageEventManager/retry.js +31 -0
  20. package/dist/managers/StorageEventManager/snapshot.d.ts +46 -0
  21. package/dist/managers/StorageEventManager/snapshot.js +53 -0
  22. package/dist/managers/StorageEventManager/state.d.ts +155 -0
  23. package/dist/managers/StorageEventManager/state.js +105 -0
  24. package/dist/managers/StorageEventManager/watching.d.ts +93 -0
  25. package/dist/managers/StorageEventManager/watching.js +36 -0
  26. package/dist/managers/StorageEventManager.d.ts +303 -83
  27. package/dist/managers/StorageEventManager.js +457 -547
  28. package/dist/serviceFeatures/offlineScanner/fileStatus.d.ts +61 -0
  29. package/dist/serviceFeatures/offlineScanner/fileStatus.js +85 -0
  30. package/dist/serviceFeatures/offlineScanner/files.d.ts +47 -0
  31. package/dist/serviceFeatures/offlineScanner/files.js +218 -0
  32. package/dist/serviceFeatures/offlineScanner/metadata.d.ts +56 -0
  33. package/dist/serviceFeatures/offlineScanner/metadata.js +320 -0
  34. package/dist/serviceFeatures/offlineScanner/paths.d.ts +20 -0
  35. package/dist/serviceFeatures/offlineScanner/paths.js +16 -0
  36. package/dist/serviceFeatures/offlineScanner/scan.d.ts +35 -0
  37. package/dist/serviceFeatures/offlineScanner/scan.js +358 -0
  38. package/dist/serviceFeatures/offlineScanner/types.d.ts +134 -0
  39. package/dist/serviceFeatures/offlineScanner/types.js +66 -0
  40. package/dist/serviceFeatures/offlineScanner.d.ts +25 -251
  41. package/dist/serviceFeatures/offlineScanner.js +36 -860
  42. package/dist/serviceModules/ServiceFileHandlerBase/chunks.d.ts +10 -0
  43. package/dist/serviceModules/ServiceFileHandlerBase/chunks.js +51 -0
  44. package/dist/serviceModules/ServiceFileHandlerBase/context.d.ts +168 -0
  45. package/dist/serviceModules/ServiceFileHandlerBase/context.js +15 -0
  46. package/dist/serviceModules/ServiceFileHandlerBase/deletion.d.ts +40 -0
  47. package/dist/serviceModules/ServiceFileHandlerBase/deletion.js +142 -0
  48. package/dist/serviceModules/ServiceFileHandlerBase/deletionRecovery.d.ts +13 -0
  49. package/dist/serviceModules/ServiceFileHandlerBase/deletionRecovery.js +194 -0
  50. package/dist/serviceModules/ServiceFileHandlerBase/events.d.ts +20 -0
  51. package/dist/serviceModules/ServiceFileHandlerBase/events.js +205 -0
  52. package/dist/serviceModules/ServiceFileHandlerBase/locking.d.ts +23 -0
  53. package/dist/serviceModules/ServiceFileHandlerBase/locking.js +51 -0
  54. package/dist/serviceModules/ServiceFileHandlerBase/protection.d.ts +26 -0
  55. package/dist/serviceModules/ServiceFileHandlerBase/protection.js +67 -0
  56. package/dist/serviceModules/ServiceFileHandlerBase/provenance.d.ts +174 -0
  57. package/dist/serviceModules/ServiceFileHandlerBase/provenance.js +182 -0
  58. package/dist/serviceModules/ServiceFileHandlerBase/reflection.d.ts +48 -0
  59. package/dist/serviceModules/ServiceFileHandlerBase/reflection.js +344 -0
  60. package/dist/serviceModules/ServiceFileHandlerBase/renaming.d.ts +23 -0
  61. package/dist/serviceModules/ServiceFileHandlerBase/renaming.js +77 -0
  62. package/dist/serviceModules/ServiceFileHandlerBase/saving.d.ts +40 -0
  63. package/dist/serviceModules/ServiceFileHandlerBase/saving.js +306 -0
  64. package/dist/serviceModules/ServiceFileHandlerBase/scanning.d.ts +22 -0
  65. package/dist/serviceModules/ServiceFileHandlerBase/scanning.js +93 -0
  66. package/dist/serviceModules/ServiceFileHandlerBase/selection.d.ts +58 -0
  67. package/dist/serviceModules/ServiceFileHandlerBase/selection.js +94 -0
  68. package/dist/serviceModules/ServiceFileHandlerBase/storage.d.ts +55 -0
  69. package/dist/serviceModules/ServiceFileHandlerBase/storage.js +37 -0
  70. package/dist/serviceModules/ServiceFileHandlerBase.d.ts +141 -183
  71. package/dist/serviceModules/ServiceFileHandlerBase.js +206 -1397
  72. package/dist/services/base/KeyValueDBService.d.ts +9 -0
  73. package/dist/services/base/KeyValueDBService.js +11 -1
  74. package/docs/conflict-resolution.md +3 -1
  75. package/docs/development.md +40 -0
  76. package/docs/offline-scanner.md +26 -1
  77. package/docs/p2p-transport-lifecycle.md +8 -1
  78. package/docs/storage-events-and-reflection.md +212 -22
  79. package/package.json +1 -1
@@ -33,6 +33,15 @@ export declare abstract class KeyValueDBService<T extends ServiceContext = Servi
33
33
  private _everyOnInitializeDatabase;
34
34
  private _everyOnloadAfterLoadSettings;
35
35
  constructor(context: T, dependencies: KeyValueDBDependencies<T>);
36
+ /**
37
+ * Create an inert namespaced handle over the service's current database.
38
+ * @param kind - Namespace identifier; stored keys receive this identifier and a trailing hyphen.
39
+ * @returns A handle whose operations resolve the current database when invoked.
40
+ * @remarks Construction performs no database I/O. Operations fail if the store
41
+ * is not ready. For keys, an undefined upper bound means the complete remaining
42
+ * namespace, including Unicode and empty keys. Explicit bounds are inclusive,
43
+ * and the optional count is passed to the database unchanged.
44
+ */
36
45
  openSimpleStore<T>(kind: string): {
37
46
  get: (key: string) => Promise<T>;
38
47
  set: (key: string, value: unknown) => Promise<void>;
@@ -101,6 +101,15 @@ class KeyValueDBService extends ServiceBase {
101
101
  this.databaseEvents.onCloseDatabase.addHandler(this._onOtherDatabaseClose.bind(this));
102
102
  }
103
103
  }
104
+ /**
105
+ * Create an inert namespaced handle over the service's current database.
106
+ * @param kind - Namespace identifier; stored keys receive this identifier and a trailing hyphen.
107
+ * @returns A handle whose operations resolve the current database when invoked.
108
+ * @remarks Construction performs no database I/O. Operations fail if the store
109
+ * is not ready. For keys, an undefined upper bound means the complete remaining
110
+ * namespace, including Unicode and empty keys. Explicit bounds are inclusive,
111
+ * and the optional count is passed to the database unchanged.
112
+ */
104
113
  openSimpleStore(kind) {
105
114
  const getDB = () => {
106
115
  if (!this._kvDB) {
@@ -120,8 +129,9 @@ class KeyValueDBService extends ServiceBase {
120
129
  await getDB().del(`${prefix}${key}`);
121
130
  },
122
131
  keys: async (from, to, count) => {
132
+ const upperBound = to === void 0 ? `${prefix.slice(0, -1)}.` : `${prefix}${to || ""}`;
123
133
  const ret = await getDB().keys(
124
- IDBKeyRange.bound(`${prefix}${from || ""}`, `${prefix}${to || ""}`),
134
+ IDBKeyRange.bound(`${prefix}${from || ""}`, upperBound, false, to === void 0),
125
135
  count
126
136
  );
127
137
  return ret.map((e) => (typeof e === "string" ? e : JSON.stringify(e)).toString()).filter((e) => e.startsWith(prefix)).map((e) => e.substring(prefix.length));
@@ -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,43 @@ 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
+ | `deletionRecovery.ts` | Recover retained logical deletions and interrupted cleanup under opt-in provenance and shared file admission. |
57
+ | `reflection.ts`, `protection.ts` | Reflect database revisions while protecting unsynchronised storage content. |
58
+ | `events.ts`, `selection.ts` | Interpret ordinary, restored, retried, and replicated events against current selection and storage. |
59
+ | `chunks.ts` | Repair chunks through the host's save method with bounded concurrency. |
60
+
61
+ The facade acquires document locks at public operation boundaries. Internal
62
+ operations reuse the caller's locks; routing them back through a public wrapper
63
+ would acquire the same lock again. The context captures the injected service
64
+ references at construction and resolves existing overridable getters and methods
65
+ when used. Its hash cache and deferred conflict checks belong to one handler
66
+ instance. It contains no additional persistent state.
67
+
68
+ Keep the final snapshot validation and the destructive storage operation in the
69
+ same reflection stage. A candidate snapshot is evidence to recheck, rather than
70
+ permission to write later. The [provenance contract](conflict-resolution.md#file-reflection-provenance)
71
+ owns branch selection and recovery policy. Function TSDoc records inputs, lock
72
+ ownership, effects, completion, and refusal conditions, including private helpers.
73
+
74
+ `src/managers/StorageEventManager.ts` likewise keeps its existing host-facing
75
+ class. Its extracted functions and their focused tests live in
76
+ `src/managers/StorageEventManager/`. These organise the event lifecycle separately
77
+ from the file handler's database and storage effects.
78
+
42
79
  ## Service composition and state ownership
43
80
 
44
81
  Commonlib uses four related forms of composition. Choose between them by ownership and dependency direction, not merely by whether an implementation has mutable state.
@@ -271,3 +308,6 @@ The shared value extraction uses the declared Octagonal Wheels dependency. Its
271
308
  package's public duration and delimiter helpers; source tests cover the
272
309
  internal JSON copy adapter. When testing a future unpublished dependency, keep
273
310
  these checks tied to the same Octagonal Wheels tarball used by the downstream consumer.
311
+
312
+ The opt-in ordinary deletion recovery contract, runtime budgets, and restart
313
+ cleanup ownership are recorded in [Deletion recovery](deletion-recovery.md).
@@ -7,6 +7,14 @@ status: unreleased
7
7
 
8
8
  # Full offline scan
9
9
 
10
+ The public entry remains `serviceFeatures/offlineScanner`. Internally,
11
+ `src/serviceFeatures/offlineScanner/` separates shared types, path comparison,
12
+ Metadata inspection and repair, last-seen persistence, file collection and
13
+ reflection, and scan orchestration. The entry module retains lifecycle integration
14
+ and re-exports its existing public functions; callers do not need to change imports.
15
+
16
+ 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.
17
+
10
18
  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
19
 
12
20
  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 +156,9 @@ Self-hosted LiveSync enables this policy only for ordinary Obsidian start-up, wh
148
156
 
149
157
  ## Files in the same timestamp bucket
150
158
 
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.
159
+ 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.
160
+
161
+ 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
162
 
153
163
  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
164
 
@@ -175,3 +185,18 @@ Identity coverage verifies early quarantine when no consistent target exists, co
175
185
  Stored-event coverage verifies that current storage content replaces saved observations, a recreated path suppresses a stale deletion, distinct-ID rename halves are admitted independently from current path state, and a same-ID rename never performs a separate deletion. It also verifies that a storage-inspection failure does not become evidence for a destructive operation, that failed work remains pending, and that an individual replay failure does not prevent the full scan from running.
176
186
 
177
187
  Maintain that interaction boundary when changing file-handler results, last-seen persistence, Fast Setup reflection, or offline deletion detection.
188
+
189
+
190
+ ## Opt-in recovery of retained logical deletions
191
+
192
+ The base action matrix remains the policy for hosts without deletion recovery.
193
+ A host whose handler reports `supportsDeletionRecovery()` may recover a
194
+ conflict-free, newer `both-db-deleted` pair during ordinary `NEWER_WINS` without
195
+ extra policies. This guarded operation does not use `update-storage` or direct
196
+ `delete-local`. Existing explicit policies retain their choices.
197
+
198
+ For `db-only-deleted` pairs, one optional provenance key enumeration identifies
199
+ stale bookkeeping. Cleanup-only work precedes new deletions and never reads file
200
+ bodies or invokes physical deletion. All affected paths are revalidated by their
201
+ handler. See [Deletion recovery](deletion-recovery.md) for completion, error,
202
+ concurrency, and cost contracts. This extension is unreleased.
@@ -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:
@@ -2,7 +2,7 @@
2
2
  date: 2026-10-26
3
3
  commonlib-version: "0.2.1"
4
4
  self-hosted-livesync-version: "1.0.40"
5
- status: unreleased
5
+ status: published
6
6
  ---
7
7
 
8
8
  # Storage events and database-to-storage reflection
@@ -11,8 +11,148 @@ This note separates storage-to-database event handling from
11
11
  database-to-storage reflection. It documents the current guard against a stale
12
12
  `DELETE` notification logically deleting Metadata while the same file is still
13
13
  present in storage, and the accepted local completion contract for queued file
14
- operations. The version fields identify the reviewed source versions; these
15
- changes remain unreleased.
14
+ operations. The version fields identify the original reviewed source versions.
15
+
16
+ > Publication note (9th November, 2026): This implementation, including the
17
+ > [ordinary-file retry extension](#retrying-ordinary-file-operations), is included
18
+ > in published [Commonlib 0.4.1](https://github.com/vrtmrz/livesync-commonlib/releases/tag/0.4.1).
19
+ > The original review date and version baseline are retained above. Host
20
+ > applications adopt this package through their own dependency updates.
21
+
22
+ ## Event-manager terminology
23
+
24
+ Hosts normally supply an adapter and, where necessary, override protected
25
+ `StorageEventManagerBase` hooks. The responsibility modules implement the shared
26
+ pipeline; hosts do not need to call every helper directly. Their TSDoc describes
27
+ inputs, completion boundaries, state changes, and persistence preconditions for
28
+ maintainers who extend or reuse them.
29
+
30
+ | Term | Meaning in this implementation |
31
+ | ------------------- | ------------------------------------------------------------------------------------------------------------------------------------ |
32
+ | Facade | The host-facing class which connects adapters and overridable hooks to the shared functions. |
33
+ | Watcher | The host integration which receives file or editor change notifications. |
34
+ | Admission | Filtering a received event and registering its operation. Its completion does not await the file handler. |
35
+ | Operation | The accepted event intent whose identity survives failed attempts until completion is durably acknowledged. |
36
+ | Attempt | One execution of an operation, with its own result and completion promise. |
37
+ | Ownership | The identity relationships which determine which operation and attempt may acknowledge retained work. |
38
+ | Batching | Delaying eligible content events so related updates can be processed together. |
39
+ | Gate | A promise deciding whether a waiting operation may proceed or has been covered by a successor. Opening it is not handler completion. |
40
+ | Coalescing | Combining pending intents by making an earlier operation depend on the result of a successor which covers it. |
41
+ | Prerequisite | A related operation whose captured attempt must succeed before the dependent handler can run. |
42
+ | Ordered predecessor | An earlier operation which must settle before an ordered event proceeds, even if the earlier result is a failure. |
43
+ | Boundary | The finite selection of operations, admissions, or observed failures relevant to one request. |
44
+ | Sentinel | A queue marker before deletion or rename which waits only for earlier operations. |
45
+ | Dispatch | Taking buffered events and starting their processing; it does not itself establish durable completion. |
46
+ | Flush | Releasing delays and waiting for the captured local completion boundary. It does not establish remote replication. |
47
+ | Snapshot | The saved pending event intents. It is not a backup of every intermediate file body. |
48
+ | Reconciliation | Re-evaluating intent against current storage, database state, and provenance before choosing an effect. |
49
+ | Retry | Starting a new eligible attempt while preserving the result already observed by an earlier caller. |
50
+ | Effects | Explicit callbacks for stateful work or I/O, separated from functions which only construct a plan. |
51
+ | Type guard | A runtime predicate which also narrows the value's TypeScript type before it is used. |
52
+
53
+ ## File-event structure and ownership
54
+
55
+ The pipeline uses several related types. Their declarations are the source of
56
+ truth; the following map explains which layer owns each value.
57
+
58
+ ```text
59
+ Host FileEvent
60
+ -> admission and selection -> FileEventItem
61
+ -> PendingFileEvent -> FileEventAttempt (one result per attempt)
62
+ -> handler(original event or transient ReconcileFileEvent)
63
+
64
+ Snapshot: original FileEventItem | FileEventItemSentinel
65
+ ```
66
+
67
+ ### Host notification: `FileEvent`
68
+
69
+ [`FileEvent`](../src/interfaces/StorageEventManager.ts) is the input to
70
+ `appendQueue()`. It contains `type`, `file`, and optional `oldPath`,
71
+ `cachedData`, `skipBatchWait`, and `cancelled` fields. Admission filters the
72
+ notification before creating a queue item; completion of `appendQueue()` means
73
+ admission has finished, not that its file effect has completed.
74
+
75
+ The event types are `CREATE`, `CHANGED`, `DELETE`, `RENAME`, and `INTERNAL`.
76
+ The ordinary file stub has `path`, `name`, and `stat` (`ctime`, `mtime`, `size`,
77
+ and `type`). An internal-file stub instead has `isInternal: true` and
78
+ `stat: undefined`; a path does not imply that storage statistics are available.
79
+ Neither stub contains the file body. A `UXFileInfo` additionally carries a
80
+ `Blob` body when content has actually been read.
81
+
82
+ ### Retained intent: `FileEventItem`
83
+
84
+ [`FileEventItem` and `FileEventArgs`](../src/common/models/fileaccess.type.ts)
85
+ are the queue and snapshot shapes:
86
+
87
+ | Field | Meaning |
88
+ | ------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
89
+ | `type` | The selected operation type, which can differ from the host notification after rename filtering. |
90
+ | `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. |
91
+ | `args.oldPath?` | The source path for a retained `RENAME`. |
92
+ | `args.renameTarget?` | The destination of a rename converted into source-only `DELETE`, retained for exclusion and preservation checks. |
93
+ | `args.cache?` | Optional cached text or `ArrayBuffer`; host `cachedData` is mapped here. It is not an authoritative historical file version. |
94
+ | `args.ctx?` | Opaque host context passed to `appendQueue()`, forwarded to the handler. Its durable representation depends on the host snapshot adapter. |
95
+ | `key` | A generated event label. Operation ownership and acknowledgement use event/attempt identity, not equality of this string or path. |
96
+ | `restoredFromPreviousRuntime?` | `true` on a replayed event; selects current-state revalidation. Restoration adds this marker and `skipBatchWait` to loaded file events. |
97
+ | `skipBatchWait?` | Bypass the intentional batch delay; processing and snapshot acknowledgement must still complete. |
98
+ | `cancelled?` | A queue-item cancellation marker. The handler rejects it rather than confirming an unperformed effect. It is not a successful completion result. |
99
+ | `batched?` | An optional field retained in the shared type for compatibility. The current manager owns batching through gates and attempt dependencies. |
100
+
101
+ Admission copies the selected type, file arguments, host context, cache, and
102
+ batch-wait policy. It does not copy the host `cancelled` field into the new
103
+ item. The declared host and queue shapes therefore must not be treated as
104
+ interchangeable objects.
105
+
106
+ For example, an ordinary rename retains these path relationships:
107
+
108
+ ```ts
109
+ {
110
+ type: 'RENAME',
111
+ key: 'generated-event-label',
112
+ args: {
113
+ file: { path: 'new.md', name: 'new.md', stat: currentStat },
114
+ oldPath: 'old.md',
115
+ },
116
+ }
117
+ ```
118
+
119
+ If only `old.md` is selected, admission emits `DELETE` with
120
+ `args.file.path: 'old.md'` and `args.renameTarget: 'new.md'` instead. This
121
+ preserves the relationship without treating the excluded destination as an
122
+ ordinary synchronisation target.
123
+
124
+ ### In-memory operation and attempts
125
+
126
+ [`PendingFileEvent` and `FileEventAttempt`](../src/managers/StorageEventManager/operations.ts)
127
+ are manager-local state. The operation retains its original `event`, insertion
128
+ `sequence`, admission time and failure boundary, path predecessors, related
129
+ prerequisites, ordering barrier, and current `attempt`. It survives a failed
130
+ attempt. The attempt owns its completion promise, result, start state, captured
131
+ dependency attempts, retry cutoff, and any admission failure. A retry replaces
132
+ the current attempt, leaving earlier callers attached to their original
133
+ result. These maps, promises, and counters are not the persisted event schema.
134
+
135
+ [`PendingSnapshotEntry`](../src/managers/StorageEventManager/state.ts) links an
136
+ event to its operation and provisional completion state. Its exact entry and
137
+ attempt identities must still match before acknowledgement. A
138
+ `FileEventItemSentinel` contains only `{ type: 'SENTINEL_FLUSH' }`; it has no
139
+ file body or operation and orders only preceding work. Snapshots contain the
140
+ original events and sentinels, with insertion and attempt state reconstructed
141
+ when a new manager restores them.
142
+
143
+ ### Transient reconciliation request
144
+
145
+ [`ReconcileFileEvent`](../src/common/models/fileaccess.definition.ts) is a
146
+ shallow copy of a valid `FileEventItem` branded by a private symbol. Construct
147
+ it with `createReconcileEvent()` and inspect it with `isReconcileEvent()`.
148
+ Its arguments are shared with the original event. It selects current-state
149
+ reconciliation for a running-session retry, while the manager continues to
150
+ persist the original event. The symbol is not a persisted format or a new
151
+ operation. Restart replay uses `restoredFromPreviousRuntime` separately.
152
+
153
+ An event records intent. Current storage, database effects, and revision
154
+ provenance determine what is still necessary when its handler executes; the
155
+ saved stub, cache, and event label cannot establish completion by themselves.
16
156
 
17
157
  ## Processing directions
18
158
 
@@ -30,7 +170,7 @@ current-storage check therefore suppresses that deletion, even when the
30
170
  current file's path would itself be excluded from synchronisation.
31
171
 
32
172
  `ServiceFileHandlerBase` serialises this work by the canonical document ID
33
- derived from each path. Before a watcher `DELETE` reaches `deleteFileFromDB`,
173
+ derived from each path. Before a watcher `DELETE` reaches the database deletion core,
34
174
  the handler rechecks current storage under that lock. Rename-derived deletions
35
175
  lock both source and destination document IDs. This direction updates database
36
176
  Metadata; it does not remove the physical file from storage.
@@ -43,11 +183,18 @@ snapshots without that field keep their conservative absence-only rule.
43
183
 
44
184
  Database-to-storage work follows the opposite direction. Replicated Metadata
45
185
  reaches `_anyProcessReplicatedDoc`, which applies target and size checks,
46
- obtains a storage stub, and calls `dbToStorage`. Logical deletion, conflicts,
186
+ obtains a storage stub, and enters the reflection core under the same lock. Logical deletion, conflicts,
47
187
  and unsynchronised storage content retain their existing reflection rules.
48
188
  The watcher guard does not intercept this path or general explicit database
49
189
  deletion operations.
50
190
 
191
+ The public `ServiceFileHandlerBase` import and operation signatures remain the
192
+ host integration boundary. Its responsibility functions live in the sibling
193
+ `ServiceFileHandlerBase/` implementation directory. Internal event processing
194
+ reuses already-held locks, so it does not call the public wrappers which acquire
195
+ those locks. The [developer guide](development.md#ordinary-file-handler-implementation)
196
+ records the module responsibilities and existing override boundaries.
197
+
51
198
  ## Startup scans and pending operations
52
199
 
53
200
  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 +252,49 @@ timers do not occupy a processing slot, and time spent waiting for a slot does
105
252
  not restart the maximum delay. Once due, the operation acquires a slot and reads
106
253
  current content for processing.
107
254
 
255
+ ## Retrying ordinary file operations
256
+
257
+ The following extension is available in Commonlib 0.4.1. A failed ordinary
258
+ `CREATE`, `CHANGED`, `DELETE`, or `RENAME` remains pending, while its attempt has
259
+ a completed failure result. A later finite `commitPendingFileEvents()` request
260
+ can start a new attempt. A subsequent event for the same path or related rename
261
+ paths can also re-evaluate failed predecessors before proceeding. These paths
262
+ share the event manager's ownership and use the existing current-state
263
+ reconciliation rules.
264
+
265
+ Each request captures a finite set of operations and attempts. It may retry an
266
+ existing failure once, shares an attempt already running, and reports failures
267
+ from its captured attempts without looping until success. Later edits do not
268
+ extend that boundary indefinitely. Independent paths can continue, and a new
269
+ file event only recovers its related dependency chain.
270
+
271
+ An earlier caller retains its failed result. Completion removes only the
272
+ operation which owns that result, after its ordered snapshot update succeeds;
273
+ it cannot remove a newer event. Reconciliation checks current file content,
274
+ database effects, and provenance instead of resending a saved body. An absent
275
+ temporary file can make its old content save unnecessary, but following
276
+ rename, deletion, and final-path save operations retain their own effects.
277
+
278
+ Already represented deletions and completed renames retain their replay rules.
279
+ Recreated files and later edits remain protected. A target's existence alone
280
+ does not prove ownership of a partially completed rename. If the displayed
281
+ source branch cannot be established, the existing conservative deletion and
282
+ rename fallback preserves the branches and requests conflict checking; the
283
+ requested deletion may remain unmet.
284
+
285
+ The database and provenance writes remain separate. Their known interruption
286
+ window may produce additional revisions or a preserved conflict under the
287
+ [provenance contract](conflict-resolution.md). An empty pending set is not proof
288
+ of preserved content or ancestry.
289
+
290
+ Start-up continues to restore the existing saved snapshot before watching.
291
+ Runtime retries reuse its file-reconciliation rules without replacing the
292
+ running manager through `restoreState()`. The saved format, handler return
293
+ contracts, and optional-provider retry policy remain unchanged. Hosts can use
294
+ their existing flush and lifecycle calls; no retry timer or new callback is
295
+ required. See the [reviewed retry decision](https://github.com/vrtmrz/obsidian-livesync/blob/09c17e90dde3b1a2000c8a2e13301245107b915b/docs/adr/2026_11_local_file_operation_retry.md)
296
+ for the operation matrix and considered alternatives.
297
+
108
298
  ## Optional file handlers
109
299
 
110
300
  `INTERNAL` events and files marked `isInternal` use their owning feature's
@@ -113,12 +303,12 @@ contract. Hosts can register `processOptionalFileEventWithResult` handlers with
113
303
  success value and a veto reason independently; a non-void payload is required
114
304
  in its branch. Dispatch follows priority and registration order:
115
305
 
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. |
306
+ | Outcome | Dispatch and completion |
307
+ | ---------------------- | ------------------------------------------------------------------------------- |
308
+ | `not-applicable` | Try the next provider. If none applies, complete the policy-approved skip. |
309
+ | `completed` | Stop and complete the event after the provider's actual save or verified no-op. |
310
+ | `veto` | Stop and retain the event with a reported refusal reason. |
311
+ | Exception or rejection | Propagate the original error and retain the event. |
122
312
 
123
313
  A completed result stops dispatch immediately; a later provider cannot veto
124
314
  it. Empty registration returns `not-applicable`. False or zero payloads remain
@@ -149,17 +339,17 @@ does not introduce an automatic retry loop for a failed operation.
149
339
 
150
340
  ## Event intent and current storage state
151
341
 
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. |
342
+ | Event intent | Current storage observation | Admitted operation |
343
+ | ---------------------------------------- | ----------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------- |
344
+ | Watcher `CREATE` or `CHANGED` | A selected regular file is present | Keep the existing storage-to-database write. |
345
+ | 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. |
346
+ | 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. |
347
+ | Watcher `DELETE` without `renameTarget` | Lookup fails | Leave the database unchanged; failure is unknown, not absence. |
348
+ | `RENAME` converted to `DELETE` | The destination is still selected when case-collision rejection is omitted | Suppress the database deletion. |
349
+ | `RENAME` converted to `DELETE` | The destination is deliberately excluded, and the source is absent | Apply the old document's deletion. |
350
+ | 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. |
351
+ | Restored `DELETE` without `renameTarget` | A current item occupies the saved path | Keep the existing restored-event suppression. |
352
+ | Replicated logical deletion | Storage contains a file | Keep the existing database-to-storage conflict and preservation rules. |
163
353
 
164
354
  ## Rename exclusion and preservation
165
355
 
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.2",
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",