@rljson/fs-agent 0.0.85 → 0.2.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,383 @@
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 what it is for. **46 exports.**
12
+
13
+ Most consumers need only the first section. The rest is exported because a host
14
+ builds on it — a scanner to watch a folder, the chain to show a history, an
15
+ atomic write to touch a synced folder safely — not because a caller is expected
16
+ to reach for every part.
17
+
18
+ | if you want | read |
19
+ | --- | --- |
20
+ | to sync a folder | [The agent](#the-agent) |
21
+ | to know what the agent did | [Signals](#signals) · [Observability](#observability) |
22
+ | the history itself | [The edit chain](#the-edit-chain) |
23
+ | to scan, store or restore a folder yourself | [Scanner and adapters](#scanner-and-adapters) |
24
+ | to write into a synced folder | [Utilities](#utilities) |
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 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**: an agent with a bare
40
+ `BsMem` can store its own blobs and never fetch a peer's. For a synced folder
41
+ pass `client.bs`, or use `FsAgent.fromClient`, which wires this correctly.
42
+
43
+ | member | returns | what it does |
44
+ | --- | --- | --- |
45
+ | `static fromClient(rootPath, treeKey, client, socket, options?)` | `Promise<FsAgent & …>` | the production path: takes `client.io`/`client.bs` and a `Connector` with the sync config the fleet needs; adds `syncToDbSimple()` and `syncFromDbSimple()` |
46
+ | `syncToDb(db, connector, treeKey)` | `Promise<() => void>` | **sending.** Watches the folder, authors an entry per change, announces its head. Returns `stop()` |
47
+ | `syncFromDb(db, connector, treeKey)` | `Promise<() => void>` | **receiving.** Hears the heads the network says and applies, adopts, announces or merges. Returns `stop()` |
48
+ | `ownHead` | `string \| undefined` | the chain entry this folder stands on; persisted in `.fsagent-state.json` |
49
+ | `dispose()` | `void` | releases the watcher and abandons a pending join |
50
+ | `extract()` | `Promise<FsTree>` | scans the folder into a tree, without storing or announcing it |
51
+ | `restore(tree, targetPath?, options?)` | `Promise<void>` | writes a tree to disk. See [`RestoreOptions`](#interface-restoreoptions) |
52
+ | `storeInDb(db, treeKey, options?)` | `Promise<string>` | scans and stores, returning the tree ref |
53
+ | `loadFromDb(db, treeKey, rootRef, targetPath?, options?)` | `Promise<void>` | fetches a tree by ref and writes it out |
54
+ | `getTree()` | `FsTree \| null` | the last scanned tree |
55
+ | `hasBlob(blobId)` · `getFileContent(blobId)` | `Promise<boolean>` · `Promise<Buffer>` | the blob store, as this agent sees it |
56
+ | `rootPath` · `bs` · `scanner` · `adapter` · `timeouts` | | what the agent was built with |
57
+
58
+ Both `sync*` methods return a `stop()`. Stopping the receive side also clears
59
+ `antiEntropyStatus`, unless a newer receive side replaced it.
60
+
61
+ ### `interface FsAgentOptions`
62
+
63
+ Everything optional. [README.public.md](README.public.md#configuration) says
64
+ what each one costs; this is the shape.
65
+
66
+ | field | type | |
67
+ | --- | --- | --- |
68
+ | `joinWaitMs` | `number` | how long a folder with files and no history waits for the network's head before it becomes the origin of its own. `0` means at once |
69
+ | `syncConfig` | `SyncConfig` | forwarded to the `Connector` `fromClient` builds. `includeClientIdentity` lets the hub tell a re-announcement from an echo |
70
+ | `clientIdentity` | `ClientId` | who this machine is on the wire |
71
+ | `onSignal` | `(signal: FsSignal) => void` | the [signal](#signals) channel, from the constructor |
72
+ | `timeouts` | [`TimeoutConfig`](#interface-timeoutconfig) | every async step is bounded |
73
+ | `logName` | `string` | tags this agent's log lines |
74
+ | `ignore` | `string[]` | patterns not to sync; globs, see [`compileIgnore`](#compileignorepatterns) |
75
+ | `maxDepth` · `followSymlinks` · `scanCachePath` | | forwarded to the [`FsScanner`](#class-fsscanner) |
76
+
77
+ ### `interface TimeoutConfig`
78
+
79
+ Every field optional; defaults shown.
80
+
81
+ ```ts
82
+ { dbQuery: 10_000, fetchTree: 20_000, extract: 15_000, restore: 15_000,
83
+ debounceMs: 300 }
84
+ ```
85
+
86
+ `restore` bounds every apply: the sending and receiving sides share one lock, so
87
+ an apply that hung on a blob nobody serves would keep the folder's own work from
88
+ being authored. `debounceMs` coalesces a burst of filesystem events into one
89
+ edit.
90
+
91
+ ### `interface RestoreOptions`
92
+
93
+ `cleanTarget` deletes anything the tree does not contain. **The sync never sets
94
+ it**: an apply deletes only what a descending head removed. Read
95
+ [README.public.md](README.public.md#restoreoptionscleantarget--read-this-before-setting-it)
96
+ before you do.
97
+
98
+ ### `SYNC_ERROR_FILE`
99
+
100
+ `'.sync-errors.log'` — the keyed, append-only record of internal failures, in
101
+ the synced folder and never synced. A refusal is a [signal](#signals), not an
102
+ error.
103
+
104
+ ---
105
+
106
+ ## Signals
107
+
108
+ **The channel a host application should read.** It reports everything a person
109
+ might care about, through one type, and is the only surface that says whether
110
+ somebody still has to act.
111
+
112
+ | member | type | |
113
+ | --- | --- | --- |
114
+ | `agent.signals` | `readonly FsSignal[]` | everything signalled, oldest first; seeded from disk on first read |
115
+ | `agent.signalsNeedingAction` | `readonly FsSignal[]` | only `action: 'required'` — the list a UI should surface |
116
+ | `agent.signalTotals` | `Record<string, number>` | how many of each kind ever happened, dropped ones included |
117
+ | `agent.onSignal(cb)` | `() => void` | subscribe; returns an unsubscribe |
118
+
119
+ ### `class FsSignals`
120
+
121
+ The sink itself: bounded, countable, subscribable, and no I/O. Exported because
122
+ a host aggregating several agents can own one and feed it from each `onSignal`.
123
+
124
+ ### `interface FsSignal`
125
+
126
+ | field | type | |
127
+ | --- | --- | --- |
128
+ | `kind` | `FsSignalKind` | what happened |
129
+ | `at` | `number` | epoch ms |
130
+ | `paths` | `readonly string[]` | affected paths, sorted, at most `SIGNAL_PATHS_MAX` |
131
+ | `pathCount` | `number` | how many were affected, which may exceed `paths.length` |
132
+ | `action` | `FsSignalAction` | whether a person has to do something |
133
+ | `decidedBy` | `FsSignalDecidedBy` | who chose the outcome |
134
+ | `copyPath` | `string` | where the version that lost the path was kept |
135
+ | `detail` | `string` | one sentence for a person; never a stack trace |
136
+
137
+ ### `type FsSignalKind`
138
+
139
+ | `kind` | `action` | what it means |
140
+ | --- | --- | --- |
141
+ | `conflict/arbitrary` | `review` | two machines changed one file at once, or one deleted what the other edited. Both versions were kept (`copyPath`), or the edit was; which keeps the name follows the order the fleet heard them in |
142
+ | `collision/type` | **`required`** | a directory and a file at one path: the directory keeps it, the file is at `copyPath` |
143
+ | `deletion/refused` | **`required`** | a deletion beyond the guard's floors was not made — not authored at the sender, not applied at a receiver |
144
+ | `join/recovered` | `review` | a joining machine moved files the history had removed into `.fsagent-recovered/` |
145
+ | `join/conflicted` | `review` | a joining machine kept its own version of a path beside the network's |
146
+ | `repair/blocked` | `review` | nothing could be decided — a history that cannot be read, or a stamp the hub never sent. Retried |
147
+ | `path/unwritable` | **`required`** | a path this filesystem rejects. It will not arrive until renamed |
148
+
149
+ ### `type FsSignalAction`
150
+
151
+ `'none' | 'review' | 'required'`. `review`: the agent dealt with it and a person
152
+ may want to know. `required`: nothing in this package will resolve it.
153
+
154
+ ### `type FsSignalDecidedBy`
155
+
156
+ `'chain' | 'stamp' | 'guard'` — the edit chain (which edit came after which),
157
+ the hub's stamps (which version reached the fleet later), or a guard that
158
+ refused, so nothing was chosen. None of them compares two machines' clocks.
159
+
160
+ ### `type FsSignalInput`
161
+
162
+ What a producer passes before the sink stamps `at` and counts `paths`.
163
+
164
+ ### `type FsSignalLog`
165
+
166
+ The persisted shape: `{ signals, totals }`.
167
+
168
+ ### `SIGNAL_LOG_FILE`
169
+
170
+ `'.fsagent-signals.json'` — where the log persists, inside the synced folder.
171
+
172
+ ### `SIGNAL_LOG_MAX`
173
+
174
+ `200` signals kept. The per-kind totals are not bounded.
175
+
176
+ ### `SIGNAL_PATHS_MAX`
177
+
178
+ `20` paths named by one signal before it only counts them.
179
+
180
+ ### `SIGNAL_ONCE_MAX`
181
+
182
+ `500` distinct "report once" keys remembered.
183
+
184
+ ---
185
+
186
+ ## Observability
187
+
188
+ | member | type | |
189
+ | --- | --- | --- |
190
+ | `agent.antiEntropyStatus` | `AntiEntropyStatus \| null` | what the last head the hub said made this node do |
191
+ | `agent.stageTimings` | `Record<string, number>` | milliseconds per stage of the last cycle: `push.scan`, `push.announce`, and the `apply.*` stages |
192
+ | `agent.scanner.onChange(cb)` | `() => void` | every filesystem event the scanner accepted |
193
+
194
+ ### `interface AntiEntropyStatus`
195
+
196
+ | field | |
197
+ | --- | --- |
198
+ | `diverged` | whether this node's head was not the hub's after receiving it |
199
+ | `divergedSince` | since when, epoch ms by this node's clock |
200
+ | `hubRef` | the head the hub said last |
201
+ | `localRef` | this node's head now |
202
+ | `repairs` | how often the hub's head made this node act |
203
+ | `lastRepair` | `{ action: 'pull' \| 'push' \| 'merge' \| 'blocked', at, hubRef, localRef, attempt }` — `attempt` counts how often in a row the same hub head made it act |
204
+
205
+ ---
206
+
207
+ ## The edit chain
208
+
209
+ `src/fs-edit-chain.ts` — the history every decision is made from.
210
+
211
+ ### `class FsEditChain`
212
+
213
+ ```ts
214
+ new FsEditChain(db: Db, treeKey: string)
215
+ ```
216
+
217
+ | member | returns | |
218
+ | --- | --- | --- |
219
+ | `init()` | `Promise<void>` | creates the tables if absent |
220
+ | `append(opts)` | `Promise<FsChainEntry>` | writes one entry |
221
+ | `entry(head)` | `Promise<FsChainEntry \| undefined>` | reads one back; `undefined` when no peer can resolve it |
222
+ | `relate(ours, theirs, maxWalk?)` | `Promise<{ verdict, base? }>` | `same` · `behind` · `ahead` · `fork` (with the `base` to merge against) · `incomplete` |
223
+ | `lastEditOf(head, path, maxWalk?)` | `Promise<FsChainEntry \| undefined>` | the nearest entry that changed or removed a path |
224
+ | `collectRemovals(head, ourHead, maxWalk?)` | `Promise<{ removed, changed, complete }>` | the net delta between a head and a state this node knows |
225
+
226
+ ### `interface FsChainEntry`
227
+
228
+ ```ts
229
+ { head: string; timeId: string; treeRef: string;
230
+ previous: string[]; changed: string[]; removed: string[]; }
231
+ ```
232
+
233
+ ### `interface FsAppendOptions`
234
+
235
+ `{ treeRef, previous, changed?, removed?, timeId? }`. `previous` is required: the
236
+ agent says what every entry was made from. `timeId` is passed for an entry that
237
+ must be a function of its content — a merge — and minted otherwise; a root's is
238
+ derived from its tree.
239
+
240
+ ### `interface FsEditData`
241
+
242
+ `{ treeRef, changed, removed }` — what is stored inside the edit row.
243
+
244
+ ### `FS_EDIT_ACTION`
245
+
246
+ The action name every edit row carries.
247
+
248
+ ### `createFsChainTables(db, treeKey)`
249
+
250
+ Creates the three chain tables. Idempotent, so the agent creates its own and a
251
+ host one release behind cannot break it.
252
+
253
+ ---
254
+
255
+ ## Scanner and adapters
256
+
257
+ ### `class FsScanner`
258
+
259
+ Scans and watches a folder. `scan()` reads it into an `FsTree`; `scanFresh()`
260
+ returns a pass that started after the call, sharing one with anyone else asking
261
+ meanwhile — what a caller that acts on the folder must use. `watch()`,
262
+ `stopWatch()`, `pauseWatch()`, `onChange(cb)`, `knownFile(path)`.
263
+
264
+ ### `interface FsScanOptions`
265
+
266
+ `ignore`, `maxDepth`, `followSymlinks`, `scanCachePath`, `settleMs`, `bs`.
267
+
268
+ ### `interface FsTree`
269
+
270
+ `{ rootHash, trees }` — the RLJSON tree of a folder, by node hash.
271
+
272
+ ### `interface FsNodeMeta`
273
+
274
+ What a tree node says about its path: `name`, `type`, `relativePath`, and for a
275
+ file `blobId` and `size`.
276
+
277
+ ### `interface FsChange`
278
+
279
+ `{ type, path }` — one event the scanner accepted.
280
+
281
+ ### `type FsChangeType`
282
+
283
+ `'added' | 'modified' | 'deleted' | 'safety-rescan'`.
284
+
285
+ ### `type FsChangeCallback`
286
+
287
+ `(change: FsChange) => void | Promise<void>`.
288
+
289
+ ### `class FsBlobAdapter`
290
+
291
+ Moves file content between the folder and a blob store: `fileToBlob` and
292
+ `blobToFile`, streaming large files.
293
+
294
+ ### `interface FileBlobMeta`
295
+
296
+ What a stored blob says about the file it came from.
297
+
298
+ ### `interface FileToBlobOptions`
299
+
300
+ How a file is read into the blob store.
301
+
302
+ ### `interface BlobToFileOptions`
303
+
304
+ How a blob is written out; `preserveMtime`.
305
+
306
+ ### `class FsDbAdapter`
307
+
308
+ Stores an `FsTree` in a `Db` and reads it back: `storeFsTree(tree, options?)`
309
+ returns the tree ref.
310
+
311
+ ### `interface StoreFsTreeOptions`
312
+
313
+ `skipNotification` — store without the `Connector` announcing the insert. The
314
+ agent announces chain heads itself.
315
+
316
+ ---
317
+
318
+ ## Utilities
319
+
320
+ **Write into a synced folder through `fs-atomic-write`, always.** `writeFile`
321
+ truncates and then writes, so two concurrent writes of one path interleave and
322
+ produce bytes nobody wrote — measured at 1 520 blended pairs in 2 000.
323
+
324
+ ### `atomicWriteFile(path, content)`
325
+
326
+ Writes to a temporary file beside the target and renames it into place.
327
+
328
+ ### `atomicWriteStream(path, stream)`
329
+
330
+ The same, from a stream.
331
+
332
+ ### `atomicTmpPath(path)`
333
+
334
+ The temporary path `atomicWriteFile` uses for `path`.
335
+
336
+ ### `ATOMIC_TMP_PREFIX`
337
+
338
+ `'.fsagent-tmp-'` — the prefix of those temporary files, which the scanner
339
+ ignores.
340
+
341
+ ### `compileIgnore(patterns)`
342
+
343
+ Compiles ignore patterns into a matcher once: globs (`*`, `?`, `**`, folders
344
+ with `/`, `!` exceptions with last-match-wins), case-insensitive. A pattern with
345
+ no glob characters keeps its old prefix meaning — `~$`, `.~lock.` and
346
+ `ATOMIC_TMP_PREFIX` depend on it.
347
+
348
+ ### `globToRegExp(pattern)`
349
+
350
+ One glob as a regular expression.
351
+
352
+ ### `interface IgnoreMatcher`
353
+
354
+ `{ ignores(relativePath, isDirectory?): boolean }` — `isDirectory` when known,
355
+ because a directory-only pattern needs it.
356
+
357
+ ---
358
+
359
+ ## Client-server
360
+
361
+ ### `runClientServerSetup(options?)`
362
+
363
+ Builds a hub and two clients over socket pairs, syncs a folder from one to the
364
+ other, and returns where it all is — a demo of the whole loop, and a smoke test.
365
+
366
+ ### `interface ClientServerSetupOptions`
367
+
368
+ `{ baseDir?, treeKey? }` — where the two folders go, and the tree table.
369
+
370
+ ### `interface ClientServerSetupResult`
371
+
372
+ `{ baseDir, folderA, folderB, contentB, cleanup }` — the two folders, what
373
+ arrived in the second, and `cleanup()`.
374
+
375
+ ---
376
+
377
+ ## Further reading
378
+
379
+ | | |
380
+ | --- | --- |
381
+ | [README.public.md](README.public.md) | install, production configuration, what each option costs, troubleshooting |
382
+ | [README.architecture.md](README.architecture.md) | the mechanism, and why each rule exists |
383
+ | [README.tests.md](README.tests.md) | what the suite proves, and what it cannot |