@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.
@@ -8,6 +8,69 @@ found in the LICENSE file in the root of this package.
8
8
 
9
9
  # Architecture
10
10
 
11
+ How `@rljson/fs-agent` keeps a folder the same on several machines, and why it
12
+ is built the way it is. For the API and the options, read
13
+ [README.public.md](README.public.md); for what is proven and how, read
14
+ [README.tests.md](README.tests.md).
15
+
16
+ ## The design in one page
17
+
18
+ **There is no master copy.** Every machine watches its own folder and announces
19
+ what changed. A hub relays and never arbitrates — it holds no opinion about what
20
+ the folder should contain. A decision therefore has to be reachable, identically,
21
+ on every machine, from data every machine has.
22
+
23
+ **A folder is a tree, identified by its content.** The scanner produces an RLJSON
24
+ tree whose ref is a content hash. Two machines holding the same bytes compute the
25
+ same ref — which needs a canonical child order, and mtime *outside* the identity.
26
+
27
+ **A change is an entry in one shared chain, and the chain is the only order.**
28
+ An entry records what changed, what was removed, and which entries it was made
29
+ from. It is written only where the change was made and adopted — never
30
+ re-authored — by a receiver. **The filesystem is an event source only**: the
31
+ watcher says something happened; what it means is answered from the chain.
32
+
33
+ **An absence is not a deletion.** A tree lacks a path because its author removed
34
+ it or because its author never had it, and a content hash cannot tell them
35
+ apart. So a deletion is applied for exactly one reason: the head that lacks the
36
+ file **descends from this node's own** — its author held this state and chose not
37
+ to have the file. Everywhere else an absence reaches the folder only through a
38
+ three-way merge, where the common ancestor says what each side did.
39
+
40
+ **Two concurrent versions are ordered by the hub, not by clocks.** When two
41
+ machines change one file at once, both versions are kept, and the one that
42
+ reached the fleet later keeps the name — later by the hub's **stamp** on the
43
+ announcement that carried it. No machine's clock is compared to another's,
44
+ anywhere.
45
+
46
+ **What is transferred is a decision, not a payload.** A machine announces the
47
+ address of an entry. A receiver resolves it and fetches only the tree rows and
48
+ blobs it is missing, so its cost is proportional to what changed rather than to
49
+ how long it was away.
50
+
51
+ **Everything is bounded.** Every async step has a timeout, every growing
52
+ structure has a cap, and every walk has a budget — an unbounded step is a silent
53
+ hang and an unbounded list is tomorrow's memory ceiling.
54
+
55
+ ## How to read this document
56
+
57
+ | if you want | read |
58
+ | --- | --- |
59
+ | why refs rather than payloads | [Pull-Based Reference Architecture](#pull-based-reference-architecture) |
60
+ | the rules that must not be broken | [Architectural Rules](#architectural-rules-do-not-violate) |
61
+ | a change's journey, end to end | [The sync, end to end](#the-sync-end-to-end) |
62
+ | what happens when two machines edit at once | [The conflict table](#the-conflict-table) |
63
+ | which version keeps the name, and why | [The stamp](#the-stamp) |
64
+ | why a big deletion is refused, and how a wiped machine is refilled | [Guards](#guards) |
65
+ | what a joining machine does | [Joining a network](#joining-a-network-planjoin) |
66
+ | who is recorded as having changed a file | [Authorship](#authorship-a-node-claims-only-what-it-changed) |
67
+ | the history itself | [Edit Chain](#edit-chain-srcfs-edit-chaints) |
68
+ | what a host application is told | [One channel for everything](#one-channel-for-everything-that-happened-srcfs-signalsts) |
69
+ | why a half-written file does not go out | [A Copy in Progress](#a-copy-in-progress-does-not-reach-the-wire-fsscanner-the-settle-rule) |
70
+ | which files are skipped | [Ignore Matching](#ignore-matching-srcfs-ignorets) |
71
+ | what 0.2.0 removed | [Removed in 0.2.0](#removed-in-020) |
72
+ | the signature of anything named here | [README.api.md](README.api.md) |
73
+
11
74
  ## Pull-Based Reference Architecture
12
75
 
13
76
  ### Why References Are Required
@@ -156,7 +219,7 @@ const connectorB = new Connector(clientDbB, Route.fromFlat('/dataSync'), socketB
156
219
  When a Connector sends a message via `connector.send(ref)`, two things happen:
157
220
 
158
221
  1. **Local Socket Echo**: The connector's own `listen()` callback is immediately triggered because sockets emit to all listeners (standard EventEmitter behavior)
159
- 2. **Server Multicast**: The server receives the message and broadcasts it to OTHER clients (sender is filtered out via `clientIdA !== clientIdB` in `@rljson/server@0.0.4+`)
222
+ 2. **Server Multicast**: The server receives the message and broadcasts it to OTHER clients (the sender is filtered out via `clientIdA !== clientIdB` in `@rljson/server`)
160
223
 
161
224
  ```typescript
162
225
  // This is NORMAL behavior:
@@ -170,9 +233,9 @@ connector.send('my-ref-123');
170
233
  // Output: "Received ref: my-ref-123" ← Local echo happens IMMEDIATELY
171
234
  ```
172
235
 
173
- **Server-Side Filtering (v0.0.4+):**
236
+ **Server-Side Filtering:**
174
237
 
175
- The `@rljson/server` package (v0.0.4 and later) correctly filters out the sender when multicasting:
238
+ `@rljson/server` filters out the sender when multicasting:
176
239
 
177
240
  ```typescript
178
241
  // Inside Server._multicastRefs():
@@ -186,30 +249,10 @@ for (const [clientIdB, { socket: socketB }] of this._clients.entries()) {
186
249
 
187
250
  This means Client A will NOT receive its message back from the server, but it WILL receive it via local socket echo.
188
251
 
189
- **Application-Level Self-Filtering:**
190
-
191
- Because of local socket echo, **application code MUST filter out its own broadcasts** to prevent infinite loops. This is done in FsAgent using the `_lastSentRef` property:
192
-
193
- ```typescript
194
- // In FsAgent:
195
- private _lastSentRef?: string;
196
-
197
- // When sending:
198
- this._lastSentRef = ref;
199
- connector.send(ref);
200
-
201
- // When receiving:
202
- if (treeRef === this._lastSentRef) {
203
- console.log('[syncFromDb] Skipping self-broadcast');
204
- return; // Don't process own message
205
- }
206
- ```
207
-
208
- **Why This Architecture:**
209
- - Socket echo is unavoidable with EventEmitter-based implementations (SocketMock, real sockets)
210
- - Server-side filtering prevents network round-trips but can't prevent local echo
211
- - Application-level filtering is defensive programming and works regardless of socket implementation
212
- - This pattern is necessary for all real-time sync systems
252
+ **What the agent does with its own echo:** nothing special. Its own head
253
+ arriving back is in sync by definition — `receive` authors local work first and
254
+ then finds the head it holds — and the Connector drops a payload carrying its
255
+ own origin before the agent sees it.
213
256
 
214
257
  ### Client-Server Pattern
215
258
 
@@ -288,267 +331,419 @@ await agentB.loadFromDb(serverDb, 'sharedTree', rootRef);
288
331
 
289
332
  **Rationale**: The `Client` class creates an internal `IoMulti` that combines local `Io` with a server peer. By using `client.io`, database operations automatically go through this multi-layer structure, maintaining proper client-server separation. Sharing the server's `Db` directly violates this architecture and bypasses the Client/Server pattern entirely.
290
333
 
291
- ## Data Synchronization Flow (How It Works)
292
-
293
- ### The Peer-to-Peer Architecture with Central Server Coordination
294
-
295
- The fs-agent implements a distributed peer-to-peer synchronization pattern where:
296
-
297
- 1. **Each client stores data locally** in its own `Io` (database) and `Bs` (blob storage)
298
- 2. **References are broadcast** through the server via Connector
299
- 3. **Data is pulled on-demand** when a client needs data it doesn't have
300
- 4. **The server coordinates** but doesn't own the data - it routes requests between clients
301
-
302
- ### Step-by-Step Sync Flow: Client A → Client B
303
-
304
- **Message Routing via Connector:**
305
-
306
- ```
307
- Client A Server Client B
308
- -------- ------ --------
309
-
310
- 1. File changes detected
311
- ↓
312
- 2. FsAgent extracts tree
313
- ↓
314
- 3. connector.send(treeRef)
315
- │
316
- ├─→ Local Socket Echo 6. Server._multicastRefs()
317
- │ (Client A's listener triggered) filters sender
318
- │ ↓
319
- └─→ socket.emit(route, {r: ref}) 7. Checks: clientIdA !== clientIdB
320
- ↓ ↓
321
- Server receives on 8. Broadcasts to OTHER clients
322
- socket.on(route, ...) (Client A excluded)
323
- ↓
324
- socketB.emit(route, {
325
- r: ref,
326
- __origin: clientIdA
327
- })
328
- ↓
329
- → Client B
330
- ↓
331
- 9. Client B's connector
332
- .listen() triggered
333
- ↓
334
- 10. syncFromDb callback
335
- processes ref
336
- ```
337
-
338
- **Key Points:**
339
- - Client A's connector receives its own message via **local socket echo** (step 1 branch)
340
- - FsAgent's `_lastSentRef` filtering prevents processing this echo
341
- - Server receives the message and broadcasts to **all OTHER clients** (step 6-8)
342
- - The `__origin` field prevents infinite forwarding loops in the server
343
- - Client B receives the message and pulls data via IoMulti/BsMulti (see below)
344
-
345
- **Data Pull Flow (when Client B needs data):**
346
-
347
- ```
348
- Client A Server Client B
349
- -------- ------ --------
350
-
351
- 1. File changes detected
352
- ↓
353
- 2. FsAgent extracts tree
354
- ↓
355
- 3. Blobs stored in clientA.bs (local BsMem)
356
- ↓
357
- 4. Tree stored in clientDbA (local IoMem)
358
- via storeInDb()
359
- ↓
360
- 5. connector.send(treeRootRef)
361
- ↓ socket →→→
362
- 6. Server receives ref
363
- ↓
364
- 7. Multicasts to all clients
365
- ↓ socket →→→
366
- 8. connectorB receives ref
367
- ↓
368
- 9. syncFromDb callback triggered
369
- ↓
370
- 10. loadFromDb(treeRef) called
371
- ↓
372
- 11. Query clientDbB for tree data
373
- ↓
374
- 12. clientDbB.io (IoMulti) checks:
375
- - localIoB: NOT FOUND
376
- - IoPeer: Query server
377
- ← socket ←←
378
- 13. Server routes to Client A
379
- ← socket ←←
380
- 14. Client A's Io returns tree data
381
- → socket →→
382
- 15. Data flows back to Server
383
- → socket →→
384
- 16. Tree data arrives at Client B
385
- ↓
386
- 17. Tree data stored in localIoB
387
- ↓
388
- 18. For each file in tree:
389
- clientB.bs.getBlob(blobId)
390
- ↓
391
- 19. clientB.bs (BsMulti) checks:
392
- - localBsB: NOT FOUND
393
- - BsPeer: Query server
394
- ← socket ←←
395
- 20. Server routes to Client A
396
- ← socket ←←
397
- 21. Client A's Bs returns blob
398
- → socket →→
399
- 22. Blob flows back to Server
400
- → socket →→
401
- 23. Blob arrives at Client B
402
- ↓
403
- 24. Blob stored in localBsB
404
- ↓
405
- 25. File written to filesystem
406
- ↓
407
- 26. Sync complete!
408
- ```
409
-
410
- ### Key Architectural Components
411
-
412
- **IoMulti (inside client.io):**
413
-
414
- - Combines local IoMem with IoPeer (server connection)
415
- - When data is requested: first checks local, then queries peer via socket
416
- - Automatically caches retrieved data locally
417
- - Transparent to the application - just use `client.io`
418
-
419
- **BsMulti (inside client.bs):**
420
-
421
- - Combines local BsMem with BsPeer (server connection)
422
- - When blob is requested: first checks local, then queries peer via socket
423
- - Automatically caches retrieved blobs locally
424
- - Transparent to the application - just use `client.bs`
425
-
426
- **Connector:**
427
-
428
- - Broadcasts tree references (not full data) via socket
429
- - Triggers `syncFromDb` callbacks on receiving clients
430
- - Minimal bandwidth - only sends references
431
-
432
- **Server:**
433
-
434
- - Routes data requests between clients
435
- - Maintains connections to all clients via sockets
436
- - Does NOT store client data - purely acts as coordinator/router
437
- - Has its own serverIo and serverBs for server-specific needs only
438
-
439
- ### Why This Architecture Matters
440
-
441
- This peer-to-peer pattern with server coordination enables:
442
-
443
- ✅ **Distributed storage**: Each client owns its data locally
444
- ✅ **Bandwidth efficiency**: Only references broadcast, data pulled on-demand
445
- ✅ **Scalability**: Server doesn't store all client data
446
- ✅ **Offline capability**: Clients can work with locally cached data
447
- ✅ **Real-world deployment**: Works across networks, not just in-memory mocks
448
-
449
- **This is why clients must NEVER access server Io/Bs directly** - it would bypass the entire peer-to-peer mechanism and make the system only work in single-process scenarios.
450
-
451
- ## Bounce-Back Prevention
452
-
453
- Bidirectional sync creates a potential infinite loop:
454
-
455
- ```
456
- Client A writes file → syncToDb stores tree → broadcasts ref →
457
- Client B receives ref → syncFromDb restores file → fs watcher fires →
458
- syncToDb stores tree → broadcasts ref → Client A receives ref → ...
459
- ```
460
-
461
- FsAgent uses three layers of deduplication to break the loop:
462
-
463
- 1. **Ref-level dedup**: After `syncToDb` stores a tree, it compares the
464
- resulting ref against `_lastSentRef`. If identical, no broadcast occurs.
465
-
466
- 2. **Content-key dedup**: Even when refs differ (e.g. different mtimes produce
467
- different hashes), `syncToDb` computes a content key from file paths +
468
- blobIds. If the content key matches `_lastSentContentKey`, the broadcast
469
- is skipped.
470
-
471
- 3. **Content comparison before restore**: In `syncFromDb`, before restoring
472
- an incoming tree, FsAgent compares its file content map against the current
473
- filesystem. If they are equivalent, the restore is skipped entirely,
474
- preventing the filesystem watcher from firing.
475
-
476
- Additionally, all sync callbacks are **debounced** (default 300ms) to coalesce
477
- rapid filesystem events (e.g. multi-file saves, editor autosave) into a single
478
- sync operation.
479
-
480
- ## Anti-Entropy (`src/fs-anti-entropy.ts`)
481
-
482
- Nothing in the message path ever asks whether a message arrived. A lost push is
483
- not resent until the folder changes again; a lost forward is repeated only by
484
- the hub's heartbeat, which the connector drops as a duplicate or delivers as
485
- "not newest". The anti-entropy closes that gap.
486
-
487
- **Trigger.** `syncFromDb` subscribes to two events on the connector's socket
488
- directly — `${route}:bootstrap` and the server's state beacon
489
- `stateBeaconEvent(route)` = `${route}:state` — not through `listen`, whose
490
- dedup is exactly what hides the repeat that would show a disagreement. Each
491
- announcement (`r`, `o`, `p`) goes to `FsAntiEntropy.observe()`.
492
-
493
- The beacon is the signal to run on. The connector does not listen to it, so it
494
- enters no apply path; the bootstrap heartbeat does, which is why the CARAT One
495
- Client runs with it off. The event name comes from `@rljson/db`
496
- (`stateBeaconEvent`), next to the Connector that deliberately ignores it; the
497
- server imports the same function.
498
-
499
- **Decision** (`antiEntropyDecision`, pure):
500
-
501
- 1. `r === _currentRef` → in sync.
502
- 2. `_currentRef === _lastPushedRef` and `o` is our connector's origin →
503
- **push**: the hub holds an earlier push of ours and missed the later one.
504
- 3. `p` contains `_currentRef` or `_lastAppliedRef` → **pull**: we missed the
505
- hub's state.
506
- 4. `_currentRef === _lastPushedRef` and `r === _lastAppliedRef` → **push**:
507
- the hub still holds what our push was made from.
508
- 5. otherwise → **merge**.
509
-
510
- Rule 4 comes AFTER the ancestry check: a peer that deletes what we added can
511
- return the folder to exactly the state we last applied — same hash, but made
512
- from ours. Measured under load: pushing there put the deleted file back on
513
- every node.
514
-
515
- Rule 2 precedes rule 3 because of a collision the hash cannot resolve:
516
- "B deleted the file A created" (hub `S0` made from `S1`, A at `S1`) and "A
517
- deleted its own file and that push was lost" (hub `S1` made from `S0`, A at the
518
- re-derived `S0`) are identical in refs and ancestry. Only the origin of the
519
- hub's state tells them apart, and each wrong answer puts a deleted file back.
520
-
521
- `_lastPushedRef` is set only where the agent authors a state (initial push,
522
- debounced push, merge revision) — never by an apply, which can leave the folder
523
- short of what it applied. Re-announcing such a state would roll peers back.
524
-
525
- **Repair**, only once this node has been out of step with the hub for
526
- `graceMs` **without its own state moving**, and nothing is pending,
527
- processing or applying. The divergence is keyed on `_currentRef` alone: a node
528
- keeping up with the traffic changes its own state with every forward it
529
- applies, while a node that lost a message sits still. Keying on the hub's
530
- state as well restarted the grace period on every change there, so a node
531
- that missed every forward while another machine kept writing was never
532
- repaired (review, ONE-446). The repair answers the latest announcement:
533
-
534
- - push → `_sendRef(connector, _currentRef, [hubRef])`
535
- - pull → `scheduleProcess(hubRef, …, p)` — the ordinary `processRef`
536
- - merge → the same with `p` on the first attempt, then with `[]`, which makes
537
- the apply additive (union), after which the next round pushes it
538
-
539
- Repeated repairs of one divergence back off exponentially up to
540
- `maxBackoffMs`. `processing` covers the pauses between `processRef` retries,
541
- where `_remoteApplyInFlight` is clear.
542
-
543
- **Why not a copy of the mongo anti-entropy.** That one is triggered by noticing
544
- a PEER's root, so a node that receives nothing never starts it, and it applies
545
- a peer tombstone without a recency check. This one is triggered by the hub's
546
- own announcement and never applies anything outside the ordinary rules.
547
-
548
- **Tested by** `test/client-server/heals-after-forced-divergence.spec.ts`: three
549
- clients, a real server with heartbeat, one ref message dropped on purpose per
550
- case — including both halves of the collision above — plus a control run with
551
- the repair off that must stay divergent.
334
+ ## The sync, end to end
335
+
336
+ ### What travels
337
+
338
+ One thing: the **head** of the edit chain — the ref of an `EditHistory` row —
339
+ and, from a hub that stamps, the head's **stamp**. A node announces its head on
340
+ the route whenever it moves; the hub relays it to every other client, stamps it
341
+ on the way, and says its latest head again on the bootstrap a connecting client
342
+ gets and on its state beacon. Nothing else is on the wire for the fs route: no
343
+ tree refs, no file lists, no prefixes.
344
+
345
+ A receiver resolves the head to a row, the row to a tree, the tree to the rows
346
+ and blobs it is missing — by hash, through the peers ([Pull-Based
347
+ Reference Architecture](#pull-based-reference-architecture)).
348
+
349
+ ### Sending: a change becomes an entry
350
+
351
+ The watcher says *something happened*; nothing more. After a debounce the agent
352
+ takes the lock, reads **a pass that began after its own last write** — the
353
+ watcher's last pass when it did, a fresh one (`FsScanner.scanFresh`) when the
354
+ agent has written since, because a pass that overlapped an apply can show it
355
+ half-done — and asks `planAuthoring` (`fs-send.ts`) what the folder did since
356
+ its own head:
357
+
358
+ - **unchanged** — nothing to author;
359
+ - **changed** — the paths written and the paths removed;
360
+ - **refused** — the sender's honesty guard ([Guards](#guards)).
361
+
362
+ A removal is authored only once the path is really gone from disk: a scan can
363
+ lag the disk, and authoring the absence of a file the agent wrote a moment ago
364
+ would delete it everywhere. Then the tree is stored, an entry is appended with
365
+ `previous: [ownHead]`, the head moves, and it is announced.
366
+
367
+ The first state of a folder with no history is its **root**: `previous: []`,
368
+ nothing stated, and a `timeId` derived from the tree (`0:<treeRef>`) — so two
369
+ nodes that start from the same content write the *same* root, and no fleet ever
370
+ begins as one lineage per node. A folder with files and no history first waits
371
+ to be told ([Joining a network](#joining-a-network-planjoin)).
372
+
373
+ ### Receiving: what a node does with a head
374
+
375
+ `receive` (`fs-receive.ts`) is the whole decision:
376
+
377
+ 1. No own head yet → it is a join, not a receive.
378
+ 2. **Author local work first.** Anything the folder holds beyond the own head is
379
+ authored before the arrived head is judged, so a head that never saw that
380
+ work cannot overwrite it — it turns what would have been `behind` into a
381
+ `fork`.
382
+ 3. Relate the two heads (`FsEditChain.relate`) and act:
383
+
384
+ | relation | meaning | action |
385
+ | --- | --- | --- |
386
+ | `same` | the one head | nothing |
387
+ | `behind` | theirs descends from ours | **apply** their tree — write what differs, delete what it lacks — and **adopt** their head |
388
+ | `ahead` | ours descends from theirs | announce ours |
389
+ | `fork`, same tree | one state under two names | every node keeps the **smaller** ref; no merge entry |
390
+ | `fork` | both sides have work | **merge** against the base ([The conflict table](#the-conflict-table)) |
391
+ | `incomplete` | an entry cannot be read and no descent was found | nothing; `repair/blocked`, retried on the next beacon |
392
+
393
+ **Deleting on `behind` is correct by construction.** Whoever made that head held
394
+ this node's state and chose not to have the file. An absence in a tree that does
395
+ *not* descend from ours is never a deletion: it reaches the folder only through
396
+ a merge, where the base says what each side did.
397
+
398
+ An apply touches only what changed between the two heads, and only while the
399
+ folder still holds the own head's version of it. A path the user changed since
400
+ stops the apply; the work is authored, and the head is received again — as a
401
+ fork, which merges.
402
+
403
+ ### Healing: the hub says its head again
404
+
405
+ There is no separate repair mechanism. A lost announcement is healed by the next
406
+ time the hub says its head — the **state beacon** (every 30 s in the host client)
407
+ and the **bootstrap** on connect. A node that hears the hub's head receives it
408
+ like any announcement, and the decision above is the repair: a node that is
409
+ behind applies, a node that is ahead announces, a fork merges.
410
+ `antiEntropyStatus` reports what the last head from the hub made this node do.
411
+
412
+ ### One lock
413
+
414
+ Authoring and receiving take the same lock and never interleave. An apply is
415
+ bounded by `timeouts.restore`: a blob nobody serves would otherwise hold the lock
416
+ that authoring needs too, and the node would go silent about its own work. A
417
+ timed-out apply is not adopted; the lock is released, and the head is tried again
418
+ the next time the hub says it.
419
+
420
+ ## The conflict table
421
+
422
+ A fork is merged path by path against the **base** — the common ancestor
423
+ `relate` names: one that no other common ancestor descends from, the smallest
424
+ ref when there are several, so every node merging the same two heads merges
425
+ against the same base. `merge3` (`fs-merge.ts`) decides each path; nothing
426
+ compares two machines' clocks, and no version is ever dropped:
427
+
428
+ | row | situation | outcome | signal |
429
+ | --- | --- | --- | --- |
430
+ | C1 | one side changed the path | that side's value | — |
431
+ | C2 | different paths, or the same change on both sides | both kept | — |
432
+ | C3 | both changed one file differently | **both kept**: the version whose introducing entry has the higher stamp keeps the name, the other becomes `<name> (conflicted copy <hub>-<n>)<ext>`, named by its own stamp | `conflict/arbitrary` (review) |
433
+ | C4 | one side deleted, the other edited | **the edit stays**; the deletion is reported, not applied | `conflict/arbitrary` (review) |
434
+ | C5 | a directory on one side, a file on the other | **both kept**: the directory keeps the path, the file becomes a conflicted copy | `collision/type` (**required**) |
435
+ | C6 | the history cannot answer | nothing | `repair/blocked` (review) |
436
+
437
+ Only a **concurrent** change is a collision: one side turning a directory into a
438
+ file while the other left the directory and everything in it alone is an
439
+ ordinary C1 edit.
440
+
441
+ **The merge entry** names both heads (`previous`, sorted) and a `timeId` derived
442
+ from them and the merged tree, so two nodes merging the same two heads write the
443
+ *same* entry, and concurrent merges converge rather than fork again. It names as
444
+ changed every path whose merged value differs from either side — which makes it
445
+ the nearest entry to name such a path for `lastEditOf`.
446
+
447
+ Every node that merges says so, one signal per contested path; a node that
448
+ applies somebody else's merge applies it like any `behind` head.
449
+
450
+ ## The stamp
451
+
452
+ ### Who stamps, and how a node learns its own
453
+
454
+ A hub configured with `stamp: { domain, hub }` (`@rljson/server`) gives every
455
+ ref it relays a `RefStamp` — `(domain, epoch, hub, n)`, compared in that order —
456
+ on the payload, in the ref log and on the bootstrap. The hub keeps no stamp
457
+ table: it persists only its epoch (`stateFile`), takes the next one on every
458
+ start — above any epoch it has relayed, and above `minEpoch`, the highest a node
459
+ heard as a client before it took office (the agent records it as `stampEpochs`
460
+ in `.fsagent-state.json`) — and counts `n` within it. **Fan-out
461
+ skips the sender**, so the hub tells the author its stamp on `${route}:stamp`,
462
+ and again when a re-announcement is held back as a duplicate.
463
+
464
+ ### A version's stamp
465
+
466
+ **A version's stamp is the stamp of the announcement that first carried it to
467
+ the fleet** (`FsStamps`, `fs-stamps.ts`). A stamped head arrives; the entries
468
+ below it that no earlier announcement carried — the edits a node made offline,
469
+ say — reached the fleet with it, so they get it too. The walk stops at the first
470
+ entry that already has one; an entry keeps the first stamp it was given. Kept in
471
+ the route's own database (`${treeKey}EditStamps`), because a conflict can be
472
+ about a version introduced long ago.
473
+
474
+ C3 compares the stamps of the two versions' **introducing entries**
475
+ (`lastEditOf`), which makes the verdict a function of the shared history and of
476
+ nothing else: every node that merges the same two versions picks the same name.
477
+
478
+ ### A walk that stops short
479
+
480
+ A walk can stop at a row it cannot read yet, or at its budget. The entry it
481
+ stopped at stays **open** — stamped, its ancestors not yet — and is persisted as
482
+ such. A merge that lacks a stamp resumes the open walks, earliest stamp first,
483
+ so an ancestor two walks reach still gets the earlier announcement's stamp. Not
484
+ on every announcement: an unreadable row can cost a blocked read each time it is
485
+ asked for.
486
+
487
+ ### Waiting for a stamp
488
+
489
+ C3 decides only when both stamps are known. Otherwise the merge is **deferred**
490
+ and nothing changes. A node whose own version lacks a stamp has a head the hub
491
+ never stamped — authored while it was cut off — so it announces its head again:
492
+ at once, then less and less often (`STAMP_ASK_MIN_MS` doubling to
493
+ `STAMP_ASK_MAX_MS`). The first wait is routine; a second wait for the same merge
494
+ is signalled `repair/blocked`, because then the hub does not stamp.
495
+
496
+ ### What the stamp cannot know
497
+
498
+ Two limits of deriving stamps from payloads alone. Neither loses data, and both
499
+ converge:
500
+
501
+ - **A node that missed an announcement derives a later stamp** for the entries
502
+ it carried, from the first announcement it did hear. Its C3 verdict can then
503
+ differ from a peer's; the two merges fork, and merging those — which is
504
+ deterministic — converges with one redundant conflicted copy.
505
+ - **A merge entry is the introducer of what it took from one side**, so a
506
+ version that passed through a merge carries the merge's stamp. In a three-way
507
+ race the name can go to a version whose original edit reached the fleet
508
+ earlier.
509
+
510
+ ## Guards
511
+
512
+ ### At the sender
513
+
514
+ `planAuthoring` refuses an edit when files **disappeared** beyond the floors —
515
+ more than `MASS_DELETE_MIN_FILES` (100) **and** more than `MASS_DELETE_MAX_RATIO`
516
+ (0.3) of the folder, or all but `ALL_GONE_MIN_FILES` (10) of a larger one. A file
517
+ disappeared when it is gone, its content is nowhere else in the folder, and the
518
+ watcher did not see it go. That is the shape of a failed mount or a wiped drive,
519
+ never of a person: nothing is authored, the folder keeps its head, and
520
+ `deletion/refused` (**required**) says why. A deletion the watcher saw, a folder
521
+ renamed while the agent was down, and a few files deleted while it was down are
522
+ all ordinary edits.
523
+
524
+ ### At the receiver
525
+
526
+ An apply that would **lose** more than the same floors — content the target tree
527
+ holds nowhere else — keeps those files. Everything else applies, the head is
528
+ adopted, and the kept files are authored again on top of it. That edit is what
529
+ refills a machine that lost its folder: the fleet does not follow it down, and
530
+ it does not stay empty either. `deletion/refused` (**required**) says what was
531
+ kept.
532
+
533
+ ### An apply that stops partway
534
+
535
+ A locked file or an unreachable blob stops an apply after it wrote some files.
536
+ The head is not adopted. What did land is recorded, path → blob, until the own
537
+ head moves: authoring does not claim it — it is somebody else's work — and the
538
+ next apply recognises it instead of mistaking it for a local edit. A locked
539
+ file's old bytes are never claimed either, since they are what the own head
540
+ already says; so every merge keeps the peer's version of it.
541
+
542
+ ## Joining a network (`planJoin`)
543
+
544
+ A folder with files and no history does not speak first: it waits up to
545
+ `joinWaitMs` (default `DEFAULT_JOIN_WAIT_MS`) for the network's head. With a head
546
+ in hand, `planJoin` puts every path in **at most one** of four lists, deciding
547
+ each against the chain and never against the disk:
548
+
549
+ | list | the path is | action |
550
+ | --- | --- | --- |
551
+ | `write` | in the head, not on disk | write it |
552
+ | `announce` | on disk, never named anywhere in the history | new local work — authored on top of the head |
553
+ | `recover` | on disk, and REMOVED by the history | a stale copy: moved into `.fsagent-recovered/`, nothing said |
554
+ | `conflict` | live on both sides, different bytes | the head's bytes win; the local copy is kept aside as `<name> (conflicted copy <UTC time> local)<ext>` |
555
+
556
+ `recover` is what makes a restored backup safe: nothing is resurrected and
557
+ nothing is destroyed. If no head arrives within the wait, the folder is the
558
+ origin of its own history. An empty head is a fact, not an absence: a fleet that
559
+ agreed the folder is empty states exactly that.
560
+
561
+ ## Authorship: a node claims only what it changed
562
+
563
+ **An edit exists only where the change was made.** A receiver adopts and never
564
+ authors; otherwise a machine catching up records itself as the author of
565
+ somebody else's file, and then — through `lastEditOf` — carries the name in a
566
+ conflict it never took part in. What keeps it true:
567
+
568
+ 1. A `behind` head is **adopted**, never re-authored.
569
+ 2. Local work is authored **before** a head is judged, against the own head.
570
+ 3. Authoring scans **afresh** under the lock, so a pass taken while an apply was
571
+ writing never reads as a local edit.
572
+ 4. What a cut-short apply wrote is not claimed.
573
+ 5. A merge entry is derived from both heads, so it is the same entry wherever it
574
+ is written.
575
+
576
+ **Tested by** `fs-agent-authorship.spec.ts`, `fs-agent-no-laundering.spec.ts`,
577
+ `fs-agent-own-echo.spec.ts` and `fs-agent-locked-file.spec.ts`.
578
+
579
+ ## Edit Chain (`src/fs-edit-chain.ts`)
580
+
581
+ Three tables per tree key — `${treeKey}EditHistory`, `${treeKey}MultiEdits`,
582
+ `${treeKey}Edits` — written by hand rather than through `MultiEditManager`,
583
+ because a merge entry has two parents, which is the one shape it refuses. An
584
+ entry records the tree ref, the paths it changed and removed (sorted, so the same
585
+ change writes the same row on every node), `previous`, and a `timeId`. The agent
586
+ says what every entry is made from: a table several nodes write has no tip of
587
+ its own, and the agent keeps its head in `.fsagent-state.json`.
588
+
589
+ | method | answers |
590
+ | --- | --- |
591
+ | `append` | writes one entry |
592
+ | `entry` | reads one back; `undefined` when no peer can resolve it |
593
+ | `relate` | how two heads stand, and a fork's base |
594
+ | `lastEditOf` | the nearest entry that changed or removed a path — the introducer C3 asks about |
595
+ | `collectRemovals` | the net removals and changes between a head and a state this node knows; what a join uses to tell a stale copy from new work |
596
+
597
+ **A hole and a budget are different truncations.** A walk that meets an entry it
598
+ cannot read answers `incomplete`: the ref it looks for may be inside the part it
599
+ cannot reach. A walk that exhausts `DEFAULT_MAX_WALK` with everything readable
600
+ answers `fork` — less precise than the truth, never destructive. Conflating them
601
+ once made every node 500 pushes into its own history stop healing, silently.
602
+
603
+ `timeId` orders nothing in a decision. It breaks a tie between two entries at
604
+ the same distance in `lastEditOf`, and that is all.
605
+
606
+ ## One folder, one ref — the canonical child order
607
+
608
+ A tree ref is a function of the folder's content: the scanner emits children in
609
+ a canonical (sorted) order, and mtime is outside the identity. Two machines
610
+ holding byte-identical content derive the same ref — which is what lets a fork
611
+ of one state converge on the smaller ref without a merge, and what makes the
612
+ tree ref comparable across machines at all.
613
+
614
+ **Tested by** `test/fs-ref-vs-content.spec.ts`: two scans of equivalent content
615
+ agree on the ref and on the content map the apply and the merge work from.
616
+
617
+ ## One channel for everything that happened (`src/fs-signals.ts`)
618
+
619
+ Everything that touches a user's folder is reported here, and only here: a
620
+ conflict a merge settled, a refused deletion, a joining machine moving files
621
+ aside, a path the filesystem rejected, a divergence nothing could decide. A host
622
+ cannot grep a log on a machine it is not running on.
623
+
624
+ Every signal says **what** happened and to **which paths**, **who decided**
625
+ (`chain`, `stamp` or `guard`), and whether a **person** has to act:
626
+
627
+ | `action` | meaning |
628
+ | --- | --- |
629
+ | `none` | resolved; nothing to do |
630
+ | `review` | resolved, but somebody may want to know — a kept copy, a name decided by the order the fleet heard two versions |
631
+ | `required` | **not** resolved, or a person must decide — a refused deletion, a directory/file collision, a path this filesystem will never accept |
632
+
633
+ `SIGNAL_LOG_MAX` (200) signals are kept; the per-kind counters are not bounded,
634
+ so a folder that produced two thousand refusals still says so. One signal names
635
+ at most `SIGNAL_PATHS_MAX` (20) paths and counts the rest. `addOnce` keys are
636
+ bounded too (`SIGNAL_ONCE_MAX`); `repair/blocked` is keyed on the **pair** of
637
+ heads it is between. The log is persisted to `SIGNAL_LOG_FILE`
638
+ (`.fsagent-signals.json`) inside the synced folder and read back lazily, without
639
+ firing subscribers. `.sync-errors.log` stays the record of internal failures —
640
+ exceptions, which are not signals.
641
+
642
+ ## What grows, and what bounds it
643
+
644
+ | structure | growth | bound |
645
+ | --- | --- | --- |
646
+ | the chain | one entry per authored edit — the debounce coalesces a burst | walks are bounded by `DEFAULT_MAX_WALK` |
647
+ | the stamps (`${treeKey}EditStamps`) | one row per entry heard, two while its walk is open | as the chain |
648
+ | the signal log | one per signal | `SIGNAL_LOG_MAX`, `SIGNAL_ONCE_MAX` |
649
+ | what a cut-short apply wrote | the paths of one apply | cleared when the own head moves |
650
+ | what restore wrote, per path | one per file written | `RESTORED_BLOB_MEMORY_MAX` |
651
+ | receiving a head again after the folder moved | per own head | `RECEIVE_AGAIN_MAX` |
652
+
653
+ ## A Copy in Progress Does Not Reach the Wire (`FsScanner`, the settle rule)
654
+
655
+ A watcher fires while a large file is still being written, and a scan that reads
656
+ it then publishes a truncated file that every peer accepts as the whole thing.
657
+ The scanner therefore defers a file rather than reading it, and the deferral is a
658
+ promise to come back: `_unsettledDuringScan` reuses the previous node for that
659
+ path and arms a follow-up scan, so a deferred file is late and never lost.
660
+
661
+ Three signals defer, and the file waits if any of them fires:
662
+
663
+ | signal | what it catches |
664
+ | --- | --- |
665
+ | `mtime > scanStartedAt` | the file changed **while this scan ran** — free, no window, cannot race |
666
+ | `growing` — the size moved since the last scan | a writer whose gaps are wider than one read |
667
+ | `firstSight` — never read, and either touched inside `settleMs` or seen for the first time | a copy already in progress when the scanner met it |
668
+
669
+ **`firstSight` is two conditions on purpose, and neither replaces the other.**
670
+ "touched inside `settleMs`" is strong while a copy is actively writing, because
671
+ its timestamp keeps moving; its hole is a writer that stalls past the window and
672
+ is then seen "cold". "Seen for the first time" closes that hole with no clock
673
+ term at all, and terminates through `growing` rather than through a window — the
674
+ first sight records the size, so the next scan reads the file once the size has
675
+ stopped moving. Keeping only the clock-free half was measured and is worse: an
676
+ active copy is then protected by the size comparison alone, and one stalled
677
+ `fsync` between two scans gets through.
678
+
679
+ **A future timestamp is not evidence of anything.** Both clock-based halves read
680
+ a timestamp ahead of now as "touched just now" — `mtime > scanStartedAt` is
681
+ permanently true and `now - mtime` is negative — so a file dated one day ahead
682
+ was invisible to the tree for good. An archive carries whatever it likes, a file
683
+ copied from a machine running fast arrives dated ahead, and a BIOS clock can be
684
+ years out; none of those is a file being written. `inTheFuture` excludes all
685
+ three.
686
+
687
+ **Only while watching.** A one-shot `extract()` or `storeInDb()` has no
688
+ follow-up scan, so deferring there does not delay a file, it drops one — and
689
+ `extract()` is public API. And nothing the agent decides reads a pass that may
690
+ have run while it was writing: after an apply, authoring scans afresh under
691
+ the lock (`scanFresh`). Without one it reads the watcher's last pass — every
692
+ extra look at a file mid-copy is another chance to hash it truncated, and
693
+ scanning afresh on every change hashed two to five times as many truncated
694
+ versions of a stalled copy.
695
+
696
+ **Never the agent's own writes.** What the agent writes whole — a restore, a
697
+ merge's conflicted copy — it tells the scanner (`noteWrite`), and the next scan
698
+ takes the file as written. Without that, a write in the second half of the
699
+ millisecond a scan starts in reads as "changed during this scan" — Node rounds
700
+ an mtime to the nearest millisecond, `Date.now()` truncates — so the scan
701
+ reuses the version before it, and a receiver authors that older version as an
702
+ edit, which reverts the writer's own copy everywhere.
703
+
704
+ What no rule over `stat` can decide is a writer that pauses for a long time, and
705
+ `README.public.md` → "Known constraints" says what that costs.
706
+
707
+ **Tested by** `test/fs-clock-skew.spec.ts` (6) for the clock half and
708
+ `test/fs-slow-copy.spec.ts` (3) for the deferral itself.
709
+
710
+ ## Ignore Matching (`src/fs-ignore.ts`)
711
+
712
+ Which files the sync never sees. Glob syntax — `*`, `?`, `**`, folders with
713
+ `/`, anchored at the root, `!` exceptions with last-match-wins,
714
+ case-insensitive, `/` equivalent to `\`.
715
+
716
+ The rule before was `name === pattern || name.startsWith(pattern)`, which
717
+ cannot express an extension: `*.exe` matched nothing, because no file is called
718
+ `*.exe` and none begins with it.
719
+
720
+ **The compatibility rule is load-bearing.** A pattern with none of `*`, `?`,
721
+ `/` or `\`, not starting with `!` and not ending with `/` keeps its old
722
+ prefix meaning. That is not courtesy to old configuration files: `~$` and
723
+ `.~lock.` are the Office and LibreOffice lock-file prefixes, and
724
+ `ATOMIC_TMP_PREFIX` (`.fsagent-tmp-`) is how the agent hides its own
725
+ in-progress writes from its own watcher. Read as globs all three would match
726
+ only a file named exactly that, every atomic write would return as a change
727
+ event, and the debounce that batches a push would be reset before it could
728
+ fire — a defect this package has already had.
729
+
730
+ The matcher is compiled once per agent, because a scan of a real catalogue asks
731
+ this question once per file.
732
+
733
+ **Tested by** `test/fs-ignore.spec.ts` (28), whose first block is one case per
734
+ pattern that appears in the shipped configuration or in the agent's own list —
735
+ that being the half which can break a running fleet.
736
+
737
+ ## Removed in 0.2.0
738
+
739
+ No compatibility with 0.1.x: every mechanism that existed to tolerate, migrate
740
+ from or diagnose it is gone, with its tests. Bucket sync and the manifest; the
741
+ tombstone log; the stated-removal gate (`planRemovals`) and the per-path edit
742
+ times; the no-chain heuristics and the anti-entropy module; the `~H~` prefix and
743
+ bare tree refs on the wire; `onConflict`, `refusedDeletions` and the conflict
744
+ log; the `resolveConflicts` option (the merge always runs); the old resolver and
745
+ its clock- and hash-based winners; `classify` and the tree-ref lookups; the
746
+ `conflict/merged`, `conflict/overwritten` and `config/degraded` signals.
552
747
 
553
748
  ## Known Constraints
554
749