@rljson/fs-agent 0.1.0 → 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.
@@ -8,20 +8,20 @@ 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. **46 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) |
21
+ | to know what the agent did | [Signals](#signals) · [Observability](#observability) |
22
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) |
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
25
  | the design behind any of it | [README.architecture.md](README.architecture.md) |
26
26
 
27
27
  ---
@@ -30,54 +30,49 @@ because every caller is expected to reach for them.
30
30
 
31
31
  ### `class FsAgent`
32
32
 
33
- One folder, one agent. Construct it, then start one or both directions.
33
+ One folder, one agent. Construct it, then start both directions.
34
34
 
35
35
  ```ts
36
36
  new FsAgent(rootPath: string, bs?: Bs, options?: FsAgentOptions)
37
37
  ```
38
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.
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.
43
42
 
44
43
  | member | returns | what it does |
45
44
  | --- | --- | --- |
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.
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
60
 
61
61
  ### `interface FsAgentOptions`
62
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.
63
+ Everything optional. [README.public.md](README.public.md#configuration) says
64
+ what each one costs; this is the shape.
66
65
 
67
66
  | field | type | |
68
67
  | --- | --- | --- |
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 |
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) |
81
76
 
82
77
  ### `interface TimeoutConfig`
83
78
 
@@ -85,54 +80,127 @@ Every field optional; defaults shown.
85
80
 
86
81
  ```ts
87
82
  { 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 }
83
+ debounceMs: 300 }
90
84
  ```
91
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
+
92
91
  ### `interface RestoreOptions`
93
92
 
94
- `cleanTarget` deletes anything the incoming tree does not contain. **The sync
95
- never sets it.** Read
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
96
95
  [README.public.md](README.public.md#restoreoptionscleantarget--read-this-before-setting-it)
97
96
  before you do.
98
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
+
99
104
  ---
100
105
 
101
- ## Observability
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.
102
111
 
103
112
  | member | type | |
104
113
  | --- | --- | --- |
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 |
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 |
111
118
 
112
- ### `interface RefusedDeletion`
119
+ ### `class FsSignals`
113
120
 
114
- ```ts
115
- { atMs: number;
116
- route: 'restore' | 'bucketSync' | 'removals';
117
- wouldRemove: number;
118
- held: number;
119
- paths: readonly string[]; }
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`.
121
123
 
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.
124
+ ### `interface FsSignal`
126
125
 
127
- ### `interface AntiEntropyStatus`
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 }`.
128
167
 
129
- `diverged`, `divergedSince`, `hubRef`, `localRef`, `differingPaths`, `repairs`,
130
- `lastRepair`.
168
+ ### `SIGNAL_LOG_FILE`
131
169
 
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).
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 |
136
204
 
137
205
  ---
138
206
 
@@ -148,23 +216,12 @@ new FsEditChain(db: Db, treeKey: string)
148
216
 
149
217
  | member | returns | |
150
218
  | --- | --- | --- |
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.
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 |
168
225
 
169
226
  ### `interface FsChainEntry`
170
227
 
@@ -173,140 +230,147 @@ the sender's `removed`, its `timeId`, what this node holds, `localTimeIds` and
173
230
  previous: string[]; changed: string[]; removed: string[]; }
174
231
  ```
175
232
 
176
- `changed` does not distinguish an addition from a modification. `removed` is
177
- separate because only a removal needs an author.
233
+ ### `interface FsAppendOptions`
178
234
 
179
- ### `compareTimeId(a, b): number`
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.
180
239
 
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.
240
+ ### `interface FsEditData`
183
241
 
184
- ### `planRemovals(question): RemovalPlan`
242
+ `{ treeRef, changed, removed }` — what is stored inside the edit row.
185
243
 
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.
244
+ ### `FS_EDIT_ACTION`
245
+
246
+ The action name every edit row carries.
190
247
 
191
248
  ### `createFsChainTables(db, treeKey)`
192
249
 
193
- Idempotent. **The agent creates its own tables**, so a host one release behind
194
- cannot break it.
250
+ Creates the three chain tables. Idempotent, so the agent creates its own and a
251
+ host one release behind cannot break it.
195
252
 
196
253
  ---
197
254
 
198
- ## Bucket sync (the wire)
255
+ ## Scanner and adapters
199
256
 
200
- `src/fs-bucket-sync.ts` — a four-message round that repairs a divergence
201
- additively.
257
+ ### `class FsScanner`
202
258
 
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.
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)`.
217
263
 
218
- ---
264
+ ### `interface FsScanOptions`
219
265
 
220
- ## The manifest (reconciliation)
266
+ `ignore`, `maxDepth`, `followSymlinks`, `scanCachePath`, `settleMs`, `bs`.
221
267
 
222
- `src/fs-manifest.ts` — what two folders compare, and what they conclude.
268
+ ### `interface FsTree`
223
269
 
224
- ### `type ManifestEntry`
270
+ `{ rootHash, trees }` — the RLJSON tree of a folder, by node hash.
225
271
 
226
- ```ts
227
- readonly [path: string, blobId: string, claimed?: 0 | 1, editedAt?: string]
228
- ```
272
+ ### `interface FsNodeMeta`
229
273
 
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.
274
+ What a tree node says about its path: `name`, `type`, `relativePath`, and for a
275
+ file `blobId` and `size`.
235
276
 
236
- ### `reconcile(ours, theirs, claimed?): ReconcilePlan`
277
+ ### `interface FsChange`
237
278
 
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.
279
+ `{ type, path }` — one event the scanner accepted.
240
280
 
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.
281
+ ### `type FsChangeType`
244
282
 
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 |
283
+ `'added' | 'modified' | 'deleted' | 'safety-rescan'`.
251
284
 
252
- ---
285
+ ### `type FsChangeCallback`
253
286
 
254
- ## Anti-entropy
287
+ `(change: FsChange) => void | Promise<void>`.
255
288
 
256
- `src/fs-anti-entropy.ts` — healing when no announcement arrives.
289
+ ### `class FsBlobAdapter`
257
290
 
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.
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.
272
315
 
273
316
  ---
274
317
 
275
- ## Conflicts
318
+ ## Utilities
276
319
 
277
- `src/fs-conflict-resolver.ts` — two people edited one file.
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.
278
323
 
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.
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.
292
356
 
293
357
  ---
294
358
 
295
- ## Scanner, adapters, utilities
359
+ ## Client-server
296
360
 
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.
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()`.
310
374
 
311
375
  ---
312
376