@rljson/fs-agent 0.0.85 → 0.1.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.
@@ -0,0 +1,319 @@
1
+ <!--
2
+ @license
3
+ Copyright (c) 2025 Rljson
4
+
5
+ Use of this source code is governed by terms that can be
6
+ found in the LICENSE file in the root of this package.
7
+ -->
8
+
9
+ # @rljson/fs-agent — API reference
10
+
11
+ Every symbol the package exports, grouped by the module it comes from, with what
12
+ it is for and what it costs. **89 exports across 11 modules.**
13
+
14
+ Most consumers need only the first section. The rest is the protocol, exported
15
+ because the sync is assembled from parts that are separately testable — not
16
+ because every caller is expected to reach for them.
17
+
18
+ | if you want | read |
19
+ | --- | --- |
20
+ | to sync a folder | [The agent](#the-agent) |
21
+ | to know what the agent is doing | [Observability](#observability) |
22
+ | the history itself | [The edit chain](#the-edit-chain) |
23
+ | the repair protocol | [Bucket sync](#bucket-sync-the-wire) and [The manifest](#the-manifest-reconciliation) |
24
+ | conflict resolution internals | [Conflicts](#conflicts) |
25
+ | the design behind any of it | [README.architecture.md](README.architecture.md) |
26
+
27
+ ---
28
+
29
+ ## The agent
30
+
31
+ ### `class FsAgent`
32
+
33
+ One folder, one agent. Construct it, then start one or both directions.
34
+
35
+ ```ts
36
+ new FsAgent(rootPath: string, bs?: Bs, options?: FsAgentOptions)
37
+ ```
38
+
39
+ `bs` defaults to a fresh `BsMem`, which is **local only**. For a synced folder
40
+ pass `client.bs` — an agent with a bare `BsMem` can store its own blobs and
41
+ never fetch a peer's, so every restore fails on its first file. Prefer
42
+ `FsAgent.fromClient`, which wires this correctly.
43
+
44
+ | member | returns | what it does |
45
+ | --- | --- | --- |
46
+ | `static fromClient(client, rootPath, options?)` | `Promise<FsAgent>` | the production path: takes `client.io`/`client.bs`, turns on conflict resolution and the sync config the fleet needs |
47
+ | `syncToDb(db, connector, treeKey, storageOptions?)` | `Promise<() => void>` | **sending.** Watches the folder, appends an Edit per change, announces its head. Returns `stop()` |
48
+ | `syncFromDb(db, connector, treeKey, restoreOptions?)` | `Promise<() => void>` | **receiving.** Resolves announcements, applies Edits, heals. Returns `stop()` |
49
+ | `dispose()` | `void` | releases the watcher and **abandons a pending join** |
50
+ | `extract()` | `Promise<FsTree>` | scan the folder into a tree, without storing or announcing |
51
+ | `restore(tree, targetDir?, options?)` | `Promise<void>` | write a tree to disk. See `RestoreOptions.cleanTarget` |
52
+ | `storeInDb(db, treeKey, options?)` | `Promise<string>` | scan and store, returning the tree ref |
53
+ | `loadFromDb(db, treeKey, ref, targetDir?)` | `Promise<void>` | fetch a tree by ref and write it out |
54
+ | `getTree()` | `FsTree \| null` | the last scanned tree, or `null` before the first scan |
55
+ | `hasBlob(blobId)` | `Promise<boolean>` | is this blob available locally |
56
+ | `getFileContent(blobId)` | `Promise<Buffer>` | the bytes behind a blob id |
57
+
58
+ Both `syncToDb` and `syncFromDb` return a `stop()`. Calling `stop()` ends that
59
+ direction; `dispose()` releases the agent.
60
+
61
+ ### `interface FsAgentOptions`
62
+
63
+ Everything optional. See
64
+ [README.public.md § Configuration](README.public.md#configuration) for defaults
65
+ and what each one costs — this table is the shape, that one is the advice.
66
+
67
+ | field | type | |
68
+ | --- | --- | --- |
69
+ | `resolveConflicts` | `boolean` | reconcile two edits of one file, keeping the loser as a renamed copy. Off, the resolver is not even constructed |
70
+ | `onConflict` | `(reports) => void` | called as conflicts are resolved; without it they are resolved silently |
71
+ | `joinWaitMs` | `number` | how long a folder with files and no history waits for the network before speaking. `0` means "this folder is its own origin" |
72
+ | `bucketSync` | `boolean` | repair a divergence by comparing manifests instead of replacing a folder |
73
+ | `antiEntropy` | `AntiEntropyOptions` | the periodic comparison that heals a lost announcement |
74
+ | `syncConfig` | `SyncConfig` | forwarded to every `Connector`. Without `causalOrdering` the wire carries no predecessors and no conflicting edit can be merged |
75
+ | `clientIdentity` | `ClientIdentity` | who this machine is, on the wire |
76
+ | `timeouts` | `TimeoutConfig` | every async step is bounded; see below |
77
+ | `logName` | `string` | tags this agent's log lines. Four agents in one process produced three identical lines with nothing saying who |
78
+ | `ignore` | `string[]` | patterns not to sync; globs supported |
79
+ | `followSymlinks` | `boolean` | |
80
+ | `settleMs` / `settleMinBytes` | `number` | how long a large file must stop growing before it is hashed |
81
+
82
+ ### `interface TimeoutConfig`
83
+
84
+ Every field optional; defaults shown.
85
+
86
+ ```ts
87
+ { dbQuery: 10_000, fetchTree: 20_000, extract: 15_000, restore: 15_000,
88
+ syncCallback: 25_000, debounceMs: 300, processRefRetries: 3,
89
+ processRefRetryDelayMs: 5_000, recoveryRetries: 10 }
90
+ ```
91
+
92
+ ### `interface RestoreOptions`
93
+
94
+ `cleanTarget` deletes anything the incoming tree does not contain. **The sync
95
+ never sets it.** Read
96
+ [README.public.md](README.public.md#restoreoptionscleantarget--read-this-before-setting-it)
97
+ before you do.
98
+
99
+ ---
100
+
101
+ ## Observability
102
+
103
+ | member | type | |
104
+ | --- | --- | --- |
105
+ | `agent.antiEntropyStatus` | `AntiEntropyStatus \| null` | whether this machine agrees with the hub, since when, and what it last did |
106
+ | `agent.refusedDeletions` | `readonly RefusedDeletion[]` | deletions the mass-delete guard refused, newest last |
107
+ | `agent.stageTimings` | `Record<string, number>` | milliseconds per stage of the **last** cycle. A total says a run was slow; this says where |
108
+ | `agent.scanner.onChange(cb)` | `() => void` | every filesystem event the scanner accepted |
109
+ | `SYNC_ERROR_FILE` | `'.sync-errors.log'` | keyed, append-only record of every refusal and failure |
110
+ | `REFUSED_DELETION_LOG_MAX` | `20` | how many refusals `refusedDeletions` keeps |
111
+
112
+ ### `interface RefusedDeletion`
113
+
114
+ ```ts
115
+ { atMs: number;
116
+ route: 'restore' | 'bucketSync' | 'removals';
117
+ wouldRemove: number;
118
+ held: number;
119
+ paths: readonly string[]; }
120
+ ```
121
+
122
+ The guard refuses on **every** machine, so a deliberate mass deletion stalls the
123
+ whole fleet and the only other trace is a line in each machine's log — which a
124
+ UI on another machine cannot read. `route` matches the sync-error key. `paths`
125
+ holds the first ten, which is enough to name the folder and ask the user.
126
+
127
+ ### `interface AntiEntropyStatus`
128
+
129
+ `diverged`, `divergedSince`, `hubRef`, `localRef`, `differingPaths`, `repairs`,
130
+ `lastRepair`.
131
+
132
+ `diverged` is a **latch** — a difference has persisted long enough to repair.
133
+ `differingPaths` is what a content comparison actually found. They can disagree,
134
+ and the known case is in
135
+ [README.public.md § Known constraints](README.public.md#known-constraints).
136
+
137
+ ---
138
+
139
+ ## The edit chain
140
+
141
+ `src/fs-edit-chain.ts` — the history every decision is made from.
142
+
143
+ ### `class FsEditChain`
144
+
145
+ ```ts
146
+ new FsEditChain(db: Db, treeKey: string)
147
+ ```
148
+
149
+ | member | returns | |
150
+ | --- | --- | --- |
151
+ | `init()` | `Promise<void>` | create the tables if absent, load the head |
152
+ | `head` | `string \| undefined` | this node's current head |
153
+ | `ready` | `boolean` | whether the chain can be used |
154
+ | `append(opts)` | `Promise<FsChainEntry>` | write one Edit |
155
+ | `entry(head)` | `Promise<FsChainEntry \| undefined>` | read an Edit by its address |
156
+ | `entryForTreeRef(treeRef)` | `Promise<FsChainEntry \| undefined>` | the newest Edit that landed on a state. **Ambiguous by nature** — a folder returning to earlier content produces a second Edit with the same tree ref — which is why `~H~` is the primary and this is the fallback |
157
+ | `oldestEntryForTreeRef(treeRef)` | `Promise<FsChainEntry \| undefined>` | the other end of that ambiguity |
158
+ | `refreshHead()` | `Promise<string \| undefined>` | re-read the tip from the table |
159
+ | `classify(ourHead, theirHead)` | `Promise<Reachability>` | `behind` · `ahead` · `fork` · `incomplete` |
160
+ | `lastEditOf(head, path, maxWalk?)` | `Promise<FsChainEntry \| undefined>` | the newest Edit mentioning a path, in `changed` **or** `removed`. Nearest to the head wins; ties break on `timeId` |
161
+ | `collectRemovals(...)` | `Promise<…>` | the removals stated between two points |
162
+
163
+ Supporting types: `FsAppendOptions` (`{ treeRef, changed?, removed?, previous? }`
164
+ — what `append` takes), `FsEditData` (`{ treeRef, changed, removed }` — what is
165
+ stored inside the Edit row), `RemovalQuestion` (what `planRemovals` is asked:
166
+ the sender's `removed`, its `timeId`, what this node holds, `localTimeIds` and
167
+ `chainTimeIds`), and `FS_EDIT_ACTION`, the action name every Edit row carries.
168
+
169
+ ### `interface FsChainEntry`
170
+
171
+ ```ts
172
+ { head: string; timeId: string; treeRef: string;
173
+ previous: string[]; changed: string[]; removed: string[]; }
174
+ ```
175
+
176
+ `changed` does not distinguish an addition from a modification. `removed` is
177
+ separate because only a removal needs an author.
178
+
179
+ ### `compareTimeId(a, b): number`
180
+
181
+ Total order over `<millis>:<nanoid>`, computed identically on every machine.
182
+ Minted once by the author of a change, never re-stamped by a receiver.
183
+
184
+ ### `planRemovals(question): RemovalPlan`
185
+
186
+ Given a sender's stated removals and what this node knows, which to apply,
187
+ which to refuse as stale, and which are a mass deletion. Takes `localTimeIds`
188
+ and `chainTimeIds` — a path this node authored, and a path only the chain can
189
+ speak for.
190
+
191
+ ### `createFsChainTables(db, treeKey)`
192
+
193
+ Idempotent. **The agent creates its own tables**, so a host one release behind
194
+ cannot break it.
195
+
196
+ ---
197
+
198
+ ## Bucket sync (the wire)
199
+
200
+ `src/fs-bucket-sync.ts` — a four-message round that repairs a divergence
201
+ additively.
202
+
203
+ | | |
204
+ | --- | --- |
205
+ | `BQ` `BR` `BG` `BE` | the four prefixes: ask roots, reply roots, ask entries, reply entries |
206
+ | `BUCKET_SYNC_PREFIXES` | all four |
207
+ | `isBucketSync(ref)` | is this a control message rather than a state |
208
+ | `encodeRoots` / `decodeRoots` | roots message |
209
+ | `encodeWanted` / `decodeWanted` | which buckets differ |
210
+ | `encodeEntries` / `decodeEntries` | the entries in those buckets |
211
+ | `class FsBucketSync` | `start()`, `receive(ref)` |
212
+ | `interface BucketSyncHost` | what the agent supplies: `manifest()`, `claimed()`, `editTimes()`, `apply(plan)`, `ready()`, `send(ref)`, `agreed()` |
213
+
214
+ Bodies are JSON because a POSIX filename may contain any byte except `/` and
215
+ NUL. A control message **names no tree**, which is why it must never reach the
216
+ anti-entropy as if it were a state.
217
+
218
+ ---
219
+
220
+ ## The manifest (reconciliation)
221
+
222
+ `src/fs-manifest.ts` — what two folders compare, and what they conclude.
223
+
224
+ ### `type ManifestEntry`
225
+
226
+ ```ts
227
+ readonly [path: string, blobId: string, claimed?: 0 | 1, editedAt?: string]
228
+ ```
229
+
230
+ `claimed` says **who** edited; `editedAt` says **when** — the `timeId` of the
231
+ newest Edit for that path, so a tombstone can be ordered against the write it
232
+ claims to supersede. Absent means "the sender did not say", and the rules that
233
+ predate the field decide. Neither is part of `digestOf`: bucket roots must
234
+ depend on content alone, or a node sees differences that are not there.
235
+
236
+ ### `reconcile(ours, theirs, claimed?): ReconcilePlan`
237
+
238
+ `{ fetch, drop, redelete, conflict }`. Both sides compute it from the same two
239
+ inputs and reach the same verdict, which is what convergence requires.
240
+
241
+ A tombstone older than our write is refused; our tombstone older than their
242
+ write makes us fetch. Without the second half each side holds its position for
243
+ ever.
244
+
245
+ | | |
246
+ | --- | --- |
247
+ | `BUCKET_COUNT` · `bucketOf(path)` | how paths are divided |
248
+ | `bucketRoots(manifest)` · `differingBuckets(a, b)` · `BucketRoots` | O(differences), not O(size) |
249
+ | `entriesInBuckets(manifest, buckets, claimed?, editTimes?)` | the entries for an exchange |
250
+ | `TOMBSTONE_BLOB` | a deletion travels as an **entry**, not an absence |
251
+
252
+ ---
253
+
254
+ ## Anti-entropy
255
+
256
+ `src/fs-anti-entropy.ts` — healing when no announcement arrives.
257
+
258
+ | | |
259
+ | --- | --- |
260
+ | `class FsAntiEntropy` | `observe(hub)`, `agreedOn(ref)`, `status`, `dispose()` |
261
+ | `antiEntropyDecision(hub, view, attempt?)` | `in-sync` · `unknown` · `blocked` · `pull` · `push` · `merge` |
262
+ | `DEFAULT_ANTI_ENTROPY` | the tuning a production fleet runs |
263
+ | `type Reachability` | `behind` · `ahead` · `fork` · `incomplete` |
264
+ | `interface HubAnnouncement` | `{ ref, origin?, predecessors?, reachability? }` |
265
+ | `interface AntiEntropyView` | what the agent reports about itself: `origin`, `currentRef`, `lastAppliedRef`, `lastPushedRef`, `reachability?` |
266
+ | `interface AntiEntropyDeps` | what the agent supplies: `view()`, `busy()`, `sameContent?()`, `repair()`, `now?()`, `log?()` |
267
+ | `type AntiEntropyAction` | `pull` · `push` · `merge` — what a repair does |
268
+ | `type AntiEntropyDecision` | an `AntiEntropyAction`, or `in-sync` · `unknown` · `blocked` |
269
+
270
+ `antiEntropyDecision` switches on `reachability` **before** any heuristic, and
271
+ `blocked` is a real answer: nothing applied, nothing latched, retried.
272
+
273
+ ---
274
+
275
+ ## Conflicts
276
+
277
+ `src/fs-conflict-resolver.ts` — two people edited one file.
278
+
279
+ | | |
280
+ | --- | --- |
281
+ | `class FsConflictResolver` | `resolve(conflict)` |
282
+ | `threeWayMerge(o, ours, theirs, winnerSide, loserClientId, loserTimestamp, winnerFor?)` | the merge table. `winnerFor` is the **per-path chain verdict**, which outranks the branch order |
283
+ | `findCommonAncestor(...)` | the `o` of the three |
284
+ | `compareTips(...)` · `decideWinner(...)` | branch order, used only where the chain cannot speak |
285
+ | `conflictCopyName(...)` · `formatConflictTimestamp(...)` | the losing version's name |
286
+ | `fsTreeToContentMap(tree)` · `ContentMap` · `DIR_MARKER` | |
287
+ | `MergePlan` · `ConflictCopy` · `BranchTip` | the plan, a renamed loser, and one side of a fork |
288
+ | `interface ConflictResolverDeps` | what the agent supplies: the history readers, `writeFileAt`, `deleteFileAt`, `scan`, `storeMerge`, `lastEditOfPath`, and the `announce` the merge revision needs — **required**, because the merge store suppresses the connector's own broadcast |
289
+
290
+ **The loser's bytes are never dropped** — they become a renamed copy, which is
291
+ why either verdict is safe.
292
+
293
+ ---
294
+
295
+ ## Scanner, adapters, utilities
296
+
297
+ | module | exports |
298
+ | --- | --- |
299
+ | `fs-scanner.ts` | `FsScanner`, `FsTree`, `FsNodeMeta`, `FsChange`, `FsChangeType`, `FsChangeCallback`, `FsScanOptions` |
300
+ | `fs-blob-adapter.ts` | `FsBlobAdapter`, `FileBlobMeta`, `FileToBlobOptions`, `BlobToFileOptions` |
301
+ | `fs-db-adapter.ts` | `FsDbAdapter`, `StoreFsTreeOptions` |
302
+ | `fs-atomic-write.ts` | `atomicWriteFile`, `atomicWriteStream`, `atomicTmpPath`, `ATOMIC_TMP_PREFIX` |
303
+ | `fs-ignore.ts` | `compileIgnore`, `globToRegExp`, `IgnoreMatcher` |
304
+ | `client-server/client-server-setup.ts` | `runClientServerSetup`, `ClientServerSetupOptions`, `ClientServerSetupResult` |
305
+
306
+ **Write through `fs-atomic-write`, always.** Three copies of "write a file"
307
+ existed and two of them corrupted content: `writeFile` truncates then writes, so
308
+ two concurrent writes of one path interleave as truncate, truncate, write, write
309
+ and produce bytes nobody wrote. Measured at 1520 blended pairs in 2000.
310
+
311
+ ---
312
+
313
+ ## Further reading
314
+
315
+ | | |
316
+ | --- | --- |
317
+ | [README.public.md](README.public.md) | install, production configuration, what each option costs, troubleshooting |
318
+ | [README.architecture.md](README.architecture.md) | the mechanism, and why each rule exists |
319
+ | [README.tests.md](README.tests.md) | what the suite proves, and what it cannot |