@rljson/fs-agent 0.1.0 → 0.2.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.
@@ -8,20 +8,21 @@ found in the LICENSE file in the root of this package.
8
8
 
9
9
  # @rljson/fs-agent — API reference
10
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.**
11
+ Every symbol the package exports, grouped by what it is for. **63 exports.**
13
12
 
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.
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
17
 
18
18
  | if you want | read |
19
19
  | --- | --- |
20
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) |
21
+ | to know what the agent did | [Signals](#signals) · [Observability](#observability) |
22
+ | to show a folder's history, or go back to a revision | [The history](#the-history) |
23
+ | the chain underneath | [The edit chain](#the-edit-chain) |
24
+ | to scan, store or restore a folder yourself | [Scanner and adapters](#scanner-and-adapters) |
25
+ | to write into a synced folder | [Utilities](#utilities) |
25
26
  | the design behind any of it | [README.architecture.md](README.architecture.md) |
26
27
 
27
28
  ---
@@ -30,54 +31,53 @@ because every caller is expected to reach for them.
30
31
 
31
32
  ### `class FsAgent`
32
33
 
33
- One folder, one agent. Construct it, then start one or both directions.
34
+ One folder, one agent. Construct it, then start both directions.
34
35
 
35
36
  ```ts
36
37
  new FsAgent(rootPath: string, bs?: Bs, options?: FsAgentOptions)
37
38
  ```
38
39
 
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.
40
+ `bs` defaults to a fresh `BsMem`, which is **local only**: an agent with a bare
41
+ `BsMem` can store its own blobs and never fetch a peer's. For a synced folder
42
+ pass `client.bs`, or use `FsAgent.fromClient`, which wires this correctly.
43
43
 
44
44
  | member | returns | what it does |
45
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.
46
+ | `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()` |
47
+ | `syncToDb(db, connector, treeKey)` | `Promise<() => void>` | **sending.** Watches the folder, authors an entry per change, announces its head. Returns `stop()` |
48
+ | `syncFromDb(db, connector, treeKey)` | `Promise<() => void>` | **receiving.** Hears the heads the network says and applies, adopts, announces or merges. Returns `stop()` |
49
+ | `ownHead` | `string \| undefined` | the chain entry this folder stands on; persisted in `.fsagent-state.json` |
50
+ | `headInfo()` | `Promise<FsHistoryEntry \| undefined>` | that entry as the history lists it — what it changed, when, and its stamp. See [The history](#the-history) |
51
+ | `history(options?)` | `Promise<FsHistoryPage>` | one page of the folder's history, newest first |
52
+ | `relationTo(head)` | `Promise<Relation \| undefined>` | how this folder's head stands to another: `same`, `behind`, `ahead`, `fork` or `incomplete` |
53
+ | `restoreRevision(head)` | `Promise<'restored' \| 'unknown' \| 'busy'>` | makes the folder exactly that revision, as a new edit every node follows |
54
+ | `dispose()` | `void` | releases the watcher and abandons a pending join |
55
+ | `extract()` | `Promise<FsTree>` | scans the folder into a tree, without storing or announcing it |
56
+ | `restore(tree, targetPath?, options?)` | `Promise<void>` | writes a tree to disk. See [`RestoreOptions`](#interface-restoreoptions) and [the restore errors](#restore-errors) |
57
+ | `storeInDb(db, treeKey, options?)` | `Promise<string>` | scans and stores, returning the tree ref |
58
+ | `loadFromDb(db, treeKey, rootRef, targetPath?, options?)` | `Promise<void>` | fetches a tree by ref and writes it out |
59
+ | `getTree()` | `FsTree \| null` | the last scanned tree |
60
+ | `hasBlob(blobId)` · `getFileContent(blobId)` | `Promise<boolean>` · `Promise<Buffer>` | the blob store, as this agent sees it |
61
+ | `rootPath` · `bs` · `scanner` · `adapter` · `timeouts` | | what the agent was built with |
62
+
63
+ Both `sync*` methods return a `stop()`. Stopping the receive side also clears
64
+ `antiEntropyStatus`, unless a newer receive side replaced it.
60
65
 
61
66
  ### `interface FsAgentOptions`
62
67
 
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.
68
+ Everything optional. [README.public.md](README.public.md#configuration) says
69
+ what each one costs; this is the shape.
66
70
 
67
71
  | field | type | |
68
72
  | --- | --- | --- |
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 |
73
+ | `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 |
74
+ | `syncConfig` | `SyncConfig` | forwarded to the `Connector` `fromClient` builds. `includeClientIdentity` lets the hub tell a re-announcement from an echo |
75
+ | `clientIdentity` | `ClientId` | who this machine is on the wire |
76
+ | `onSignal` | `(signal: FsSignal) => void` | the [signal](#signals) channel, from the constructor |
77
+ | `timeouts` | [`TimeoutConfig`](#interface-timeoutconfig) | every async step is bounded |
78
+ | `logName` | `string` | tags this agent's log lines |
79
+ | `ignore` | `string[]` | patterns not to sync; globs, see [`compileIgnore`](#compileignorepatterns) |
80
+ | `maxDepth` · `followSymlinks` · `scanCachePath` | | forwarded to the [`FsScanner`](#class-fsscanner) |
81
81
 
82
82
  ### `interface TimeoutConfig`
83
83
 
@@ -85,54 +85,240 @@ Every field optional; defaults shown.
85
85
 
86
86
  ```ts
87
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 }
88
+ debounceMs: 300 }
90
89
  ```
91
90
 
91
+ `restore` bounds every apply: the sending and receiving sides share one lock, so
92
+ an apply that hung on a blob nobody serves would keep the folder's own work from
93
+ being authored. `debounceMs` coalesces a burst of filesystem events into one
94
+ edit.
95
+
92
96
  ### `interface RestoreOptions`
93
97
 
94
- `cleanTarget` deletes anything the incoming tree does not contain. **The sync
95
- never sets it.** Read
98
+ `cleanTarget` deletes anything the tree does not contain. **The sync never sets
99
+ it**: an apply deletes only what a descending head removed. Read
96
100
  [README.public.md](README.public.md#restoreoptionscleantarget--read-this-before-setting-it)
97
101
  before you do.
98
102
 
103
+ ### `SYNC_ERROR_FILE`
104
+
105
+ `'.sync-errors.log'` — the keyed, append-only record of internal failures, in
106
+ the synced folder and never synced. A refusal is a [signal](#signals), not an
107
+ error.
108
+
99
109
  ---
100
110
 
101
- ## Observability
111
+ ## Signals
112
+
113
+ **The channel a host application should read.** It reports everything a person
114
+ might care about, through one type, and is the only surface that says whether
115
+ somebody still has to act.
102
116
 
103
117
  | member | type | |
104
118
  | --- | --- | --- |
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 |
119
+ | `agent.signals` | `readonly FsSignal[]` | everything signalled, oldest first; seeded from disk on first read |
120
+ | `agent.signalsNeedingAction` | `readonly FsSignal[]` | only `action: 'required'` — the list a UI should surface |
121
+ | `agent.signalTotals` | `Record<string, number>` | how many of each kind ever happened, dropped ones included |
122
+ | `agent.onSignal(cb)` | `() => void` | subscribe; returns an unsubscribe |
123
+
124
+ ### `class FsSignals`
125
+
126
+ The sink itself: bounded, countable, subscribable, and no I/O. Exported because
127
+ a host aggregating several agents can own one and feed it from each `onSignal`.
128
+
129
+ ### `interface FsSignal`
130
+
131
+ | field | type | |
132
+ | --- | --- | --- |
133
+ | `id` | `string` | the signal's identity: a hash of what it says, unique within the log, the same on every read. Key a row by it, or remember by it what a person has seen |
134
+ | `kind` | `FsSignalKind` | what happened |
135
+ | `at` | `number` | epoch ms |
136
+ | `paths` | `readonly string[]` | affected paths, sorted, at most `SIGNAL_PATHS_MAX` |
137
+ | `pathCount` | `number` | how many were affected, which may exceed `paths.length` |
138
+ | `action` | `FsSignalAction` | whether a person has to do something |
139
+ | `decidedBy` | `FsSignalDecidedBy` | who chose the outcome |
140
+ | `copyPath` | `string` | where the version that lost the path was kept |
141
+ | `copies` | `Record<string, string>` | for a join: where each named path's own version went, original → copy. A path the join could not move has none |
142
+ | `head` | `string` | the chain entry the signal belongs to — for a merge conflict, the merge, which `history()` lists |
143
+ | `detail` | `string` | one sentence for a person; never a stack trace |
144
+
145
+ ### `type FsSignalKind`
146
+
147
+ | `kind` | `action` | what it means |
148
+ | --- | --- | --- |
149
+ | `conflict/arbitrary` | `review` | two machines changed one file at once, or one deleted what the other edited. Both versions were kept (`copyPath`, `decidedBy: 'stamp'`): which keeps the name follows the order the fleet heard them in. Or the edit was (no `copyPath`, `decidedBy: 'chain'`): an edit beats a deletion by rule |
150
+ | `collision/type` | **`required`** | a directory and a file at one path: the directory keeps it, the file is at `copyPath` |
151
+ | `deletion/refused` | **`required`** | a deletion beyond the guard's floors was not made — not authored at the sender, not applied at a receiver |
152
+ | `join/recovered` | `review` | a joining machine moved files the history had removed into `.fsagent-recovered/` |
153
+ | `join/conflicted` | `review` | a joining machine kept its own version of a path beside the network's |
154
+ | `repair/blocked` | `review` | nothing could be decided — a history that cannot be read, or a stamp the hub never sent. Retried |
155
+ | `path/unwritable` | **`required`** | a path this filesystem rejects. It will not arrive until renamed |
156
+
157
+ ### `type FsSignalAction`
158
+
159
+ `'none' | 'review' | 'required'`. `review`: the agent dealt with it and a person
160
+ may want to know. `required`: nothing in this package will resolve it.
161
+
162
+ ### `type FsSignalDecidedBy`
163
+
164
+ `'chain' | 'stamp' | 'guard'` — the edit chain (which edit came after which),
165
+ the hub's stamps (which version reached the fleet later), or a guard that
166
+ refused, so nothing was chosen. None of them compares two machines' clocks.
167
+
168
+ ### `type FsSignalInput`
169
+
170
+ What a producer passes before the sink stamps `at`, derives `id` and counts
171
+ `paths`.
172
+
173
+ ### `type FsSignalLog`
174
+
175
+ The persisted shape: `{ signals, totals }`.
176
+
177
+ ### `SIGNAL_LOG_FILE`
178
+
179
+ `'.fsagent-signals.json'` — where the log persists, inside the synced folder.
180
+
181
+ ### `SIGNAL_LOG_MAX`
182
+
183
+ `200` signals kept. The per-kind totals are not bounded.
184
+
185
+ ### `SIGNAL_PATHS_MAX`
186
+
187
+ `20` paths named by one signal before it only counts them.
188
+
189
+ ### `SIGNAL_ONCE_MAX`
190
+
191
+ `500` distinct "report once" keys remembered.
111
192
 
112
- ### `interface RefusedDeletion`
193
+ ---
194
+
195
+ ## The history
196
+
197
+ **What a host shows about a folder's past, and how it goes back.** Read from
198
+ the edit chain, the one order every node agrees on — not from a node's own
199
+ insert rows, which miss every state it took from a peer.
200
+
201
+ | member | |
202
+ | --- | --- |
203
+ | `agent.headInfo()` | where the folder stands, as one `FsHistoryEntry` |
204
+ | `agent.history(options?)` | one page, newest first, from the own head or `options.from` |
205
+ | `agent.relationTo(head)` | how the own head stands to another |
206
+ | `agent.restoreRevision(head)` | goes back to a revision, exactly |
207
+ | `readFsHistory(db, treeKey, options)` | the same pages from a store this process does not own |
208
+
209
+ **The order.** Newest first by stamp — the announcement that first carried an
210
+ entry to the fleet; an entry not stamped yet first of all — then, within one
211
+ announcement, by the authoring node's time. Never an entry above one made on
212
+ top of it. A page continues exactly where the last stopped:
113
213
 
114
214
  ```ts
115
- { atMs: number;
116
- route: 'restore' | 'bucketSync' | 'removals';
117
- wouldRemove: number;
118
- held: number;
119
- paths: readonly string[]; }
215
+ let page = await agent.history({ limit: 50 });
216
+ show(page.entries);
217
+ while (page.cursor) {
218
+ page = await agent.history({ cursor: page.cursor });
219
+ show(page.entries);
220
+ }
221
+ if (page.missing.length > 0) say('older history is not on this machine');
120
222
  ```
121
223
 
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.
224
+ **Going back.** `restoreRevision(head)` makes the folder exactly that
225
+ revision: what it holds is written, what it lacks is deleted, and the result is
226
+ authored as a new edit, so every node follows and the revision being left stays
227
+ in the history. Work not yet recorded is recorded first, and a file still being
228
+ written is waited out. It returns `unknown` for an entry this node cannot read,
229
+ and `busy` when a file is still being written after the wait. It rejects with a
230
+ `MassDeleteRefusedError` when the revision would delete a large part of the
231
+ folder. In all three cases the folder is unchanged.
126
232
 
127
- ### `interface AntiEntropyStatus`
233
+ ### `interface FsHistoryEntry`
234
+
235
+ An `FsChainEntry` (`head`, `timeId`, `treeRef`, `previous`, `changed`,
236
+ `removed`) and:
237
+
238
+ | field | type | |
239
+ | --- | --- | --- |
240
+ | `kind` | `'edit' \| 'merge' \| 'root'` | a change one node made; two lineages joined (`previous` names both); where a lineage began |
241
+ | `at` | `number` | when the authoring node made the edit, epoch ms by **its** clock. Absent for a merge and a root, which carry no time |
242
+ | `stamp` | `RefStamp` | the announcement that first carried it to the fleet, as this node learned it — the order no clock decides. Absent until this node learned it |
243
+
244
+ Two entries with one `treeRef` hold the same files — a restore, or two merges
245
+ of one fork.
246
+
247
+ ### `interface FsHistoryOptions`
248
+
249
+ `from` — the entry to start from (the agent defaults it to its own head);
250
+ `cursor` — the previous page's, which wins over `from`; `limit` — entries per
251
+ page, default `FS_HISTORY_PAGE` (50), at most 500.
252
+
253
+ ### `interface FsHistoryPage`
128
254
 
129
- `diverged`, `divergedSince`, `hubRef`, `localRef`, `differingPaths`, `repairs`,
130
- `lastRepair`.
255
+ `entries`, newest first; `cursor`, absent when nothing is left (opaque — pass it
256
+ back as it came); `missing`, entries named as a `previous` that this node cannot
257
+ read, below which nothing can be listed.
131
258
 
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).
259
+ ### `readFsHistory(db, treeKey, options)`
260
+
261
+ The history from a database this process does not own — the store of an agent
262
+ running in another process, opened read-only. Writes nothing: no table is
263
+ created, and stamps are absent when their table is.
264
+
265
+ ### `walkFsHistory(source, options)` · `interface FsHistorySource`
266
+
267
+ The walk underneath both, over any source that can read an entry
268
+ (`entry(head)`) and its stamp (`stamp(head)`).
269
+
270
+ ### `readFsStamps(db, treeKey)`
271
+
272
+ Every stamp a route's entries carry, read without writing: `Map<entry, RefStamp>`.
273
+
274
+ ### `FS_HISTORY_PAGE`
275
+
276
+ `50` — a page's size when the caller does not say.
277
+
278
+ ### `type Relation`
279
+
280
+ `{ verdict: 'same' | 'behind' | 'ahead' | 'incomplete' }` or
281
+ `{ verdict: 'fork'; base }`. `incomplete`: an entry could not be read, so a
282
+ fork cannot be told from a lag. Two different heads can hold the same files;
283
+ compare their tree refs for that.
284
+
285
+ ### `type ReceiveOutcome`
286
+
287
+ What receiving one head made a node do: `no-head`, `in-sync`, `applied`,
288
+ `refused`, `announced`, `adopted`, `merged`, `deferred` or `blocked`.
289
+
290
+ ### Restore errors
291
+
292
+ A restore that could not finish rejects with a `RestoreIncompleteError`:
293
+
294
+ | class | |
295
+ | --- | --- |
296
+ | `MassDeleteRefusedError` | the prune would delete a large part of the folder (`wouldPrune`, `totalFiles`, `incomingFiles`). Judged before anything is written: the folder is unchanged |
297
+ | `PartialRestoreError` | files another process holds open; everything else was written |
298
+ | `BlobUnavailableError` | content no reachable store serves yet |
299
+ | `UnwritablePathError` | a path this filesystem rejects |
300
+ | `DiskFullError` | no space left |
301
+
302
+ ---
303
+
304
+ ## Observability
305
+
306
+ | member | type | |
307
+ | --- | --- | --- |
308
+ | `agent.antiEntropyStatus` | `AntiEntropyStatus \| null` | what the last head the hub said made this node do |
309
+ | `agent.stageTimings` | `Record<string, number>` | milliseconds per stage of the last cycle: `push.scan`, `push.announce`, and the `apply.*` stages |
310
+ | `agent.scanner.onChange(cb)` | `() => void` | every filesystem event the scanner accepted |
311
+
312
+ ### `interface AntiEntropyStatus`
313
+
314
+ | field | |
315
+ | --- | --- |
316
+ | `diverged` | whether this node's head was not the hub's after receiving it |
317
+ | `divergedSince` | since when, epoch ms by this node's clock |
318
+ | `hubRef` | the head the hub said last |
319
+ | `localRef` | this node's head now |
320
+ | `repairs` | how often the hub's head made this node act |
321
+ | `lastRepair` | `{ action: 'pull' \| 'push' \| 'merge' \| 'blocked', at, hubRef, localRef, attempt }` — `attempt` counts how often in a row the same hub head made it act |
136
322
 
137
323
  ---
138
324
 
@@ -148,23 +334,12 @@ new FsEditChain(db: Db, treeKey: string)
148
334
 
149
335
  | member | returns | |
150
336
  | --- | --- | --- |
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.
337
+ | `init()` | `Promise<void>` | creates the tables if absent |
338
+ | `append(opts)` | `Promise<FsChainEntry>` | writes one entry |
339
+ | `entry(head)` | `Promise<FsChainEntry \| undefined>` | reads one back; `undefined` when no peer can resolve it |
340
+ | `relate(ours, theirs, maxWalk?)` | `Promise<{ verdict, base? }>` | `same` · `behind` · `ahead` · `fork` (with the `base` to merge against) · `incomplete` |
341
+ | `lastEditOf(head, path, maxWalk?)` | `Promise<FsChainEntry \| undefined>` | the nearest entry that changed or removed a path |
342
+ | `collectRemovals(head, ourHead, maxWalk?)` | `Promise<{ removed, changed, complete }>` | the net delta between a head and a state this node knows |
168
343
 
169
344
  ### `interface FsChainEntry`
170
345
 
@@ -173,140 +348,152 @@ the sender's `removed`, its `timeId`, what this node holds, `localTimeIds` and
173
348
  previous: string[]; changed: string[]; removed: string[]; }
174
349
  ```
175
350
 
176
- `changed` does not distinguish an addition from a modification. `removed` is
177
- separate because only a removal needs an author.
351
+ ### `interface FsAppendOptions`
352
+
353
+ `{ treeRef, previous, changed?, removed?, timeId? }`. `previous` is required: the
354
+ agent says what every entry was made from. `timeId` is passed for an entry that
355
+ must be a function of its content — a merge — and minted otherwise; a root's is
356
+ derived from its tree.
178
357
 
179
- ### `compareTimeId(a, b): number`
358
+ ### `interface FsEditData`
180
359
 
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.
360
+ `{ treeRef, changed, removed }` — what is stored inside the edit row.
183
361
 
184
- ### `planRemovals(question): RemovalPlan`
362
+ ### `FS_EDIT_ACTION`
185
363
 
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.
364
+ The action name every edit row carries.
190
365
 
191
366
  ### `createFsChainTables(db, treeKey)`
192
367
 
193
- Idempotent. **The agent creates its own tables**, so a host one release behind
194
- cannot break it.
368
+ Creates the three chain tables. Idempotent, so the agent creates its own and a
369
+ host one release behind cannot break it.
195
370
 
196
371
  ---
197
372
 
198
- ## Bucket sync (the wire)
373
+ ## Scanner and adapters
199
374
 
200
- `src/fs-bucket-sync.ts` — a four-message round that repairs a divergence
201
- additively.
375
+ ### `class FsScanner`
202
376
 
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.
377
+ Scans and watches a folder. `scan()` reads it into an `FsTree`; `scanFresh()`
378
+ returns a pass that started after the call, sharing one with anyone else asking
379
+ meanwhile — what a caller that acts on the folder must use. `watch()`,
380
+ `stopWatch()`, `pauseWatch()`, `onChange(cb)`, `knownFile(path)`.
217
381
 
218
- ---
382
+ ### `interface FsScanOptions`
219
383
 
220
- ## The manifest (reconciliation)
384
+ `ignore`, `maxDepth`, `followSymlinks`, `scanCachePath`, `settleMs`, `bs`.
221
385
 
222
- `src/fs-manifest.ts` — what two folders compare, and what they conclude.
386
+ ### `interface FsTree`
223
387
 
224
- ### `type ManifestEntry`
388
+ `{ rootHash, trees }` — the RLJSON tree of a folder, by node hash.
225
389
 
226
- ```ts
227
- readonly [path: string, blobId: string, claimed?: 0 | 1, editedAt?: string]
228
- ```
390
+ ### `interface FsNodeMeta`
229
391
 
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.
392
+ What a tree node says about its path: `name`, `type`, `relativePath`, and for a
393
+ file `blobId` and `size`.
235
394
 
236
- ### `reconcile(ours, theirs, claimed?): ReconcilePlan`
395
+ ### `interface FsChange`
237
396
 
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.
397
+ `{ type, path }` — one event the scanner accepted.
240
398
 
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.
399
+ ### `type FsChangeType`
244
400
 
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 |
401
+ `'added' | 'modified' | 'deleted' | 'safety-rescan'`.
251
402
 
252
- ---
403
+ ### `type FsChangeCallback`
253
404
 
254
- ## Anti-entropy
405
+ `(change: FsChange) => void | Promise<void>`.
255
406
 
256
- `src/fs-anti-entropy.ts` — healing when no announcement arrives.
407
+ ### `class FsBlobAdapter`
257
408
 
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.
409
+ Moves file content between the folder and a blob store: `fileToBlob` and
410
+ `blobToFile`, streaming large files.
411
+
412
+ ### `interface FileBlobMeta`
413
+
414
+ What a stored blob says about the file it came from.
415
+
416
+ ### `interface FileToBlobOptions`
417
+
418
+ How a file is read into the blob store.
419
+
420
+ ### `interface BlobToFileOptions`
421
+
422
+ How a blob is written out; `preserveMtime`.
423
+
424
+ ### `class FsDbAdapter`
425
+
426
+ Stores an `FsTree` in a `Db` and reads it back: `storeFsTree(tree, options?)`
427
+ returns the tree ref.
428
+
429
+ ### `interface StoreFsTreeOptions`
430
+
431
+ `skipNotification` — store without the `Connector` announcing the insert. The
432
+ agent announces chain heads itself.
272
433
 
273
434
  ---
274
435
 
275
- ## Conflicts
436
+ ## Utilities
276
437
 
277
- `src/fs-conflict-resolver.ts` — two people edited one file.
438
+ **Write into a synced folder through `fs-atomic-write`, always.** `writeFile`
439
+ truncates and then writes, so two concurrent writes of one path interleave and
440
+ produce bytes nobody wrote — measured at 1 520 blended pairs in 2 000.
278
441
 
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.
442
+ ### `atomicWriteFile(path, content)`
443
+
444
+ Writes to a temporary file beside the target and renames it into place.
445
+
446
+ ### `atomicWriteFileSync(path, content)`
447
+
448
+ The same, synchronously — for a small file that must be on disk before the
449
+ caller returns. The agent writes its signal log and state file through it.
450
+
451
+ ### `atomicWriteStream(path, stream)`
452
+
453
+ The same, from a stream.
454
+
455
+ ### `atomicTmpPath(path)`
456
+
457
+ The temporary path `atomicWriteFile` uses for `path`.
458
+
459
+ ### `ATOMIC_TMP_PREFIX`
460
+
461
+ `'.fsagent-tmp-'` — the prefix of those temporary files, which the scanner
462
+ ignores.
463
+
464
+ ### `compileIgnore(patterns)`
465
+
466
+ Compiles ignore patterns into a matcher once: globs (`*`, `?`, `**`, folders
467
+ with `/`, `!` exceptions with last-match-wins), case-insensitive. A pattern with
468
+ no glob characters keeps its old prefix meaning — `~$`, `.~lock.` and
469
+ `ATOMIC_TMP_PREFIX` depend on it.
470
+
471
+ ### `globToRegExp(pattern)`
472
+
473
+ One glob as a regular expression.
474
+
475
+ ### `interface IgnoreMatcher`
476
+
477
+ `{ ignores(relativePath, isDirectory?): boolean }` — `isDirectory` when known,
478
+ because a directory-only pattern needs it.
292
479
 
293
480
  ---
294
481
 
295
- ## Scanner, adapters, utilities
482
+ ## Client-server
296
483
 
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.
484
+ ### `runClientServerSetup(options?)`
485
+
486
+ Builds a hub and two clients over socket pairs, syncs a folder from one to the
487
+ other, and returns where it all is — a demo of the whole loop, and a smoke test.
488
+
489
+ ### `interface ClientServerSetupOptions`
490
+
491
+ `{ baseDir?, treeKey? }` — where the two folders go, and the tree table.
492
+
493
+ ### `interface ClientServerSetupResult`
494
+
495
+ `{ baseDir, folderA, folderB, contentB, cleanup }` — the two folders, what
496
+ arrived in the second, and `cleanup()`.
310
497
 
311
498
  ---
312
499