@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.
@@ -1,7 +1,9 @@
1
1
  import { Bs } from '@rljson/bs';
2
2
  import { ClientId, SyncConfig } from '@rljson/rljson';
3
3
  import { AntiEntropyOptions, AntiEntropyStatus } from './fs-anti-entropy.ts';
4
+ import { ATOMIC_TMP_PREFIX } from './fs-atomic-write.ts';
4
5
  import { FsBlobAdapter } from './fs-blob-adapter.ts';
6
+ import { FsConflictReport } from './fs-conflict-resolver.ts';
5
7
  import { StoreFsTreeOptions } from './fs-db-adapter.ts';
6
8
  import { FsScanner, FsTree } from './fs-scanner.ts';
7
9
  import { Connector, Db } from '@rljson/db';
@@ -9,6 +11,23 @@ import { Connector, Db } from '@rljson/db';
9
11
  * Options for FsAgent operations
10
12
  */
11
13
  export interface FsAgentOptions {
14
+ /**
15
+ * Reconcile a divergence ADDITIVELY instead of replacing a folder.
16
+ *
17
+ * With this on, a divergence the anti-entropy would have answered with
18
+ * `pull` or `merge` runs a bucket-sync round instead: the two sides compare
19
+ * manifests and each fetches what it is missing. Nothing is replaced, so
20
+ * neither side's work can be discarded — which is the property §3.1 of the
21
+ * plan says makes the two measured data losses impossible rather than
22
+ * rarer.
23
+ *
24
+ * **Default off.** It replaces the repair model rather than correcting it,
25
+ * and `src/fs-agent.ts` records that this class of change "has been reverted
26
+ * four times for being shipped on reasoning". On in the mesh, where the
27
+ * additive outcome is asserted; off everywhere else until an integration run
28
+ * says otherwise.
29
+ */
30
+ bucketSync?: boolean;
12
31
  /** Ignore patterns for scanning */
13
32
  ignore?: string[];
14
33
  /** Maximum depth for directory traversal */
@@ -16,20 +35,15 @@ export interface FsAgentOptions {
16
35
  /** Follow symlinks (default: false) */
17
36
  followSymlinks?: boolean;
18
37
  /**
19
- * Persist a path→(mtime, size, blobId) scan cache at this file path so a RESTART
20
- * does not re-read + re-hash the whole folder (a cold scan of an 80 GB catalog
21
- * is ~48 min). Forwarded to the {@link FsScanner}. Requires a PERSISTENT blob
22
- * store (e.g. `@rljson/bs-fs`). See {@link FsScanOptions.scanCachePath}.
38
+ * Persist a path→(mtime, size, blobId) scan cache at this file path so a
39
+ * RESTART does not re-read + re-hash the whole folder (a cold scan of an 80
40
+ * GB catalog is ~48 min). Forwarded to the {@link FsScanner}. Requires a
41
+ * PERSISTENT blob store (e.g. `@rljson/bs-fs`). See
42
+ * {@link FsScanOptions.scanCachePath}.
23
43
  */
24
44
  scanCachePath?: string;
25
- /** Database instance for automatic syncing */
26
- db?: Db;
27
- /** Tree key for database storage */
28
- treeKey?: string;
29
45
  /** Storage options for database operations */
30
46
  storageOptions?: StoreFsTreeOptions;
31
- /** Enable bidirectional sync (both fs→db and db→fs) */
32
- bidirectional?: boolean;
33
47
  /** Restore options applied when syncing from DB */
34
48
  restoreOptions?: RestoreOptions;
35
49
  /** Timeout configuration for async operations */
@@ -57,9 +71,24 @@ export interface FsAgentOptions {
57
71
  * registers a DAG-branch conflict observer that resolves forks into a single
58
72
  * merge revision (winner keeps the path, loser is renamed). This is a
59
73
  * **client-only** behaviour — hubs are dumb relays and must leave it off
60
- * (the default). See `doc/conflict-resolution-design.md`.
74
+ * (the default). See `README.architecture.md`, "Conflicts".
61
75
  */
62
76
  resolveConflicts?: boolean;
77
+ /**
78
+ * Called when a same-file conflict has been resolved, with one entry per
79
+ * conflicting path.
80
+ *
81
+ * This is the only way to learn that it happened. Before it existed,
82
+ * resolving a conflict renamed a file and said nothing — the user's whole
83
+ * evidence was an unexplained `… (conflicted copy …)` appearing in a folder.
84
+ * Nothing is lost either way; what was missing is anybody being told.
85
+ *
86
+ * Not an error channel: two people editing one document at once is ordinary,
87
+ * both versions are kept, and the folder converges. Hosts that want it after
88
+ * a restart should read {@link CONFLICT_LOG_FILE}, which this agent writes
89
+ * regardless of whether a callback is given.
90
+ */
91
+ onConflict?: (reports: FsConflictReport[]) => void;
63
92
  /**
64
93
  * Repair a divergence from the hub that no message is going to fix — a
65
94
  * push the hub never received, a forward this node never received, an
@@ -69,10 +98,71 @@ export interface FsAgentOptions {
69
98
  * fires. On by default. See `src/fs-anti-entropy.ts`.
70
99
  */
71
100
  antiEntropy?: AntiEntropyOptions;
101
+ /**
102
+ * How long a folder with files and NO history waits for the network's state
103
+ * before saying anything about its own, in milliseconds. `0` disables the
104
+ * wait, which is the default.
105
+ *
106
+ * **The chain applies first; the filesystem only then.** A starting agent
107
+ * authors a lineage root from whatever it happens to hold and announces it
108
+ * as the network's newest claim, and that is one defect wearing two faces:
109
+ * every node gets its own lineage root, so `classify` answers `fork` to
110
+ * every announcement ever made; and a node restored from a backup pushes
111
+ * deleted files back to the whole fleet. With a wait set, such a node defers
112
+ * instead, reconciles against the first head it hears (`planJoin` — write
113
+ * what the head has, keep what the history never named, set aside what it
114
+ * REMOVED, treat a path live on both sides as a conflict) and speaks
115
+ * afterwards.
116
+ *
117
+ * **Bounded, and that is not a detail.** If no head arrives this folder IS
118
+ * the origin and its contents are the first state — a brand-new network has
119
+ * to be startable, so the wait is a deferral and never a refusal. It also
120
+ * cannot deadlock a fleet whose nodes all start with files: they all time
121
+ * out, they all announce, and their roots agree by content.
122
+ *
123
+ * **Off by default, deliberately.** It changes what a node says in its first
124
+ * seconds, which is the class of change this package has reverted four times
125
+ * for being shipped on reasoning. It is proven at the mesh tier
126
+ * (`fs-mesh-matrix.spec.ts`, `J4+J5`) and belongs on after an integration
127
+ * run, in the same way `bucketSync` did — see `README.architecture.md`,
128
+ * "Joining a Network".
129
+ */
130
+ joinWaitMs?: number;
131
+ /**
132
+ * A short name for this agent, shown in every line it logs.
133
+ *
134
+ * **Because a log without it cannot be read when more than one agent runs.**
135
+ * Four nodes in one process produced three identical
136
+ * `applied 3 peer deletions: …` lines with nothing saying who, and a
137
+ * convergence investigation stopped there: the three nodes that applied a
138
+ * removal and the one that stayed silent were indistinguishable. The One
139
+ * Client has the same problem for a different reason — several routes, one
140
+ * console.
141
+ *
142
+ * Omitted, every line reads `[FsAgent]` exactly as before.
143
+ */
144
+ logName?: string;
72
145
  }
73
146
  /** Restore options */
74
147
  export interface RestoreOptions {
75
- /** Remove files/dirs on target that are not present in the tree */
148
+ /**
149
+ * Remove files and directories on the target that the tree does not contain.
150
+ *
151
+ * **Destructive, and the peer-apply path never sets it.** Deleting what a
152
+ * tree happens to lack is an INFERENCE, and it is the one this package spent
153
+ * its whole history getting wrong: a tree lacks a path because the sender
154
+ * removed it, or because the sender never had it, and a content hash cannot
155
+ * say which. `syncFromDb` therefore applies additively and takes deletions
156
+ * from the chain, where they are STATED — see `_applyIncomingRemovals`.
157
+ *
158
+ * Still honoured by a direct {@link FsAgent.restore} call, which is a caller
159
+ * saying "make this folder be exactly this tree". That is a different
160
+ * question, and its answer is one the caller already knows.
161
+ *
162
+ * `syncFromDb` still ACCEPTS it, so a configuration carrying
163
+ * `cleanTarget: true` keeps working unchanged; it no longer authorises a
164
+ * prune there.
165
+ */
76
166
  cleanTarget?: boolean;
77
167
  }
78
168
  /**
@@ -133,11 +223,83 @@ export declare const DISCONNECT_PAUSE_MAX_MS = 30000;
133
223
  /** Filename for sync error log written to the sync folder */
134
224
  export declare const SYNC_ERROR_FILE = ".sync-errors.log";
135
225
  /**
136
- * Filename prefix for the staging files used by atomic writes. The scanner
137
- * ignores anything starting with this so the transient temp + rename never
138
- * pollutes the tree or churns the watcher.
226
+ * Where resolved same-file conflicts are recorded, newest last.
227
+ *
228
+ * Its own file rather than a line in `.fsagent-state.json`, because that file
229
+ * is rewritten WHOLE on every deletion — appending a growing list to it would
230
+ * make deleting the next file slower in proportion to how many conflicts the
231
+ * folder has ever had, which is the cost {@link TOMBSTONE_LOG_MAX} exists to
232
+ * bound.
233
+ *
234
+ * And JSON rather than the free text of {@link SYNC_ERROR_FILE}, because this
235
+ * is meant to be READ by a UI, not grepped by a person.
139
236
  */
140
- export declare const ATOMIC_TMP_PREFIX = ".fsagent-tmp-";
237
+ export declare const CONFLICT_LOG_FILE = ".fsagent-conflicts.json";
238
+ /**
239
+ * Where a file the history had DELETED is kept when this node joins.
240
+ *
241
+ * **Outside the synced tree, and that is the whole point.** A recovered file
242
+ * must not be announced — it is content the fleet deliberately removed, and a
243
+ * folder restored from last month's backup would otherwise push every one of
244
+ * those deletions back to every node. But leaving it in the folder cannot
245
+ * achieve that: a tree ref carries CONTENT, so the file travels whatever the
246
+ * entry claims about it. Measured exactly that way — the set-aside copy
247
+ * arrived on a peer while the chain entry said nothing about it.
248
+ *
249
+ * So it goes in an ignored directory, which is local by construction, and the
250
+ * user can see it and move it back if they want it. Visible, keepable, and
251
+ * silent.
252
+ */
253
+ export declare const RECOVERED_DIR = ".fsagent-recovered";
254
+ /**
255
+ * How often a joining node asks for the network's state, in milliseconds.
256
+ *
257
+ * The hub volunteers it — the connector has a bootstrap channel and a
258
+ * bootstrap heartbeat — but a node that misses those cannot tell "I heard
259
+ * nothing" from "there is nothing", and that is the difference between joining
260
+ * a fleet and announcing a stale folder over it. So it keeps asking, which
261
+ * costs a read of its own database and puts nothing on the wire.
262
+ */
263
+ export declare const JOIN_ASK_INTERVAL_MS = 150;
264
+ /**
265
+ * How often a node ASKS whether the fleet has moved on without it.
266
+ *
267
+ * **Because listening is not enough, and the gap is invisible.** The
268
+ * anti-entropy compares this folder against the last state it HEARD the hub
269
+ * announce. Under silent announcement loss — which is what a relay under load
270
+ * does, reporting success and delivering nothing — a receiver hears nothing,
271
+ * so its idea of the hub stays equal to its own state, the two agree, and it
272
+ * reports `diverged: false` with zero repairs. *The repair mechanism's own
273
+ * input is the thing that failed, so the harder the transport fails the
274
+ * healthier the fleet reports itself.* Measured: receivers six versions behind
275
+ * a writer, every one of them claiming health.
276
+ *
277
+ * Asking costs a read of this node's own database and puts nothing on the
278
+ * wire: the fleet's entries replicate there, and the newest one is the
279
+ * question. It cannot help while NOTHING arrives — no local source can — but
280
+ * it closes the window that matters, where the rows are present and the
281
+ * announcement that would have triggered a repair was the thing dropped.
282
+ */
283
+ export declare const ANTI_ENTROPY_ASK_MS = 2000;
284
+ /**
285
+ * How long a joining node asks before concluding it is the origin.
286
+ *
287
+ * The default for every route. Long enough for a hub's bootstrap to arrive on
288
+ * a real connection, short enough that the first client of a brand-new network
289
+ * is not kept waiting — and it is a deferral, never a refusal: when it expires
290
+ * the folder IS the origin and its contents are the first state.
291
+ */
292
+ export declare const DEFAULT_JOIN_WAIT_MS = 1500;
293
+ /**
294
+ * How many resolved conflicts the log keeps.
295
+ *
296
+ * Small on purpose. This is a notification surface, not an audit trail: what a
297
+ * user needs is "here is what recently happened to your documents", and a
298
+ * thousand entries answer a question nobody asked while making the file
299
+ * expensive to write.
300
+ */
301
+ export declare const CONFLICT_LOG_MAX = 200;
302
+ export { ATOMIC_TMP_PREFIX };
141
303
  /**
142
304
  * Filename for the agent's own state, kept beside the synced folder's content
143
305
  * and ignored by the scanner like the other two above.
@@ -148,6 +310,22 @@ export declare const ATOMIC_TMP_PREFIX = ".fsagent-tmp-";
148
310
  * no ancestry is one every peer has to treat as untrustworthy for deletion.
149
311
  */
150
312
  export declare const AGENT_STATE_FILE = ".fsagent-state.json";
313
+ /**
314
+ * Marks an announced ref as a CHAIN HEAD rather than a tree ref.
315
+ *
316
+ * A tree ref is a content hash and never starts with `~`, so the two are
317
+ * unambiguous on one channel — the trick `@rljson/mongo-agent` uses for its
318
+ * own protocol refs (`~R~`, `~AEQ~`…), blessed by §6 of the plan.
319
+ *
320
+ * The marker is not decoration. Without it a receiver cannot tell a head from
321
+ * a tree ref, so it has to TRY resolving every ref it hears — and a miss goes
322
+ * to the network. Measured: the first version did exactly that, and awaiting
323
+ * that read before scheduling the apply dropped the hub's bootstrap on a late
324
+ * joiner, which then never received a file that already existed. A receive
325
+ * path that awaits a peer read before acting can lose a message to a slow
326
+ * peer, silently.
327
+ */
328
+ export declare const CHAIN_HEAD_PREFIX = "~H~";
151
329
  /**
152
330
  * Orchestrates filesystem operations with tree structures and blob storage
153
331
  */
@@ -192,7 +370,7 @@ export declare const RESTORED_BLOB_MEMORY_MAX = 50000;
192
370
  * A restore's cost is dominated by `getBlob`, and a blob this node does not
193
371
  * already hold is a socket round trip. Walking the tree strictly sequentially
194
372
  * makes the whole restore `files × RTT` — invisible on localhost, and about
195
- * sixteen files a second on the lab, where a 1 200-file folder then takes
373
+ * sixteen files a second on a real fleet, where a 1 200-file folder then takes
196
374
  * minutes and reads as a stalled node.
197
375
  *
198
376
  * Sixteen rather than sixty-four: blobs carry file CONTENT, so the ceiling is
@@ -201,15 +379,81 @@ export declare const RESTORED_BLOB_MEMORY_MAX = 50000;
201
379
  */
202
380
  export declare const RESTORE_FETCH_CONCURRENCY = 16;
203
381
  /**
204
- * How many of its own past states a node remembers.
382
+ * How many heard-but-not-yet-applied peer heads a node parks.
383
+ *
384
+ * A head arrives when an announcement is resolved and is used when the apply
385
+ * for that state runs, which is a debounce later, so the two have to be
386
+ * bridged. Announcements that never reach an apply — superseded by a newer
387
+ * one, dropped by a guard — leave their head behind, so the map is bounded and
388
+ * the oldest is forgotten. Forgetting costs a lineage join, never a file.
389
+ */
390
+ export declare const ANNOUNCED_HEAD_MAX = 200;
391
+ /**
392
+ * How many deletions the tombstone log remembers.
393
+ *
394
+ * The log is the one structure in this agent that grows without bound. Measured
395
+ * on 400 deletions: 337 entries, ~11 bytes each in `.fsagent-state.json`, and
396
+ * the file is rewritten SYNCHRONOUSLY on every deletion — so the cost of
397
+ * deleting the next file grows with every file already deleted. A folder with
398
+ * years of churn turns that into a megabyte rewritten per delete.
205
399
  *
206
- * Used to recognise a sender that is BEHIND this node — one that declares a
207
- * state this node has held and left. A burst on a large folder produces a few
208
- * dozen states, so this is generous; forgetting the oldest costs only the
209
- * ability to spot a very stale sender, which the mass-delete guard still
210
- * catches.
400
+ * Everything else was measured and is already bounded: the chain grows one
401
+ * entry per PUSH rather than per change (400 deletions produced 7, because the
402
+ * debounce coalesces them), `_localPathTimeIds` is pruned by the removals it
403
+ * records, and `_announcedHeads` has {@link ANNOUNCED_HEAD_MAX}.
404
+ *
405
+ * Ten thousand is chosen to be far past any real partition and still small
406
+ * enough to rewrite cheaply (~110 KB). Evicting a tombstone can RESURRECT a
407
+ * file — that is the whole point of keeping it — so eviction is oldest-first
408
+ * and loud, and the number is deliberately generous rather than tight.
211
409
  */
212
- export declare const STATE_HISTORY_MAX = 1000;
410
+ export declare const TOMBSTONE_LOG_MAX = 10000;
411
+ /**
412
+ * How many path edit times survive a restart. See `_pathEditTimes`.
413
+ *
414
+ * Larger than the tombstone log because it covers every path either side has
415
+ * touched rather than only the deletions, and smaller than a catalogue because
416
+ * the whole point is to bound the state file. Past it the oldest entries go,
417
+ * and a path with no remembered time is one whose tombstone ordering falls
418
+ * back to the rules that shipped before the field existed.
419
+ */
420
+ export declare const EDIT_TIME_LOG_MAX = 50000;
421
+ /** How many refused deletions {@link FsAgent.refusedDeletions} keeps. */
422
+ export declare const REFUSED_DELETION_LOG_MAX = 20;
423
+ /**
424
+ * A deletion the mass-delete guard refused to carry out.
425
+ *
426
+ * THE GUARD IS NOT A FAILURE, IT IS A DECISION DEFERRED — and until something
427
+ * asks the user, the deletion simply does not happen. It is refused on every
428
+ * node, so the fleet stays split and no message will ever fix that: the
429
+ * refusal is the correct answer to "a wiped peer is telling everyone to wipe",
430
+ * and it is the wrong answer to "the user deleted 10 000 files on purpose".
431
+ * Nothing in this package can tell those apart, which is why it is surfaced
432
+ * rather than resolved.
433
+ *
434
+ * Already written to the log and to the sync-error file at every site. This is
435
+ * the same fact in a form a client can READ: a UI cannot grep a log on a
436
+ * machine it is not running on, and "why did my deletion not arrive" is the
437
+ * question it has to answer.
438
+ */
439
+ export interface RefusedDeletion {
440
+ /** When it was refused. */
441
+ readonly atMs: number;
442
+ /**
443
+ * Which rule refused it, matching the sync-error key.
444
+ *
445
+ * `restore` is an incoming whole tree, `bucketSync` an additive round's drop
446
+ * list, `removals` a peer's stated removals. All three share the floors; a
447
+ * client showing this does not need to care which, but a support case does.
448
+ */
449
+ readonly route: 'restore' | 'bucketSync' | 'removals';
450
+ /** How many paths would have been deleted. */
451
+ readonly wouldRemove: number;
452
+ /** How many this folder holds, which is what the ratio is taken against. */
453
+ readonly held: number;
454
+ /** The first few paths, for a message a person can act on. */
455
+ readonly paths: readonly string[];
456
+ }
213
457
  /**
214
458
  * What an agent concluded about an inbound ref.
215
459
  *
@@ -260,8 +504,8 @@ export declare class PartialRestoreError extends RestoreIncompleteError {
260
504
  * the fetch.
261
505
  *
262
506
  * **Size is no longer one of those reasons.** The case that produced this class
263
- * was a file larger than the transport's `maxHttpBufferSize`, where no number of
264
- * retries made 63 MB fit through a 50 MB socket. Since `@rljson/bs` 0.0.27 a
507
+ * was a file larger than the transport's `maxHttpBufferSize`, where no number
508
+ * of retries made 63 MB fit through a 50 MB socket. Since `@rljson/bs` 0.0.27 a
265
509
  * blob crosses as a series of ranged pulls, so no single message carries the
266
510
  * whole file and the cap no longer bounds file size. The class stays, because a
267
511
  * blob can still be genuinely unreachable; the reason it was first needed is
@@ -277,10 +521,10 @@ export declare class PartialRestoreError extends RestoreIncompleteError {
277
521
  * silently ignoring every delete.
278
522
  *
279
523
  * Measured on four nodes: one 63 MB file (120% of the cap) left three of them
280
- * holding a file the fourth had deleted, permanently, and `projekte-shape`'s
281
- * deletion had still not propagated after 300 seconds. The customer's largest
282
- * file was 45.9 MB against the same 50 MB cap — close enough that the next
283
- * revision of one document would have reproduced it in production.
524
+ * holding a file the fourth had deleted, permanently, and the large-folder
525
+ * shape's deletion had still not propagated after 300 seconds. The largest
526
+ * observed file was 45.9 MB against the same 50 MB cap — close enough that the
527
+ * next revision of one document would have reproduced it in production.
284
528
  */
285
529
  export declare class BlobUnavailableError extends RestoreIncompleteError {
286
530
  readonly unavailablePaths: string[];
@@ -298,21 +542,58 @@ export declare class BlobUnavailableError extends RestoreIncompleteError {
298
542
  * judgement has to be made here, and it is deliberately biased: refusing a
299
543
  * real mass delete costs one manual step, applying a false one costs the data.
300
544
  */
545
+ /**
546
+ * A restore could not write a path this filesystem will not accept.
547
+ *
548
+ * Its own class rather than a {@link BlobUnavailableError}, because the
549
+ * message is what somebody reads in a support request and "could not fetch
550
+ * blob" for a 300-character filename sends them to the network when the
551
+ * problem is the name. The bytes arrived; the path cannot exist here.
552
+ *
553
+ * Not retryable, unlike {@link PartialRestoreError}: a name does not become
554
+ * legal by waiting. The rest of the tree is applied around it.
555
+ */
556
+ export declare class UnwritablePathError extends RestoreIncompleteError {
557
+ readonly impossiblePaths: string[];
558
+ constructor(impossiblePaths: string[]);
559
+ }
560
+ /**
561
+ * The volume ran out of space mid-restore.
562
+ *
563
+ * Its own class because it is the one restore failure that is not about the
564
+ * tree at all, and because retrying it is pointless until a person acts. It
565
+ * aborts rather than skipping the file: a folder being filled on a full disk
566
+ * would otherwise lose a different file on every attempt.
567
+ */
568
+ export declare class DiskFullError extends RestoreIncompleteError {
569
+ readonly path: string;
570
+ constructor(path: string);
571
+ }
301
572
  export declare class MassDeleteRefusedError extends RestoreIncompleteError {
302
573
  readonly wouldPrune: number;
303
574
  readonly totalFiles: number;
304
575
  readonly incomingFiles: number;
305
576
  constructor(wouldPrune: number, totalFiles: number, incomingFiles: number);
306
577
  }
578
+ /** What one push changed, against the state announced before it. */
579
+ export interface FsTreeDelta {
580
+ /** Relative paths added or modified, `/`-separated. */
581
+ changed: string[];
582
+ /** Relative paths removed, `/`-separated. */
583
+ removed: string[];
584
+ }
307
585
  export declare class FsAgent {
586
+ /**
587
+ * The prefix on every line this agent logs — see {@link FsAgentOptions.logName}.
588
+ *
589
+ * `[FsAgent]` when unnamed, so an unnamed agent's output is byte-identical
590
+ * to what it was before this existed.
591
+ */
592
+ private readonly _tag;
308
593
  private _scanner;
309
594
  private _adapter;
310
595
  private _rootPath;
311
596
  private _bs;
312
- private _db?;
313
- private _treeKey?;
314
- private _stopSync?;
315
- private _stopSyncFromDb?;
316
597
  private _lastSentRef?;
317
598
  /**
318
599
  * The ref this agent last pushed as its OWN work.
@@ -371,14 +652,180 @@ export declare class FsAgent {
371
652
  */
372
653
  private readonly _pendingDeletes;
373
654
  /**
374
- * The states this node has held, oldest first.
655
+ * This folder's history: one entry per state this node pushed.
656
+ *
657
+ * Created on the first `syncToDb`, and BEST-EFFORT throughout — a chain that
658
+ * cannot be written must never stop a folder syncing. Nothing consumes it
659
+ * yet; see `src/fs-edit-chain.ts`.
660
+ */
661
+ private _chain?;
662
+ /**
663
+ * The chain entry that names the state this node last pushed.
664
+ *
665
+ * Announcements carry the HEAD rather than the tree ref (see
666
+ * {@link _announceAs}), and a re-announcement has to find the head for a
667
+ * state it did not just append. Cached as a pair so that costs a comparison
668
+ * rather than a read.
669
+ */
670
+ private _chainHead?;
671
+ /**
672
+ * `relativePath → timeId` of the newest edit ANYBODY made to each path, as
673
+ * far as this node has heard.
674
+ *
675
+ * Not the same as {@link _localPathTimeIds}, which holds only this node's
676
+ * OWN edits and drops a path when this node deletes it. This one keeps every
677
+ * path either side ever touched, removals included, because the question it
678
+ * answers is "when was the last word on this path" and a deletion is a word.
679
+ *
680
+ * It exists for the bucket manifest: `ManifestEntry.editedAt` is read from
681
+ * here, and it is what lets a peer order our tombstone against its write
682
+ * rather than taking either on trust. Fed only from chain entries — our own
683
+ * in `_recordChainEntry`, a peer's in `_applyIncomingRemovals` — so nothing
684
+ * in it is inferred from a filesystem observation.
685
+ *
686
+ * In memory, like `_localPathTimeIds`. A restart loses it and the manifest
687
+ * then says nothing about those paths, which puts the round back on the
688
+ * rules that shipped before the field existed. Losing the ordering is not
689
+ * losing the ability to sync.
690
+ */
691
+ private readonly _pathEditTimes;
692
+ /** See {@link FsAgent.refusedDeletions}. Bounded, newest last. */
693
+ private readonly _refusedDeletions;
694
+ /**
695
+ * Records the time of an edit for each path it names, keeping the newest.
696
+ *
697
+ * `compareTimeId` rather than "last write wins": entries arrive out of
698
+ * order — a peer's older state can be heard after a newer one — and taking
699
+ * whatever came last would make the manifest claim a stale edit is current,
700
+ * which is the exact failure this index exists to prevent.
701
+ * @param paths - The paths the entry changed or removed.
702
+ * @param timeId - That entry's time.
703
+ */
704
+ private _notePathEdits;
705
+ /**
706
+ * `relativePath → timeId` of the newest edit THIS node made to each path.
707
+ *
708
+ * A peer's removal is refused when this node has newer work on that path
709
+ * (see `planRemovals`), and this is the claim it is judged against. Grown
710
+ * from the `changed` list of every entry this node appends, so it is exactly
711
+ * as complete as the chain is.
712
+ */
713
+ private readonly _localPathTimeIds;
714
+ /**
715
+ * Removals carried by an announcement, waiting for its apply.
716
+ *
717
+ * The resolve happens when the ref arrives and the apply happens later, after
718
+ * a debounce, so the removal list has to be parked in between. Keyed by the
719
+ * tree ref it accompanies and consumed once, because an entry applied twice
720
+ * would delete on the authority of a message already acted on.
721
+ */
722
+ private readonly _incomingRemovals;
723
+ /**
724
+ * `treeRef → chain head`, for announcements heard but not yet applied.
725
+ *
726
+ * **Hearing a head is not holding its state.** The resolve happens when the
727
+ * ref arrives and the apply happens after a debounce, and plenty of
728
+ * announcements never get that far: a newer ref supersedes them, a guard
729
+ * refuses them, the node is already there. Parking the head here and only
730
+ * promoting it at the apply keeps `_adoptedChainHead` to its documented
731
+ * meaning.
732
+ *
733
+ * Measured before this existed: two nodes each saving one file at the same
734
+ * instant. A merely HEARD B's head, recorded it as a parent of its own next
735
+ * entry, and so claimed a lineage descending from a state it never held —
736
+ * whereupon its own `ahead` guard correctly refused B's file as "a state
737
+ * this node has already left". The file never arrived. A false parent is not
738
+ * a cosmetic inaccuracy: reachability is what the whole protocol decides on.
739
+ */
740
+ private readonly _announcedHeads;
741
+ /**
742
+ * A peer head this node has applied, waiting to become a chain parent.
743
+ *
744
+ * **Without this, reachability cannot answer anything.** Every node appends
745
+ * to its OWN lineage and chains are never merged, so if an entry only ever
746
+ * names this node's previous head, A's head can never be an ancestor of B's
747
+ * — and `classify` returns `fork` for every disagreement there has ever
748
+ * been. Measured: adding reachability without this made T4 WORSE, because
749
+ * cases that used to pull or push correctly all became merges.
750
+ *
751
+ * Naming the adopted head as a second parent is what joins the lineages, and
752
+ * it is the shape `FsEditChain` writes its rows by hand to allow.
753
+ */
754
+ private _adoptedChainHead?;
755
+ /**
756
+ * `relativePath → content hash` of the tree this node last announced.
375
757
  *
376
- * A push declaring one of these — but not the current one — comes from a
377
- * sender that is behind this node. Applying such a tree is what puts a
378
- * deleted file back, so it is ignored outright rather than applied
379
- * additively.
758
+ * The chain entry has to say what a push CHANGED and what it REMOVED, and
759
+ * only a comparison against the previously announced content tells those
760
+ * apart from "everything, because this is the first push". Kept beside
761
+ * {@link _announcedFiles}, which answers the coarser question of which paths
762
+ * peers could know about.
380
763
  */
381
- private readonly _stateHistory;
764
+ private _announcedContent;
765
+ /**
766
+ * Set while a folder with files and no history waits for a head.
767
+ *
768
+ * The deferral in `syncToDb`: until a head has been seen, nothing in this
769
+ * folder has been established, so the node says nothing about it. Cleared by
770
+ * the reconcile, or by the first push once it turns out this node is the
771
+ * origin.
772
+ */
773
+ private _joinPending;
774
+ /** See {@link FsAgentOptions.joinWaitMs}. */
775
+ private readonly _joinWaitMs;
776
+ /** Ends the wait, so a node that is the origin is never silent for good. */
777
+ private _joinWaitTimer;
778
+ /** Asks for the network's state, repeatedly, while a join is pending. */
779
+ private _joinAskTimer;
780
+ /**
781
+ * The two sides of a merge in progress, so its entry claims only its own
782
+ * work.
783
+ *
784
+ * **A merge authors the bytes it PRODUCES, and nothing else.** Where it keeps
785
+ * this side's content, the author is whoever wrote it here; where it adopts
786
+ * the other side's, the author is the peer. The only bytes a merge brings
787
+ * into the world are the ones at paths neither side had — the conflict
788
+ * copies.
789
+ *
790
+ * The merge revision's `changed` was a diff against what this node last
791
+ * ANNOUNCED, which says nothing about authorship. Measured end to end: node
792
+ * C merged against a late v5 announcement, took the writer's v5 bytes, and
793
+ * claimed `doc.txt` — a claim 28 seconds newer than the writer's own v8
794
+ * edit, so the per-path question answered truthfully and still chose v5.
795
+ * Then the writer adopted C's state and claimed v5 as well. Two nodes
796
+ * recorded themselves as the author of a version neither had written.
797
+ */
798
+ private _mergeInputs;
799
+ /**
800
+ * The reconcile that is running, so only ONE ever does.
801
+ *
802
+ * Announcements arrive in bursts and the reconcile awaits a query, a tree
803
+ * read and a restore. A second announcement landing in that window used to
804
+ * take the ordinary path, schedule an apply, and act on the peer's stated
805
+ * removal — which deleted the very file the reconcile was about to set
806
+ * aside. Measured: the joiner's stale copy destroyed instead of recovered,
807
+ * with "set aside 1 file" in the log, because the rename had nothing left to
808
+ * move.
809
+ *
810
+ * `_joinPending` therefore stays set until the reconcile FINISHES, so every
811
+ * announcement in that window funnels into this one promise and none of them
812
+ * schedules anything.
813
+ */
814
+ private _joinInFlight;
815
+ /**
816
+ * Whether this node has ever announced anything.
817
+ *
818
+ * Kept separately from {@link _announcedContent} being empty, because an
819
+ * empty folder announced is a real statement and an unspoken node is not.
820
+ */
821
+ private _hasAnnounced;
822
+ /**
823
+ * The ref last written to {@link AGENT_STATE_FILE}.
824
+ *
825
+ * Held because the state file now carries two things, and a tombstone write
826
+ * must not blank the ref that was already recorded.
827
+ */
828
+ private _currentRefPersisted;
382
829
  /**
383
830
  * Absolute paths of the files this agent has actually TOLD anyone about.
384
831
  *
@@ -397,6 +844,19 @@ export declare class FsAgent {
397
844
  * on the line.
398
845
  */
399
846
  private _restorePruned;
847
+ /**
848
+ * Files this restore refused to re-create because they are tombstoned.
849
+ *
850
+ * Counted and reported, because the alternative is a guard whose work is
851
+ * invisible. The same mistake was made once already with `_restorePruned`:
852
+ * reported before the prune that sets it, so every restore that deleted
853
+ * files announced itself as one that had deleted none — *"a log that cannot
854
+ * report an event is worse than no log, because it reads as evidence of
855
+ * absence"*. A tombstone that silently stops a write is exactly that shape,
856
+ * and when a deleted file reappears anyway this count is the first thing
857
+ * worth knowing.
858
+ */
859
+ private _restoreTombstoned;
400
860
  /** Paths the current {@link restore} could not write because they were held open. */
401
861
  private _restoreLocked;
402
862
  /**
@@ -405,14 +865,63 @@ export declare class FsAgent {
405
865
  * cannot abandon the rest of the tree and, above all, cannot stop the prune.
406
866
  */
407
867
  private _restoreUnavailable;
868
+ /** Paths this filesystem rejected outright. See {@link UnwritablePathError}. */
869
+ private _restoreImpossible;
870
+ /**
871
+ * Paths whose KIND changed — a file where a directory was, or the reverse.
872
+ *
873
+ * Counted and reported because such a change removes whatever was there,
874
+ * and a restore that silently deletes a subtree is one nobody can audit
875
+ * afterwards.
876
+ */
877
+ private _restoreRetyped;
878
+ /**
879
+ * How long each stage of the last push and the last apply took, in ms.
880
+ *
881
+ * measured on a real fleet: *"im Schnitt 3 Sekunden, im schlechtesten Fall
882
+ * 84. Alle Zeitbudgets der Testsuite hängen an dieser Zahl."* And the reason
883
+ * nobody could say more than that: *"bisher wird nur die Gesamtzeit
884
+ * gemessen. Die einzelnen Schritte mitmessen — Scan, Prüfsumme, Ablage,
885
+ * Meldung, Abholen, Schreiben —, sonst rät man."* (`the weakness register`
886
+ * F5/C7.)
887
+ *
888
+ * A total tells you a sync was slow. It does not tell you whether the folder
889
+ * was being hashed, a blob was crossing the network, or a disk was writing —
890
+ * and those have different people to talk to. Kept as a plain record so a
891
+ * host can log or display it without this agent deciding how.
892
+ */
893
+ private readonly _stageMs;
894
+ /**
895
+ * Times one stage into {@link _stageMs}.
896
+ *
897
+ * Overwrites rather than accumulates: the question is "what did the last
898
+ * cycle cost", and a running total answers a different one and never resets.
899
+ * @param stage - The stage name.
900
+ * @param work - What to time.
901
+ * @returns Whatever `work` returned.
902
+ */
903
+ private _timed;
904
+ /**
905
+ * What each stage of the last push and apply cost, in milliseconds.
906
+ *
907
+ * A snapshot, safe to keep: `push.*` is the send side, `apply.*` the receive
908
+ * side, and a stage absent simply has not run yet in this process.
909
+ */
910
+ get stageTimings(): Readonly<Record<string, number>>;
408
911
  /**
409
912
  * What this agent last wrote to each absolute path, so a repeat restore can
410
913
  * recognise its own work without re-reading the file.
411
914
  */
412
915
  private _restoredBlobs;
413
916
  private _timeouts;
917
+ /** Told when a same-file conflict was resolved. See `onConflict`. */
918
+ private readonly _onConflict?;
414
919
  /** Client-only: resolve DAG-branch conflicts into merge revisions. */
415
920
  private _resolveConflicts;
921
+ /** See {@link FsAgentOptions.bucketSync}. */
922
+ private _bucketSyncOn;
923
+ /** The bucket-sync conversation, when {@link _bucketSyncOn}. */
924
+ private _bucketSync?;
416
925
  /**
417
926
  * Ancestry head: the content ref of the revision currently representing the
418
927
  * filesystem state. New local revisions descend from it; received revisions
@@ -448,6 +957,21 @@ export declare class FsAgent {
448
957
  * A divergence that lasts is the one thing a lost message leaves behind, and
449
958
  * until now nothing reported it: this is what a diagnostics view should show.
450
959
  */
960
+ /**
961
+ * Deletions the mass-delete guard refused, newest last.
962
+ *
963
+ * For a client that has to answer "why did my deletion not arrive". The
964
+ * guard refuses on every node, so a real mass deletion stalls the whole
965
+ * fleet silently as far as a UI is concerned — the only trace today is a
966
+ * line in each machine's log. See {@link RefusedDeletion} and
967
+ * `README.public.md`, "Known constraints".
968
+ *
969
+ * Bounded at {@link REFUSED_DELETION_LOG_MAX}; in memory, so a restart
970
+ * clears it while the folders stay split. That is a reason to show it
971
+ * promptly, not a reason to persist it: the refusal repeats on the next
972
+ * announcement, so the list refills on its own.
973
+ */
974
+ get refusedDeletions(): readonly RefusedDeletion[];
451
975
  get antiEntropyStatus(): AntiEntropyStatus | null;
452
976
  /**
453
977
  * Records the ref this folder is now at, so a restart can still say what it
@@ -470,6 +994,40 @@ export declare class FsAgent {
470
994
  */
471
995
  private _ensureWatching;
472
996
  private _persistCurrentRef;
997
+ /**
998
+ * Writes the tombstone log, keeping whatever ref is already recorded.
999
+ *
1000
+ * Separate from {@link _persistCurrentRef} because a deletion is recorded the
1001
+ * moment the watcher reports it — before the push that moves the ref — and
1002
+ * losing it in that window is the whole defect.
1003
+ */
1004
+ private _persistTombstones;
1005
+ /**
1006
+ * Writes `.fsagent-state.json`: the ref this folder is at, and the paths
1007
+ * deleted here.
1008
+ *
1009
+ * One file for both, written whole, because a partial write of either is
1010
+ * indistinguishable from a first run — and both answer `undefined` /
1011
+ * "nothing tombstoned", which is the safe direction for each.
1012
+ */
1013
+ private _writeAgentState;
1014
+ /**
1015
+ * Loads the tombstone log a previous run left behind.
1016
+ *
1017
+ * A restart that forgot what it had deleted is how a deletion is undone by
1018
+ * the first peer that never heard about it.
1019
+ */
1020
+ private _loadPersistedTombstones;
1021
+ /**
1022
+ * Reloads the path edit times written by a previous run.
1023
+ *
1024
+ * Absent, unreadable and malformed all mean "this process cannot say when
1025
+ * these paths were last edited", and all leave the map empty — which puts
1026
+ * tombstone ordering back on the rules that shipped before `editedAt`
1027
+ * existed. Safe, and the reason it is worth reloading at all is that the
1028
+ * safe answer is also the one that loses a file: see `_writeAgentState`.
1029
+ */
1030
+ private _loadPersistedEditTimes;
473
1031
  /**
474
1032
  * The ref this folder was last recorded at, from a previous run.
475
1033
  *
@@ -479,6 +1037,21 @@ export declare class FsAgent {
479
1037
  * @returns The persisted ref, or `undefined`.
480
1038
  */
481
1039
  private _loadPersistedRef;
1040
+ /**
1041
+ * Records resolved conflicts and tells the host.
1042
+ *
1043
+ * Both, not either: the callback is for a UI that is running now, the file is
1044
+ * for one that starts later. A conflict the user never hears about is the
1045
+ * thing this exists to stop, so it does not depend on anyone having
1046
+ * subscribed.
1047
+ *
1048
+ * The whole file is rewritten rather than appended, because it has to stay
1049
+ * valid JSON and bounded. At {@link CONFLICT_LOG_MAX} entries that is a few
1050
+ * tens of kilobytes, and conflicts are rare — unlike deletions, which is why
1051
+ * the tombstone log made the opposite choice.
1052
+ * @param reports - What the resolver resolved, one entry per path.
1053
+ */
1054
+ private _recordConflicts;
482
1055
  /**
483
1056
  * Appends a sync error entry to the error log file in the sync folder.
484
1057
  * Uses synchronous I/O to guarantee the write completes even in catch blocks.
@@ -507,13 +1080,12 @@ export declare class FsAgent {
507
1080
  */
508
1081
  private static _withRetry;
509
1082
  /**
510
- * Atomically writes a file: stages the content in a sibling `.<rand>.tmp`,
511
- * then renames over the target. The rename is atomic, so a crash mid-write
512
- * leaves only the temp behind — never a half-written target file. (We do not
513
- * `fsync` the temp: it adds significant per-file latency under bursty
514
- * restores, and durability-on-power-loss is secondary here since the content
515
- * is replicated and re-synced.) The random suffix keeps concurrent restores
516
- * of the same path from trampling each other.
1083
+ * Writes a file through a staging file and a rename.
1084
+ *
1085
+ * Kept as a thin named wrapper because the restore path reads as a pair with
1086
+ * {@link FsAgent._atomicWriteStream}. The rule, and the byte-level
1087
+ * corruption that made it a rule on every platform rather than on Windows
1088
+ * only, are in `fs-atomic-write.ts`.
517
1089
  * @param filePath - Destination path
518
1090
  * @param content - Bytes to write
519
1091
  */
@@ -523,10 +1095,11 @@ export declare class FsAgent {
523
1095
  *
524
1096
  * The two have different answers. A blob that cannot be fetched costs one
525
1097
  * file and the tree applies without it; a file that cannot be written is
526
- * usually a CARAT document a user still has open, and that one must not abort
527
- * the rest of the restore either. Conflating them would report an offline peer
528
- * as a locked file, and the field reports are read by people who act on that
529
- * distinction.
1098
+ * usually a document the host application still has open for a user, and that
1099
+ * one must not abort
1100
+ * the rest of the restore either. Conflating them would report an offline
1101
+ * peer as a locked file, and the field reports are read by people who act on
1102
+ * that distinction.
530
1103
  * @param error - The error thrown while writing the file.
531
1104
  * @returns Whether it came from the blob source.
532
1105
  */
@@ -534,12 +1107,12 @@ export declare class FsAgent {
534
1107
  /**
535
1108
  * Writes a file from a stream, holding one chunk at a time.
536
1109
  *
537
- * The twin of {@link FsAgent._atomicWriteFile}, with the same platform rule
538
- * and the same reason for it, but never materialising the whole file. A 500 MB
539
- * file used to cost 500 MB of Buffer on the receiving agent, another copy in
540
- * the socket parser, and — on the serving hub — the same again. That is the
541
- * shape that killed the cloud EventHub: memory that is work in flight rather
542
- * than garbage, so no collection can reclaim any of it.
1110
+ * The twin of {@link FsAgent._atomicWriteFile} — temp and rename on every
1111
+ * platform, for the same reasons — but never materialising the whole file. A
1112
+ * 500 MB file used to cost 500 MB of Buffer on the receiving agent, another
1113
+ * copy in the socket parser, and — on the serving hub — the same again. That
1114
+ * is the shape that exhausted a cloud relay: memory that is work in flight
1115
+ * rather than garbage, so no collection can reclaim any of it.
543
1116
  *
544
1117
  * Read failures are tagged, because from here on the bytes arrive during the
545
1118
  * write rather than before it, and {@link FsAgent._isBlobReadError} is what
@@ -569,20 +1142,24 @@ export declare class FsAgent {
569
1142
  */
570
1143
  private _sendRef;
571
1144
  /**
572
- * Starts automatic syncing to database
573
- * Note: Auto-sync requires Connector which is not available in constructor.
574
- * Consider using syncToDb() directly instead of constructor options.
575
- */
576
- private _startAutoSync;
577
- /**
578
- * Starts automatic syncing from database
579
- * @param bidirectional - Whether bidirectional sync is enabled
580
- * Note: Auto-sync requires Connector which is not available in constructor.
581
- * Consider using syncFromDb() directly instead of constructor options.
582
- */
583
- private _startAutoSyncFromDb;
584
- /**
585
- * Stops automatic syncing and cleans up resources
1145
+ * Abandons a join this agent is still waiting on.
1146
+ *
1147
+ * **This method used to do nothing at all**, and the host application calls
1148
+ * it in
1149
+ * six places on shutdown. It read two fields that were never assigned —
1150
+ * leftovers of the constructor auto-sync pattern, which was removed — each
1151
+ * behind a `v8 ignore` that hid the fact. The real stopping is done by the
1152
+ * functions `syncToDb` and `syncFromDb` return, which the client already
1153
+ * calls first.
1154
+ *
1155
+ * What it does now is the one thing those cannot: cancel a pending join. A
1156
+ * folder that deferred its first announcement keeps asking the network for a
1157
+ * head every {@link JOIN_ASK_INTERVAL_MS} until the wait expires, and a
1158
+ * `stop()` does not end it — so a node shut down mid-join went on asking a
1159
+ * connector that was being torn down, and every refusal reached the sync
1160
+ * error log. The timers are `unref`'d, so this was never a reason the
1161
+ * process stayed alive; it was noise at exactly the moment a shutdown is
1162
+ * being diagnosed.
586
1163
  */
587
1164
  dispose(): void;
588
1165
  /**
@@ -625,6 +1202,89 @@ export declare class FsAgent {
625
1202
  * @param err - The caught value.
626
1203
  * @returns `true` for a lock-shaped error.
627
1204
  */
1205
+ /**
1206
+ * Whether a write failed because the PATH is impossible here, rather than
1207
+ * because the file is busy.
1208
+ *
1209
+ * The rules differ per platform and this agent must not encode them: Windows
1210
+ * refuses a component over 255, a total path over 260, the reserved device
1211
+ * names (`CON`, `PRN`, `AUX`, `NUL`, `COM1`…), a trailing space or dot;
1212
+ * POSIX refuses a component over 255 and an embedded NUL. What they share is
1213
+ * the errno, so the errno is what this reads.
1214
+ *
1215
+ * Deliberately NOT retried, unlike a lock: a name does not become legal by
1216
+ * waiting. The file is reported as unavailable and the tree is applied
1217
+ * around it.
1218
+ * @param err - The caught value.
1219
+ * @returns Whether the path itself is the problem.
1220
+ */
1221
+ /**
1222
+ * Whether a tree's path stays inside the folder being restored.
1223
+ *
1224
+ * A tree is DATA FROM ANOTHER MACHINE. Nothing has checked where its paths
1225
+ * point, and `join(target, '../escaped.txt')` resolves outside the target —
1226
+ * so a peer, or one corrupted node, could write anywhere this process can.
1227
+ * Measured before this existed: a tree carrying `../escaped.txt` put a file
1228
+ * next to the sync folder, and the restore reported success.
1229
+ *
1230
+ * It needs no malice to matter. A relative path assembled wrongly, a
1231
+ * `relativePath` left absolute by a future scanner, a tree edited by hand to
1232
+ * reproduce a bug — all of them become an arbitrary file write on every node
1233
+ * that applies the tree.
1234
+ *
1235
+ * Checked by RESOLVING rather than by looking for `..`, because `a/../../b`,
1236
+ * a symlinked parent and an absolute path are all the same question and only
1237
+ * one of them contains the obvious substring.
1238
+ * @param target - The folder being restored into.
1239
+ * @param relativePath - The path the tree claims.
1240
+ * @returns Whether it is safe to write.
1241
+ */
1242
+ /**
1243
+ * Clears whatever is at a path so a node of a DIFFERENT KIND can be written
1244
+ * there.
1245
+ *
1246
+ * A path does not only change its contents; it changes what it IS. A user
1247
+ * replaces a stray file with the folder it should have been, an export
1248
+ * writes a single document where an unpacked directory used to sit. Both
1249
+ * mature comparable projects test exactly these transitions —
1250
+ * Syncthing as `filetype_test.go`, Unison as "file replacement" and
1251
+ * "directory replacement" — and this agent did neither.
1252
+ *
1253
+ * Measured before this existed, all three aborting the WHOLE restore with a
1254
+ * raw errno, so a single type change stopped the folder syncing:
1255
+ *
1256
+ * file → directory EEXIST: file already exists, mkdir
1257
+ * empty directory → file EISDIR: illegal operation on a directory
1258
+ * directory with files → file the same
1259
+ *
1260
+ * Nothing is destroyed that the tree does not already say is gone, and the
1261
+ * mass-delete guard has already counted it: the subtree's files are in
1262
+ * `preRestore` and absent from `expectedFiles`, which is exactly the
1263
+ * population it judges. So a type change that would empty a folder is still
1264
+ * refused before the walk reaches here.
1265
+ *
1266
+ * `lstat`, not `stat`: a symlink is a third kind of thing and must not be
1267
+ * followed to decide what to remove.
1268
+ * @param path - Where the node is to be written.
1269
+ * @param want - What the tree says should be there.
1270
+ * @returns Whether something had to be removed.
1271
+ */
1272
+ /**
1273
+ * Whether a path the prune is about to delete is actually the expected file
1274
+ * under another spelling of its name.
1275
+ *
1276
+ * On a case-insensitive filesystem `Angebot.docx` and `angebot.docx` are one
1277
+ * file, so the two paths share an inode. On a case-sensitive one they are
1278
+ * two files with two inodes, and the entry really is extraneous. Comparing
1279
+ * the inode answers both without knowing which kind of filesystem this is.
1280
+ * @param fullPath - The entry the prune found on disk.
1281
+ * @param expectedByLowerCase - Expected paths indexed by lower case.
1282
+ * @returns Whether the entry must be kept.
1283
+ */
1284
+ private _isSameFileAsExpected;
1285
+ private _makeRoomFor;
1286
+ static _isInsideRoot(target: string, relativePath: string): boolean;
1287
+ private static _isImpossiblePath;
628
1288
  private static _isLocked;
629
1289
  /**
630
1290
  * The content identity this agent believes is on disk at `filePath`, or
@@ -731,6 +1391,9 @@ export declare class FsAgent {
731
1391
  * @param expectedDirs - Allowed directory paths
732
1392
  * @param expectedFiles - Allowed file paths
733
1393
  * @param preRestore - Files present before the restore (prune candidates)
1394
+ * @param expectedByLowerCase - Expected paths indexed by lower case, so a
1395
+ * file the tree spells with different capitalisation is recognised as the
1396
+ * same file rather than pruned.
734
1397
  */
735
1398
  private _pruneExtraneous;
736
1399
  /**
@@ -746,9 +1409,9 @@ export declare class FsAgent {
746
1409
  /**
747
1410
  * Resolves the `previous` (InsertHistory predecessor timeIds) for a new
748
1411
  * revision from the parent's shared content refs. timeIds are per-db, so we
749
- * map each shared parent ref to *this* db's local timeId(s). Returns undefined
750
- * when ancestry tracking is off (default) or no parent is known — in which
751
- * case the store behaves exactly as before.
1412
+ * map each shared parent ref to *this* db's local timeId(s). Returns
1413
+ * undefined when ancestry tracking is off (default) or no parent is known —
1414
+ * in which case the store behaves exactly as before.
752
1415
  * @param db - Database instance
753
1416
  * @param treeKey - Tree table key
754
1417
  * @param parentRefs - Parent content refs (local head, or received predecessors)
@@ -779,8 +1442,70 @@ export declare class FsAgent {
779
1442
  * @param incomingRef - The incoming revision's content ref
780
1443
  * @param incomingTree - The fetched incoming tree
781
1444
  * @param predecessorRefs - The incoming revision's predecessor content refs
1445
+ * @param connector - Used to announce the merge revision once the chain
1446
+ * entry for it exists. See `storeMerge`.
782
1447
  */
783
1448
  private _resolveConflictInline;
1449
+ /**
1450
+ * Stops a merge from making this node look like the author of what it kept.
1451
+ *
1452
+ * A merge that resolves `doc.txt` by keeping this side's existing bytes has
1453
+ * not EDITED `doc.txt`. But the next push computes its delta against what
1454
+ * this node last announced, and after a merge that is some other state — so
1455
+ * the diff reports the path as changed and the entry claims it. The claim is
1456
+ * then the newest edit of that path in the whole fleet, and it carries the
1457
+ * OLDER content.
1458
+ *
1459
+ * Measured on *every node ends on the last save*, with the per-path verdict
1460
+ * already in place and working: the side holding v5 had a LATER edit of
1461
+ * `doc.txt` (…253668) than the writer's v8 (…225297), so the per-path
1462
+ * question answered truthfully and still chose v5. The question was right;
1463
+ * one of its two inputs was a lie.
1464
+ *
1465
+ * The CLAIMS are not touched. A node that legitimately authored a path and
1466
+ * then kept it through a merge still authored it, and dropping that would
1467
+ * lose its work in the other direction.
1468
+ * @param beforeMerge - This node's tree before the merge.
1469
+ * @param afterMerge - Its tree after the merge materialised.
1470
+ */
1471
+ private _dontClaimUnchangedPaths;
1472
+ /**
1473
+ * Records the paths whose current bytes CAME FROM A PEER.
1474
+ *
1475
+ * **`changed` has to mean "I changed this", and it did not.** It is computed
1476
+ * by diffing this folder against `_announcedContent` — a pure content diff,
1477
+ * with no notion of WHO changed a path. So a node claimed every path where
1478
+ * its folder differed from its last announcement, including paths it had
1479
+ * merely received, paths it had failed to receive, and paths where a merge
1480
+ * had kept one side's bytes. The entry it then authored was a real edit with
1481
+ * a correct stamp for the moment of authoring, and that is exactly why it
1482
+ * won: it should never have existed.
1483
+ *
1484
+ * Measured: `changed=[doc (conflicted copy …).txt, doc.txt]` on a node that
1485
+ * had edited neither, whose v5 then out-ordered the writer's v8 and rolled
1486
+ * the writer's own folder back.
1487
+ *
1488
+ * Recording the arrival in `_announcedContent` is what keeps the path out of
1489
+ * the next delta, and dropping the local claim is what stops a peer's later
1490
+ * removal of it looking stale. Peers DO know these bytes — they sent them —
1491
+ * so this is not a suppression, it is the truth being written down.
1492
+ *
1493
+ * The conflict copy in that measurement is genuinely this node's work and
1494
+ * keeps being claimed: its bytes sit at a path no peer sent.
1495
+ * **Only what actually ARRIVED, which needs the before-state.** Comparing
1496
+ * the incoming tree against the folder afterwards cannot tell "the apply
1497
+ * delivered this" from "we already had it" — and the second case is a
1498
+ * node's OWN work coming back to it, which happens constantly: a peer
1499
+ * re-announces a state it adopted, and the author receives its own bytes.
1500
+ * Treating those as received drops the author's claim to a file it wrote,
1501
+ * and then the bucket round hands the file to whoever is holding a stale
1502
+ * copy. Measured: the writer-rollback invariant failing 8 runs of 8, where
1503
+ * the rule it was meant to fix fails 6.
1504
+ * @param arrived - The tree that came from the peer.
1505
+ * @param before - This folder as it stood before the apply.
1506
+ * @param after - This folder as it stands now.
1507
+ */
1508
+ private _recordReceived;
784
1509
  /**
785
1510
  * Builds a map of relativePath → blobId for all files in a tree.
786
1511
  * Used to compare trees by content rather than by hash (which includes mtime).
@@ -813,15 +1538,15 @@ export declare class FsAgent {
813
1538
  * @param treeRef - The ref that now describes this folder.
814
1539
  */
815
1540
  /**
816
- * Re-announce this folder's current state after refusing an incoming tree.
1541
+ * Re-announce this folder's state to a sender that holds far less of it.
817
1542
  *
818
- * A refusal means the sender holds less than this node does, so it is the one
819
- * that needs telling. Without this the network settles into a state that is
820
- * stable and wrong: the sparse node cannot push, the full node has nothing
821
- * new to push, and nothing moves until an unrelated edit happens somewhere.
1543
+ * The sender is the one that needs telling. Without this the network settles
1544
+ * into a state that is stable and wrong: the sparse node cannot push, the
1545
+ * full node has nothing new to push, and nothing moves until an unrelated
1546
+ * edit happens somewhere.
822
1547
  *
823
- * Rate-limited because two nodes can refuse each other — each holding files
824
- * the other lacks — and an unthrottled answer to every refusal is a loop.
1548
+ * Rate-limited because two nodes can each hold what the other lacks, and an
1549
+ * unthrottled answer is a loop.
825
1550
  * @param connector - Connector to broadcast on.
826
1551
  */
827
1552
  private _readvertiseAfterRefusal;
@@ -887,17 +1612,415 @@ export declare class FsAgent {
887
1612
  * @param tree - The tree that just went out, or was adopted as ours.
888
1613
  */
889
1614
  /**
890
- * Records a state this node is now in.
891
- * @param ref - The content ref of that state.
1615
+ * Announces this folder as it stands, as the ordinary first push would.
1616
+ *
1617
+ * Used when a deferred join times out: no head arrived, so no history exists
1618
+ * anywhere and this folder is the origin. Re-scanned rather than reusing the
1619
+ * tree from start-up, because the wait is seconds long and the user may have
1620
+ * carried on working through it.
1621
+ * @param db - The route's database.
1622
+ * @param connector - Connector to announce on.
1623
+ * @param treeKey - The trees table key.
1624
+ */
1625
+ private _pushCurrentState;
1626
+ /**
1627
+ * Reconciles a folder that has files and no history against the fleet's head.
1628
+ *
1629
+ * **The chain applies first; the filesystem only then.** Every question here
1630
+ * is answered by {@link planJoin} against the chain, and the folder is
1631
+ * consulted for what it holds — never for what that means.
1632
+ *
1633
+ * The four answers, and why each is what it is:
1634
+ *
1635
+ * - **write** — the head has it and this folder does not. The fleet's state
1636
+ * is the starting point, not this folder's.
1637
+ * - **announce** — this folder has it and the history has never named it. New
1638
+ * work, made before this node ever joined; dropping it is how a node loses
1639
+ * its own files on joining.
1640
+ * - **recover** — this folder has it and the history REMOVED it. A stale
1641
+ * copy: a backup restore, or a folder that sat while a directory was
1642
+ * deleted. Set aside under `(recovered)` and NOT announced, because
1643
+ * announcing would push every one of those deletions back to every node.
1644
+ * - **conflict** — live on both sides with different bytes, edited while this
1645
+ * node was away. The head's bytes win because the chain states them, and
1646
+ * the local bytes become an ordinary conflict copy, which IS announced.
1647
+ *
1648
+ * Returns having adopted the head's entry, so this node's first word to the
1649
+ * network is the fleet's own state plus whatever it legitimately adds.
1650
+ * @param db - The route's database.
1651
+ * @param treeKey - The trees table key.
1652
+ * @param entry - The head this node is joining onto.
1653
+ */
1654
+ private _reconcileJoin;
1655
+ /**
1656
+ * The body of {@link _reconcileJoin}, run once under its guard.
1657
+ *
1658
+ * The watcher is paused for the whole of it. The reconcile renames files and
1659
+ * then restores over the result, and a watcher awake for that would read its
1660
+ * own work as local edits and announce them.
1661
+ * @param db - The route's database.
1662
+ * @param treeKey - The trees table key.
1663
+ * @param entry - The head this node is joining onto.
1664
+ */
1665
+ /**
1666
+ * Says nothing about this folder until the network's state has been seen.
1667
+ *
1668
+ * Two situations need it, and they are the same situation: this folder's
1669
+ * contents have not been established, so announcing them would make a claim
1670
+ * rather than report a fact.
1671
+ *
1672
+ * - a folder with files and NO history — a client joining for the first
1673
+ * time, or one whose folder was copied in from somewhere;
1674
+ * - a folder that has LOST its contents while having a history — a wipe,
1675
+ * which is not a deletion anybody performed.
1676
+ *
1677
+ * It keeps ASKING rather than waiting to be told once. The hub volunteers
1678
+ * its state — the connector has a bootstrap channel and a heartbeat — but a
1679
+ * node that misses those cannot tell "I heard nothing" from "there is
1680
+ * nothing", and those demand opposite actions at the moment it decides
1681
+ * whether to speak.
1682
+ *
1683
+ * BOUNDED: no head anywhere means no history anywhere, so this folder is the
1684
+ * origin and the ordinary push states it. A deferral, never a refusal.
1685
+ * @param db - The route's database.
1686
+ * @param connector - Connector to announce on, once there is something to say.
1687
+ * @param treeKey - The trees table key.
1688
+ * @param why - How this folder got here, for the log.
1689
+ */
1690
+ private _deferToNetwork;
1691
+ /** Stops asking, whichever way the join ended. */
1692
+ private _stopAsking;
1693
+ private _reconcileJoinOnce;
1694
+ /**
1695
+ * What joining actually does to the folder.
1696
+ * @param db - The route's database.
1697
+ * @param treeKey - The trees table key.
1698
+ * @param entry - The head this node is joining onto.
1699
+ */
1700
+ /**
1701
+ * Moves one file out of the way of the state this node is joining onto.
1702
+ *
1703
+ * A method rather than a closure inside the join so that the failure can be
1704
+ * TESTED. A rename that cannot be performed — the source gone between the
1705
+ * scan and the move, the destination occupied by a directory — leaves the
1706
+ * file where it is, and the restore then overwrites it. That loses less than
1707
+ * refusing to join, which is why it is recorded rather than thrown; and a
1708
+ * path that is only ever recorded is a path that needs a test, because
1709
+ * nothing else will ever tell anybody it stopped working.
1710
+ * @param path - The file to move, relative to the root, `/`-separated.
1711
+ * @param name - Where to move it, same form.
1712
+ */
1713
+ private _setAside;
1714
+ /**
1715
+ * Where an announced state sits relative to this node, per the chain.
1716
+ *
1717
+ * A method rather than an inline block so the two ways the chain can fail
1718
+ * here can be TESTED — both are `.catch`es, so nothing else would ever
1719
+ * report them.
1720
+ *
1721
+ * `classify` compares chain HEADS and what arrived is a TREE ref. The head
1722
+ * the ANNOUNCEMENT carried is the right one: it is what the sender said
1723
+ * about itself. The lookup by tree ref is only the fallback, for a ref that
1724
+ * came without one — the hub's own advertisements, an older peer — and it is
1725
+ * ambiguous by nature, because a tree ref is a content hash and two nodes
1726
+ * holding the same bytes produce the same one. Two freshly started nodes
1727
+ * both have an entry for the EMPTY tree, so asking by hash there can return
1728
+ * either node's.
1729
+ *
1730
+ * `incomplete` means no entry covers this state, which leaves the decision
1731
+ * to the caller's own branches rather than guessing — and an unreadable
1732
+ * chain has to give the same answer as a missing one, because in both cases
1733
+ * the history says nothing.
1734
+ * @param treeRef - The announced state.
1735
+ * @returns The relation, or `incomplete` when the chain cannot say.
1736
+ */
1737
+ /**
1738
+ * The chain head that stands for a tree ref, when anything names one.
1739
+ *
1740
+ * Two sources, in this order, and neither is a guess — both are statements
1741
+ * somebody made. The head a peer ANNOUNCED for that state, parked by
1742
+ * `_rememberAnnouncedHead`; failing that, this node's own chain, which knows
1743
+ * the head if it ever recorded an entry landing on that tree.
1744
+ *
1745
+ * Pulled out of {@link _classifyAnnouncedRef} because the merge needs the
1746
+ * same answer for a different reason: to name the side it merged IN as a
1747
+ * parent. See {@link _resolveConflictInline}.
1748
+ * @param treeRef - The state to name.
1749
+ * @returns The head standing for it, or undefined when nothing does.
1750
+ */
1751
+ private _headForTreeRef;
1752
+ private _classifyAnnouncedRef;
1753
+ private _joinReconcileBody;
1754
+ /**
1755
+ * Agrees with the fleet on ONE entry for the state this folder is in.
1756
+ *
1757
+ * **This is where the fleet's single history is actually made.** Every node
1758
+ * authors an entry for the state it starts in, and those states are usually
1759
+ * IDENTICAL — peers already in sync hold the same bytes, so they derive the
1760
+ * same tree ref. Without this, the fleet has one lineage per node from the
1761
+ * first second, and then nothing is ever `behind` or `ahead`: `classify`
1762
+ * finds neither head reachable from the other and answers `fork` to every
1763
+ * announcement there has ever been.
1764
+ *
1765
+ * Measured on `a document never goes backwards while one person edits it`,
1766
+ * 6 runs in 8, and the control confirms it predates this session: one writer
1767
+ * saving v0…v8, two receivers cut and healed underneath. Each node's seed
1768
+ * entry listed `changed=[]` — nothing, because nothing had changed — and was
1769
+ * still its own lineage root. A healed receiver's announcement was therefore
1770
+ * a FORK of the writer's, the writer merged it, a conflicted copy appeared
1771
+ * on a file one person had edited, and the writer's own folder went from v8
1772
+ * back to v5.
1773
+ *
1774
+ * **THE OLDEST ENTRY WINS**, asked BY CONTENT rather than taken from the
1775
+ * announcement. Every node can see the same rows, so every node picks the
1776
+ * same one without coordination; and adoption that only moves backwards in
1777
+ * time is monotone, so it cannot oscillate as rows replicate. Whoever
1778
+ * reached this content first described it first.
1779
+ *
1780
+ * Called wherever a ref is recognised as describing this folder as it
1781
+ * stands — and the ECHO path is the one that matters, because that is where
1782
+ * identical seed states meet. There is no content to apply, only a name to
1783
+ * agree on, so the apply never runs and no other path sees them.
1784
+ * @param treeRef - The ref describing this folder's current content.
892
1785
  */
893
- private _rememberState;
1786
+ private _agreeOnEntryFor;
894
1787
  /**
895
- * Whether a push comes from a sender this node has already moved past.
896
- * @param predecessorRefs - What the push declares it descends from.
897
- * @returns True when every declared parent is a state this node has left.
1788
+ * Parks the chain head an announcement resolved to, for its apply to find.
1789
+ *
1790
+ * Bounded by {@link ANNOUNCED_HEAD_MAX}, oldest first — insertion order is
1791
+ * arrival order, so the oldest parked head is the one whose apply is least
1792
+ * likely to still be coming.
1793
+ * @param treeRef - The state announced.
1794
+ * @param head - The sender's chain head that produced it.
898
1795
  */
899
- private _senderIsBehind;
1796
+ private _rememberAnnouncedHead;
900
1797
  private _rememberAnnounced;
1798
+ /**
1799
+ * Creates this folder's history if it does not exist yet.
1800
+ *
1801
+ * Called from BOTH `syncToDb` and `syncFromDb`, and the second one cost a
1802
+ * red run to discover. A node that only RECEIVES — a late joiner, which
1803
+ * starts `syncFromDb` alone because scanning its empty folder would push
1804
+ * emptiness over everyone else's data — still has to resolve the heads its
1805
+ * peers announce. With the chain created on the send path only, such a node
1806
+ * dropped every announcement it heard and never received a file that already
1807
+ * existed. The chain is per-route state, not per-direction.
1808
+ *
1809
+ * Idempotent in both senses: this method is a no-op once a chain exists, and
1810
+ * `FsEditChain.init` creates its tables with `createOrExtendTable` and
1811
+ * continues the lineage a previous process left behind.
1812
+ *
1813
+ * Best-effort. fs-agent creates its OWN tables — the host application creates
1814
+ * the trees table, and an agent expecting tables its host never created would
1815
+ * fail at runtime on any node whose host is one release behind.
1816
+ * @param db - The route's database.
1817
+ * @param treeKey - The trees table key.
1818
+ */
1819
+ private _ensureChain;
1820
+ /**
1821
+ * What to put on the wire for a state this node is announcing.
1822
+ *
1823
+ * **The head, not the tree ref.** A tree ref is a content hash, so a folder
1824
+ * that returns to a state it held earlier re-derives that state's exact ref —
1825
+ * and a receiver cannot then find the chain row for it by hash, only by
1826
+ * query. Announcing the head makes every announcement resolvable to an entry,
1827
+ * which is what the `previous` walk needs in order to exist at all (§13.5).
1828
+ *
1829
+ * It also makes each announcement UNIQUE. An A → B → A deletion produces
1830
+ * three entries with three heads, so the returning state is news by
1831
+ * construction rather than by clearing the connector's dedup for it.
1832
+ * @param treeRef - The state being announced.
1833
+ * @returns The head that names it, or `treeRef` when this node has no chain
1834
+ * entry for that state — a re-announcement of something older, or a build
1835
+ * whose chain could not be created.
1836
+ */
1837
+ private _announceAs;
1838
+ /**
1839
+ * The state an incoming announcement is about, with its chain entry.
1840
+ *
1841
+ * The entry is what carries the sender's REMOVALS, which is the whole point
1842
+ * of announcing a head: a removal is a fact the sender states, where an
1843
+ * absence from a tree is only something a receiver can try to infer.
1844
+ * @param ref - What arrived on the wire.
1845
+ * @returns The tree ref and, for a marked head, the entry it resolved to.
1846
+ */
1847
+ private _resolveAnnouncement;
1848
+ /**
1849
+ * What the chain says about an announced head, for the decision.
1850
+ *
1851
+ * Reachability is supplied ONLY when this node has a head of its own.
1852
+ * Without one there is nothing to be reachable from, and answering
1853
+ * `incomplete` would block a node that is simply new — a late joiner has no
1854
+ * entries and must be free to pull. Absent, the decision falls back to the
1855
+ * heuristics that shipped before, which is the right behaviour for a node
1856
+ * with no history rather than a degraded one.
1857
+ * @param announced - The ref as it arrived on the wire.
1858
+ * @returns The tree ref and, when both sides have a head, how the two
1859
+ * histories stand; `undefined` for a head this node cannot resolve.
1860
+ */
1861
+ private _reachabilityOf;
1862
+ /**
1863
+ * Builds the bucket-sync host and the conversation that drives it.
1864
+ *
1865
+ * The host is the only thing that may touch the folder: the protocol decides
1866
+ * what to say and what a reply means and cannot delete anything itself,
1867
+ * which is what keeps the destructive half where the mass-delete guard can
1868
+ * see it.
1869
+ * @param connector - The transport.
1870
+ * @param db - The route's database, for fetching what the plan asks for.
1871
+ * @param treeKey - The trees table key.
1872
+ * @returns The conversation.
1873
+ */
1874
+ private _makeBucketSync;
1875
+ /**
1876
+ * This folder's manifest: `path → blobId`, tombstones included.
1877
+ *
1878
+ * A tombstoned path is carried at {@link TOMBSTONE_BLOB}, so a deletion
1879
+ * travels through the ordinary comparison instead of as an absence — the
1880
+ * ambiguity the whole plan exists to remove. A path that is both tombstoned
1881
+ * and live is LIVE: the user created it again, and a stale tombstone must
1882
+ * not advertise it as gone.
1883
+ * @returns The manifest.
1884
+ */
1885
+ private _manifest;
1886
+ /**
1887
+ * Performs what a bucket-sync round concluded.
1888
+ *
1889
+ * **Additive, except for the drops, and those are bounded.** `fetch` only
1890
+ * ever writes a path this node does not hold, so nothing it does can
1891
+ * destroy work. `drop` is the delete-wins direction and goes through the
1892
+ * same mass-delete reasoning an ordinary prune does.
1893
+ * @param plan - What to do.
1894
+ * @param db - Unused today; kept so a fetch can reach the route's store when
1895
+ * a blob is not already local.
1896
+ * @param treeKey - Likewise.
1897
+ */
1898
+ private _applyReconcilePlan;
1899
+ /**
1900
+ * Records a tombstone for a deletion the watcher reported.
1901
+ *
1902
+ * Two shapes arrive here. A FILE this node announced is tombstoned directly.
1903
+ * A DIRECTORY is not in `_announcedFiles` — only files are — and it stands
1904
+ * for every announced file beneath it.
1905
+ *
1906
+ * THE DIRECTORY CASE IS NOT INFERENCE FROM ABSENCE. The watcher reported
1907
+ * that path deleted, and removing a directory necessarily removes what is
1908
+ * inside it, so each announced file under that prefix is a deletion this node
1909
+ * performed and may be stated as one.
1910
+ *
1911
+ * It matters because on Linux the child events do not arrive. `rm -r` unlinks
1912
+ * the children and then the directory; when the watched directory goes,
1913
+ * inotify removes its watch and drops any queued child events, so one child's
1914
+ * deletion is observed and the rest are lost. macOS FSEvents reports them
1915
+ * all, which is why this branch cannot be reached on a developer's Mac and
1916
+ * has a test that calls it directly.
1917
+ *
1918
+ * The consequence was not a slow deletion but an UNDONE one: nothing stated
1919
+ * those removals, so a peer still holding the files announced them back and
1920
+ * this node restored the directory it had just deleted. Measured on Linux CI
1921
+ * twice, a different subset surviving each time.
1922
+ *
1923
+ * Bounded by `_announcedFiles` in both shapes: a path no peer could know
1924
+ * about needs no tombstone, because no peer can push it back.
1925
+ * @param relativePath - The path the watcher reported deleted.
1926
+ * @returns How many tombstones were recorded.
1927
+ */
1928
+ private _tombstoneDeleted;
1929
+ /**
1930
+ * Says, once, that a deletion was refused — in the log, the sync-error file
1931
+ * and {@link FsAgent.refusedDeletions}.
1932
+ *
1933
+ * Three call sites had three copies of this, which is how they came to say
1934
+ * three different things about the same decision. A client reading one of
1935
+ * them saw a third of the picture.
1936
+ * @param route - Which rule refused it.
1937
+ * @param wouldRemove - How many paths it would have deleted.
1938
+ * @param held - How many this folder holds.
1939
+ * @param paths - The paths, of which the first few are kept.
1940
+ * @param detail - Extra wording for the log line, where a route has some.
1941
+ */
1942
+ private _refuseDeletion;
1943
+ /**
1944
+ * Records that a bucket round proved this folder and the hub's agree.
1945
+ *
1946
+ * The roots matched, so the two hold the same content whatever either calls
1947
+ * itself. The anti-entropy is comparing REFS and cannot reach that
1948
+ * conclusion on its own — and without being told it re-reports the same
1949
+ * divergence on every beacon.
1950
+ *
1951
+ * Nothing is recorded when there is no hub ref to record it against. A round
1952
+ * can finish after the announcement that prompted it has been superseded, or
1953
+ * before any beacon has arrived at all, and an agreement needs both sides to
1954
+ * name: see `FsAntiEntropy`'s agreement key.
1955
+ *
1956
+ * A method rather than a closure inside `_makeBucketSync` so that both
1957
+ * answers can be measured; as a closure neither was.
1958
+ */
1959
+ private _bucketRoundAgreed;
1960
+ /**
1961
+ * Gathers the deletions behind a plain TREE REF, via its chain entry.
1962
+ *
1963
+ * The bridge from an unmarked announcement to the chain — the hub's
1964
+ * announcements and an older peer's both arrive this way. Best-effort and
1965
+ * never awaited by the apply path: see the call site.
1966
+ * @param treeRef - The state announced, unmarked.
1967
+ */
1968
+ private _collectRemovalsForTreeRef;
1969
+ /**
1970
+ * Gathers the deletions between a peer's head and a state this node knows.
1971
+ *
1972
+ * NOT just the head's own `removed` list. A removal is stated once, in the
1973
+ * entry that made it, and a node partitioned at that moment states it in an
1974
+ * entry nobody received — its next entry says nothing about the deletion,
1975
+ * because that is computed against its own last announcement. Reading the
1976
+ * head alone therefore learns nothing, and the file survives everywhere
1977
+ * except on the node that deleted it. Measured; see
1978
+ * `FsEditChain.collectRemovals`.
1979
+ *
1980
+ * An incomplete walk is DISCARDED rather than applied in part. A missing
1981
+ * ancestor may be the re-add that cancels a removal we did collect, so
1982
+ * acting on the fragment can delete a live file — mongo's `complete: false`
1983
+ * contract, and the reason it exists.
1984
+ * @param entry - The entry the announcement resolved to.
1985
+ */
1986
+ private _collectIncomingRemovals;
1987
+ /**
1988
+ * Applies the stated delta an announcement carried, if any.
1989
+ *
1990
+ * Both halves, and the second one has to be here rather than anywhere else:
1991
+ * it runs BEFORE the restore, which is the step a tombstone refuses.
1992
+ *
1993
+ * Every path that is deleted is also TOMBSTONED, for the same reason a local
1994
+ * deletion is: between applying a peer's delete and announcing the result,
1995
+ * this node's own advertised state still contains the file, and a third node
1996
+ * pushing in that window would put it back.
1997
+ *
1998
+ * **And nothing used to lift a tombstone set that way.** The watcher clears
1999
+ * one when the path is written again LOCALLY, but a peer's re-creation can
2000
+ * only arrive through the restore the tombstone refuses — so the path was
2001
+ * refused for the rest of the session. Measured once the chain started
2002
+ * stating these deletions at all: a file created, deleted and created again
2003
+ * at the same path never reached the second node, three runs of three,
2004
+ * `restore: wrote 0 … REFUSED 1 tombstoned`.
2005
+ *
2006
+ * Lifted only for a path the sender STATES it changed. A tree that merely
2007
+ * contains the path says nothing — every tree predating the deletion
2008
+ * contains it, which is the window the tombstone exists for.
2009
+ * @param treeRef - The state being applied, which the delta arrived with.
2010
+ */
2011
+ private _applyIncomingRemovals;
2012
+ /**
2013
+ * Appends one entry to this folder's history. Best-effort.
2014
+ *
2015
+ * A chain that cannot be written must never stop a folder syncing, so every
2016
+ * failure is recorded and swallowed — the same discipline as
2017
+ * {@link _persistCurrentRef}. A gap is what `complete: false` is for, and it
2018
+ * is read: `classify` answers `incomplete` across one, which is what stops a
2019
+ * walk it cannot trust from being mistaken for a clean verdict.
2020
+ * @param treeRef - The state the folder ended up at.
2021
+ * @param delta - What that push changed and removed.
2022
+ */
2023
+ private _recordChainEntry;
901
2024
  private _adoptAppliedRef;
902
2025
  /**
903
2026
  * Derives a deterministic content key from an FsTree.
@@ -922,6 +2045,9 @@ export declare class FsAgent {
922
2045
  * settles to a no-op instead of re-broadcasting.
923
2046
  * @param db - Database instance
924
2047
  * @param treeKey - Tree table key
2048
+ * @param announce - Puts the merge revision on the wire, called after its
2049
+ * chain entry exists. REQUIRED: the merge store suppresses the connector's
2050
+ * own broadcast, so without this the merge never leaves the node.
925
2051
  */
926
2052
  private _buildConflictResolverDeps;
927
2053
  /**
@@ -936,8 +2062,8 @@ export declare class FsAgent {
936
2062
  syncFromDb(db: Db, connector: Connector, treeKey: string, restoreOptions?: RestoreOptions): Promise<() => void>;
937
2063
  /**
938
2064
  * Creates a fully configured FsAgent from a Client instance.
939
- * This factory method provides a simplified API where sync methods don't require
940
- * db, connector, and treeKey parameters - they are stored internally.
2065
+ * This factory method provides a simplified API where sync methods don't
2066
+ * require db, connector, and treeKey parameters - they are stored internally.
941
2067
  * @param filePath - Directory path to sync
942
2068
  * @param treeKey - Tree table key (route will be `/${treeKey}`)
943
2069
  * @param client - Client instance with io and bs properties