@rljson/fs-agent 0.1.0 → 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -16,41 +16,41 @@ is built the way it is. For the API and the options, read
16
16
  ## The design in one page
17
17
 
18
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.
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.
43
45
 
44
46
  **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.
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
50
 
51
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.
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
54
 
55
55
  ## How to read this document
56
56
 
@@ -58,21 +58,17 @@ a silent hang and an unbounded list is tomorrow's memory ceiling.
58
58
  | --- | --- |
59
59
  | why refs rather than payloads | [Pull-Based Reference Architecture](#pull-based-reference-architecture) |
60
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) |
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) |
73
66
  | 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) |
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) |
75
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) |
76
72
  | the signature of anything named here | [README.api.md](README.api.md) |
77
73
 
78
74
  ## Pull-Based Reference Architecture
@@ -253,30 +249,10 @@ for (const [clientIdB, { socket: socketB }] of this._clients.entries()) {
253
249
 
254
250
  This means Client A will NOT receive its message back from the server, but it WILL receive it via local socket echo.
255
251
 
256
- **Application-Level Self-Filtering:**
257
-
258
- 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:
259
-
260
- ```typescript
261
- // In FsAgent:
262
- private _lastSentRef?: string;
263
-
264
- // When sending:
265
- this._lastSentRef = ref;
266
- connector.send(ref);
267
-
268
- // When receiving:
269
- if (treeRef === this._lastSentRef) {
270
- console.log('[syncFromDb] Skipping self-broadcast');
271
- return; // Don't process own message
272
- }
273
- ```
274
-
275
- **Why This Architecture:**
276
- - Socket echo is unavoidable with EventEmitter-based implementations (SocketMock, real sockets)
277
- - Server-side filtering prevents network round-trips but can't prevent local echo
278
- - Application-level filtering is defensive programming and works regardless of socket implementation
279
- - 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.
280
256
 
281
257
  ### Client-Server Pattern
282
258
 
@@ -355,1339 +331,365 @@ await agentB.loadFromDb(serverDb, 'sharedTree', rootRef);
355
331
 
356
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.
357
333
 
358
- ## Data Synchronization Flow (How It Works)
359
-
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
364
-
365
- Three things exist, and only one of them is broadcast:
366
-
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** |
372
-
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.
377
-
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.
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
- }
392
- ```
393
-
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>`
419
- ```
420
-
421
- Three steps are easy to get wrong and are load-bearing:
422
-
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.
435
-
436
- ### Receiving: an Edit becomes a folder
437
-
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:
440
-
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
- ```
462
-
463
- Then the apply, with the watcher paused for its whole duration:
464
-
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
- ```
479
-
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.
484
-
485
- ### Healing: when no announcement arrives
486
-
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.
492
-
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
334
+ ## The sync, end to end
512
335
 
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.
336
+ ### What travels
517
337
 
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.
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.
521
344
 
522
- ### Key Architectural Components
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)).
523
348
 
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.
349
+ ### Sending: a change becomes an entry
529
350
 
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`.
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:
534
357
 
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.
358
+ - **unchanged** — nothing to author;
359
+ - **changed** — the paths written and the paths removed;
360
+ - **refused** — the sender's honesty guard ([Guards](#guards)).
539
361
 
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.
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.
544
366
 
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.
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)).
549
372
 
550
- ### Why it is built this way
373
+ ### Receiving: what a node does with a head
551
374
 
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
375
+ `receive` (`fs-receive.ts`) is the whole decision:
560
376
 
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.
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:
565
383
 
566
- ## Bounce-Back Prevention
567
-
568
- Bidirectional sync creates a potential infinite loop:
569
-
570
- ```
571
- Client A writes file → syncToDb stores tree → broadcasts ref →
572
- Client B receives ref → syncFromDb restores file → fs watcher fires →
573
- syncToDb stores tree → broadcasts ref → Client A receives ref → ...
574
- ```
575
-
576
- FsAgent uses three layers of deduplication to break the loop:
577
-
578
- 1. **Ref-level dedup**: After `syncToDb` stores a tree, it compares the
579
- resulting ref against `_lastSentRef`. If identical, no broadcast occurs.
580
-
581
- 2. **Content-key dedup**: Even when refs differ (e.g. different mtimes produce
582
- different hashes), `syncToDb` computes a content key from file paths +
583
- blobIds. If the content key matches `_lastSentContentKey`, the broadcast
584
- is skipped.
585
-
586
- 3. **Content comparison before restore**: In `syncFromDb`, before restoring
587
- an incoming tree, FsAgent compares its file content map against the current
588
- filesystem. If they are equivalent, the restore is skipped entirely,
589
- preventing the filesystem watcher from firing.
590
-
591
- Additionally, all sync callbacks are **debounced** (default 300ms) to coalesce
592
- rapid filesystem events (e.g. multi-file saves, editor autosave) into a single
593
- sync operation.
594
-
595
- ## Anti-Entropy (`src/fs-anti-entropy.ts`)
596
-
597
- Nothing in the message path ever asks whether a message arrived. A lost push is
598
- not resent until the folder changes again; a lost forward is repeated only by
599
- the hub's heartbeat, which the connector drops as a duplicate or delivers as
600
- "not newest". The anti-entropy closes that gap.
601
-
602
- **Trigger.** `syncFromDb` subscribes to two events on the connector's socket
603
- directly — `${route}:bootstrap` and the server's state beacon
604
- `stateBeaconEvent(route)` = `${route}:state` — not through `listen`, whose
605
- dedup is exactly what hides the repeat that would show a disagreement. Each
606
- announcement (`r`, `o`, `p`) goes to `FsAntiEntropy.observe()`.
607
-
608
- The beacon is the signal to run on. The connector does not listen to it, so it
609
- enters no apply path; the bootstrap heartbeat does, which is why the host
610
- Client runs with it off. The event name comes from `@rljson/db`
611
- (`stateBeaconEvent`), next to the Connector that deliberately ignores it; the
612
- server imports the same function.
613
-
614
- **Decision** (`antiEntropyDecision`, pure):
615
-
616
- 1. `r === _currentRef` → in sync.
617
- 2. `_currentRef === _lastPushedRef` and `o` is our connector's origin →
618
- **push**: the hub holds an earlier push of ours and missed the later one.
619
- 3. `p` contains `_currentRef` or `_lastAppliedRef` → **pull**: we missed the
620
- hub's state.
621
- 4. `_currentRef === _lastPushedRef` and `r === _lastAppliedRef` → **push**:
622
- the hub still holds what our push was made from.
623
- 5. otherwise → **merge**.
624
-
625
- Rule 4 comes AFTER the ancestry check: a peer that deletes what we added can
626
- return the folder to exactly the state we last applied — same hash, but made
627
- from ours. Measured under load: pushing there put the deleted file back on
628
- every node.
629
-
630
- Rule 2 precedes rule 3 because of a collision the hash cannot resolve:
631
- "B deleted the file A created" (hub `S0` made from `S1`, A at `S1`) and "A
632
- deleted its own file and that push was lost" (hub `S1` made from `S0`, A at the
633
- re-derived `S0`) are identical in refs and ancestry. Only the origin of the
634
- hub's state tells them apart, and each wrong answer puts a deleted file back.
635
-
636
- `_lastPushedRef` is set only where the agent authors a state (initial push,
637
- debounced push, merge revision) — never by an apply, which can leave the folder
638
- short of what it applied. Re-announcing such a state would roll peers back.
639
-
640
- **Repair**, only once this node has been out of step with the hub for
641
- `graceMs` **without its own state moving**, and nothing is pending,
642
- processing or applying. The divergence is keyed on `_currentRef` alone: a node
643
- keeping up with the traffic changes its own state with every forward it
644
- applies, while a node that lost a message sits still. Keying on the hub's
645
- state as well restarted the grace period on every change there, so a node
646
- that missed every forward while another machine kept writing was never
647
- repaired. The repair answers the latest announcement:
648
-
649
- - push → `_sendRef(connector, _currentRef, [hubRef])`
650
- - pull → `scheduleProcess(hubRef, …, p)` — the ordinary `processRef`
651
- - merge → the same with `p` on the first attempt, then with `[]`, which makes
652
- the apply additive (union), after which the next round pushes it
653
-
654
- Repeated repairs of one divergence back off exponentially up to
655
- `maxBackoffMs`. `processing` covers the pauses between `processRef` retries,
656
- where `_remoteApplyInFlight` is clear.
657
-
658
- **Why not a copy of the mongo anti-entropy.** That one is triggered by noticing
659
- a PEER's root, so a node that receives nothing never starts it, and it applies
660
- a peer tombstone without a recency check. This one is triggered by the hub's
661
- own announcement and never applies anything outside the ordinary rules.
662
-
663
- **Tested by** `test/client-server/heals-after-forced-divergence.spec.ts`: three
664
- clients, a real server with heartbeat, one ref message dropped on purpose per
665
- case — including both halves of the collision above — plus a control run with
666
- the repair off that must stay divergent.
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 |
384
+ | relation | meaning | action |
679
385
  | --- | --- | --- |
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 |
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 |
937
550
  | --- | --- | --- |
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
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>` |
1302
555
 
1303
- Without the mirror each side holds its own position for ever and the round never
1304
- converges.
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.
1305
560
 
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.
561
+ ## Authorship: a node claims only what it changed
1312
562
 
1313
- ### What was tried first, and why it cannot work
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:
1314
567
 
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.
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.
1319
575
 
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.
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`.
1325
578
 
1326
579
  ## Edit Chain (`src/fs-edit-chain.ts`)
1327
580
 
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:
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`.
1338
588
 
1339
- | field | |
589
+ | method | answers |
1340
590
  | --- | --- |
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.
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 |
1551
596
 
1552
- ### What the merge revision is
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.
1553
602
 
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.
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.
1558
605
 
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.
606
+ ## One folder, one ref — the canonical child order
1563
607
 
1564
- ### And a merge claims only what it made
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.
1565
613
 
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.
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.
1572
616
 
1573
- ### Telling somebody
617
+ ## One channel for everything that happened (`src/fs-signals.ts`)
1574
618
 
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.
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.
1579
623
 
1580
- ## Joining a Network (`planJoin`)
624
+ Every signal says **what** happened and to **which paths**, **who decided**
625
+ (`chain`, `stamp` or `guard`), and whether a **person** has to act:
1581
626
 
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:
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, through a staging file and a
639
+ rename, and read back lazily, without firing subscribers. `.sync-errors.log`
640
+ stays the record of internal failures — exceptions, which are not signals.
641
+
642
+ **A signal's `id` is derived, not counted**: a hash of what it says, with a
643
+ counter only for two signals that say the same thing in one millisecond. A log
644
+ written before ids existed gets the same ids on every read, so a host can key a
645
+ row by one, or remember what a person has seen. A merge conflict names the merge
646
+ (`head`), and a join names where each file it moved went (`copies`).
647
+
648
+ ## The history a host shows, and going back (`src/fs-history.ts`)
649
+
650
+ A host lists a folder's past from the chain, never from a node's own insert
651
+ rows: those record only the trees that node stored itself, so after a pull the
652
+ newest row is not the state the folder is in.
653
+
654
+ **The order is a walk, not a sort.** The chain is a graph — two lineages run
655
+ side by side until a merge — and a person reads it a page at a time, so the
656
+ walk keeps a queue and takes the newest waiting entry: by stamp (an
657
+ announcement carries everything below the head it names, so an entry is never
658
+ stamped later than one made on top of it; an unstamped entry has not reached
659
+ the fleet and is newest of all), then within one announcement by the authoring
660
+ node's time, a merge taking the time of the entry it was reached from. And an
661
+ entry is never taken while one made on top of it waits, whatever the keys say.
662
+ The queue is the page's cursor.
663
+
664
+ **Going back is an edit.** `restoreRevision` records what the folder holds,
665
+ writes the revision with `cleanTarget`, and authors the result on top of the own
666
+ head, so every node follows and nothing leaves the history. Three things make
667
+ that safe:
668
+
669
+ - a file the scanner deferred — new, or written to while the scan ran — is in
670
+ no entry yet, and a prune or an overwrite would lose it with no copy
671
+ anywhere; the restore rescans until nothing is deferred, and gives up as
672
+ `busy` after `RESTORE_SETTLE_PASSES`;
673
+ - the prune's deletions are recorded as deletions seen, so the authoring guard
674
+ does not hold back what a person asked for;
675
+ - the mass-delete guard judges before anything is written. Judged after, a
676
+ refused restore had already overwritten what the tree holds, and the watcher
677
+ recorded that half as an edit.
678
+
679
+ A prune with `cleanTarget` touches content only: what the scanner ignores — the
680
+ agent's own state and signal log, `.fsagent-recovered/`, the host's ignore
681
+ list — is in no tree, so no tree's absence can delete it.
682
+
683
+ ## What grows, and what bounds it
1598
684
 
1599
- | bucket | the path is | action |
685
+ | structure | growth | bound |
1600
686
  | --- | --- | --- |
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.
687
+ | the chain | one entry per authored edit — the debounce coalesces a burst | walks are bounded by `DEFAULT_MAX_WALK` |
688
+ | the stamps (`${treeKey}EditStamps`) | one row per entry heard, two while its walk is open | as the chain |
689
+ | the signal log | one per signal | `SIGNAL_LOG_MAX`, `SIGNAL_ONCE_MAX` |
690
+ | what a cut-short apply wrote | the paths of one apply | cleared when the own head moves |
691
+ | what restore wrote, per path | one per file written | `RESTORED_BLOB_MEMORY_MAX` |
692
+ | receiving a head again after the folder moved | per own head | `RECEIVE_AGAIN_MAX` |
1691
693
 
1692
694
  ## A Copy in Progress Does Not Reach the Wire (`FsScanner`, the settle rule)
1693
695
 
@@ -1723,12 +725,22 @@ copied from a machine running fast arrives dated ahead, and a BIOS clock can be
1723
725
  years out; none of those is a file being written. `inTheFuture` excludes all
1724
726
  three.
1725
727
 
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.
728
+ **Only while watching.** A one-shot `extract()` or `storeInDb()` has no
729
+ follow-up scan, so deferring there does not delay a file, it drops one — and
730
+ `extract()` is public API. And nothing the agent decides reads a pass that may
731
+ have run while it was writing: after an apply, authoring scans afresh under
732
+ the lock (`scanFresh`). Without one it reads the watcher's last pass — every
733
+ extra look at a file mid-copy is another chance to hash it truncated, and
734
+ scanning afresh on every change hashed two to five times as many truncated
735
+ versions of a stalled copy.
736
+
737
+ **Never the agent's own writes.** What the agent writes whole — a restore, a
738
+ merge's conflicted copy — it tells the scanner (`noteWrite`), and the next scan
739
+ takes the file as written. Without that, a write in the second half of the
740
+ millisecond a scan starts in reads as "changed during this scan" — Node rounds
741
+ an mtime to the nearest millisecond, `Date.now()` truncates — so the scan
742
+ reuses the version before it, and a receiver authors that older version as an
743
+ edit, which reverts the writer's own copy everywhere.
1732
744
 
1733
745
  What no rule over `stat` can decide is a writer that pauses for a long time, and
1734
746
  `README.public.md` → "Known constraints" says what that costs.
@@ -1736,6 +748,44 @@ What no rule over `stat` can decide is a writer that pauses for a long time, and
1736
748
  **Tested by** `test/fs-clock-skew.spec.ts` (6) for the clock half and
1737
749
  `test/fs-slow-copy.spec.ts` (3) for the deferral itself.
1738
750
 
751
+ ## Ignore Matching (`src/fs-ignore.ts`)
752
+
753
+ Which files the sync never sees. Glob syntax — `*`, `?`, `**`, folders with
754
+ `/`, anchored at the root, `!` exceptions with last-match-wins,
755
+ case-insensitive, `/` equivalent to `\`.
756
+
757
+ The rule before was `name === pattern || name.startsWith(pattern)`, which
758
+ cannot express an extension: `*.exe` matched nothing, because no file is called
759
+ `*.exe` and none begins with it.
760
+
761
+ **The compatibility rule is load-bearing.** A pattern with none of `*`, `?`,
762
+ `/` or `\`, not starting with `!` and not ending with `/` keeps its old
763
+ prefix meaning. That is not courtesy to old configuration files: `~$` and
764
+ `.~lock.` are the Office and LibreOffice lock-file prefixes, and
765
+ `ATOMIC_TMP_PREFIX` (`.fsagent-tmp-`) is how the agent hides its own
766
+ in-progress writes from its own watcher. Read as globs all three would match
767
+ only a file named exactly that, every atomic write would return as a change
768
+ event, and the debounce that batches a push would be reset before it could
769
+ fire — a defect this package has already had.
770
+
771
+ The matcher is compiled once per agent, because a scan of a real catalogue asks
772
+ this question once per file.
773
+
774
+ **Tested by** `test/fs-ignore.spec.ts` (28), whose first block is one case per
775
+ pattern that appears in the shipped configuration or in the agent's own list —
776
+ that being the half which can break a running fleet.
777
+
778
+ ## Removed in 0.2.0
779
+
780
+ No compatibility with 0.1.x: every mechanism that existed to tolerate, migrate
781
+ from or diagnose it is gone, with its tests. Bucket sync and the manifest; the
782
+ tombstone log; the stated-removal gate (`planRemovals`) and the per-path edit
783
+ times; the no-chain heuristics and the anti-entropy module; the `~H~` prefix and
784
+ bare tree refs on the wire; `onConflict`, `refusedDeletions` and the conflict
785
+ log; the `resolveConflicts` option (the merge always runs); the old resolver and
786
+ its clock- and hash-based winners; `classify` and the tree-ref lookups; the
787
+ `conflict/merged`, `conflict/overwritten` and `config/degraded` signals.
788
+
1739
789
  ## Known Constraints
1740
790
 
1741
791
  ### macOS Finder Paste and Rename