@rljson/fs-agent 0.0.84 β†’ 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -8,919 +8,556 @@ found in the LICENSE file in the root of this package.
8
8
 
9
9
  # @rljson/fs-agent
10
10
 
11
- > **A powerful filesystem agent that seamlessly synchronizes your file system with RLJSON databases, providing automatic bidirectional sync, tree structures, and content-addressed blob storage.**
12
-
13
- ## Overview
14
-
15
- `@rljson/fs-agent` bridges the gap between your filesystem and RLJSON databases. It watches for changes, extracts hierarchical tree structures, stores file content efficiently in blob storage with automatic deduplication, and maintains complete version history. With built-in bidirectional synchronization, your filesystem and database stay perfectly in syncβ€”automatically.
16
-
17
- ### Why Use fs-agent?
18
-
19
- - πŸ”„ **Automatic Synchronization**: Changes flow seamlessly between filesystem and database
20
- - 🌳 **Tree Structures**: Represents directories as RLJSON tree structures with parent-child relationships
21
- - πŸ’Ύ **Smart Storage**: Content-addressed blob storage eliminates duplicate file content
22
- - πŸ“œ **Version History**: Every change is tracked with complete insert history
23
- - πŸ” **Bidirectional Sync**: Changes in either direction are automatically propagated
24
- - πŸ›‘οΈ **Loop Prevention**: Content-based dedup, ref tracking, and debounce prevent infinite sync loops
25
- - ⏱️ **Timeout Guards**: Every async operation is bounded to prevent silent hangs
26
- - 🎯 **Debounce**: Rapid filesystem events are coalesced into a single sync cycle
27
- - βœ… **Type-Safe**: Full TypeScript support with comprehensive type definitions
28
- - πŸ§ͺ **Battle-Tested**: 100% test coverage with 204 tests (SocketMock + Socket.IO)
29
- - 🧹 **Target Cleanup**: Optional `cleanTarget` restore prunes stale files and directories
30
-
31
- ## Installation
11
+ > **Keeps a folder on several machines the same, without a central authority
12
+ > deciding what the folder contains.**
13
+
14
+ Each machine watches its own folder, writes down what changed, and tells the
15
+ others. There is no master copy: a hub relays, it does not arbitrate. Two
16
+ people editing at once get one agreed result with both versions kept, and a
17
+ machine switched off for a week catches up without replaying the week.
18
+
19
+ - [What it is, in one page](#what-it-is-in-one-page)
20
+ - [Install](#install)
21
+ - [Quick start](#quick-start)
22
+ - [Starting and stopping](#starting-and-stopping)
23
+ - [Configuration](#configuration)
24
+ - [Ignore patterns](#ignore-patterns)
25
+ - [Reading what the agent is doing](#reading-what-the-agent-is-doing)
26
+ - [Using it without sync](#using-it-without-sync)
27
+ - [What it guarantees β€” and what it does not](#what-it-guarantees--and-what-it-does-not)
28
+ - [Troubleshooting](#troubleshooting)
29
+ - [Known constraints](#known-constraints)
30
+ - [Further reading](#further-reading)
31
+
32
+ ---
33
+
34
+ ## What it is, in one page
35
+
36
+ Three things, and the third is the one that matters.
37
+
38
+ **A folder becomes a tree.** The scanner walks the folder and produces an
39
+ RLJSON tree: one node per directory, one entry per file, each file's bytes in
40
+ content-addressed blob storage. Two files with the same bytes are stored once,
41
+ anywhere in the fleet. The tree has a **ref** β€” a content hash β€” and two
42
+ machines holding the same bytes compute the same ref. A file's modification
43
+ time is deliberately *not* part of that identity, because it does not survive a
44
+ restore byte for byte and on Windows regularly does not.
45
+
46
+ **A change becomes an edit.** Every change a machine makes is written into an
47
+ **edit chain**: what changed, what was removed, when, and which state it
48
+ followed. The chain is one shared history, identical on every machine, and it
49
+ is the only thing that answers a question. The filesystem is an *event source
50
+ only* β€” the watcher says something happened, and what that means is read from
51
+ the chain.
52
+
53
+ **That is why a deletion works.** An absence is not a deletion. A tree lacks a
54
+ path because the sender removed it, or because the sender never had it, and a
55
+ content hash cannot tell the two apart. So a removal is **stated** by the
56
+ machine that performed it, and a receiver applies what is stated rather than
57
+ inferring from what is missing. Every attempt to guess it instead cost data β€”
58
+ see [Known constraints](#known-constraints).
59
+
60
+ Consequences worth knowing before you start:
61
+
62
+ | | |
63
+ | --- | --- |
64
+ | **A deletion is a fact, not a gap** | so it survives a partition, a restart, and a peer who never heard about it |
65
+ | **A receiver never claims authorship** | so a machine catching up cannot out-order the person who actually typed |
66
+ | **A conflict keeps both versions** | one wins deterministically on every machine, the loser is kept as a renamed copy, and the conflict is reported |
67
+ | **Nothing is pruned on a peer's authority** | a tree you receive can add and overwrite; only a stated removal deletes |
68
+ | **A joining machine applies the history first** | and a file the history deliberately deleted is moved aside, not resurrected and not destroyed |
69
+
70
+ ---
71
+
72
+ ## Install
32
73
 
33
74
  ```bash
34
75
  npm install @rljson/fs-agent
35
76
  ```
36
77
 
37
- ## Quick Start
78
+ Peers: `@rljson/rljson`, `@rljson/db`, `@rljson/io`, `@rljson/bs`,
79
+ `@rljson/server`. Node 22 or newer.
80
+
81
+ ---
38
82
 
39
- ### Basic Usage - Automatic Sync
83
+ ## Quick start
40
84
 
41
- The simplest way to get started is with automatic synchronization:
85
+ **This is the production configuration.** Every option is here for the reason
86
+ named beside it; a setup without them runs, and quietly gives up guarantees you
87
+ probably want.
42
88
 
43
89
  ```typescript
44
90
  import { FsAgent } from '@rljson/fs-agent';
91
+ import { BsMem } from '@rljson/bs';
45
92
  import { Connector, Db } from '@rljson/db';
46
93
  import { IoMem, SocketMock } from '@rljson/io';
47
- import { BsMem } from '@rljson/bs';
48
- import { Route, createTreesTableCfg } from '@rljson/rljson';
94
+ import { createTreesTableCfg, Route } from '@rljson/rljson';
49
95
 
50
- // Setup database
96
+ // --- the database the folder is mirrored through -------------------------
51
97
  const io = new IoMem();
52
98
  await io.init();
53
99
  const db = new Db(io);
54
100
 
55
- // Create tree table (must end with "Tree")
101
+ // The table name MUST end in `Tree`. That suffix is what selects the
102
+ // filesystem engine at runtime β€” it is not a naming convention.
56
103
  const treeKey = 'projectFilesTree';
57
- const treeTableCfg = createTreesTableCfg(treeKey);
58
- await db.core.createTableWithInsertHistory(treeTableCfg);
104
+ await db.core.createTableWithInsertHistory(createTreesTableCfg(treeKey));
59
105
 
60
- // Create FsAgent
106
+ // --- the agent ----------------------------------------------------------
61
107
  const agent = new FsAgent('./my-project', new BsMem(), {
62
- ignore: ['node_modules', '.git', 'dist'],
63
- maxDepth: 10,
64
- });
65
-
66
- // Create Connector for socket-based synchronization
67
- const socket = new SocketMock();
68
- const route = Route.fromFlat(`/${treeKey}`);
69
- const connector = new Connector(db, route, socket);
108
+ ignore: ['node_modules', '.git', 'dist', '*.log'],
70
109
 
71
- // Start syncing
72
- const stopSync = await agent.syncToDb(db, connector, treeKey);
73
-
74
- // The agent now:
75
- // βœ“ Watches your filesystem for changes
76
- // βœ“ Extracts tree structures from directories
77
- // βœ“ Stores file content in blob storage
78
- // βœ“ Broadcasts changes via Connector
79
-
80
- // When you're done:
81
- stopSync();
82
- agent.dispose();
83
- ```
110
+ // Reconciles two edits to one file and keeps both versions. The host
111
+ // application
112
+ // sets this; a hub deliberately leaves it off to stay a dumb relay. Off,
113
+ // a conflicting edit is never merged.
114
+ resolveConflicts: true,
84
115
 
85
- ### Bidirectional Sync
116
+ // Told, not discovered: where a conflict is reported to a user.
117
+ onConflict: (reports) => console.warn('conflict', reports),
86
118
 
87
- Enable two-way synchronization so changes in the database also update the filesystem:
88
-
89
- ```typescript
90
- import { Connector } from '@rljson/db';
91
- import { Route } from '@rljson/rljson';
92
- import { SocketMock } from '@rljson/io';
93
-
94
- const agent = new FsAgent('./my-project', new BsMem(), {
95
- ignore: ['node_modules', '.git', 'dist'],
119
+ // So a restart does not re-read and re-hash the whole folder.
120
+ scanCachePath: '.cache/fs-agent-scan.json',
96
121
  });
97
122
 
98
- // Create Connector for bidirectional communication
123
+ // --- the transport ------------------------------------------------------
99
124
  const socket = new SocketMock();
100
125
  const route = Route.fromFlat(`/${treeKey}`);
101
- const connector = new Connector(db, route, socket);
102
-
103
- // Start filesystem β†’ database sync
104
- const stopToDb = await agent.syncToDb(db, connector, treeKey);
105
-
106
- // Start database β†’ filesystem sync (same Connector)
107
- const stopFromDb = await agent.syncFromDb(db, connector, treeKey);
108
-
109
- // Now the agent handles changes in BOTH directions:
110
- // 1. Filesystem changes β†’ automatically synced to database
111
- // 2. Database changes β†’ automatically synced to filesystem
112
- // 3. Loop prevention ensures no infinite sync cycles
113
- // 4. Both sides stay perfectly synchronized
114
-
115
- // Stop syncing
116
- stopToDb();
117
- stopFromDb();
118
- ```
119
-
120
- ## Core Concepts
121
-
122
- ### Tree Structures
123
-
124
- `fs-agent` represents your filesystem as RLJSON tree structures:
125
-
126
- ```typescript
127
- // Directory hierarchy:
128
- // my-project/
129
- // β”œβ”€β”€ src/
130
- // β”‚ β”œβ”€β”€ index.ts
131
- // β”‚ └── utils.ts
132
- // └── package.json
133
-
134
- // Becomes a tree structure where:
135
- // - Each file/directory is a tree node
136
- // - Nodes are content-addressed (identified by hash)
137
- // - Parent-child relationships are preserved
138
- // - Changes are tracked via insert history
139
- ```
140
-
141
- ### Blob Storage
142
-
143
- Files are stored efficiently using content-addressed blob storage:
144
-
145
- - **Deduplication**: Identical files are stored only once
146
- - **Content-Addressed**: Files are identified by their content hash
147
- - **Efficient**: Only changed files are re-stored
148
- - **Flexible**: Works with any `Bs` (Blob Storage) implementation
149
-
150
- ### Automatic Watching
151
-
152
- ### Automatic Synchronization (Constructor-based)
153
-
154
- **Note:** Constructor-based automatic synchronization using `db`, `treeKey`, and `bidirectional` options is deprecated and will throw an error. Use the explicit `syncToDb()` and `syncFromDb()` methods with a `Connector` instance instead (see examples above).
155
-
156
- The new approach provides better control and uses the Connector pattern for socket-based synchronization:
157
-
158
- ```typescript
159
- // ❌ Deprecated (will throw error)
160
- const agent = new FsAgent('./my-project', new BsMem(), {
161
- db,
162
- treeKey,
163
- bidirectional: true,
126
+ const connector = new Connector(db, route, socket, {
127
+ // A REQUIREMENT, not a tuning option: the predecessor refs this puts on
128
+ // the wire are what let a conflicting edit be merged at all. The agent
129
+ // warns, once and loudly, if it is missing.
130
+ causalOrdering: true,
131
+ includeClientIdentity: true,
164
132
  });
165
133
 
166
- // βœ… Use this instead
167
- const agent = new FsAgent('./my-project', new BsMem());
168
- const connector = new Connector(db, route, socket);
169
- const stopToDb = await agent.syncToDb(db, connector, treeKey);
134
+ // --- start: RECEIVE FIRST, then push ------------------------------------
135
+ // A machine that announces before it can hear speaks about a state it may be
136
+ // about to replace.
170
137
  const stopFromDb = await agent.syncFromDb(db, connector, treeKey);
171
- ```
172
-
173
- ### Live Client-Server Demo
174
-
175
- Run the live in-process demo that mirrors changes between two folders using the same approach as our sync tests (SocketMock, IoMem, BsMem):
176
-
177
- ```bash
178
- pnpm exec vite-node src/live-client-server.ts
179
- ```
180
-
181
- It wipes and recreates `demo/live-client-server/folder-a` and `demo/live-client-server/folder-b`, seeds sample files, and keeps them in sync until you press Ctrl+C. Pass `--keep-existing` to skip the reset.
182
-
183
- ## API Reference
184
-
185
- ### FsAgent
186
-
187
- Main class that orchestrates filesystem operations.
188
-
189
- #### Constructor
190
-
191
- ```typescript
192
- new FsAgent(rootPath: string, bs?: Bs, options?: FsAgentOptions)
193
- ```
194
-
195
- **Parameters:**
196
-
197
- - `rootPath` - Root directory to monitor
198
- - `bs` - Blob storage instance (defaults to `BsMem`)
199
- - `options` - Configuration options
200
-
201
- **Options:**
202
-
203
- ```typescript
204
- interface FsAgentOptions {
205
- // Scanning options
206
- ignore?: string[]; // Patterns to ignore (e.g., ['node_modules', '*.log'])
207
- maxDepth?: number; // Maximum directory depth to scan
208
- followSymlinks?: boolean; // Whether to follow symbolic links (default: false)
209
-
210
- // Deprecated options (will throw error if used)
211
- // Use syncToDb()/syncFromDb() methods with Connector instead
212
- db?: Db; // DEPRECATED
213
- treeKey?: string; // DEPRECATED
214
- bidirectional?: boolean; // DEPRECATED
215
- storageOptions?: StoreFsTreeOptions; // DEPRECATED
216
- restoreOptions?: RestoreOptions; // DEPRECATED
217
- }
218
- maxDepth?: number; // Maximum directory depth (default: 10)
219
- followSymlinks?: boolean; // Follow symbolic links (default: false)
220
-
221
- // Automatic sync options
222
- db?: Db; // Database instance for auto-sync
223
- treeKey?: string; // Tree table key for storage
224
- storageOptions?: {
225
- // Options for database storage
226
- includeBlobs?: boolean; // Include blob data in tree (default: true)
227
- };
228
-
229
- // Bidirectional sync
230
- bidirectional?: boolean; // Enable database β†’ filesystem sync (default: false)
231
-
232
- // Restore options applied when syncing from DB (e.g., cleanTarget)
233
- restoreOptions?: RestoreOptions;
234
- }
235
- ```
236
-
237
- #### Properties
238
-
239
- ```typescript
240
- agent.rootPath: string // Root directory path
241
- agent.bs: Bs // Blob storage instance
242
- agent.scanner: FsScanner // File scanner instance
243
- agent.adapter: FsBlobAdapter // Blob adapter instance
244
- ```
245
-
246
- #### Methods
247
-
248
- ##### `extract(): Promise<FsTree>`
249
-
250
- Extracts the current filesystem as a tree structure.
251
-
252
- ```typescript
253
- const tree = await agent.extract();
254
- // Returns: { rootHash: string, trees: Map<string, Tree> }
255
- ```
256
-
257
- ##### `restore(tree: FsTree, targetPath?: string, options?: RestoreOptions): Promise<void>`
258
-
259
- Restores a tree structure to the filesystem. Use `options.cleanTarget` to remove files and directories that are not part of the tree (helpful for propagating renames or deletions):
260
-
261
- ```typescript
262
- await agent.restore(tree, './restore-location', { cleanTarget: true });
263
- ```
264
-
265
- ##### `storeInDb(db: Db, treeKey: string, options?: StoreFsTreeOptions): Promise<void>`
266
-
267
- Manually stores the current filesystem state in the database.
268
-
269
- ```typescript
270
- await agent.storeInDb(db, 'myFilesTree', { includeBlobs: true });
271
- ```
272
-
273
- ##### `syncToDb(db: Db, connector: Connector, treeKey: string, options?: StoreFsTreeOptions): Promise<() => void>`
274
-
275
- Starts watching filesystem and syncing to database using Connector for socket-based broadcasts.
276
-
277
- ```typescript
278
- import { Connector } from '@rljson/db';
279
- import { Route } from '@rljson/rljson';
280
- import { SocketMock } from '@rljson/io';
281
-
282
- const socket = new SocketMock();
283
- const route = Route.fromFlat(`/${treeKey}+`);
284
- const connector = new Connector(db, route, socket);
285
-
286
- const stopSync = await agent.syncToDb(db, connector, 'myFilesTree');
287
- // Later: stopSync();
288
- ```
289
-
290
- ##### `syncFromDb(db: Db, connector: Connector, treeKey: string, restoreOptions?: RestoreOptions): Promise<() => void>`
291
-
292
- Starts listening to database changes via Connector and syncing to filesystem.
293
-
294
- ```typescript
295
- import { Connector } from '@rljson/db';
296
- import { Route } from '@rljson/rljson';
297
- import { SocketMock } from '@rljson/io';
298
-
299
- const socket = new SocketMock();
300
- const route = Route.fromFlat(`/${treeKey}+`);
301
- const connector = new Connector(db, route, socket);
302
-
303
- const stopSync = await agent.syncFromDb(db, connector, 'myFilesTree', {
304
- cleanTarget: true // Optional: remove files not in tree
305
- });
306
- // Later: stopSync();
307
- ```
308
-
309
- ##### `dispose(): void`
310
-
311
- Stops all syncing and cleans up resources.
312
-
313
- ```typescript
314
- agent.dispose();
315
- ```
316
-
317
- ##### `static fromClient(filePath, treeKey, client, socket, options?): Promise<FsAgent>`
318
-
319
- Factory method that creates an FsAgent wired to a `@rljson/server` Client. Returns an enhanced agent with simplified sync methods:
320
-
321
- ```typescript
322
- import { Client } from '@rljson/server';
323
-
324
- const agent = await FsAgent.fromClient(
325
- './my-project',
326
- 'sharedTree',
327
- client,
328
- socket,
329
- { ignore: ['node_modules', '.git'] },
330
- );
331
-
332
- // Simplified sync (no need to manage Db/Connector manually)
333
- const stopToDb = await agent.syncToDbSimple({ notify: true });
334
- const stopFromDb = await agent.syncFromDbSimple({ cleanTarget: true });
335
-
336
- // Stop when done
337
- stopToDb();
338
- stopFromDb();
339
- ```
340
-
341
- **Reconnect handling:** When the Client supports `onDisconnect` / `onReconnect` (available since `@rljson/server` β‰₯ 0.0.10), `fromClient()` automatically:
342
-
343
- - **Pauses** the filesystem watcher on disconnect (prevents futile sync attempts while the server is unreachable)
344
- - **Resumes** the watcher on reconnect (the server's bootstrap message triggers a catch-up sync via the Connector)
345
-
346
- No application code is needed β€” the wiring is built into `fromClient()`. Clients created with older server versions that lack these methods continue to work without interruption.
347
-
348
- ### FsScanner
349
-
350
- Low-level filesystem scanner (usually accessed via `agent.scanner`).
351
-
352
- #### Methods
353
-
354
- ```typescript
355
- // Scan filesystem once
356
- const tree = await scanner.scan();
357
-
358
- // Start watching for changes
359
- await scanner.watch();
360
-
361
- // Register change callback
362
- scanner.onChange(async (change) => {
363
- console.log(change.type, change.path);
364
- });
365
-
366
- // Pause/resume watching (for loop prevention)
367
- scanner.pauseWatch();
368
- scanner.resumeWatch();
369
-
370
- // Get root tree
371
- const rootTree = scanner.getRootTree();
372
- ```
373
-
374
- ## Advanced Usage
375
-
376
- ### Manual Sync Control
377
-
378
- If you need fine-grained control over synchronization:
379
-
380
- ```typescript
381
- import { Connector } from '@rljson/db';
382
- import { Route } from '@rljson/rljson';
383
- import { SocketMock } from '@rljson/io';
384
-
385
- const agent = new FsAgent('./my-project', new BsMem());
386
-
387
- // Create Connector for synchronization
388
- const treeKey = 'myFilesTree';
389
- const socket = new SocketMock();
390
- const route = Route.fromFlat(`/${treeKey}`);
391
- const connector = new Connector(db, route, socket);
392
-
393
- // Start filesystem β†’ database sync
394
138
  const stopToDb = await agent.syncToDb(db, connector, treeKey);
395
139
 
396
- // Start database β†’ filesystem sync
397
- const stopFromDb = await agent.syncFromDb(db, connector, treeKey);
398
-
399
- // Stop when needed
140
+ // ... later
400
141
  stopToDb();
401
142
  stopFromDb();
143
+ agent.dispose();
402
144
  ```
403
145
 
404
- ### Custom Blob Storage
146
+ ### Against a `Client` from `@rljson/server`
405
147
 
406
- Use any blob storage implementation:
148
+ What the host application does, and **the path that defaults to the
149
+ configuration above**. `fromClient` builds the `Db`, the `Connector` and the
150
+ blob store from an initialised client, adds two convenience wrappers, and
151
+ defaults `resolveConflicts`, `causalOrdering` and `includeClientIdentity` to
152
+ `true`, because that is the only mode this package measures end to end. Your own
153
+ values still win if you pass them.
407
154
 
408
- ```typescript
409
- import { BsSql } from '@rljson/bs-sql';
410
-
411
- // SQL-backed blob storage
412
- const sqlBs = new BsSql(myDatabase);
413
- const agent = new FsAgent('./my-project', sqlBs, {
414
- db,
415
- treeKey: 'filesTree',
416
- });
417
- ```
418
-
419
- ### Ignore Patterns
420
-
421
- Control what gets scanned and synced:
155
+ `new FsAgent(...)` keeps the primitive defaults β€” it is the building block, and
156
+ the quick start above sets them explicitly for exactly that reason.
422
157
 
423
158
  ```typescript
424
- const agent = new FsAgent('./my-project', new BsMem(), {
425
- db,
426
- treeKey: 'filesTree',
427
- ignore: [
428
- 'node_modules',
429
- '.git',
430
- 'dist',
431
- 'coverage',
432
- '*.log',
433
- '.DS_Store',
434
- 'tmp/**',
435
- ],
159
+ const agent = await FsAgent.fromClient(folder, treeKey, client, socket, {
160
+ ignore,
161
+ resolveConflicts: true,
162
+ scanCachePath,
436
163
  });
437
- ```
438
-
439
- ### Limited Depth Scanning
440
164
 
441
- Control how deep to traverse directories:
442
-
443
- ```typescript
444
- const agent = new FsAgent('./my-project', new BsMem(), {
445
- db,
446
- treeKey: 'filesTree',
447
- maxDepth: 3, // Only scan 3 levels deep
448
- });
165
+ const stopFromDb = await agent.syncFromDbSimple();
166
+ const stopToDb = await agent.syncToDbSimple();
449
167
  ```
450
168
 
451
- ### Extract and Restore
169
+ ---
452
170
 
453
- Work with tree structures directly:
171
+ ## Starting and stopping
454
172
 
455
- ```typescript
456
- // Extract current state
457
- const tree = await agent.extract();
173
+ Three calls, and they are not interchangeable.
458
174
 
459
- // Trees are content-addressed
460
- console.log('Root hash:', tree.rootHash);
461
- console.log('Total nodes:', tree.trees.size);
175
+ | call | starts | returns |
176
+ | --- | --- | --- |
177
+ | `syncFromDb(db, connector, treeKey, restoreOptions?)` | receiving β€” applying what peers announce | a `stop()` |
178
+ | `syncToDb(db, connector, treeKey, storageOptions?)` | sending β€” watching the folder and announcing | a `stop()` |
179
+ | `dispose()` | β€” | nothing; **abandons a pending join** |
462
180
 
463
- // Restore to a different location
464
- await agent.restore(tree, './backup-location');
181
+ **Start receiving first.** A machine that pushes before it can receive
182
+ announces a state it may be about to replace, and on an established fleet that
183
+ is how a stale folder becomes the newest claim.
465
184
 
466
- // Or restore from database
467
- const dbAdapter = new FsDbAdapter(db, 'myFilesTree');
468
- const treeFromDb = await dbAdapter.loadFsTree('abc123'); // tree hash
469
- await agent.restore(treeFromDb, './restore-here');
470
- ```
185
+ **Each `stop()` stops its own direction** β€” the watcher, the debounce, the
186
+ poll. Call both.
471
187
 
472
- ### Version History
188
+ **`dispose()` is not the stopper.** It cancels a join this agent is still
189
+ waiting on. A folder that starts with files and no history defers its first
190
+ announcement and asks the network for its state repeatedly until a bounded wait
191
+ expires, and no `stop()` ends that β€” so a machine shut down mid-join keeps
192
+ asking a transport that is being torn down. Call it last, after both stops.
473
193
 
474
- Access historical versions via insert history:
194
+ ### What happens in the first few seconds
475
195
 
476
- ```typescript
477
- import { Route } from '@rljson/rljson';
196
+ Worth knowing, because it looks like a stall and is not.
478
197
 
479
- // Get insert history for the tree
480
- const route = Route.fromFlat(`${treeKey}/`);
481
- const historyResult = await db.getInsertHistory(route, {});
198
+ 1. **The folder is scanned.** A cold scan of a large catalogue is minutes, not
199
+ milliseconds. Pass `scanCachePath`.
200
+ 2. **If the folder has files but no history, the agent says nothing yet.** It
201
+ asks the network for its state first (`joinWaitMs`, default 1 500 ms). This
202
+ is what stops a restored backup pushing a month of deleted files back to the
203
+ fleet.
204
+ 3. **If a head arrives**, the agent reconciles against it: writes what it
205
+ lacks, keeps its own new work, moves anything the history deliberately
206
+ deleted into `.fsagent-recovered/`, and keeps a locally edited file as a
207
+ conflict copy.
208
+ 4. **If nothing arrives** within the wait, this folder is the origin of its own
209
+ history and announces normally.
482
210
 
483
- // historyResult contains all versions with timestamps
484
- for (const entry of historyResult.history) {
485
- const treeRef = entry.treeRef;
486
- const timestamp = entry.insertedAt;
211
+ If your folder *is* the origin β€” a fixture, a test, a brand-new network β€” set
212
+ `joinWaitMs: 0` and skip the wait honestly.
487
213
 
488
- // Load and restore specific version
489
- const tree = await agent.loadFromDb(db, treeKey, treeRef);
490
- await agent.restore(tree, `./version-${timestamp}`);
491
- }
492
- ```
214
+ ---
493
215
 
494
- ### Change Detection
216
+ ## Configuration
495
217
 
496
- React to specific filesystem changes:
218
+ Everything `FsAgentOptions` accepts, its default, and what choosing otherwise
219
+ costs.
497
220
 
498
- ```typescript
499
- agent.scanner.onChange(async (change) => {
500
- switch (change.type) {
501
- case 'add':
502
- console.log('File added:', change.path);
503
- break;
504
- case 'change':
505
- console.log('File modified:', change.path);
506
- break;
507
- case 'unlink':
508
- console.log('File deleted:', change.path);
509
- break;
510
- case 'addDir':
511
- console.log('Directory created:', change.path);
512
- break;
513
- case 'unlinkDir':
514
- console.log('Directory deleted:', change.path);
515
- break;
516
- }
517
- });
518
- ```
221
+ ### Sync behaviour
519
222
 
520
- ## Error Handling
223
+ | option | default | what it does |
224
+ | --- | --- | --- |
225
+ | `resolveConflicts` | `false` on the constructor, **`true` via `fromClient`** | Reconciles two edits to one file, keeping the loser as a renamed copy. Off, a conflicting edit is never merged β€” the resolver is not even constructed. The constructor keeps the primitive default because a hub may relay without arbitrating |
226
+ | `onConflict` | β€” | Called with the conflict reports. Without it a conflict is resolved and nobody is told |
227
+ | `joinWaitMs` | `1500` | How long a folder with files and no history waits for the network before speaking. `0` means "this folder is its own origin" |
228
+ | `bucketSync` | `true` | Repairs a divergence by comparing manifests and fetching only what is missing, instead of replacing a folder |
229
+ | `antiEntropy` | `DEFAULT_ANTI_ENTROPY` | The periodic comparison that heals a lost announcement. A machine that is behind **asks**, rather than waiting to be told |
230
+ | `syncConfig` | **`causalOrdering` and `includeClientIdentity` default to `true` via `fromClient`** | Forwarded to every `Connector` the agent builds. Without `causalOrdering` the wire carries no predecessor refs, so no conflicting edit can be merged β€” the agent warns once, loudly |
231
+ | `clientIdentity` | β€” | Who this machine is, on the wire |
521
232
 
522
- `fs-agent` provides robust error handling with clear error messages:
233
+ ### Scanning
523
234
 
524
- ```typescript
525
- try {
526
- const agent = new FsAgent('./nonexistent', new BsMem(), {
527
- db,
528
- treeKey: 'filesTree',
529
- });
530
- } catch (error) {
531
- // Error: Root path "./nonexistent" does not exist. Cannot scan non-existent directory.
532
- }
533
- ```
235
+ | option | default | what it does |
236
+ | --- | --- | --- |
237
+ | `ignore` | `[]` | Patterns not to sync β€” see [Ignore patterns](#ignore-patterns) |
238
+ | `maxDepth` | unlimited | Stop descending after N levels |
239
+ | `followSymlinks` | `false` | Follow links out of the folder. Leave it off unless you mean it |
240
+ | `scanCachePath` | β€” | Where to persist file hashes between runs. **Pass this.** Without it every restart re-reads and re-hashes the whole folder |
534
241
 
535
- ### Common Error Scenarios
242
+ ### Timeouts (`timeouts`)
536
243
 
537
- 1. **Missing Root Path**: Clear error if directory doesn't exist
538
- 2. **Database Failures**: Errors include context about what operation failed
539
- 3. **Invalid Tree Data**: Validation errors explain what's wrong
540
- 4. **Sync Failures**: Non-fatal errors logged, syncing continues
541
- 5. **Loop Detection**: Automatic prevention via pause/resume
244
+ Every async step is bounded, because an unbounded one is a silent hang.
542
245
 
543
- ## Examples
246
+ | field | default |
247
+ | --- | --- |
248
+ | `dbQuery` | 10 000 ms |
249
+ | `fetchTree` | 20 000 ms |
250
+ | `extract` | 15 000 ms |
251
+ | `restore` | 15 000 ms |
252
+ | `syncCallback` | 25 000 ms |
253
+ | `debounceMs` | 300 ms |
254
+ | `processRefRetries` | 3 |
255
+ | `processRefRetryDelayMs` | 5 000 ms |
256
+ | `recoveryRetries` | 10 |
544
257
 
545
- ### Example 1: Simple Project Sync
258
+ `debounceMs` coalesces a burst of filesystem events into one sync cycle. Raise
259
+ it on a folder under constant churn, lower it to make a single save feel
260
+ immediate. A large catalogue wants a larger `extract` and `restore` than the
261
+ defaults.
546
262
 
547
- ```typescript
548
- import { FsAgent } from '@rljson/fs-agent';
549
- import { Connector, Db } from '@rljson/db';
550
- import { IoMem, SocketMock } from '@rljson/io';
551
- import { BsMem } from '@rljson/bs';
552
- import { Route, createTreesTableCfg } from '@rljson/rljson';
553
-
554
- async function syncProject() {
555
- // Setup
556
- const io = new IoMem();
557
- await io.init();
558
- const db = new Db(io);
559
-
560
- const treeKey = 'projectTree';
561
- const treeTableCfg = createTreesTableCfg(treeKey);
562
- await db.core.createTableWithInsertHistory(treeTableCfg);
563
-
564
- // Create agent
565
- const agent = new FsAgent('./src', new BsMem(), {
566
- ignore: ['*.tmp'],
567
- });
568
-
569
- // Create Connector and start syncing
570
- const socket = new SocketMock();
571
- const route = Route.fromFlat(`/${treeKey}+`);
572
- const connector = new Connector(db, route, socket);
573
- const stopSync = await agent.syncToDb(db, connector, treeKey);
574
-
575
- // Clean up when done
576
- process.on('SIGINT', () => {
577
- stopSync();
578
- agent.dispose();
579
- process.exit();
580
- });
581
- }
582
- ```
263
+ ### `restoreOptions.cleanTarget` β€” read this before setting it
583
264
 
584
- ### Example 2: Backup and Restore
265
+ `cleanTarget: true` makes `restore()` prune anything not in the tree. **The
266
+ sync path ignores it and always applies additively**, because pruning on a
267
+ received tree is precisely how an absence becomes a deletion. It is honoured
268
+ only by a direct `restore()` call, where *you* are asserting the tree is the
269
+ whole truth. Passing it to `syncFromDb` is harmless and has no effect.
585
270
 
586
- ```typescript
587
- async function backupAndRestore() {
588
- // Create agent
589
- const agent = new FsAgent('./my-data', new BsMem());
271
+ ---
590
272
 
591
- // Extract current state
592
- const backup = await agent.extract();
593
- console.log('Backed up', backup.trees.size, 'nodes');
273
+ ## Ignore patterns
594
274
 
595
- // ... later, restore from backup
596
- await agent.restore(backup, './my-data-restored');
597
- }
598
- ```
275
+ Glob syntax, matched case-insensitively, with `/` and `\` equivalent in both
276
+ the path and the pattern.
599
277
 
600
- ### Example 2b: Clean Restore (remove stale files)
278
+ | | |
279
+ | --- | --- |
280
+ | `*` | any run of characters within one path segment |
281
+ | `?` | one character within one segment |
282
+ | `**` | crosses separators. A leading `**/` also matches at the root, so `**/tmp` means `tmp` anywhere |
283
+ | `/` in the pattern | matches the whole path, **anchored at the folder root** β€” `build/out.txt` is the top-level one, not every `build` |
284
+ | trailing `/` | names a directory, and covers its contents |
285
+ | leading `!` | an exception, rescuing what an earlier line ignored |
601
286
 
602
- ```typescript
603
- async function cleanRestore() {
604
- const agent = new FsAgent('./source', new BsMem());
605
- const snapshot = await agent.extract();
287
+ **Order matters: the last matching line decides.** `['*.log', '!keep.log']`
288
+ keeps `keep.log`; reversed, it does not. A scan does not descend into an
289
+ ignored directory, so an `!` line cannot rescue a file inside one.
606
290
 
607
- // Restore to target and prune anything not in the snapshot
608
- await agent.restore(snapshot, './target', { cleanTarget: true });
609
- }
610
- ```
291
+ Blank lines and `#` comments are allowed.
611
292
 
612
- ### Example 3: Bidirectional Sync
293
+ ### The compatibility rule
613
294
 
614
- ```typescript
615
- async function bidirectionalSync() {
616
- // Setup database
617
- const io = new IoMem();
618
- await io.init();
619
- const db = new Db(io);
620
-
621
- const treeTableCfg = createTreesTableCfg('sharedTree');
622
- await db.core.createTableWithInsertHistory(treeTableCfg);
623
-
624
- // Agent 1: Watches ./alice and syncs to DB
625
- const alice = new FsAgent('./alice', new BsMem(), {
626
- db,
627
- treeKey: 'sharedTree',
628
- bidirectional: true, // ← Bidirectional
629
- });
630
-
631
- // Agent 2: Watches ./bob and syncs to DB
632
- const bob = new FsAgent('./bob', new BsMem(), {
633
- db,
634
- treeKey: 'sharedTree',
635
- bidirectional: true, // ← Bidirectional
636
- });
637
-
638
- // Now:
639
- // - Changes in ./alice β†’ sync to DB β†’ appear in ./bob
640
- // - Changes in ./bob β†’ sync to DB β†’ appear in ./alice
641
- // - Loop prevention ensures stability
642
- }
643
- ```
295
+ **A pattern containing none of `*`, `?`, `/` or `\`, not starting with `!` and
296
+ not ending with `/` keeps its older meaning: equal to, or a prefix of, any path
297
+ segment.**
644
298
 
645
- ### Example 4: Custom Change Handling
299
+ That is deliberate and load-bearing, not politeness to old configuration files.
300
+ `~$` is Word's lock-file prefix and `.~lock.` is LibreOffice's β€” neither is a
301
+ fixed name β€” and `.fsagent-tmp-` is how this agent hides its own in-progress
302
+ writes from its own watcher. Read as globs they would match only a file named
303
+ exactly that.
646
304
 
647
305
  ```typescript
648
- async function customHandling() {
649
- const agent = new FsAgent('./watched', new BsMem(), {
650
- db,
651
- treeKey: 'watchedTree',
652
- });
653
-
654
- let changeCount = 0;
655
-
656
- agent.scanner.onChange(async (change) => {
657
- changeCount++;
658
-
659
- if (change.type === 'add' && change.path.endsWith('.ts')) {
660
- console.log(`New TypeScript file: ${change.path}`);
661
- // Could trigger build, linting, etc.
662
- }
663
-
664
- if (changeCount % 10 === 0) {
665
- console.log(`Processed ${changeCount} changes`);
666
- }
667
- });
668
- }
306
+ ignore: [
307
+ 'node_modules', // prefix: also matches anything starting with it
308
+ '~$', // every Word lock file
309
+ '*.log', // every log file, at any depth
310
+ 'build/', // the top-level build folder and its contents
311
+ '**/tmp', // tmp anywhere
312
+ '!build/keep.txt', // ...except this one
313
+ ]
669
314
  ```
670
315
 
671
- ## Best Practices
672
-
673
- ### 1. Use Ignore Patterns
674
-
675
- Always ignore build artifacts, dependencies, and temporary files:
316
+ `compileIgnore` is exported, so a UI can validate or preview a list before
317
+ saving it:
676
318
 
677
319
  ```typescript
678
- {
679
- ignore: [
680
- 'node_modules',
681
- '.git',
682
- 'dist',
683
- 'build',
684
- 'coverage',
685
- '*.log',
686
- '.DS_Store',
687
- 'tmp',
688
- ];
689
- }
690
- ```
320
+ import { compileIgnore } from '@rljson/fs-agent';
691
321
 
692
- ### 2. Dispose When Done
693
-
694
- Always clean up resources:
695
-
696
- ```typescript
697
- const agent = new FsAgent(path, bs, options);
698
-
699
- try {
700
- // Use agent...
701
- } finally {
702
- agent.dispose();
703
- }
322
+ const matcher = compileIgnore(patterns);
323
+ matcher.ignores('src/server.log'); // true
704
324
  ```
705
325
 
706
- ### 3. Use Bidirectional Sync Carefully
707
-
708
- Bidirectional sync is powerful but consider:
709
-
710
- - Multiple agents sharing the same `treeKey` will sync to each other
711
- - Loop prevention is automatic but adds slight latency
712
- - Best for collaborative scenarios or distributed systems
713
-
714
- ### 4. Monitor Depth
715
-
716
- Use `maxDepth` for deep directory structures:
326
+ ---
717
327
 
718
- ```typescript
719
- {
720
- maxDepth: 5, // Prevents extremely deep recursion
721
- }
722
- ```
328
+ ## Reading what the agent is doing
723
329
 
724
- ### 5. Handle Errors
330
+ | | |
331
+ | --- | --- |
332
+ | `agent.stageTimings` | milliseconds per stage of the **last** cycle β€” scan, hash, store, announce, fetch, write, re-derive. A total says a run was slow; this says where |
333
+ | `agent.antiEntropyStatus` | whether this machine agrees with the hub, and what it last did about it |
334
+ | `agent.refusedDeletions` | deletions the mass-delete guard **refused**, newest last β€” `{ atMs, route, wouldRemove, held, paths }`. Read this to answer "why did my deletion not arrive": the guard refuses on every machine, so a deliberate mass deletion stalls the whole fleet and the only other trace is a line in each machine's log. Bounded at `REFUSED_DELETION_LOG_MAX`, in memory, and it refills on the next announcement |
335
+ | `agent.scanner.onChange(cb)` | every filesystem event the scanner accepted |
336
+ | `onConflict` | conflicts, as they are resolved |
337
+ | `SYNC_ERROR_FILE` | `.sync-errors.log` in the folder: a keyed, append-only record of every refusal and failure β€” a locked file, an unfetchable blob, an impossible path, a refused mass deletion |
338
+ | `.fsagent-conflicts.json` | resolved conflicts, bounded |
339
+ | `.fsagent-recovered/` | files a join kept but deliberately did not announce |
340
+ | `.fsagent-state.json` | what this machine remembers across restarts: the state it was last at, the paths it deleted, and **when each path was last edited**. The edit times are what let a peer's tombstone be ordered against the write it claims to supersede β€” a machine that has forgotten them sends no time, and the comparison has one operand |
725
341
 
726
- Wrap agent creation in try-catch for better error handling:
342
+ All of these live inside the synced folder and all are ignored by the scanner β€”
343
+ otherwise the notification would itself be content, propagate, and be rewritten
344
+ by every peer.
727
345
 
728
- ```typescript
729
- try {
730
- const agent = new FsAgent(userProvidedPath, bs, options);
731
- } catch (error) {
732
- console.error('Failed to create agent:', error.message);
733
- }
734
- ```
346
+ ---
735
347
 
736
- ## Timeout & Debounce Configuration
348
+ ## Using it without sync
737
349
 
738
- Every async operation in FsAgent is guarded by a timeout to prevent silent hangs.
739
- Rapid filesystem events are debounced to coalesce into a single sync cycle.
350
+ The scanner and the tree are useful on their own.
740
351
 
741
352
  ```typescript
742
- const agent = new FsAgent('./my-project', bs, {
743
- timeouts: {
744
- dbQuery: 10_000, // Single db.get() query (default: 10s)
745
- fetchTree: 20_000, // Fetching an entire tree from the DB (default: 20s)
746
- extract: 15_000, // Filesystem extract/scan (default: 15s)
747
- restore: 15_000, // Filesystem restore (default: 15s)
748
- syncCallback: 25_000, // Overall syncFromDb callback (default: 25s)
749
- debounceMs: 300, // Coalesce rapid FS events (default: 300ms)
750
- processRefRetries: 3, // Retry failed refs before dropping (default: 3)
751
- processRefRetryDelayMs: 5_000, // Base delay between retries (default: 5s)
752
- },
753
- });
754
- ```
755
-
756
- ### processRef Retry Behavior
757
-
758
- When `syncFromDb` receives a tree ref and fails to process it (e.g. `db.get`
759
- times out because the IoPeer transport hasn't connected yet), the ref is
760
- retried up to `processRefRetries` times with increasing delay
761
- (`attempt * processRefRetryDelayMs`). This prevents a single transient
762
- timeout from permanently breaking the sync pipeline.
353
+ const agent = new FsAgent('./folder', new BsMem());
763
354
 
764
- ## Anti-Entropy β€” healing a lost message
765
-
766
- Every change reaches a peer as exactly one message. If that message is lost β€”
767
- a push the hub never received, a forward a peer never received, an apply that
768
- gave up β€” nothing would ever send it again, and two machines would sit on two
769
- states for good. The anti-entropy notices and repairs that, with nobody doing
770
- anything.
771
-
772
- It is driven by the hub's periodic announcement of its state, so the server
773
- must send one. Use the **state beacon** (`@rljson/server` 0.0.67+): it goes on
774
- its own event, which the connector never processes, so it costs nothing in
775
- the apply path. The bootstrap heartbeat works too, but a periodic heartbeat
776
- is delivered into every agent's apply path and has been measured
777
- net-harmful in production.
778
-
779
- ```typescript
780
- const server = new Server(route, io, bs, {
781
- syncConfig: { causalOrdering: true, includeClientIdentity: true },
782
- stateBeaconMs: 30_000,
783
- });
784
-
785
- const agent = new FsAgent('./my-project', bs, {
786
- antiEntropy: {
787
- enabled: true, // default: true
788
- graceMs: 10_000, // how long this node may sit still, out of step, before a repair (default: 10s)
789
- maxBackoffMs: 300_000 // cap for repeated repairs of one divergence (default: 5 min)
790
- },
791
- });
792
- ```
355
+ // Folder -> tree (+ blobs)
356
+ const tree = await agent.extract();
793
357
 
794
- Each announcement carries the hub's tree ref β€” a content hash of the whole
795
- folder, so comparing it with our own is the per-folder checksum comparison β€”
796
- plus who produced it and what it descends from. A divergence that outlives
797
- `graceMs` while nothing is applying is repaired:
798
-
799
- | Hub state | Repair |
800
- |---|---|
801
- | an earlier push of ours, or what our push was made from | **push** β€” re-announce our state |
802
- | made from the state we are in | **pull** β€” apply it, deletions included |
803
- | neither can be shown | **merge** β€” apply it; if that makes no progress, additively |
804
-
805
- Every repair goes through the ordinary apply and push paths, with their
806
- ancestry and mass-delete rules; the anti-entropy never deletes anything
807
- itself. Without a beacon or heartbeat it never fires. `agent.antiEntropyStatus`
808
- reports whether this node and the hub agree, since when they have not, and
809
- the last repair β€” a lasting divergence is the one trace a lost message leaves.
810
-
811
- ## Bounce-Back Prevention
812
-
813
- Bidirectional sync can cause infinite loops when both clients detect each
814
- other's restores as changes. FsAgent prevents this with three layers:
815
-
816
- 1. **Ref tracking** (`_lastSentRef`): Skips re-broadcast if the stored tree
817
- produces the same ref as the last one we sent.
818
- 2. **Content-key dedup** (`_lastSentContentKey`): Compares file paths + blobIds
819
- (ignoring mtimes) to detect identical content with different tree hashes.
820
- 3. **Content comparison before restore**: `syncFromDb` compares the incoming
821
- tree's content with the current filesystem and skips restore if identical.
822
-
823
- ## Performance
824
-
825
- - **Efficient Scanning**: Only scans changed directories
826
- - **Deduplication**: Identical files stored once
827
- - **Content-Addressed**: Fast lookups via hashes
828
- - **Optimized Watching**: Uses native filesystem events
829
- - **Smart Sync**: Only syncs when changes detected
830
- - **Debounced Events**: Rapid changes coalesced into single operations
831
- - **Bounded Operations**: All async operations time out to prevent hangs
358
+ // Tree -> folder, additively
359
+ await agent.restore(tree, './elsewhere');
360
+
361
+ // Tree -> folder, exactly: prune anything not in the tree
362
+ await agent.restore(tree, './elsewhere', { cleanTarget: true });
363
+ ```
364
+
365
+ A restore writes only what differs. Re-restoring the same tree over a folder
366
+ that already matches writes nothing β€” which is what keeps one new file from
367
+ rewriting a whole catalogue.
368
+
369
+ ---
370
+
371
+ ## What it guarantees β€” and what it does not
372
+
373
+ **It does:**
374
+
375
+ - converge β€” every machine ends on the same content, or reports why not;
376
+ - never lose a user's edit to a merge, a catch-up or a reconnect;
377
+ - propagate a deletion made while partitioned or unheard-of by a peer, and
378
+ keep it deleted;
379
+ - keep both sides of a conflict, and say there was one;
380
+ - survive a locked file, an impossible path, a full disk, a vanishing entry, a
381
+ wrong clock and a peer whose history cannot be read β€” each failing only
382
+ itself;
383
+ - cost one blob to catch up on twenty missed saves of one file, not twenty.
384
+
385
+ **It does not:**
386
+
387
+ - **split a large file into blocks.** A file transfers whole, so the transport's
388
+ message limit is the per-file ceiling;
389
+ - **let you approve a mass deletion.** One that looks like a loss is refused
390
+ and reported through `agent.refusedDeletions`; there is no override yet;
391
+ - **collect garbage.** Every superseded version stays on every machine;
392
+ - **promise a latency.** Nothing in the suite asserts an arrival deadline, so
393
+ nothing here should be read as one;
394
+ - **repair a folder reverted under a running agent.** Restoring a backup while
395
+ the agent is stopped is handled; doing it underneath a live one is not
396
+ decidable from the history, and the reasoning is in the test;
397
+ - **promise that a deletion made while the agent was NOT RUNNING propagates.**
398
+ **Delete files with the client running.** One deleted while it is stopped may
399
+ come back from the history on the next sync.
400
+
401
+ This is a deliberate trade, and the reason is worth knowing. A removal is
402
+ only ever announced for a file the agent WATCHED being deleted β€” never for
403
+ any file merely missing from the folder. Announcing an absence is the same "an
404
+ absence is a deletion" inference the edit chain exists to remove, just moved
405
+ to the sending side, and the chain would then carry that guess as a stated,
406
+ ordered, authoritative removal that every peer obeys β€” correctly, because
407
+ obeying a stated removal is the whole design. A node whose idea of its own
408
+ last state had drifted could tell the entire fleet to delete files nobody had
409
+ touched.
410
+
411
+ So the asymmetry is chosen on purpose: a file that comes back is visible and
412
+ recoverable β€” delete it again with the client running and it propagates
413
+ properly β€” while a file deleted across every machine on a mistaken statement
414
+ is neither. In practice the offline case is often still caught, but it is not
415
+ promised here, and nothing in this package should be read as promising it.
416
+
417
+ ---
832
418
 
833
419
  ## Troubleshooting
834
420
 
835
- ### Agent not syncing changes
836
-
837
- Make sure you've called `syncToDb()` with a Connector:
838
-
839
- ```typescript
840
- import { Connector } from '@rljson/db';
841
- import { Route } from '@rljson/rljson';
842
- import { SocketMock } from '@rljson/io';
843
-
844
- const agent = new FsAgent(path, bs);
845
-
846
- // Create Connector and start syncing
847
- const socket = new SocketMock();
848
- const route = Route.fromFlat(`/${treeKey}+`);
849
- const connector = new Connector(db, route, socket);
850
- const stopSync = await agent.syncToDb(db, connector, treeKey);
851
- ```
852
-
853
- ### Bidirectional sync not working
854
-
855
- Ensure you've started both `syncToDb()` and `syncFromDb()` with the same Connector:
856
-
857
- ```typescript
858
- const connector = new Connector(db, route, socket);
859
-
860
- // Start both directions
861
- const stopToDb = await agent.syncToDb(db, connector, treeKey);
862
- const stopFromDb = await agent.syncFromDb(db, connector, treeKey);
863
- ```
864
-
865
- ### High memory usage
866
-
867
- Reduce scan depth or add more ignore patterns:
868
-
869
- ```typescript
870
- {
871
- maxDepth: 3,
872
- ignore: ['large-directory/**'],
873
- }
874
- ```
875
-
876
- ### Files not appearing
877
-
878
- Check ignore patterns aren't too broad:
879
-
880
- ```typescript
881
- // Bad: ignores everything
882
- ignore: ['*'];
883
-
884
- // Good: specific patterns
885
- ignore: ['node_modules', '*.log'];
886
- ```
887
-
888
- ## Known Constraints
889
-
890
- ### macOS Finder paste and rename
891
-
892
- Bidirectional sync relies on Node.js `fs.watch` (FSEvents on macOS) to detect
893
- filesystem changes. This works reliably for **programmatic** file operations:
894
-
895
- - βœ… `writeFile`, `copyFile`, `rename` from Node.js or shell commands
896
- - βœ… Editor saves (VS Code, Vim, etc.)
897
- - βœ… Terminal commands (`echo`, `cp`, `mv`, `touch`, etc.)
898
- - βœ… Application-generated file changes
899
-
900
- However, **macOS Finder's paste-and-rename workflow** generates rapid,
901
- non-atomic, multi-step event sequences (create temporary file β†’ write β†’ rename β†’
902
- delete temporary) that FSEvents may coalesce, reorder, or split unpredictably.
903
- This can cause intermediate states to be scanned and broadcast before the
904
- operation completes, leading to sync conflicts.
905
-
906
- **This is a known limitation of filesystem watching on macOS and is not
907
- supported.** If you need to add or rename files in synced folders, use
908
- programmatic operations or terminal commands instead of Finder drag-and-drop or
909
- paste-and-rename.
910
-
911
- ## Related Packages
912
-
913
- - `@rljson/db` - RLJSON database
914
- - `@rljson/bs` - Blob storage interface
915
- - `@rljson/rljson` - Core RLJSON library
916
- - `@rljson/io` - I/O abstractions
421
+ **Nothing syncs and the log says `carries no ancestry`.**
422
+ `syncConfig.causalOrdering` is not `true`, so conflicting edits will not be
423
+ merged. Set it on the `Connector`.
424
+
425
+ **A conflict happened and nobody was told.** `resolveConflicts` defaults to
426
+ `false`. Set it `true` and pass `onConflict`.
427
+
428
+ **An ignore pattern does nothing.** With no `*`, `?` or `/` it is a *prefix*,
429
+ not a glob: `exe` ignores files starting with `exe`, while `*.exe` is what
430
+ ignores the extension. Check it with `compileIgnore`.
431
+
432
+ **A deletion is slow rather than lost.** A removal travels as a statement, and
433
+ a walk that cannot complete yet does nothing and waits for the next
434
+ announcement. The failure mode is *delayed*, not *silently dropped*, and that
435
+ is deliberate.
436
+
437
+ **A whole-folder deletion was refused.** The mass-delete guard.
438
+ `.sync-errors.log` names the count and the threshold. There is no override yet.
439
+
440
+ **A machine sits empty after its folder was wiped.** Above a hundred files the
441
+ agent recognises the loss and re-joins. Between eleven and ninety-nine it
442
+ announces the emptiness, the fleet correctly refuses it, and that machine is
443
+ not refilled β€” no data is lost anywhere, but it needs a restart.
444
+
445
+ **The first start takes minutes.** A cold scan reads and hashes every file.
446
+ Pass `scanCachePath`.
447
+
448
+ **Files appear in `.fsagent-recovered/`.** A join found files the shared
449
+ history had deliberately deleted. They are kept, not announced and not
450
+ destroyed. Usually it means that folder was restored from a backup.
451
+
452
+ **A big restore times out.** Blob transfer is streamed, but a 15-second
453
+ `restore` budget is not enough for a catalogue. Raise `timeouts.restore` and
454
+ `timeouts.extract`.
455
+
456
+ ---
457
+
458
+ ## Known constraints
459
+
460
+ **macOS Finder paste and rename.** Sync relies on Node's `fs.watch` (FSEvents
461
+ on macOS), which is reliable for programmatic operations and ordinary editor
462
+ saves β€” but Finder's paste and in-place rename do not always emit an event. A
463
+ periodic safety rescan catches these, so the gap is the rescan interval rather
464
+ than forever. See [doc/safety-rescan.md](doc/safety-rescan.md).
465
+
466
+ **Windows file locks are covered on one machine only.** The behaviour is right
467
+ β€” a locked file blocks itself and nothing else, and a half-applied state is not
468
+ advertised β€” but no mesh test runs on Windows, so this wants a Windows CI
469
+ runner.
470
+
471
+ **An upgrade changes every tree ref in the fleet.** Content identity now
472
+ excludes mtime and fixes a canonical child order, so the same bytes hash
473
+ differently than in older releases. Nothing is destroyed, but the fleet reads
474
+ divergent until every machine has re-scanned. **Upgrade machines together**:
475
+ there is no switch for speaking an older wire format, deliberately β€” a build
476
+ that cannot read a chain head cannot read the bucket protocol either, so one
477
+ flag would select two different consistency models.
478
+
479
+ **A deliberate mass deletion does not arrive.** Deleting most of a folder is
480
+ refused on every machine, and nothing asks the user β€” see "what it does not do"
481
+ above. Read `agent.refusedDeletions` to find out it happened: the guard cannot
482
+ tell a person deleting a project from a machine that was wiped telling the fleet
483
+ to wipe, and the second one is why the guard exists.
484
+
485
+ **On Linux, deleting a whole directory may leave its files behind.** `rm -r`
486
+ unlinks the children and then the directory; when the watched directory goes,
487
+ inotify removes its watch and the queued child events are lost. A removal is
488
+ only stated for a deletion the agent **watched** β€” an absence is not a deletion,
489
+ which is what stops a folder that failed to mount from wiping the fleet β€” so an
490
+ unobserved child is not merely unpropagated: a peer still holding it announces
491
+ it back and the folder is restored. Measured on Linux CI across four runs, a
492
+ different subset surviving each time. macOS reports every child deletion and is
493
+ unaffected. Deleting the files individually, or deleting the directory a second
494
+ time, propagates normally.
495
+
496
+ **A file still being written cannot be recognised with certainty.** The settle
497
+ rule holds a file back on the first sight of it and for as long as its size keeps
498
+ moving, which covers a copy in progress whatever the machine's clock says. What
499
+ no rule over `stat` can decide is a writer that pauses for a long time: a file
500
+ whose timestamp looks finished and whose size has not moved between two scans is
501
+ indistinguishable from one that was written and closed. If that happens the file
502
+ is hashed and distributed truncated, and a reader of the shared folder sees the
503
+ truncated version until the copy finishes β€” at which point the size and timestamp
504
+ change, the file is re-read, and the complete version propagates. Nothing is
505
+ corrupted permanently.
506
+
507
+ **Heavy churn is now gated, and two constraints that stood here are gone.**
508
+ Earlier releases of this document listed three things the churn fuzzer found.
509
+ What they actually were:
510
+
511
+ - **Two machines holding different bytes for one path while both reported
512
+ perfect health β€” FIXED.** A same-path conflict where both sides had edited the
513
+ file was settled by whichever content hash sorted higher, because the edit time
514
+ carried on the wire was read only when one side had deleted the path. The newer
515
+ edit now wins, and both sides compute the same verdict. The fleet converged on
516
+ the superseded write about half the time this arose.
517
+ - **A re-created file lost from every machine β€” DID NOT EXIST.** It was an error
518
+ in the test's own instrument. The count of entries in a node's tree used a
519
+ field the tree nodes do not have, so it counted every directory and the folder
520
+ root as files: `6 entries` beside `4 files on disk` was four files, one
521
+ subdirectory and the root, exactly consistent. Nothing was ever lost. The
522
+ measurement that appeared to confirm it on older code was the same miscount.
523
+ - **A machine finishing one file short β€” FIXED, and it was never rare.** This was
524
+ written down as a limit while the test read the fleet's convergence verdict and
525
+ threw it away, so nothing had ever gated it. Asserting it exposed the cause at
526
+ once: a node that deletes a file keeps a tombstone until it has announced it,
527
+ and that tombstone was allowed to refuse a peer's LATER write of the same path
528
+ β€” although the comparison had already established the write was newer. The
529
+ deleting node stayed permanently short of a file every peer held, still
530
+ advertising a deletion the fleet had moved past, with nothing to end it. On
531
+ Linux, 6 runs in 8 of one churn scenario. The stale tombstone is now lifted,
532
+ and the node says so in its log when it happens.
533
+
534
+ So the churn scenarios are a real gate: every node ends with the same files and
535
+ the same bytes, and any disagreement must at least be visible in some node's
536
+ `diverged` or `differingPaths`. A run that ends disagreeing says so in the test
537
+ output rather than passing quietly. Measured 8 of 8 on Linux where the same
538
+ scenario failed 6 of 8 before these two fixes.
539
+
540
+ **What to watch in production.** `agent.antiEntropyStatus.differingPaths` names
541
+ the paths rather than reporting that the checksums differ, so it is the more
542
+ useful of the two. `localRef` is this node's state right now and `hubRef` is what
543
+ the hub last announced, so the pair can legitimately differ for a moment while
544
+ `diverged` still reports the previous comparison's verdict.
545
+
546
+ ---
547
+
548
+ ## Further reading
549
+
550
+ | document | what is in it |
551
+ | --- | --- |
552
+ | [README.architecture.md](README.architecture.md) | the design: why references rather than payloads, the edit chain, additive reconciliation, anti-entropy |
553
+ | [README.api.md](README.api.md) | every export, grouped by module β€” the shape, where this document gives the advice |
554
+ | [README.tests.md](README.tests.md) | the 810 scenarios this package ships, by what they prove |
555
+
556
+ Related packages: `@rljson/rljson` (trees), `@rljson/db` (database and
557
+ `Connector`), `@rljson/io` (sockets and storage), `@rljson/bs` (blobs),
558
+ `@rljson/server` (hub and client), `@rljson/mongo-agent` (the same idea for
559
+ documents).
917
560
 
918
561
  ## License
919
562
 
920
- See [LICENSE](LICENSE) file.
921
-
922
- ## More Information
923
-
924
- - [Example Code](src/example.ts)
925
- - [Architecture](README.architecture.md)
926
- - [Contributors](README.contributors.md)
563
+ See [LICENSE](LICENSE).