@rljson/fs-agent 0.0.84 → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -8,6 +8,73 @@ 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
20
+ what the folder should contain. That is the constraint everything else follows
21
+ from: a decision has to be reachable, identically, on every machine, from data
22
+ every machine has.
23
+
24
+ **A folder is a tree, identified by its content.** The scanner produces an
25
+ RLJSON tree whose ref is a content hash. Two machines holding the same bytes
26
+ compute the same ref — which requires a canonical child order and requires
27
+ mtime to be *outside* the identity, because mtimes do not survive a restore and
28
+ on Windows regularly do not.
29
+
30
+ **A change is an edit, in one shared chain.** The chain records what changed,
31
+ what was removed, when, and which state it followed. It is identical on every
32
+ machine, written only where the change was made, and adopted — never re-authored
33
+ — by a receiver. **The filesystem is an event source only.** The watcher says
34
+ something happened; what it means is answered from the chain.
35
+
36
+ **An absence is not a deletion.** This is the whole reason the chain exists. A
37
+ tree lacks a path because the sender removed it, or because the sender never
38
+ had it, and a content hash cannot distinguish them. Four separate rules were
39
+ built to infer it and all four were withdrawn, costing 155 files of measured
40
+ drift across four machines and a file deleted from 3 642 that came back moments
41
+ later. A removal is therefore **stated**, by the machine that performed it, and
42
+ nothing is pruned on a peer's authority.
43
+
44
+ **What is transferred is a decision, not a payload.** A machine announces the
45
+ ADDRESS OF AN EDIT — not its folder, not a file list, not a tree. A receiver
46
+ resolves the address, reads the Edit, and fetches only the tree rows and blobs
47
+ it is missing. That makes a receiver's cost proportional to what actually
48
+ changed rather than to how long it was away: twenty saves of one document are
49
+ twenty small row reads and one blob.
50
+
51
+ **Everything is bounded.** Every async step has a timeout, every growing
52
+ structure has a cap, and every walk has a budget — because an unbounded step is
53
+ a silent 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 | [Data Synchronization Flow](#data-synchronization-flow-how-it-works) |
62
+ | why a node does not echo itself | [Bounce-Back Prevention](#bounce-back-prevention) |
63
+ | how a lost message heals | [Anti-Entropy](#anti-entropy-srcfs-anti-entropyts) |
64
+ | why two folders agree on one ref | [One Folder, One Ref](#one-folder-one-ref--the-canonical-child-order) |
65
+ | how a divergence is repaired without replacing a folder | [Additive Reconciliation](#additive-reconciliation-fs-manifestts--fs-bucket-syncts) |
66
+ | why a node sometimes gives no verdict about itself | [A Verdict Is Only About This Folder](#a-verdict-is-only-about-this-folder-while-the-head-names-it) |
67
+ | how a deletion travels | [A Delete Travels as a Fact](#a-delete-travels-as-a-fact-collectremovals--planremovals) |
68
+ | why a big deletion is refused, and how to find out | [Refused Deletions Are Reported](#refused-deletions-are-reported-not-only-logged-fsagentrefuseddeletions) |
69
+ | what a restart remembers | [Tombstone Log](#tombstone-log-_pendingdeletes--fsagent-statejson) |
70
+ | why an older edit cannot beat a newer one | [Ordering Every Difference](#ordering-every-difference-by-when-it-happened-manifestentryeditedat) |
71
+ | the history itself | [Edit Chain](#edit-chain-srcfs-edit-chaints) |
72
+ | what a joining machine does | [Joining a Network](#joining-a-network-planjoin) |
73
+ | who is recorded as having changed a file | [Authorship](#authorship-a-node-claims-only-what-it-changed) |
74
+ | which files are skipped | [Ignore Matching](#ignore-matching-srcfs-ignorets) |
75
+ | 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) |
76
+ | the signature of anything named here | [README.api.md](README.api.md) |
77
+
11
78
  ## Pull-Based Reference Architecture
12
79
 
13
80
  ### Why References Are Required
@@ -156,7 +223,7 @@ const connectorB = new Connector(clientDbB, Route.fromFlat('/dataSync'), socketB
156
223
  When a Connector sends a message via `connector.send(ref)`, two things happen:
157
224
 
158
225
  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+`)
226
+ 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
227
 
161
228
  ```typescript
162
229
  // This is NORMAL behavior:
@@ -170,9 +237,9 @@ connector.send('my-ref-123');
170
237
  // Output: "Received ref: my-ref-123" ← Local echo happens IMMEDIATELY
171
238
  ```
172
239
 
173
- **Server-Side Filtering (v0.0.4+):**
240
+ **Server-Side Filtering:**
174
241
 
175
- The `@rljson/server` package (v0.0.4 and later) correctly filters out the sender when multicasting:
242
+ `@rljson/server` filters out the sender when multicasting:
176
243
 
177
244
  ```typescript
178
245
  // Inside Server._multicastRefs():
@@ -290,163 +357,211 @@ await agentB.loadFromDb(serverDb, 'sharedTree', rootRef);
290
357
 
291
358
  ## Data Synchronization Flow (How It Works)
292
359
 
293
- ### The Peer-to-Peer Architecture with Central Server Coordination
360
+ **Read this section before any other.** It is the mechanism, and the rest of
361
+ the document is the rules that protect it.
362
+
363
+ ### What travels, and what does not
294
364
 
295
- The fs-agent implements a distributed peer-to-peer synchronization pattern where:
365
+ Three things exist, and only one of them is broadcast:
296
366
 
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
367
+ | | what it is | how it moves |
368
+ | --- | --- | --- |
369
+ | **blob** | the bytes of one file | pulled by id, on demand |
370
+ | **tree** | `path → blobId` for a whole folder, as rows | pulled by ref, on demand |
371
+ | **Edit** | what changed, what was removed, which Edits it came from, and when | **its address is broadcast** |
301
372
 
302
- ### Step-by-Step Sync Flow: Client A → Client B
373
+ An announcement is a short string — `~H~<editHistoryRef>` — plus the sender's
374
+ identity and a sequence number. No file content, no path list, no tree. A
375
+ receiver resolves the address, reads the Edit, and only then fetches the tree
376
+ and the blobs it is missing.
303
377
 
304
- **Message Routing via Connector:**
378
+ So a message is never "here is my folder". It is **"here is the decision I
379
+ made"**, and the folder is what you get by applying it.
305
380
 
381
+ ### An Edit
382
+
383
+ ```ts
384
+ interface FsChainEntry {
385
+ head: string; // this Edit's identity — what gets announced
386
+ timeId: string; // fleet-wide order, minted once by its author
387
+ treeRef: string; // the state the folder ended up at
388
+ previous: string[]; // the Edits this one was made from
389
+ changed: string[]; // paths added OR modified
390
+ removed: string[]; // paths removed — stated, never inferred
391
+ }
306
392
  ```
307
- Client A Server Client B
308
- -------- ------ --------
309
393
 
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!
394
+ `changed` does not distinguish an addition from a modification, because both
395
+ mean the same thing: the bytes at this path are now whatever the tree says.
396
+ `removed` is separate because only a removal needs an author — **an absence is
397
+ not a deletion**, and a node that merely lacks a file is behind, not
398
+ authoritative.
399
+
400
+ Two links matter. `previous` joins **Edit to Edit** — that is the chain.
401
+ `treeRef` joins **Edit to state** — which is how one Edit names a complete
402
+ folder rather than only a delta.
403
+
404
+ ### Sending: a local change becomes an Edit
405
+
406
+ `syncToDb` watches the folder. On a change, in this order:
407
+
408
+ ```
409
+ 1 scanner event FsScanner.onChange
410
+ 2 debounce 300 ms coalesce a burst into one push
411
+ 3 content key of the scanned tree _contentKeyFromTree
412
+ 4 unchanged? ──► RETURN nothing is sent
413
+ 5 which state do we descend from _ancestryPrevious
414
+ 6 write blobs + tree rows storeFsTree({ skipNotification: true })
415
+ 7 remember + persist the new ref _currentRef, .fsagent-state.json
416
+ 8 already announced this ref? ─► RETURN
417
+ 9 APPEND THE EDIT _recordChainEntry ◄── before the wire
418
+ 10 announce its head _sendRef → `~H~<head>`
408
419
  ```
409
420
 
410
- ### Key Architectural Components
421
+ Three steps are easy to get wrong and are load-bearing:
411
422
 
412
- **IoMulti (inside client.io):**
423
+ - **step 4 compares CONTENT, not refs.** A folder that returns to a state it
424
+ held before re-derives that state's exact ref, and a ref-based check would
425
+ call the return an echo. Deleting a file created in the same session is
426
+ exactly that shape — A → B → A — and under a ref check the deletion reached
427
+ no peer at all.
428
+ - **step 6 passes `skipNotification: true`.** `Connector` observes local
429
+ inserts and broadcasts the raw `<table>Ref` — a bare tree ref. Writing the
430
+ tree *is* an announcement unless it is suppressed, and an unsuppressed write
431
+ announces a state before the Edit for it exists.
432
+ - **step 9 precedes step 10.** The head is the Edit's identity; announcing
433
+ before appending has nothing to announce, and `_announceAs` would fall back
434
+ to the bare ref.
413
435
 
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`
436
+ ### Receiving: an Edit becomes a folder
418
437
 
419
- **BsMulti (inside client.bs):**
438
+ `syncFromDb` registers one callback with `connector.listen`. What arrives is an
439
+ address, so the first job is to find out what it names:
420
440
 
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`
441
+ ```
442
+ announcement arrives
443
+ │
444
+ ┌────────┴─────────┐
445
+ │ bucket envelope? │ ~BQ~ ~BR~ ~BG~ ~BE~ ──► FsBucketSync.receive, return
446
+ └────────┬─────────┘ (a control protocol; it names no tree)
447
+ │
448
+ ┌────────┴──────────┐
449
+ │ starts with ~H~ ? │
450
+ └───┬───────────┬───┘
451
+ no yes
452
+ │ │
453
+ │ _resolveAnnouncement ──► { treeRef, entry } (bounded read)
454
+ │ │ │
455
+ │ │ park the head _rememberAnnouncedHead
456
+ │ │ collect its removals _collectIncomingRemovals
457
+ │ │
458
+ schedule(ref) ◄──┘ debounced, so N announcements cost one apply
459
+ │
460
+ + ask the chain anyway _collectRemovalsForTreeRef
461
+ ```
425
462
 
426
- **Connector:**
463
+ Then the apply, with the watcher paused for its whole duration:
427
464
 
428
- - Broadcasts tree references (not full data) via socket
429
- - Triggers `syncFromDb` callbacks on receiving clients
430
- - Minimal bandwidth - only sends references
465
+ ```
466
+ 1 pause the watcher so the restore is not read as user edits
467
+ 2 apply the sender's STATED removals _applyIncomingRemovals
468
+ 3 fetch the tree by ref _fetchTreeFromDb (may reach a peer)
469
+ 4 same content already? ─► skip _treesHaveEquivalentContent
470
+ 5 ASK THE CHAIN _classifyAnnouncedRef
471
+ ahead ──► ignore it: we have left that state
472
+ fork ──► merge _resolveConflictInline
473
+ behind ──► restore additive; prune only under the rules
474
+ incomplete──► do nothing destructive
475
+ 6 re-scan, and compare what we derived with what we applied
476
+ 7 adopt the sender's head, or park it as a second parent
477
+ 8 resume the watcher
478
+ ```
431
479
 
432
- **Server:**
480
+ Step 5 is the whole design. Every other branch in this file exists because the
481
+ chain could not answer — and `incomplete` is a real answer, not a failure: a
482
+ node whose own head does not name its own folder is not entitled to a verdict
483
+ about anybody else's.
433
484
 
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
485
+ ### Healing: when no announcement arrives
438
486
 
439
- ### Why This Architecture Matters
487
+ An announcement can be lost, and nothing above notices — the mechanism is
488
+ driven by messages. So `FsAntiEntropy` reads the hub's beacon **directly off
489
+ the socket**, not through `listen`, because the connector correctly drops a
490
+ heartbeat it has already delivered and that is exactly the repeat that would
491
+ reveal a disagreement.
440
492
 
441
- This peer-to-peer pattern with server coordination enables:
493
+ ```
494
+ hub beacon ──► _reachabilityOf ──► observe({ ref, predecessors, reachability })
495
+ │
496
+ antiEntropyDecision(hub, view, attempt)
497
+ │
498
+ in-sync · blocked ──► nothing
499
+ pull · push · merge ──► repair
500
+ │
501
+ bucket round first, if enabled ──► additive, cannot destroy
502
+ otherwise: push = re-announce where we are
503
+ pull/merge = schedule the hub's state
504
+ ```
505
+
506
+ A node that is behind also **asks** rather than only listening
507
+ (`ANTI_ENTROPY_ASK_MS`): it reads the fleet's newest entry locally and offers it
508
+ to the anti-entropy as though it had been announced — which is what it would
509
+ have been, had the message not been lost.
510
+
511
+ ### Where the hub fits
442
512
 
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
513
+ The hub relays and never arbitrates. `Server._multicastRefs` forwards each ref
514
+ to every client except the sender, tagging it with `__origin` so a relay cannot
515
+ loop, and `_latestRef` keeps the last ref it relayed — prefix intact — so a
516
+ late joiner can be bootstrapped with it.
517
+
518
+ It stores no folder. Its `Io` and `Bs` exist for its own needs, and a client
519
+ that needs a tree or a blob the hub happens to hold reads it the same way it
520
+ reads a peer's.
521
+
522
+ ### Key Architectural Components
448
523
 
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.
524
+ **`IoMulti` (inside `client.io`)** combines this machine's local `Io` with an
525
+ `IoPeer` to the hub. A read checks local first, then asks the peer, and caches
526
+ what it gets. Reads are bounded per source and per priority group: a source that
527
+ is open but never answers is set aside rather than waited on, because "nobody
528
+ has this row" is the common case for an unreplicated ref, not the rare one.
529
+
530
+ **`BsMulti` (inside `client.bs`)** is the same for blobs. **Hand an agent a bare
531
+ `BsMem` and it can store its own blobs and never fetch anybody else's** — every
532
+ restore then fails on its first file and nothing propagates, which looks exactly
533
+ like a sync defect. Use `client.bs`.
534
+
535
+ **`Connector`** carries the announcement: `~H~<editHistoryRef>` plus the
536
+ sender's identity, a sequence number, and the predecessor TREE refs. It
537
+ deduplicates by ref on both sides, which is why `_sendRef` clears a ref the
538
+ folder has legitimately returned to.
539
+
540
+ It also observes local inserts and broadcasts the raw `<table>Ref` of anything
541
+ written to the route's root table. That is a **bare tree ref** — an
542
+ announcement the chain cannot be asked about — so every write this agent makes
543
+ passes `skipNotification: true` and announces for itself.
544
+
545
+ **`Server`** relays and never arbitrates. `_multicastRefs` forwards each ref to
546
+ every client but the sender, tagged with `__origin` so a relay cannot loop, and
547
+ `_latestRef` keeps the last ref relayed — prefix intact — to bootstrap a late
548
+ joiner. It stores no folder; its own `Io` and `Bs` are for its own needs.
549
+
550
+ ### Why it is built this way
551
+
552
+ - **no master copy** — every machine owns its folder, and a decision must be
553
+ reachable identically on all of them from data they all have
554
+ - **a decision is cheap to send** — an address is a short string; folders are
555
+ not
556
+ - **cost follows change, not absence** — coming back after a week costs what
557
+ changed, not what you missed
558
+ - **it works across a network** — real sockets, real partitions, not an
559
+ in-process mock
560
+
561
+ **A client must never read the server's `Io` or `Bs` directly.** It bypasses
562
+ `IoMulti`/`BsMulti` entirely, so the code appears to work in one process and
563
+ cannot work between machines — and the failure arrives later, as a sync defect
564
+ rather than as a wiring error.
450
565
 
451
566
  ## Bounce-Back Prevention
452
567
 
@@ -491,7 +606,7 @@ dedup is exactly what hides the repeat that would show a disagreement. Each
491
606
  announcement (`r`, `o`, `p`) goes to `FsAntiEntropy.observe()`.
492
607
 
493
608
  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
609
+ enters no apply path; the bootstrap heartbeat does, which is why the host
495
610
  Client runs with it off. The event name comes from `@rljson/db`
496
611
  (`stateBeaconEvent`), next to the Connector that deliberately ignores it; the
497
612
  server imports the same function.
@@ -529,7 +644,7 @@ keeping up with the traffic changes its own state with every forward it
529
644
  applies, while a node that lost a message sits still. Keying on the hub's
530
645
  state as well restarted the grace period on every change there, so a node
531
646
  that missed every forward while another machine kept writing was never
532
- repaired (review, ONE-446). The repair answers the latest announcement:
647
+ repaired. The repair answers the latest announcement:
533
648
 
534
649
  - push → `_sendRef(connector, _currentRef, [hubRef])`
535
650
  - pull → `scheduleProcess(hubRef, …, p)` — the ordinary `processRef`
@@ -550,6 +665,1077 @@ clients, a real server with heartbeat, one ref message dropped on purpose per
550
665
  case — including both halves of the collision above — plus a control run with
551
666
  the repair off that must stay divergent.
552
667
 
668
+ ## One Folder, One Ref — the canonical child order
669
+
670
+ A tree ref is supposed to be a function of the folder's content. It was not.
671
+
672
+ `readdir` (`fs-scanner.ts`) returns directory entries in whatever order the
673
+ filesystem chooses, and the ref hashes the resulting `children` array.
674
+ `_getFileContentMap` — the apply path's definition of "the same folder" —
675
+ ignores order entirely. So **two machines holding byte-identical content could
676
+ derive different refs for it**, and the two predicates disagreed:
677
+
678
+ | predicate | compares | asked by |
679
+ | --- | --- | --- |
680
+ | the tree ref | the whole tree row hash | anti-entropy: *am I diverged?* |
681
+ | `_treesHaveEquivalentContent` | path → blobId, plus directories | the apply path: *is there work to do?* |
682
+
683
+ When they disagree the system deadlocks against itself by design: the apply
684
+ path correctly concludes there is nothing to transfer, the anti-entropy
685
+ correctly concludes the refs differ, and neither is wrong.
686
+
687
+ **Measured on two machines (fs-agent 0.0.81).** After a forced 40 s
688
+ partition both sides held 38 identical files with identical hashes, and one
689
+ reported `diverged: true` for over **eight minutes** across six merge repairs,
690
+ logging *"equivalent content, skipping restore"* every time. It costs nothing in
691
+ data and it makes the divergence signal permanently untrustworthy — which is
692
+ the signal every repair decision is built on, and a permanent red "weicht ab"
693
+ in the UI.
694
+
695
+ The scan now emits children in a **canonical (sorted) order**, so the ref is a
696
+ function of content alone. Asserted on the scanner rather than on an arbitrary
697
+ tree, because that is where the guarantee has to live: any two scans of
698
+ equivalent content agree by construction, whatever order their filesystems hand
699
+ back.
700
+
701
+ **This changes every tree ref once.** Two machines only agree if both sort, so
702
+ it must roll out in lockstep — a node on an older build derives the old ref for
703
+ the same folder and looks permanently diverged to a new one. That is the same
704
+ constraint the package already has (`pnpm overrides`, exact pins).
705
+
706
+ **Tested by** `test/fs-ref-vs-content.spec.ts`, including the control: the
707
+ canonical-order assertion is red without the sort.
708
+
709
+ ## Additive Reconciliation (`fs-manifest.ts` + `fs-bucket-sync.ts`)
710
+
711
+ Every reconciliation this agent has is **whole-folder**: `pull` replaces the
712
+ folder with the peer's version, `push` asserts ours over everyone's. Every
713
+ decision is all-or-nothing, so every wrong decision is maximally destructive —
714
+ which is how a copied folder was deleted off the machine that made it, and how
715
+ deleted files came back across a fleet, on the same day.
716
+
717
+ `@rljson/mongo-agent` never does this: *"PULL IS ADDITIVE: the body-pull path
718
+ only ever fetches docs the peer has and we lack; it never overwrites live
719
+ content."* There is no "whose folder wins". Two nodes compare manifests and each
720
+ fetches what it is missing. **That single property is what makes the two
721
+ measured failures impossible rather than less likely.**
722
+
723
+ ### The comparison
724
+
725
+ An fs manifest is `path → blobId` — which `_getFileContentMap` already
726
+ produces. Each path falls in one of `BUCKET_COUNT` (4096) buckets by a hash of
727
+ the **path only**, so a modification stays in its bucket instead of looking
728
+ like a delete in one and an add in another. A bucket's root is the **XOR** of
729
+ its entries' digests, so it does not depend on the order a folder was walked in
730
+ — the canonical child order's lesson, one level down.
731
+
732
+ `BUCKET_COUNT` is a fixed constant. Mongo: *"MUST be identical on every node for
733
+ the per-bucket roots to be comparable."* Roots are sent **sparsely** (non-empty
734
+ buckets only), because a folder is three orders of magnitude smaller than a
735
+ mongo collection and 4096 fixed slots would be almost all empty.
736
+
737
+ **A deletion is an ENTRY**, carried at an empty blob id, so it travels through
738
+ the ordinary comparison rather than a side channel. A peer still holding the
739
+ file sees something to drop; a peer missing a file it has itself tombstoned
740
+ re-advertises the tombstone instead of fetching the file back.
741
+
742
+ **Every difference is settled by WHEN, with two tie-breaks under it.** An entry
743
+ carries the `timeId` of the newest edit its sender knows for that path
744
+ (`ManifestEntry.editedAt`), so both sides read the same two times and reach the
745
+ same verdict with no coordination. The order is:
746
+
747
+ 1. **the newer edit wins** — whichever side edited the path last, whether the
748
+ difference is content against content, content against a tombstone, or a
749
+ tombstone against content;
750
+ 2. **otherwise whoever's history claims the path**, for a peer that cannot date
751
+ its edits;
752
+ 3. **otherwise the greater blob id** — arbitrary, but identical on both nodes, so
753
+ two versions never sit there for ever.
754
+
755
+ Rule 1 reached only the tombstone cases at first, and the gap is worth naming
756
+ because it looked like it was covered: a conflict between two LIVE versions means
757
+ both sides edited the path, so both claim it, so rule 2 cannot separate them
758
+ either and rule 3 decided it. The fleet converged on whichever content hash
759
+ sorted higher — the writer's own folder going backwards about half the time,
760
+ measured as four nodes settling on a file's second-to-last version.
761
+
762
+ ### Four messages, not mongo's six
763
+
764
+ | | |
765
+ | --- | --- |
766
+ | `~BQ~` → | ask for the peer's bucket roots |
767
+ | `~BR~` ← | the roots, non-empty buckets only |
768
+ | `~BG~` → | ask for the entries of these buckets |
769
+ | `~BE~` ← | the entries of those buckets |
770
+
771
+ Mongo needs `AEW`/`AEH` because a document body must be requested and returned.
772
+ An fs entry is `path → blobId` and a blob is **already** content-addressed and
773
+ already fetchable over the existing path, so a node that knows the peer's
774
+ entries fetches the bodies itself.
775
+
776
+ Nothing here sends file content. Mongo's header records what happens otherwise:
777
+ broadcasting bodies made *"a 453 MB backfill balloon the hub to 3.4 GB and crash
778
+ it"*. The heaviest message is a list of paths.
779
+
780
+ **The body is JSON.** Mongo delimits with `|` because a collection name cannot
781
+ contain one; a relative PATH has no such guarantee — on POSIX a filename may
782
+ contain any byte but `/` and NUL. No delimiter is safe without escaping, and an
783
+ escaping bug in a message carrying DELETIONS is the expensive kind.
784
+
785
+ ### Every message carries a round id
786
+
787
+ Not decoration. `@rljson/db`'s `Connector` dedups by ref on **both** sides, and
788
+ a protocol message is byte-identical every time it is sent — `~BQ~` asking for
789
+ roots never varies. Marked received once, every later copy is dropped, and the
790
+ SECOND reconciliation a node ever attempts goes unanswered for the rest of the
791
+ session. Mongo sidesteps this with an `emitRaw` that bypasses dedup; this
792
+ `Connector` has no such method, so the messages are made unique instead.
793
+
794
+ It buys a second thing: a reply can be matched to its request, so a late answer
795
+ from an abandoned round is recognisable rather than merely surprising — and
796
+ still worth acting on, because its buckets are derivable from the entries and
797
+ the round trip is already paid for.
798
+
799
+ A body that cannot be parsed is **claimed and ignored** — a build speaking a
800
+ different dialect is not a reason to stop syncing, and claiming it stops
801
+ anything else trying to apply it as a tree ref.
802
+
803
+ ### It is driven, not autonomous
804
+
805
+ `FsBucketSync` decides what to say and what a reply means. It never touches a
806
+ folder, never reads a socket and **cannot delete anything**: a host supplies the
807
+ manifest and performs the plan, so the destructive half stays where the
808
+ mass-delete guard can see it. That is also why it is testable against a stub
809
+ with no sockets, folders or peers — two stubs wired together are a complete
810
+ two-node conversation.
811
+
812
+ `reconcile`'s whole vocabulary is `fetch` / `drop` / `redelete` / `conflict`.
813
+ There is no outcome in which one side's folder replaces the other's, and the
814
+ enumeration over {absent, live-x, live-y, tombstone}² proves `drop` and
815
+ `redelete` appear only where one side holds a tombstone for a path the other
816
+ holds live.
817
+
818
+ A genuine edit conflict is **named, not resolved** — whole-folder replacement
819
+ answered that question by guessing, and the guessing is what this plan removes.
820
+
821
+ ### The cold-start gate
822
+
823
+ `ready()` — mongo's, for mongo's reason: until a baseline is complete the roots
824
+ are partial *"and would make a peer see spurious differences"*. A node
825
+ mid-cold-start neither answers nor asks, because answering with partial roots is
826
+ worse than silence.
827
+
828
+ ### Wired, and ON by default
829
+
830
+ A divergence the anti-entropy would have answered with `pull` or `merge` runs a
831
+ bucket round instead. `bucketSync: false` returns to whole-folder repair and is
832
+ kept only as an escape hatch.
833
+
834
+ It was off for one revision, and the reason given was that such changes "have
835
+ been reverted four times for being shipped on reasoning". That was backwards:
836
+ those reverts were of changes shipped on reasoning, and this is the only part of
837
+ the work shipped on a controlled measurement. Turning it on surfaced three real
838
+ gaps — listed below — and fixing them is what the default is worth.
839
+
840
+ **Making it the default needed three things that were not in the plan:**
841
+
842
+ | gap | fix |
843
+ | --- | --- |
844
+ | deletions had to wait for an anti-entropy round, failing 20 tests | the prune is no longer withheld wholesale; the prune RULE is correct instead |
845
+ | the inline merge pruned on a tree whose ancestor it could not resolve | its materialisation is additive, and its deletions are targeted at the paths the merge actually resolved away |
846
+ | a same-file conflict was named and left — three clients then held three versions for ever | resolved by a rule both sides compute identically |
847
+
848
+ The third is the one the plan explicitly scoped out: *"It does not decide who
849
+ wins when two people edit the same file."* It has to. An additive step cannot
850
+ settle a conflict, so leaving it unsettled is not neutrality — it is
851
+ non-convergence. The greater blob id wins, both sides see both ids, so each
852
+ reaches the same answer with no message. No more arbitrary than the
853
+ last-advertisement-wins it replaces, and unlike that one it is the same choice
854
+ everywhere.
855
+
856
+ **Switching the repair was not enough on its own, and the two leftovers are the
857
+ interesting part.** Whole-folder replacement lives in three places, not one:
858
+
859
+ | | |
860
+ | --- | --- |
861
+ | the anti-entropy repair | `pull` replaces, `merge` applies the hub's tree |
862
+ | the ordinary apply | `cleanTarget` prunes whatever the incoming tree lacks |
863
+ | the inline merge | materialises a merged tree with `cleanTarget` |
864
+
865
+ The last two are reached from an ordinary incoming ref, not from a repair, so
866
+ with only the repair switched the partitioned node still lost its own new file —
867
+ measured, two runs in four, with the bucket round working perfectly alongside.
868
+ Under bucket sync all three are off:
869
+
870
+ - **an absence is never a deletion.** That is the whole point of carrying
871
+ deletions as tombstone entries: a path missing from a peer's tree means the
872
+ peer has not got it, not that the peer deleted it. Deletions arrive as `drop`
873
+ from a round that knows which side deleted.
874
+ - **the inline merge is skipped.** It is whole-folder replacement by another
875
+ name, and under bucket sync there is nothing for it to decide: the apply only
876
+ adds, and the round reconciles.
877
+
878
+ **Measured 8 of 8** on three scenarios — a fork keeping both sides' work (§1.1),
879
+ a delete made while partitioned staying deleted (§1.2 / T4), and the three-node
880
+ version of both at once. The same scenarios run 5 of 8 without it.
881
+
882
+ ## Rolling Out: what a peer can notice
883
+
884
+ This release makes two changes a peer can see, and they are not equally hard.
885
+
886
+ **Every tree ref in the fleet changes.** Two causes, one effect: content
887
+ identity now fixes a canonical child order, and mtime has left the identity
888
+ altogether — because a modification time does not survive a restore byte for
889
+ byte, and on Windows regularly does not, so while it was in the hash the same
890
+ bytes gave a different ref per machine and a node's deletions were refused by
891
+ everybody.
892
+
893
+ This is unavoidable and not destructive: `_treesHaveEquivalentContent` sees the
894
+ two trees as the same folder, so no data moves. It shows as a red divergence
895
+ flag during the rollout window — §2.1b's symptom — and clears once every node
896
+ has re-scanned. **Upgrade machines together**, and expect the flag until the
897
+ last one has.
898
+
899
+ **`~H~` is unintelligible to a build that does not speak it**, and there is no
900
+ compatibility switch — deliberately. A build that cannot parse `~H~` cannot
901
+ parse `~BQ~` either, so such a switch would also have to disable the bucket
902
+ protocol: one flag selecting two different consistency models.
903
+
904
+ So the rollout rule is the simple one: **upgrade machines together.** The ref
905
+ change above already requires it.
906
+
907
+ ### Two paths that look like compatibility and are not
908
+
909
+ Both exist for a runtime condition, not for an older peer:
910
+
911
+ - **`_ancestryRelation`**, the whole-`InsertHistory` ancestry walk, serves a
912
+ node whose chain failed to **initialise**. That is degradation: a node that
913
+ cannot read its own history still has to sync, it just cannot contribute an
914
+ ordering.
915
+ - **the bare-ref receive path**, because a bare ref is what any sender produces
916
+ whose chain could not name the state it is announcing.
917
+
918
+ Whether the second is still REACHABLE is a measurement rather than an
919
+ assumption: the invariant `every announcement carries a chain head` passes
920
+ across the whole mesh tier — **zero bare refs**. That is the evidence for
921
+ deleting it, whenever it is deleted.
922
+
923
+ Two facts the path rests on are worth stating, because both are easy to get
924
+ wrong. Finding a row BY a field is a query, not a content read, and a relay does
925
+ serve one across `IoPeer` — verified against a real `Server`/`Client` pair. And
926
+ a tree ref is a content hash, so a folder that returns to earlier content
927
+ produces a SECOND entry with the same `dataRef` — §2.1 exactly, the ambiguity the chain exists to remove.
928
+ The newest by `timeId` is the right pick and is still a pick, which is why the
929
+ head is the primary and the lookup never runs on the apply path.
930
+
931
+ ## What Grows, and What Bounds It
932
+
933
+ Measured on 400 files created then deleted one at a time, rather than reasoned
934
+ about:
935
+
936
+ | structure | growth | bound |
937
+ | --- | --- | --- |
938
+ | the chain (`editHistory`/`edits`/`multiEdits`) | one entry per **push**, not per change — 400 deletions produced **7**, because the debounce coalesces them | the walk budget, `DEFAULT_MAX_WALK` |
939
+ | `_localPathTimeIds` | one entry per changed path | pruned by the removals it records |
940
+ | `_stateHistory` | one per state entered | `STATE_HISTORY_MAX` |
941
+ | **the tombstone log** | **one per deletion, for ever** — ~11 bytes each, and the file is rewritten SYNCHRONOUSLY on every deletion | `TOMBSTONE_LOG_MAX` |
942
+
943
+ The tombstone log was the only unbounded one, and its shape is the bad kind:
944
+ the cost of deleting the next file grew with every file already deleted, so a
945
+ folder with years of churn turns into a megabyte rewritten per delete. Capped
946
+ at 10 000, evicted oldest-first, and **loudly** — evicting a tombstone can
947
+ resurrect a file, which is what a tombstone exists to prevent. A sighting in
948
+ the field means the log needs a real garbage-collection rule (one that knows
949
+ when every peer has seen a deletion), not a bigger number. The cap applies on
950
+ READ as well, so a file written by a build without it cannot reintroduce a size
951
+ this process has declined to carry.
952
+
953
+ ### A hole and a budget are different truncations
954
+
955
+ Found by the growth measurement, which was supposed to be about storage.
956
+
957
+ `classify` walks ancestry, and it can stop for two reasons that look alike and
958
+ are not:
959
+
960
+ - **a hole** — an entry exists and this node cannot read it. The ref being
961
+ looked for may be inside the part it could not reach, so the only honest
962
+ answer is `incomplete`.
963
+ - **the budget** — everything asked for WAS readable, and no relation was found
964
+ within `DEFAULT_MAX_WALK` entries.
965
+
966
+ Conflating them meant any node more than 500 pushes into its own history
967
+ answered `incomplete` for ever. The decision turns that into `blocked`, which
968
+ never repairs — **a long-lived node would simply stop healing, silently**, and
969
+ nothing in the suite would have noticed. A bounded walk now answers `fork`:
970
+ both sides keep their work, reconciliation is additive. Less precise than the
971
+ truth and never destructive.
972
+
973
+ `collectRemovals` keeps the strict reading for both cases, because a re-add
974
+ hiding below the bound would turn a skipped removal into a deleted live file.
975
+
976
+ ## Deciding From Reachability
977
+
978
+ A content hash plus ONE generation of ancestry cannot decide this, and §2.2 is
979
+ the proof: "a peer deleted what we added" and "a peer forked from an ancestor we
980
+ share" arrive at that signature as the **same value**. Narrowing such a rule was
981
+ tried twice — it cost a discarded folder the first time and a livelock the
982
+ second. **Do not re-derive this decision from that input.**
983
+
984
+ The chain answers instead, and where it answers no heuristic may overrule it:
985
+
986
+ | `hub.reachability` | decision |
987
+ | --- | --- |
988
+ | `behind` — theirs descends from ours | `pull` |
989
+ | `ahead` — ours descends from theirs | `push` |
990
+ | `fork` — neither descends from the other | `merge` |
991
+ | `incomplete` — a walk was truncated | **`blocked`** |
992
+ | absent — no chain on either side | the old heuristics, unchanged |
993
+
994
+ **`ahead` does not require `lastPushedRef` to match**, and must never be
995
+ narrowed to it. Authorship is not a stand-in for "a state the other side does
996
+ not have yet": a node that ADOPTED a peer's tree and then deleted a file authors
997
+ nothing, so under that condition it could never re-announce the deletion and the
998
+ delete never propagated. Reachability proves the same thing properly, whoever
999
+ wrote it.
1000
+
1001
+ **`blocked` is reported and not repaired.** Every action available is
1002
+ destructive in one direction or the other, and an incomplete walk that answers
1003
+ "not an ancestor" is indistinguishable from a definite no. So the divergence
1004
+ stays open, the backoff grows, and the next announcement tries again. It appears
1005
+ in `lastRepair.action` because a node stuck this way must be diagnosable, and it
1006
+ is **not** counted in `repairs`, because nothing was repaired.
1007
+
1008
+ Absence must never read as `fork`: an older peer, or a node whose chain failed
1009
+ to initialise, gets exactly the behaviour that shipped before, including its
1010
+ known limits.
1011
+
1012
+ ### The keystone: lineages have to be joined
1013
+
1014
+ **Reachability on its own makes things WORSE**, and only a measurement catches
1015
+ it. Every node appends to its OWN lineage, so an entry naming only this node's
1016
+ previous head can never be reachable from a peer's — `classify` answers `fork`
1017
+ for every disagreement, and cases a heuristic pushed or pulled correctly all
1018
+ become merges.
1019
+
1020
+ So an entry that applies a peer's state names **that peer's head as a second
1021
+ parent**. It is the shape `FsEditChain` writes its rows by hand to allow, and it
1022
+ is what makes one node's history reachable from another's. Consumed once:
1023
+ naming it on every later entry would claim to descend from it repeatedly and
1024
+ grow every walk for nothing.
1025
+
1026
+ ## A Verdict Is Only About This Folder While the Head Names It
1027
+
1028
+ `FsEditChain.classify` compares two chain **heads**. A node's head can lag its
1029
+ own folder — a write is on disk and in `_currentRef` before
1030
+ `_recordChainEntry` has appended the entry for it, and an apply that re-derives
1031
+ a different ref leaves the head naming the state it came from.
1032
+
1033
+ Asked inside that window the chain answers truthfully about a state the node
1034
+ has already left:
1035
+
1036
+ ```
1037
+ ours=fZ79puL0 theirs=KDeHB45d -> behind
1038
+ chainHeadTree=B4-SH9ZX current=hd3PHz1r
1039
+ ```
1040
+
1041
+ `behind` was correct about `fZ79puL0` and wrong about the folder, which was at
1042
+ `hd3PHz1r` and held a file no peer had. The repair read `behind` as `pull`,
1043
+ replaced the folder, and the divergence reopened — **45 times in 89 seconds**.
1044
+
1045
+ So `_classifyAnnouncedRef` answers `incomplete` unless
1046
+ `_chainHead.treeRef === _currentRef`. `antiEntropyDecision` turns that into
1047
+ `blocked`: nothing applied, nothing latched, retried. `fork` was tried instead,
1048
+ on the reasoning that a fork's repair is additive and therefore safe, and
1049
+ measured **worse** — 3 of 8 churn runs failing against 1 of 8. A merge invented
1050
+ from a verdict the node is not entitled to is still a merge.
1051
+
1052
+ This is the same family as `fork-is-not-a-lag`: a marker that does not mean
1053
+ "where I am" used as though it did.
1054
+
1055
+ ### It is what made the agreement memo correctable
1056
+
1057
+ `FsAntiEntropy` memoises "the hub's ref X describes the same content as the
1058
+ state I am in". That is a statement about **two** sides, true only while
1059
+ neither moves — and it was keyed on X alone, so it survived this node changing
1060
+ underneath it. A later announcement of X then cleared the divergence with no
1061
+ content check at all, for ever.
1062
+
1063
+ The cost was not a misreported flag. The repair is **gated** on it:
1064
+
1065
+ ```
1066
+ A: 11 files diverged=false hub=goDX1oLq local=kderYtfA differing=[]
1067
+ B: 10 files diverged=false hub=goDX1oLq local=goDX1oLq differing=[sub/three.txt]
1068
+ ```
1069
+
1070
+ B had deleted `sub/three.txt`, nobody re-created it, and A, C and D all held it
1071
+ while reporting no divergence — so none of them ever repaired. The fleet did
1072
+ not heal **and** did not say it needed to.
1073
+
1074
+ The key is now the pair, with the local side read from `view` on each call
1075
+ rather than from `_localRef` — that field is assigned as announcements arrive,
1076
+ so it lags its own folder and keying on it reintroduces exactly the staleness
1077
+ the pair removes.
1078
+
1079
+ It had been tried twice before and reverted both times, because correcting it
1080
+ turns the detector back on and the repair behind it was choosing `pull` for a
1081
+ node that was ahead. Fixing what the repair is **told** had to come first; the
1082
+ memo is one line at the end of that.
1083
+
1084
+ ## One Decision Site, and No Prune Authority
1085
+
1086
+ **`antiEntropyDecision` is the only place that asks *"has the other side seen a
1087
+ state I am in?"*** It asks the chain first and falls back to heuristics only for
1088
+ a peer the chain cannot speak for — see
1089
+ [Deciding From Reachability](#deciding-from-reachability).
1090
+
1091
+ There is deliberately no second site asking whether an incoming tree may
1092
+ **prune** local files. Such a rule can only read `[currentRef, lastAppliedRef]`
1093
+ against the other side's declared predecessors, and that input carries the
1094
+ ambiguity above: one generation of ancestry cannot separate "a peer deleted what
1095
+ we added" from "a peer forked from an ancestor we share". Narrowing it is what
1096
+ cost a discarded folder once and a livelock the second time.
1097
+
1098
+ So **nothing prunes on a peer's authority at all.** A received tree may add and
1099
+ may overwrite; a file disappears only when some machine has *stated* its removal
1100
+ in the chain, and that statement is applied by `_applyIncomingRemovals` —
1101
+ ordered by `timeId`, bounded by the mass-delete guard, and walked back through
1102
+ `previous` so a deletion made during a partition is still found.
1103
+
1104
+ The `causalOrdering` warning is therefore not about data loss. The predecessor
1105
+ refs it names are what let the merge gate fire, so a transport without them
1106
+ reconciles no conflicting edit — that, and only that, is what it reports.
1107
+
1108
+ ## A Delete Travels as a Fact (`collectRemovals` + `planRemovals`)
1109
+
1110
+ A tree records what a folder holds, so a deletion reaches a peer only as an
1111
+ **absence** — and an absence is indistinguishable from a state that merely
1112
+ predates the file.
1113
+
1114
+ That difference was once inferred from ancestry, which works only while the
1115
+ ancestor can be resolved. A partitioned node's cannot, and that is where the
1116
+ data loss was measured: 155 files of drift across four machines, and a file
1117
+ deleted from 3 642 that was back moments later. Four rules were built on that
1118
+ inference and all four were withdrawn; the one that is left is **not to
1119
+ infer**. See [One Decision Site](#one-decision-site-and-no-prune-authority).
1120
+
1121
+ The chain carries the removal instead, as something the sender **states**.
1122
+
1123
+ ### Reading the head is not enough
1124
+
1125
+ A removal is stated ONCE, in the entry that made it. A node partitioned at that
1126
+ moment states it in an entry nobody received — and its next entry, computed
1127
+ against its own last announcement, says nothing about the deletion. So a peer
1128
+ reading only the head learns nothing.
1129
+
1130
+ `FsEditChain.collectRemovals(head, stopAt)` walks `previous` back to a state the
1131
+ receiver knows and replays the range **oldest-first**, so a re-add cancels an
1132
+ earlier removal. Order is the whole correctness: taking the union of `removed`
1133
+ would delete a live file.
1134
+
1135
+ The stop entry is excluded entirely. A receiver that knows `T1` already holds
1136
+ the state in which those paths are gone, and including its `timeId` would let an
1137
+ old removal out-order the receiver's newer work.
1138
+
1139
+ **`complete: false` is the contract that matters most.** An unresolved entry
1140
+ means its ancestry — and any re-add hiding in it — is unknown, so the answer is
1141
+ **discarded rather than applied in part**. Truncation comes from a hole or from
1142
+ the walk bound; mongo states the rule as *"a caller must not latch the head;
1143
+ ancestors beyond the missing row would otherwise be lost forever"*.
1144
+
1145
+ ### Bounded twice, because it deletes without asking the ancestry rule
1146
+
1147
+ `planRemovals` decides what to act on:
1148
+
1149
+ | bound | rule |
1150
+ | --- | --- |
1151
+ | recency | `timeId`, minted once by the author, so every node orders the same pair identically. A removal older than this node's own newest edit to that path is refused. |
1152
+ | volume | the mass-delete circuit breaker, blocked **wholesale** — a partial mass delete leaves the folder in a state neither side asked for. |
1153
+
1154
+ The ratio is judged on what would ACTUALLY be deleted, so paths this node does
1155
+ not hold and paths refused as stale cannot trip the breaker on a message that
1156
+ removes almost nothing. A missing or malformed `timeId` is **not comparable**,
1157
+ never "older": judging silence as untrustworthy refused every deletion across
1158
+ twenty tests when it was last tried.
1159
+
1160
+ ### Why a deletion gets out at all
1161
+
1162
+ The deleting node has to be able to **re-announce** its own deletion, and two
1163
+ properties are what make that possible.
1164
+
1165
+ **`ahead` does not require authorship.** A node that has applied a peer's tree
1166
+ no longer authors its current state; if `ahead` meant "a state I authored", such
1167
+ a node could only `pull` or `merge` and its deletion would never go out.
1168
+ Reachability proves "the other side is behind" whoever wrote the state.
1169
+
1170
+ **A node that is behind ASKS**, rather than waiting to be told. That is what
1171
+ refills a machine whose folder was wiped, and what holds the fleet-level
1172
+ invariant *every node ends on the last save*.
1173
+
1174
+ T4 — *a delete made while cut off is not resurrected on rejoin* — is an ordinary
1175
+ assertion in `test/mesh/fs-mesh.spec.ts`, measured **8 of 8** under
1176
+ `bucketSync`.
1177
+
1178
+ ## Refused Deletions Are Reported, Not Only Logged (`FsAgent.refusedDeletions`)
1179
+
1180
+ The mass-delete guard refuses any incoming deletion that would remove most of a
1181
+ folder, on three routes — an incoming whole tree, a bucket round's drop list,
1182
+ and a peer's stated removals. It refuses on **every** node, so a user who
1183
+ deletes 10 000 files on purpose ends up with one machine short of them and the
1184
+ rest unchanged, and no further message closes that gap.
1185
+
1186
+ The guard is right anyway, because the two cases are indistinguishable from
1187
+ inside this package: a machine that was wiped telling the fleet to wipe, and a
1188
+ person deleting a project. Both arrive as "most of the folder is gone". The
1189
+ guard exists because the first one happened — a peer that had been emptied
1190
+ produced a round dropping **39 of 40** files, and before the floors covered
1191
+ that shape, 39 files were deleted on every node with no refusal logged at all.
1192
+
1193
+ What changed is that the refusal is now **readable**. One place
1194
+ (`_refuseDeletion`) reports it three ways, so they cannot drift apart as the
1195
+ three copies had:
1196
+
1197
+ | where | what it carries |
1198
+ | --- | --- |
1199
+ | the log | `MASS DELETE REFUSED on <folder>: <route> would remove N of M files.` |
1200
+ | `.sync-errors.log` | the key `restore/`, `bucketSync/` or `removals/massDeleteGuard` |
1201
+ | the API | `FsAgent.refusedDeletions` — `{ atMs, route, wouldRemove, held, paths }` |
1202
+
1203
+ A UI cannot grep a log on a machine it is not running on, and *"why did my
1204
+ deletion not arrive"* is exactly the question it has to answer. Fixing it
1205
+ properly is a product decision — an approval path — and until that exists the
1206
+ refusal is the correct behaviour and the gap is a missing dialog.
1207
+
1208
+ ## Tombstone Log (`_pendingDeletes` + `.fsagent-state.json`)
1209
+
1210
+ **What this node deleted, remembered past the push.**
1211
+
1212
+ A deleted file is simply absent from the next tree, so nothing in the content
1213
+ says the absence was deliberate. `_restoreTree` consults `_pendingDeletes` —
1214
+ "never re-create a file deleted here and not yet announced" — and the set is
1215
+ **persisted** in `.fsagent-state.json` beside `currentRef`, reloaded on start.
1216
+
1217
+ Clearing it on the next announcement is one push too early: "once peers have
1218
+ been told, a file's absence is theirs to know about" holds only for a peer that
1219
+ HEARD. A partitioned node's deletion reaches nobody, and on rejoin the fleet's
1220
+ tree still contains the file.
1221
+
1222
+ | trigger | effect |
1223
+ | --- | --- |
1224
+ | local `deleted`, path in `_announcedFiles` | record a tombstone, persist |
1225
+ | local `added` / `modified` for a tombstoned path | forget it, persist |
1226
+ | restore about to write a tombstoned path | skip the write |
1227
+
1228
+ **Only an announced FILE may be tombstoned**, because the watcher's path is not
1229
+ trustworthy on its own: deleting one nested file on macOS emits two deletions,
1230
+ the first naming the root folder itself, and directories arrive as `modified`.
1231
+ `_announcedFiles` is the set the prune rule already uses for "a file peers could
1232
+ know about", and it excludes the root, directories, and files deleted before
1233
+ anyone was told — the last of which need no tombstone, because no peer can push
1234
+ them back.
1235
+
1236
+ **This is half a mechanism.** Measured: it stops a node resurrecting its own
1237
+ deletion, reliably. It does not make the deletion win on a peer that never heard
1238
+ it, so the residual failure is a permanent divergence rather than a data loss.
1239
+ The other half needs the edit chain below.
1240
+
1241
+ **Not yet bounded.** Deleting a large folder writes one tombstone per file and
1242
+ keeps them. `@rljson/mongo-agent` routes tombstone application through the same
1243
+ mass-delete circuit breaker that bounds a prune; fs does not yet.
1244
+
1245
+ ## Ordering Every Difference by When It Happened (`ManifestEntry.editedAt`)
1246
+
1247
+ A bucket round compares two manifests. A manifest says what a node **holds**;
1248
+ until this release it never said **when the node decided**. So `reconcile` took
1249
+ a peer's tombstone as authority on its own:
1250
+
1251
+ ```ts
1252
+ if (theirsIsTombstone) {
1253
+ plan.drop.push(path); // no comparison with the write that superseded it
1254
+ }
1255
+ ```
1256
+
1257
+ A deletion made *before* a re-creation therefore still won, and the file was
1258
+ lost on every node that heard the older side. Measured by `I7b: a delivered
1259
+ deletion does not beat a later re-creation` — B deletes `flip.txt` while
1260
+ connected, is cut off, C re-creates it, and B's rejoin round dropped it from
1261
+ everybody.
1262
+
1263
+ `reconcile` already knew this about itself. Its comment on the conflict branch
1264
+ says the conflict resolver *"had the same defect — winners were chosen by
1265
+ content hash — and was fixed by ordering on the chain; this rule survived
1266
+ because it is the one that must work with no history at all."* That holds for
1267
+ the hash tie-break, which is the fallback for two nodes sharing no history. It
1268
+ does not hold for a tombstone, where a history exists and says plainly which
1269
+ came first.
1270
+
1271
+ **Nor does it hold for two live versions, and that is the half this section
1272
+ originally missed.** The field below was added, carried on the wire by both
1273
+ sides, and then read only by the two tombstone branches. A content-versus-content
1274
+ conflict kept falling through to the hash, and the paragraph above is the reason
1275
+ nobody looked: it reads as though the hash were reserved for nodes with no
1276
+ history, when in fact it was deciding every ordinary same-file conflict. Both
1277
+ sides of such a conflict have edited the path, so both claim it, so the claim
1278
+ rule cannot separate them either. Measured as four nodes converging on a file's
1279
+ second-to-last version. **The newer edit wins in every branch now**, and the
1280
+ claim and the hash are what remain for a peer that cannot date its edits at all.
1281
+
1282
+ ### The fix: the Edit's own identity travels
1283
+
1284
+ `ManifestEntry` gains a fourth element:
1285
+
1286
+ ```ts
1287
+ readonly [path: string, blobId: string, claimed?: 0 | 1, editedAt?: string]
1288
+ ```
1289
+
1290
+ `editedAt` is the `timeId` of the newest edit known for that path — the write
1291
+ that produced the blob, or the removal that produced the tombstone. It is not a
1292
+ wall-clock reading taken at send time; it is the identity of an Edit, minted
1293
+ once by whoever made it, so **both sides of a round order it identically**.
1294
+
1295
+ Every branch then became symmetric, and the mirror matters as much as the rule:
1296
+
1297
+ - their tombstone older than our write → **keep** the file
1298
+ - our tombstone older than their write → **fetch** it, rather than re-asserting
1299
+ a deletion the fleet has moved past
1300
+ - their content newer than ours → **fetch** it
1301
+ - our content newer than theirs → **keep** ours, and their own round fetches it
1302
+
1303
+ Without the mirror each side holds its own position for ever and the round never
1304
+ converges.
1305
+
1306
+ Absent means "the sender did not say", exactly as for `claimed`, and the rules
1307
+ that predate the field decide — which is also what happens after a restart
1308
+ until edits have been noted again. `editedAt` is read from `_pathEditTimes`,
1309
+ persisted in `.fsagent-state.json` beside the tombstones: without that the
1310
+ defect returns on every restart, because a node that cannot date its edits
1311
+ sends no time and the comparison has one operand.
1312
+
1313
+ ### What was tried first, and why it cannot work
1314
+
1315
+ A receiver-side rule: refuse a drop whenever this node's own chain has a newer
1316
+ write for the path. It fixed `I7b` and broke three deletion deliveries —
1317
+ *delivers a deletion a peer never received*, *does not undo a peer deletion it
1318
+ missed*, and the churn fuzzer.
1319
+
1320
+ The reason is structural. A node that has never **heard** a deletion has
1321
+ exactly the same local history as one whose write superseded it. Its own chain
1322
+ cannot tell the two apart, and in `I7b` it provably cannot: B was partitioned
1323
+ when C re-created the path, so C's write is unreachable from B's head. The
1324
+ ordering has to come from the side that holds the fact, which is why it travels.
1325
+
1326
+ ## Edit Chain (`src/fs-edit-chain.ts`)
1327
+
1328
+ **Written, and read by nobody. That is deliberate.**
1329
+
1330
+ A tree ref is a content hash of the whole folder, so a folder that returns to a
1331
+ state it held earlier re-derives that state's exact ref. "We returned to an old
1332
+ state" and "we never left it" are the same string — which is why two data-loss
1333
+ failures in opposite directions were measured on one day, and why neither is
1334
+ fixable by reading `antiEntropyDecision` more cleverly.
1335
+
1336
+ The chain gives every change its own identity. One entry per folder-changing
1337
+ scan:
1338
+
1339
+ | field | |
1340
+ | --- | --- |
1341
+ | `dataRef` | the tree ref the folder ended up at |
1342
+ | `previous` | the entries it was made from — **two** for a merge |
1343
+ | `timeId` | `<millis>:<nanoid>`, minted once, a fleet-wide order |
1344
+ | `changed` | relative paths added or modified |
1345
+ | `removed` | relative paths removed — **what a tree cannot express** |
1346
+
1347
+ `removed` is the point of carrying more than a ref. A tree records what a folder
1348
+ holds; only this records what it deliberately stopped holding.
1349
+
1350
+ ### What writes it
1351
+
1352
+ `FsAgent` appends one entry per state it pushes — the initial push, every
1353
+ debounced push, and a merge revision. The chain is created on the first
1354
+ `syncToDb`, which is where a `Db` and a `treeKey` first exist together, and
1355
+ `init()` continues the lineage a previous process left behind rather than
1356
+ starting a new root.
1357
+
1358
+ **Best-effort throughout.** Creating the chain, and every append, is recorded
1359
+ via `_writeSyncError` and swallowed — the same discipline as
1360
+ `_persistCurrentRef`. A folder must never stop syncing because its history
1361
+ could not be written. Nothing reads the chain yet, so a gap costs nothing; when
1362
+ something does, a gap is what `complete: false` is for.
1363
+
1364
+ `changed` and `removed` come from comparing the pushed tree's content map with
1365
+ the one announced before it (`_announcedContent`). The FIRST announcement
1366
+ records neither: everything would count as changed, which on a real folder
1367
+ makes the opening entry list 1 200 paths, and the tree ref already says what
1368
+ the baseline is. Only the deltas after it are worth recording.
1369
+
1370
+ ### What goes on the wire
1371
+
1372
+ **The chain HEAD, marked `~H~`** — not the tree ref.
1373
+
1374
+ A receiver holding a tree ref cannot find the chain row for it by hash, only by
1375
+ query, so nothing could walk ancestry. Announcing the head makes every
1376
+ announcement resolvable to an entry, which is what the `previous` walk needs in
1377
+ order to exist at all. It also makes each announcement UNIQUE: an A → B → A
1378
+ deletion produces three entries with three heads, so a returning content state
1379
+ is news by construction rather than by clearing the connector's dedup for it.
1380
+
1381
+ The marker matters. A tree ref is a content hash and never starts with `~`, so
1382
+ the two are unambiguous on one channel — the trick `@rljson/mongo-agent` uses
1383
+ for its own protocol refs. Without it a receiver would have to TRY resolving
1384
+ every ref it hears, and a miss goes to the network.
1385
+
1386
+ | | |
1387
+ | --- | --- |
1388
+ | `r` on the payload | `~H~<editHistory ref>` |
1389
+ | `p` on the payload | **tree refs, unchanged** |
1390
+
1391
+ The predecessors stay tree refs deliberately. A receiver's prune rule compares
1392
+ them against `[_currentRef, _lastAppliedRef]`, which are tree refs, so
1393
+ translating them here would break the one rule that separates a deletion from a
1394
+ straggler. The head is an additional identity for the announced state, not a
1395
+ replacement for the ancestry already on the payload. A receiver that resolves
1396
+ the head gets the chain's own `previous` for free, and that is the ancestry the
1397
+ walk will use.
1398
+
1399
+ **Three rules this cost a red run each to learn:**
1400
+
1401
+ 1. **An unmarked ref is scheduled SYNCHRONOUSLY.** Making the receive callback
1402
+ `async` deferred the schedule by a microtask even for a tree ref, and that
1403
+ was enough to lose a late joiner's bootstrap — it never received a file that
1404
+ already existed. The connector's bookkeeping runs around that call; an await
1405
+ between hearing a ref and queuing it reorders the two. The same applies to
1406
+ the anti-entropy's socket read, where three tests read the status straight
1407
+ after a beacon.
1408
+ 2. **The chain is created in `syncFromDb` too.** A node that only receives — a
1409
+ late joiner starts `syncFromDb` alone, because scanning its empty folder
1410
+ would push emptiness over everyone's data — still has to resolve the heads
1411
+ its peers announce. Created on the send path only, it dropped every
1412
+ announcement it heard. The chain is per-route state, not per-direction.
1413
+ 3. **A head that cannot be resolved answers `undefined`**, and nothing is
1414
+ concluded from it. Not even divergence: reporting a disagreement this node
1415
+ cannot describe is how the §2.1b symptom arrives by a second route.
1416
+
1417
+ **Mixed fleet: this must roll out in lockstep.** An older build receiving
1418
+ `~H~…` would try to fetch a tree by that hash and fail. The canonical child
1419
+ order above already imposes the same constraint, so the package as a whole
1420
+ needs the exact-pin discipline it already has.
1421
+
1422
+ A merge revision's chain entry is still LINEAR. It is the one state with two
1423
+ parents — the shape these rows are written by hand to allow — and naming both
1424
+ means mapping two tree refs to two chain heads, which nothing resolves yet.
1425
+
1426
+ ### Three tables, no cake
1427
+
1428
+ `<treeKey>Edits`, `<treeKey>MultiEdits`, `<treeKey>EditHistory` — and
1429
+ `createEditHistoryTableCfg(treeKey)` already declares `dataRef` as a reference
1430
+ to `treeKey`, which for fs IS the trees table. The fit is exact.
1431
+
1432
+ **fs-agent creates them itself**, idempotently, via `createFsChainTables`.
1433
+ `@rljson/db`'s `createTable` is `createOrExtendTable`, so an init may run on
1434
+ every start. The host application creates the trees table (in its own server and
1435
+ client entry points); an agent expecting tables its host had never created fails
1436
+ at runtime on any node whose host is one release behind, which is exactly the
1437
+ mixed-version case a rollout guarantees. Creating our own removes the coupling
1438
+ rather than versioning it — the reason `@rljson/mongo-agent` could evolve its
1439
+ schema without release-locking its host.
1440
+
1441
+ ### Why the rows are written by hand
1442
+
1443
+ `MultiEditManager` is the ordinary way to append an edit and is not usable here:
1444
+
1445
+ - it refuses more than one `previous` (*"has multiple previous refs. Not
1446
+ supported"*), and an fs **merge revision has two parents** by design
1447
+ (`StoreFsTreeOptions.previous`) — so the chain could not express the one
1448
+ revision shape that matters most; and
1449
+ - it is inseparable from the cake model: `edit()` needs a `cakeRef` and a
1450
+ `MultiEditProcessor` that applies edits onto a cake. fs has no components.
1451
+ Its content is the tree, already in the trees table. Only the history was
1452
+ missing.
1453
+
1454
+ `EditHistory.previous` is `string[]` in the type and `jsonArray` in the table,
1455
+ so multiple parents are representable — it is only the manager that will not
1456
+ walk them.
1457
+
1458
+ ### The head, and why it is not a single slot
1459
+
1460
+ A chain that is only written has no use for more than one head, nor for a walk.
1461
+ A chain that **decides** needs both, in three ways:
1462
+
1463
+ - **A head is parked per announced tree ref, not held in one slot.** When an
1464
+ announcement arrives, the sender's head is remembered against the tree ref it
1465
+ described (`_announcedHeads`, bounded by `ANNOUNCED_HEAD_MAX`, oldest first)
1466
+ and promoted only when that state is actually applied. The slot version made
1467
+ a node claim a lineage descending from a state it had merely *heard about* —
1468
+ **hearing a head is not holding its state**.
1469
+ - **`classify` walks, with a budget.** It answers `behind` / `ahead` / `fork` /
1470
+ `incomplete` by walking `previous`, bounded by `DEFAULT_MAX_WALK`, with a
1471
+ lineage cache. A truncated walk answers `incomplete`, never `fork` — acting
1472
+ on a truncated walk is how a node decides it is ahead of a peer it is behind.
1473
+ - **Per-path ancestry, where a branch verdict was wrong.** `lastEditOf` answers
1474
+ "who last edited *this path*" by walking generation by generation and sorting
1475
+ within a generation. Taking the greatest `timeId` was not enough: two edits
1476
+ in the same millisecond break on a random tail, so it could name an entry its
1477
+ own successor had superseded.
1478
+
1479
+ `@rljson/mongo-agent` holds per-node lineages for the same reason: a single
1480
+ `_lastApplied` slot there lost updates.
1481
+
1482
+ **Tested by** `test/fs-edit-chain.spec.ts` (20), `test/fs-classify.spec.ts`
1483
+ (11), `test/fs-collect-removals.spec.ts` (31),
1484
+ `test/fs-agent-announced-heads.spec.ts` (the cap) and
1485
+ `test/fs-chain-crosses-the-wire.spec.ts` (a peer walking `previous` through
1486
+ entries it never held).
1487
+
1488
+ ## Conflicts: two people saved the same file (`src/fs-conflict-resolver.ts`)
1489
+
1490
+ Everything else in this document is about folders that disagree because a
1491
+ message was lost or late. This is the case where both machines are right: two
1492
+ people edited one path while neither could see the other.
1493
+
1494
+ Enabled by `resolveConflicts`. With it off the resolver is not constructed, and
1495
+ a conflicting edit is never merged — which is correct for a hub, since a hub
1496
+ relays and must not arbitrate.
1497
+
1498
+ ### The three-way merge
1499
+
1500
+ `FsConflictResolver.resolve` is given a `dagBranch` conflict — two tips of one
1501
+ table — and works out one result:
1502
+
1503
+ 1. **`findCommonAncestor`** walks both lineages for the newest state they share.
1504
+ That is the `o` of the three-way. It tolerates a dangling predecessor and a
1505
+ diamond, and returns `null` when there is no shared ancestor at all.
1506
+ 2. **`threeWayMerge(o, ours, theirs, …)`** decides per path:
1507
+
1508
+ | `ours` vs `theirs` | result |
1509
+ | --- | --- |
1510
+ | equal | keep it (including both-absent and both-added-identically) |
1511
+ | only theirs diverged from `o` | take theirs |
1512
+ | only ours diverged from `o` | take ours |
1513
+ | both diverged, differently | **a conflict** — including edit-vs-delete |
1514
+
1515
+ 3. For a real conflict, one side keeps the path and **the other side's bytes are
1516
+ preserved under a renamed copy.** That is the property that makes either
1517
+ verdict safe: no answer loses content.
1518
+
1519
+ ### Which side keeps the path
1520
+
1521
+ By the chain, per path — not by which branch is "newer".
1522
+
1523
+ `winnerFor` is built from `lastEditOfPath` on both tips and compared with
1524
+ `compareTimeId`. A side that touched the path beats a side that did not; where
1525
+ both touched it, the later edit of **that path** wins; where the chain cannot
1526
+ speak for either, the branch order stands.
1527
+
1528
+ The branch order alone was the whole rule once, and it is the defect the chain
1529
+ was brought in to remove: it ordered a *tip*, so a tip could win files it never
1530
+ opened. Measured — a machine came back from being offline, wrote one unrelated
1531
+ file, and that newer tip took `doc.txt` with it, moving the writer's own folder
1532
+ from v8 back to v5. "Cannot say" is never read as "did not touch it".
1533
+
1534
+ ### The name of the losing copy
1535
+
1536
+ ```
1537
+ document.txt → document (conflicted copy <machine> 2026-06-18 091500).txt
1538
+ ```
1539
+
1540
+ Inserted before the final extension; appended when there is none; a leading-dot
1541
+ name is treated as extensionless. Repeats get a numeric suffix, and the
1542
+ candidate is checked against every real path **and** every copy already planned,
1543
+ so a copy can never collide.
1544
+
1545
+ The identity and timestamp come from the **losing revision**, not from the clock
1546
+ of the machine doing the merge — so every peer computes the identical name and
1547
+ the copy does not itself become a conflict. Where no identity is available the
1548
+ marker degrades to the timestamp plus a short ref rather than printing an empty
1549
+ one: `(conflicted copy 2026-…)` with a double space is the kind of detail a
1550
+ user reports as a bug.
1551
+
1552
+ ### What the merge revision is
1553
+
1554
+ One state with **two parents** — the only shape in the chain that has them. It
1555
+ is announced as a chain head like any other state, and
1556
+ `_resolveConflictInline` adopts the incoming side's head first, so the Edit
1557
+ names both branches.
1558
+
1559
+ That ordering is load-bearing. A merge that resolves both branches but descends
1560
+ from one is classified `fork` by the very peer whose branch it merged, for ever
1561
+ — announcing such a head converts a finished merge into a standing
1562
+ disagreement.
1563
+
1564
+ ### And a merge claims only what it made
1565
+
1566
+ Choosing between two versions is not writing one. A merge that resolves
1567
+ `doc.txt` by keeping one side's existing bytes has not edited `doc.txt`, and
1568
+ claiming it would make this machine the newest author of content it did not
1569
+ write — which then out-ranks the real writer. So the claim is filtered to the
1570
+ paths whose merged bytes came from neither side: the conflict copies, which this
1571
+ machine genuinely made.
1572
+
1573
+ ### Telling somebody
1574
+
1575
+ `onConflict` fires with the reports as they are resolved, for a UI that is
1576
+ running now. `.fsagent-conflicts.json` records them, bounded, for one that
1577
+ starts later. Both, not either — a conflict nobody hears about is the thing this
1578
+ exists to prevent, so it does not depend on anyone having subscribed.
1579
+
1580
+ ## Joining a Network (`planJoin`)
1581
+
1582
+ The case the chain exists for, and the one a folder's contents cannot decide.
1583
+
1584
+ If a joining node authored a lineage root from its own contents and pushed it as
1585
+ the network's newest claim, that would be one defect with two faces: every node
1586
+ gets its own root, so `classify` answers `fork` to every announcement ever made;
1587
+ and a machine restored from a backup pushes a month of deletions back to the
1588
+ whole fleet.
1589
+
1590
+ **The chain applies first, and the filesystem only then.** A folder with files
1591
+ and no history does not speak: it defers its first announcement and asks the
1592
+ network for a head, every `JOIN_ASK_INTERVAL_MS`, until a bounded
1593
+ `joinWaitMs` expires. That default is **on, on every route** — a joiner that
1594
+ cannot be told must ask, and keep asking.
1595
+
1596
+ With a head in hand, `planJoin` puts every path in **at most one** of four
1597
+ buckets, deciding each against the chain and never against the disk:
1598
+
1599
+ | bucket | the path is | action |
1600
+ | --- | --- | --- |
1601
+ | `write` | in the head, not on disk | write it |
1602
+ | `announce` | on disk, never named anywhere in the history | new local work — announce it |
1603
+ | `recover` | on disk, and REMOVED by the history | a stale copy: rename aside, say nothing |
1604
+ | `conflict` | live on both sides, different bytes | the head's bytes win, the local copy is kept aside |
1605
+
1606
+ `recover` is what makes a restored backup safe. The files are moved into
1607
+ `.fsagent-recovered/`, which the scanner ignores — because a tree ref carries
1608
+ content, so a "kept but not announced" file cannot exist *inside* the synced
1609
+ folder. Nothing is resurrected and nothing is destroyed.
1610
+
1611
+ If no head arrives within the wait, this folder is the origin of its own
1612
+ history and announces normally. An empty head is a **fact**, not an absent
1613
+ one: a fleet that has agreed the folder is empty states exactly that, and each
1614
+ local path is still judged as new work or as a stale copy. Conflating the two
1615
+ is what would make an emptied network un-joinable.
1616
+
1617
+ **Tested by** `test/fs-plan-join.spec.ts` (9 decision cases, including that
1618
+ every path lands in at most one bucket) and at mesh tier by
1619
+ `fs-mesh-matrix.spec.ts` **J4+J5** and **J9** twice — the latter using a
1620
+ stopped PROCESS rather than a broken network, because that is what a restart
1621
+ is.
1622
+
1623
+ ## Authorship: a node claims only what it changed
1624
+
1625
+ The standing design rule, and the one most easily violated in a single branch:
1626
+ **an edit exists only where the change was made.** A receiver adopts and never
1627
+ authors. Without it, a machine catching up records itself as the author of
1628
+ somebody else's file, and then correctly out-orders the person who actually
1629
+ typed.
1630
+
1631
+ Four places broke it, and each is now a test:
1632
+
1633
+ 1. **A merge claimed too much.** `storeMerge` recorded an entry claiming every
1634
+ path whose bytes differed from what that node had last *announced* — so a
1635
+ receiver merging against a late announcement wrote itself down as the author
1636
+ of a file it had never edited, 28 seconds after the real edit. A merge now
1637
+ claims only the paths whose merged bytes differ from **both** inputs: the
1638
+ ones it genuinely synthesised.
1639
+ 2. **A received path was claimed.** `_recordReceived` records only what
1640
+ actually ARRIVED, measured against the state before the apply — without the
1641
+ before-state, a node's own bytes returning from a peer drop its claim.
1642
+ 3. **The first local edit was authorless.** "Have I announced before" is not
1643
+ "is what I announced empty": `previous.size === 0` is true both for a node
1644
+ that has never spoken and for one that has announced an empty folder, which
1645
+ is every fresh client. The first real file written on a new node was never
1646
+ claimed.
1647
+ 4. **A re-derived state got a stale identity.** Returning to a content state is
1648
+ a NEW entry, not the old one.
1649
+
1650
+ **The practical rule for anyone adding a guard to the push path:** check
1651
+ whether the signal it reads is populated *before* or *after* the push. Claims
1652
+ are recorded by `_recordChainEntry` **after** the state being judged, so a node
1653
+ is a stranger to its own newest work at that moment — which is why three
1654
+ attempts at a restore detector each suppressed ordinary work instead (a
1655
+ rename's target, an atomic save, a create/delete/recreate are all unclaimed at
1656
+ that instant). And a guard that needs an `await` in the push path is already
1657
+ wrong: the yield between "this is what I am announcing" and "this is the entry
1658
+ for it" lets another apply land in the middle.
1659
+
1660
+ **Tested by** `test/fs-agent-authorship.spec.ts`,
1661
+ `fs-agent-no-laundering.spec.ts`, `fs-agent-own-echo.spec.ts`,
1662
+ `fs-agent-self-parent.spec.ts`, `fs-agent-inbound-verdict.spec.ts` and
1663
+ `fs-agent-stale-reconnect.spec.ts`.
1664
+
1665
+ ## Ignore Matching (`src/fs-ignore.ts`)
1666
+
1667
+ Which files the sync never sees. Glob syntax — `*`, `?`, `**`, folders with
1668
+ `/`, anchored at the root, `!` exceptions with last-match-wins,
1669
+ case-insensitive, `/` equivalent to `\`.
1670
+
1671
+ The rule before was `name === pattern || name.startsWith(pattern)`, which
1672
+ cannot express an extension: `*.exe` matched nothing, because no file is called
1673
+ `*.exe` and none begins with it.
1674
+
1675
+ **The compatibility rule is load-bearing.** A pattern with none of `*`, `?`,
1676
+ `/` or `\`, not starting with `!` and not ending with `/` keeps its old
1677
+ prefix meaning. That is not courtesy to old configuration files: `~$` and
1678
+ `.~lock.` are the Office and LibreOffice lock-file prefixes, and
1679
+ `ATOMIC_TMP_PREFIX` (`.fsagent-tmp-`) is how the agent hides its own
1680
+ in-progress writes from its own watcher. Read as globs all three would match
1681
+ only a file named exactly that, every atomic write would return as a change
1682
+ event, and the debounce that batches a push would be reset before it could
1683
+ fire — a defect this package has already had.
1684
+
1685
+ The matcher is compiled once per agent, because a scan of a real catalogue asks
1686
+ this question once per file.
1687
+
1688
+ **Tested by** `test/fs-ignore.spec.ts` (28), whose first block is one case per
1689
+ pattern that appears in the shipped configuration or in the agent's own list —
1690
+ that being the half which can break a running fleet.
1691
+
1692
+ ## A Copy in Progress Does Not Reach the Wire (`FsScanner`, the settle rule)
1693
+
1694
+ A watcher fires while a large file is still being written, and a scan that reads
1695
+ it then publishes a truncated file that every peer accepts as the whole thing.
1696
+ The scanner therefore defers a file rather than reading it, and the deferral is a
1697
+ promise to come back: `_unsettledDuringScan` reuses the previous node for that
1698
+ path and arms a follow-up scan, so a deferred file is late and never lost.
1699
+
1700
+ Three signals defer, and the file waits if any of them fires:
1701
+
1702
+ | signal | what it catches |
1703
+ | --- | --- |
1704
+ | `mtime > scanStartedAt` | the file changed **while this scan ran** — free, no window, cannot race |
1705
+ | `growing` — the size moved since the last scan | a writer whose gaps are wider than one read |
1706
+ | `firstSight` — never read, and either touched inside `settleMs` or seen for the first time | a copy already in progress when the scanner met it |
1707
+
1708
+ **`firstSight` is two conditions on purpose, and neither replaces the other.**
1709
+ "touched inside `settleMs`" is strong while a copy is actively writing, because
1710
+ its timestamp keeps moving; its hole is a writer that stalls past the window and
1711
+ is then seen "cold". "Seen for the first time" closes that hole with no clock
1712
+ term at all, and terminates through `growing` rather than through a window — the
1713
+ first sight records the size, so the next scan reads the file once the size has
1714
+ stopped moving. Keeping only the clock-free half was measured and is worse: an
1715
+ active copy is then protected by the size comparison alone, and one stalled
1716
+ `fsync` between two scans gets through.
1717
+
1718
+ **A future timestamp is not evidence of anything.** Both clock-based halves read
1719
+ a timestamp ahead of now as "touched just now" — `mtime > scanStartedAt` is
1720
+ permanently true and `now - mtime` is negative — so a file dated one day ahead
1721
+ was invisible to the tree for good. An archive carries whatever it likes, a file
1722
+ copied from a machine running fast arrives dated ahead, and a BIOS clock can be
1723
+ years out; none of those is a file being written. `inTheFuture` excludes all
1724
+ three.
1725
+
1726
+ **Only while watching, and never while paused.** A one-shot `extract()` or
1727
+ `storeInDb()` has no follow-up scan, so deferring there does not delay a file, it
1728
+ drops one — and `extract()` is public API. A pause means the agent is writing the
1729
+ folder itself, where every restored file looks fresh; deferring those made the
1730
+ post-restore scan reuse pre-restore nodes, which is how a node leaves the
1731
+ ancestry conversation and gets its deletions refused everywhere.
1732
+
1733
+ What no rule over `stat` can decide is a writer that pauses for a long time, and
1734
+ `README.public.md` → "Known constraints" says what that costs.
1735
+
1736
+ **Tested by** `test/fs-clock-skew.spec.ts` (6) for the clock half and
1737
+ `test/fs-slow-copy.spec.ts` (3) for the deferral itself.
1738
+
553
1739
  ## Known Constraints
554
1740
 
555
1741
  ### macOS Finder Paste and Rename