@rljson/fs-agent 0.1.0 → 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,33 +1,17 @@
1
1
  import { Bs } from '@rljson/bs';
2
2
  import { ClientId, SyncConfig } from '@rljson/rljson';
3
- import { AntiEntropyOptions, AntiEntropyStatus } from './fs-anti-entropy.ts';
4
3
  import { ATOMIC_TMP_PREFIX } from './fs-atomic-write.ts';
5
4
  import { FsBlobAdapter } from './fs-blob-adapter.ts';
6
- import { FsConflictReport } from './fs-conflict-resolver.ts';
7
5
  import { StoreFsTreeOptions } from './fs-db-adapter.ts';
6
+ import { FsSignal } from './fs-signals.ts';
7
+ import { FsHistoryEntry, FsHistoryOptions, FsHistoryPage } from './fs-history.ts';
8
+ import { AntiEntropyStatus, Relation } from './fs-receive.ts';
8
9
  import { FsScanner, FsTree } from './fs-scanner.ts';
9
10
  import { Connector, Db } from '@rljson/db';
10
11
  /**
11
12
  * Options for FsAgent operations
12
13
  */
13
14
  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;
31
15
  /** Ignore patterns for scanning */
32
16
  ignore?: string[];
33
17
  /** Maximum depth for directory traversal */
@@ -42,10 +26,6 @@ export interface FsAgentOptions {
42
26
  * {@link FsScanOptions.scanCachePath}.
43
27
  */
44
28
  scanCachePath?: string;
45
- /** Storage options for database operations */
46
- storageOptions?: StoreFsTreeOptions;
47
- /** Restore options applied when syncing from DB */
48
- restoreOptions?: RestoreOptions;
49
29
  /** Timeout configuration for async operations */
50
30
  timeouts?: TimeoutConfig;
51
31
  /**
@@ -67,47 +47,25 @@ export interface FsAgentOptions {
67
47
  */
68
48
  clientIdentity?: ClientId;
69
49
  /**
70
- * Enable Nextcloud-style conflict resolution. When true, {@link syncFromDb}
71
- * registers a DAG-branch conflict observer that resolves forks into a single
72
- * merge revision (winner keeps the path, loser is renamed). This is a
73
- * **client-only** behaviour — hubs are dumb relays and must leave it off
74
- * (the default). See `README.architecture.md`, "Conflicts".
50
+ * Told about everything that happened to this folder that a person might
51
+ * care about — see {@link FsSignal}. The one output channel: a same-file
52
+ * merge, a joining machine moving files aside, a deletion the guard refused,
53
+ * a path that could not be written. Each signal says which paths it touched,
54
+ * how the outcome was chosen, and whether a PERSON still has to do
55
+ * something. {@link signals} holds the same, for a host that starts later.
75
56
  */
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;
92
- /**
93
- * Repair a divergence from the hub that no message is going to fix — a
94
- * push the hub never received, a forward this node never received, an
95
- * apply that gave up. Driven by the hub's periodic announcement: the state
96
- * beacon (`stateBeaconMs` on the server — the one to use) or the bootstrap
97
- * heartbeat (`syncConfig.bootstrapHeartbeatMs`). Without either it never
98
- * fires. On by default. See `src/fs-anti-entropy.ts`.
99
- */
100
- antiEntropy?: AntiEntropyOptions;
57
+ onSignal?: (signal: FsSignal) => void;
101
58
  /**
102
59
  * 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.
60
+ * before saying anything about its own, in milliseconds. Default
61
+ * {@link DEFAULT_JOIN_WAIT_MS}; `0` makes the folder the origin of its
62
+ * history at once.
105
63
  *
106
64
  * **The chain applies first; the filesystem only then.** A starting agent
107
65
  * authors a lineage root from whatever it happens to hold and announces it
108
66
  * 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
67
+ * every node gets its own lineage root, so every announcement ever made is
68
+ * a fork; and a node restored from a backup pushes
111
69
  * deleted files back to the whole fleet. With a wait set, such a node defers
112
70
  * instead, reconciles against the first head it hears (`planJoin` — write
113
71
  * what the head has, keep what the history never named, set aside what it
@@ -124,8 +82,7 @@ export interface FsAgentOptions {
124
82
  * seconds, which is the class of change this package has reverted four times
125
83
  * for being shipped on reasoning. It is proven at the mesh tier
126
84
  * (`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".
85
+ * run — see `README.architecture.md`, "Joining a Network".
129
86
  */
130
87
  joinWaitMs?: number;
131
88
  /**
@@ -177,40 +134,20 @@ export interface TimeoutConfig {
177
134
  fetchTree?: number;
178
135
  /** Timeout for a filesystem extract / scan. Default: 15 000 ms */
179
136
  extract?: number;
180
- /** Timeout for a filesystem restore. Default: 15 000 ms */
181
- restore?: number;
182
- /** Timeout for the overall syncFromDb callback. Default: 25 000 ms */
183
- syncCallback?: number;
184
- /**
185
- * Debounce delay for sync callbacks (milliseconds). Default: 300 ms.
186
- * Rapid filesystem events (e.g. macOS Finder "Keep Both" copy+rename)
187
- * are coalesced into a single sync operation after this quiet period.
188
- * Also applies to incoming database refs in syncFromDb.
189
- */
190
- debounceMs?: number;
191
- /**
192
- * Number of retries for processRef in syncFromDb. Default: 3.
193
- * When a ref fails to process (e.g. db.get timeout because the IoPeer
194
- * transport hasn't connected yet), the ref is retried this many times
195
- * with increasing delay before being dropped.
196
- */
197
- processRefRetries?: number;
198
137
  /**
199
- * Base delay between processRef retries (milliseconds). Default: 5 000 ms.
200
- * Each retry waits `attempt * processRefRetryDelayMs` (i.e. 5s, 10s, 15s).
138
+ * Timeout for writing one received head into the folder. Default: 15 000 ms.
139
+ * The receive and send sides share one lock, so an apply that hangs on a
140
+ * blob nobody serves would keep this node from authoring its own work. A
141
+ * timed-out apply changes nothing it had not written yet, and the next time
142
+ * the hub says the head it is tried again.
201
143
  */
202
- processRefRetryDelayMs?: number;
144
+ restore?: number;
203
145
  /**
204
- * Number of **recovery re-queues** for a ref whose per-cycle retries were
205
- * all exhausted (e.g. `db.get` kept timing out because the transport was
206
- * disconnected/contended during a hub crash, reconnect or restart). Instead
207
- * of permanently dropping the ref — which loses the file written in that
208
- * window — it is re-queued up to this many times so it is eventually applied
209
- * once the transport recovers. A newer incoming ref supersedes a pending
210
- * recovery; `tearDown()` stops it. Default: 10. Set 0 to restore the old
211
- * drop-on-exhaustion behaviour.
146
+ * Debounce delay for authoring (milliseconds). Default: 300 ms. Rapid
147
+ * filesystem events (e.g. macOS Finder "Keep Both" copy+rename) are
148
+ * coalesced into a single edit after this quiet period.
212
149
  */
213
- recoveryRetries?: number;
150
+ debounceMs?: number;
214
151
  }
215
152
  /**
216
153
  * Longest a disconnect may keep the watcher paused.
@@ -222,19 +159,6 @@ export interface TimeoutConfig {
222
159
  export declare const DISCONNECT_PAUSE_MAX_MS = 30000;
223
160
  /** Filename for sync error log written to the sync folder */
224
161
  export declare const SYNC_ERROR_FILE = ".sync-errors.log";
225
- /**
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.
236
- */
237
- export declare const CONFLICT_LOG_FILE = ".fsagent-conflicts.json";
238
162
  /**
239
163
  * Where a file the history had DELETED is kept when this node joins.
240
164
  *
@@ -251,36 +175,6 @@ export declare const CONFLICT_LOG_FILE = ".fsagent-conflicts.json";
251
175
  * silent.
252
176
  */
253
177
  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
178
  /**
285
179
  * How long a joining node asks before concluding it is the origin.
286
180
  *
@@ -290,61 +184,17 @@ export declare const ANTI_ENTROPY_ASK_MS = 2000;
290
184
  * the folder IS the origin and its contents are the first state.
291
185
  */
292
186
  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
187
  export { ATOMIC_TMP_PREFIX };
303
188
  /**
304
189
  * Filename for the agent's own state, kept beside the synced folder's content
305
190
  * and ignored by the scanner like the other two above.
306
191
  *
307
- * It holds one thing: the ref this folder was last known to be at. That
308
- * survives a restart, which is the whole point — a process that comes back
309
- * with no idea what it descends from cannot declare ancestry, and a push with
310
- * no ancestry is one every peer has to treat as untrustworthy for deletion.
192
+ * `ownHead` — the chain entry this folder stands on, so a restart continues the
193
+ * history rather than starting one. `stampEpochs` — the highest stamp epoch
194
+ * heard, per domain: a hub taking office on this machine passes it as
195
+ * `minEpoch`, so its stamps order after every stamp the fleet has seen.
311
196
  */
312
197
  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~";
329
- /**
330
- * Orchestrates filesystem operations with tree structures and blob storage
331
- */
332
- /**
333
- * A prune smaller than this many files is always allowed through.
334
- *
335
- * Below it, "most of the folder" is not a meaningful statement: emptying a
336
- * three-file folder is an ordinary edit, and a guard that blocked it would
337
- * fire constantly on small trees and be turned off.
338
- */
339
- /**
340
- * How long an agent waits before answering another refusal.
341
- *
342
- * Two nodes can refuse each other — each holding files the other lacks — and an
343
- * unthrottled answer to every refusal is a loop. Long enough that a genuine
344
- * catch-up (a restore of the answered ref) completes inside it, short enough
345
- * that a node joining an idle network is not left waiting.
346
- */
347
- export declare const REFUSAL_ANSWER_COOLDOWN_MS = 5000;
348
198
  /**
349
199
  * How many tree nodes are fetched at once while walking a tree.
350
200
  *
@@ -378,97 +228,29 @@ export declare const RESTORED_BLOB_MEMORY_MAX = 50000;
378
228
  * high concurrency is how a client runs out of heap.
379
229
  */
380
230
  export declare const RESTORE_FETCH_CONCURRENCY = 16;
231
+ export declare const MASS_DELETE_MIN_FILES = 100;
381
232
  /**
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.
399
- *
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.
409
- */
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.
233
+ * How often one head is received again because the folder moved under its
234
+ * apply, before the next announcement has to bring it back.
438
235
  */
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
- }
236
+ export declare const RECEIVE_AGAIN_MAX = 3;
457
237
  /**
458
- * What an agent concluded about an inbound ref.
459
- *
460
- * See `FsAgent._inboundRefVerdict` for why this is one decision rather than
461
- * several conditions.
238
+ * How soon a node announces its head again when a merge still lacks its own
239
+ * stamp — doubling each time, up to {@link STAMP_ASK_MAX_MS}.
462
240
  */
463
- export type InboundRefVerdict = 'apply' | 'own-echo' | 'stale';
464
- /** How each non-applying verdict reads in a log line. */
465
- export declare const VERDICT_REASON: Record<Exclude<InboundRefVerdict, 'apply'>, string>;
466
- export declare const MASS_DELETE_MIN_FILES = 100;
241
+ export declare const STAMP_ASK_MIN_MS = 500;
242
+ /** The longest a node waits between two announcements asking for its stamp. */
243
+ export declare const STAMP_ASK_MAX_MS = 30000;
467
244
  /**
468
245
  * Above this share of the folder, a prune is treated as suspicious rather than
469
246
  * intentional.
470
247
  */
471
248
  export declare const MASS_DELETE_MAX_RATIO = 0.3;
249
+ /**
250
+ * How many passes {@link FsAgent.restoreRevision} makes over a folder that
251
+ * holds a file still being written, before it gives up and changes nothing.
252
+ */
253
+ export declare const RESTORE_SETTLE_PASSES = 10;
472
254
  /**
473
255
  * A restore that could not put the folder into the state the tree describes.
474
256
  *
@@ -594,63 +376,9 @@ export declare class FsAgent {
594
376
  private _adapter;
595
377
  private _rootPath;
596
378
  private _bs;
597
- private _lastSentRef?;
598
- /**
599
- * The ref this agent last pushed as its OWN work.
600
- *
601
- * Not the same as {@link _lastSentRef}, which an apply also sets when it
602
- * leaves the folder equal to — or short of — what it applied. Only a state
603
- * this agent authored may be re-announced by the anti-entropy: re-announcing
604
- * one it is still catching up to would roll its peers back.
605
- */
606
- private _lastPushedRef?;
607
- /** Tuning for the anti-entropy, as passed in. */
608
- private readonly _antiEntropyOptions?;
609
- /** The running anti-entropy, while {@link syncFromDb} is active. */
610
- private _antiEntropy?;
611
- /**
612
- * The incoming ref most recently applied. Retired from the connector's dedup
613
- * sets when the next one supersedes it, so a peer returning the tree to that
614
- * state can still reach this agent.
615
- */
616
- private _lastAppliedRef?;
617
- /** When this agent last answered a refusal, for the cooldown. */
618
- private _lastRefusalAnswerMs;
619
- /** Content fingerprint of the last tree we broadcasted (paths+blobIds) */
620
- private _lastSentContentKey?;
621
- /**
622
- * True while a ref received from a peer is being applied to disk.
623
- *
624
- * The safety rescan cannot tell a local change the watcher missed (which it
625
- * must broadcast) from a remote change not yet applied here (which it must
626
- * not). The agent can: while this is set, the disk is mid-way through
627
- * someone else's revision, so a rescan-driven push would re-assert our stale
628
- * view — and undo a deletion the peer just made.
629
- */
630
- private _remoteApplyInFlight;
631
- /**
632
- * Whether a safety rescan was suppressed while a remote apply was running.
633
- *
634
- * The rescan is what covers a watcher that drops or coalesces events, so a
635
- * suppressed one has to be re-run rather than forgotten — see the deferral in
636
- * `syncToDb`'s change handler.
637
- */
638
- private _rescanDeferred;
639
- /** Re-runs a deferred rescan once the apply that blocked it has finished. */
640
- private _flushDeferredRescan;
641
379
  /** Files written vs left alone by the current {@link restore}. */
642
380
  private _restoreWritten;
643
381
  private _restoreSkipped;
644
- /**
645
- * Absolute paths deleted here since the last announcement.
646
- *
647
- * The mirror of {@link _announcedFiles}. Between a local unlink and the push
648
- * that announces it, this node's advertised state still CONTAINS the file —
649
- * so a peer pushing in that window descends from a state the file is in, and
650
- * an apply re-creates it. The local scan then sees the file present, and the
651
- * deletion is never announced at all: silently undone, everywhere.
652
- */
653
- private readonly _pendingDeletes;
654
382
  /**
655
383
  * This folder's history: one entry per state this node pushed.
656
384
  *
@@ -659,181 +387,8 @@ export declare class FsAgent {
659
387
  * yet; see `src/fs-edit-chain.ts`.
660
388
  */
661
389
  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.
757
- *
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.
763
- */
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
390
  /** See {@link FsAgentOptions.joinWaitMs}. */
775
391
  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;
829
- /**
830
- * Absolute paths of the files this agent has actually TOLD anyone about.
831
- *
832
- * A prune may only remove a file that peers could know exists. Anything
833
- * written since the last announcement is invisible to every sender, so a
834
- * tree that lacks it is not deleting it — it simply predates it.
835
- */
836
- private readonly _announcedFiles;
837
392
  /**
838
393
  * Files this restore DELETED.
839
394
  *
@@ -844,19 +399,6 @@ export declare class FsAgent {
844
399
  * on the line.
845
400
  */
846
401
  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;
860
402
  /** Paths the current {@link restore} could not write because they were held open. */
861
403
  private _restoreLocked;
862
404
  /**
@@ -914,21 +456,16 @@ export declare class FsAgent {
914
456
  */
915
457
  private _restoredBlobs;
916
458
  private _timeouts;
917
- /** Told when a same-file conflict was resolved. See `onConflict`. */
918
- private readonly _onConflict?;
919
- /** Client-only: resolve DAG-branch conflicts into merge revisions. */
920
- private _resolveConflicts;
921
- /** See {@link FsAgentOptions.bucketSync}. */
922
- private _bucketSyncOn;
923
- /** The bucket-sync conversation, when {@link _bucketSyncOn}. */
924
- private _bucketSync?;
925
- /**
926
- * Ancestry head: the content ref of the revision currently representing the
927
- * filesystem state. New local revisions descend from it; received revisions
928
- * advance it. Only tracked when `resolveConflicts` is enabled, so the
929
- * InsertHistory predecessor DAG forms only where conflict resolution is on.
930
- */
931
- private _currentRef?;
459
+ /**
460
+ * Everything this folder has signalled, bounded and countable.
461
+ *
462
+ * Seeded from {@link SIGNAL_LOG_FILE} on the first write rather than in the
463
+ * constructor, because the constructor does no I/O and a host may construct
464
+ * an agent for a folder that does not exist yet.
465
+ */
466
+ private readonly _signals;
467
+ /** Whether {@link SIGNAL_LOG_FILE} has been read back yet this process. */
468
+ private _signalsRestored;
932
469
  constructor(rootPath: string, bs?: Bs, options?: FsAgentOptions);
933
470
  /**
934
471
  * Gets the root path
@@ -951,27 +488,47 @@ export declare class FsAgent {
951
488
  */
952
489
  get timeouts(): Required<TimeoutConfig>;
953
490
  /**
954
- * Whether this node and the hub agree, and what the anti-entropy has done
955
- * about it when they did not. `null` until {@link syncFromDb} runs.
491
+ * Everything that happened to this folder that a person might care about,
492
+ * oldest first — see {@link FsSignal}.
956
493
  *
957
- * A divergence that lasts is the one thing a lost message leaves behind, and
958
- * until now nothing reported it: this is what a diagnostics view should show.
494
+ * Seeded from {@link SIGNAL_LOG_FILE} the first time it is read, so a host
495
+ * that starts after the event still sees it. Bounded; {@link signalTotals}
496
+ * keeps the count of what was dropped.
497
+ * @returns The signals kept.
959
498
  */
499
+ get signals(): readonly FsSignal[];
960
500
  /**
961
- * Deletions the mass-delete guard refused, newest last.
501
+ * The signals a person still has to act on — `action: 'required'`.
962
502
  *
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".
503
+ * The list a UI should surface. Everything else is a record of something the
504
+ * agent already dealt with.
505
+ * @returns The unresolved signals.
506
+ */
507
+ get signalsNeedingAction(): readonly FsSignal[];
508
+ /**
509
+ * How many signals of each kind this folder has EVER produced.
510
+ *
511
+ * Not bounded by the log, so a folder that produced two thousand refusals
512
+ * still says two thousand after the oldest are dropped.
513
+ * @returns Counts keyed by {@link FsSignalKind}.
514
+ */
515
+ get signalTotals(): Readonly<Record<string, number>>;
516
+ /**
517
+ * Subscribes to signals as they happen.
968
518
  *
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.
519
+ * The same channel as the `onSignal` option, for a host that wants to attach
520
+ * later or more than once.
521
+ * @param listener - Called once per signal.
522
+ * @returns Unsubscribes.
523
+ */
524
+ onSignal(listener: (signal: FsSignal) => void): () => void;
525
+ /**
526
+ * Whether this node and the hub agree, and what the anti-entropy has done
527
+ * about it when they did not. `null` until {@link syncFromDb} runs.
528
+ *
529
+ * A divergence that lasts is the one thing a lost message leaves behind, and
530
+ * until now nothing reported it: this is what a diagnostics view should show.
973
531
  */
974
- get refusedDeletions(): readonly RefusedDeletion[];
975
532
  get antiEntropyStatus(): AntiEntropyStatus | null;
976
533
  /**
977
534
  * Records the ref this folder is now at, so a restart can still say what it
@@ -993,65 +550,58 @@ export declare class FsAgent {
993
550
  * A crash is a poor reason to choose an unsafe order.
994
551
  */
995
552
  private _ensureWatching;
996
- private _persistCurrentRef;
997
553
  /**
998
- * Writes the tombstone log, keeping whatever ref is already recorded.
554
+ * Records one signal, tells subscribers, and persists the log.
999
555
  *
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.
556
+ * **Never throws.** A notification that cannot be filed must not take the
557
+ * operation it describes with it. Nothing about a sync depends on anybody
558
+ * being told.
559
+ * @param input - What happened; see {@link FsSignal}.
1003
560
  */
1004
- private _persistTombstones;
561
+ private _signal;
1005
562
  /**
1006
- * Writes `.fsagent-state.json`: the ref this folder is at, and the paths
1007
- * deleted here.
563
+ * Reports what joining a network did to this folder.
1008
564
  *
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.
565
+ * **The case a person is most likely to ask about**, and it had no channel at
566
+ * all: a machine rejoining with files the network has since deleted, or with
567
+ * its own edits of paths that moved on — a restored backup, a laptop back
568
+ * from a fortnight away. Nothing is lost either way, because the files are
569
+ * moved aside rather than removed. But a folder that quietly grows a
570
+ * `.fsagent-recovered/` directory is unexplainable from outside the machine,
571
+ * and a line in that machine's console is not an answer.
1016
572
  *
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.
573
+ * Extracted from the join body so it can be tested without standing up a
574
+ * chain, a db and a peer — the emission is a separate concern from deciding
575
+ * what to emit about.
576
+ * @param recovered - Paths moved aside because the history removed them.
577
+ * @param conflicted - Paths edited here while away and changed elsewhere.
578
+ * @param copies - Where each moved file went, `path → name`; a path the
579
+ * join could not move has no entry.
1019
580
  */
1020
- private _loadPersistedTombstones;
581
+ private _signalJoinOutcome;
1021
582
  /**
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`.
583
+ * Records a standing condition at most once per agent.
584
+ * @param key - What is being reported once.
585
+ * @param input - What happened.
1029
586
  */
1030
- private _loadPersistedEditTimes;
587
+ private _signalOnce;
1031
588
  /**
1032
- * The ref this folder was last recorded at, from a previous run.
589
+ * Reads {@link SIGNAL_LOG_FILE} back, once.
1033
590
  *
1034
- * Absent, unreadable and malformed all mean the same thing — this process
1035
- * cannot vouch for what it descends from — and all answer `undefined`, which
1036
- * the caller treats as "declare no ancestry".
1037
- * @returns The persisted ref, or `undefined`.
591
+ * Lazily rather than in the constructor, which does no I/O: a host may
592
+ * construct an agent for a folder that is created later, and a signal log is
593
+ * never worth failing a construction over.
1038
594
  */
1039
- private _loadPersistedRef;
595
+ private _restoreSignals;
1040
596
  /**
1041
- * Records resolved conflicts and tells the host.
597
+ * Writes the signal log, best effort.
1042
598
  *
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.
599
+ * Through a staging file, because a host reads this file while the agent
600
+ * writes it, and a crash between truncate and write left an empty file —
601
+ * which the next start could not parse, so the whole history was dropped and
602
+ * the next signal overwrote it.
1053
603
  */
1054
- private _recordConflicts;
604
+ private _persistSignals;
1055
605
  /**
1056
606
  * Appends a sync error entry to the error log file in the sync folder.
1057
607
  * Uses synchronous I/O to guarantee the write completes even in catch blocks.
@@ -1059,26 +609,6 @@ export declare class FsAgent {
1059
609
  * @param err - The error value caught
1060
610
  */
1061
611
  _writeSyncError(context: string, err: unknown): void;
1062
- /**
1063
- * Extracts a human-readable message from a thrown value. The non-`Error`
1064
- * branch is defensive (the DB/transport always throw `Error`s).
1065
- * @param err - The caught value.
1066
- * @returns A message string.
1067
- */
1068
- private static _errMessage;
1069
- /**
1070
- * Retries an async operation up to `attempts` times with exponential backoff
1071
- * (each delay doubles from `baseDelayMs`). For transient failures — a file
1072
- * briefly locked by antivirus or a save-and-rename editor, a peer briefly
1073
- * unreachable. Non-final failures are logged once at warn level so retry
1074
- * pressure is visible without log-spam.
1075
- * @param fn - The operation to run
1076
- * @param attempts - Maximum number of attempts
1077
- * @param baseDelayMs - Initial backoff delay (doubles each retry)
1078
- * @param label - Human-readable label for log messages
1079
- * @returns The operation's resolved value
1080
- */
1081
- private static _withRetry;
1082
612
  /**
1083
613
  * Writes a file through a staging file and a rename.
1084
614
  *
@@ -1130,17 +660,6 @@ export declare class FsAgent {
1130
660
  * @param label - Human-readable label included in the error message
1131
661
  */
1132
662
  private static _withTimeout;
1133
- /**
1134
- * Sends a ref through the connector.
1135
- * Uses `sendWithAck()` when the connector has `requireAck` enabled,
1136
- * otherwise falls back to fire-and-forget `send()`.
1137
- * @param connector - The Connector to send through
1138
- * @param ref - The ref to broadcast
1139
- * @param predecessorRefs - Causal predecessor content refs to attach (for
1140
- * conflict ancestry); set explicitly here because the FsAgent broadcasts
1141
- * via an explicit send, which pre-empts the Connector's db-observer path.
1142
- */
1143
- private _sendRef;
1144
663
  /**
1145
664
  * Abandons a join this agent is still waiting on.
1146
665
  *
@@ -1396,301 +915,12 @@ export declare class FsAgent {
1396
915
  * same file rather than pruned.
1397
916
  */
1398
917
  private _pruneExtraneous;
1399
- /**
1400
- * Watches filesystem for changes and syncs to database
1401
- * Uses Connector for socket-based broadcast
1402
- * @param db - Database instance
1403
- * @param connector - Connector instance for socket-based sync
1404
- * @param treeKey - Tree table key
1405
- * @param options - Storage options (e.g., skipNotification)
1406
- * @returns Function to stop watching
1407
- */
1408
- syncToDb(db: Db, connector: Connector, treeKey: string, options?: StoreFsTreeOptions): Promise<() => void>;
1409
- /**
1410
- * Resolves the `previous` (InsertHistory predecessor timeIds) for a new
1411
- * revision from the parent's shared content refs. timeIds are per-db, so we
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.
1415
- * @param db - Database instance
1416
- * @param treeKey - Tree table key
1417
- * @param parentRefs - Parent content refs (local head, or received predecessors)
1418
- */
1419
- private _ancestryPrevious;
1420
- /**
1421
- * Classifies an incoming revision relative to our current head using the
1422
- * local InsertHistory DAG (keyed on shared content refs):
1423
- * - `behind` → incoming descends from our head → fast-forward (restore).
1424
- * - `ahead` → our head descends from incoming (e.g. a reconnect bootstrap
1425
- * re-sending an older ancestor) → ignore; we are newer.
1426
- * - `diverged` → siblings produced by concurrent edits → resolve the fork.
1427
- * @param db - Database instance
1428
- * @param treeKey - Tree table key
1429
- * @param currentRef - Our current head's content ref
1430
- * @param incomingRef - The incoming revision's content ref
1431
- * @param incomingPredecessorRefs - The incoming revision's predecessor refs
1432
- */
1433
- private _ancestryRelation;
1434
- /**
1435
- * Resolves a divergent incoming revision inline (called from `processRef`
1436
- * with the watcher paused, so resolution cannot race the sync loop). Records
1437
- * the incoming revision as a fork tip without clobbering local content, then
1438
- * merges our head and the incoming tip into a single merge revision D that is
1439
- * materialised to disk and broadcast.
1440
- * @param db - Database instance
1441
- * @param treeKey - Tree table key
1442
- * @param incomingRef - The incoming revision's content ref
1443
- * @param incomingTree - The fetched incoming tree
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`.
1447
- */
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;
1509
918
  /**
1510
919
  * Builds a map of relativePath → blobId for all files in a tree.
1511
920
  * Used to compare trees by content rather than by hash (which includes mtime).
1512
921
  * @param tree - Tree structure to extract file content map from
1513
922
  */
1514
923
  private _getFileContentMap;
1515
- /**
1516
- * Derives a deterministic string key from a content map so that two trees
1517
- * with identical file paths + blobIds produce the same key regardless of
1518
- * mtime differences.
1519
- * @param map - Content map (relativePath → blobId)
1520
- */
1521
- private _contentKeyFromMap;
1522
- /**
1523
- * Records `treeRef` as the ref describing this folder's current state, and
1524
- * retires the one it supersedes from the connector's dedup sets.
1525
- *
1526
- * A tree ref is a pure content hash, so a folder that returns to an earlier
1527
- * state re-derives that state's exact ref. The connector drops an incoming
1528
- * ref it has already received, which assumes a state is reached once and
1529
- * never returned to — false for content-addressed state, and false in the
1530
- * most ordinary way possible: create a file, then delete it again.
1531
- *
1532
- * Retiring the SUPERSEDED ref is what keeps the return trip deliverable.
1533
- * The ref just adopted stays deduped, so a peer re-advertising the state
1534
- * this folder is actually in is still suppressed as the echo it is. That
1535
- * only works if every adopted state passes through here — a state adopted
1536
- * silently is never retired and blocks its own return for good.
1537
- * @param connector - Connector whose dedup sets to retire from.
1538
- * @param treeRef - The ref that now describes this folder.
1539
- */
1540
- /**
1541
- * Re-announce this folder's state to a sender that holds far less of it.
1542
- *
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.
1547
- *
1548
- * Rate-limited because two nodes can each hold what the other lacks, and an
1549
- * unthrottled answer is a loop.
1550
- * @param connector - Connector to broadcast on.
1551
- */
1552
- private _readvertiseAfterRefusal;
1553
- /**
1554
- * Whether a tree describes a folder holding nothing whatsoever.
1555
- *
1556
- * Deliberately conservative: an empty DIRECTORY counts as content. A user who
1557
- * creates a folder and puts a directory in it has made a statement about what
1558
- * should be there, and the silence this gates is only correct for an agent
1559
- * that has established nothing at all. Being wrong in that direction would
1560
- * mean a folder that never advertises until something else happens to change.
1561
- * @param tree - The tree to inspect.
1562
- * @returns `true` when the tree carries no entries at all.
1563
- */
1564
- private _treeIsEmpty;
1565
- /**
1566
- * Whether an inbound ref is news to this agent, and if not, why.
1567
- *
1568
- * "Is this ref news to me" is the question this subsystem keeps getting
1569
- * wrong. It has been answered in five separate places — the connector's sent
1570
- * and received dedup sets, `_lastSentContentKey`, `_lastSentRef`,
1571
- * `_lastAppliedRef` — and each has been wrong at least once:
1572
- *
1573
- * - an agent applied its OWN last advertisement over its own newer edit,
1574
- * destroying it and then declining to re-send (fixed 0.0.30);
1575
- * - a delete propagated only from the client that had created the file,
1576
- * because the send path never retired the state it left (0.0.31);
1577
- * - a refusal consumed the ref it refused, so the same emptiness arriving
1578
- * twice was silent the second time (0.0.33);
1579
- * - a restarted agent inherited its predecessor's conclusions (0.0.34);
1580
- * - a quiet join announced anyway, because the connector broadcasts on
1581
- * local insert and the gate was on the send (0.0.38).
1582
- *
1583
- * Collecting the pre-fetch gates here does not fix a sixth. It makes the
1584
- * question answerable in one place, in one order, with the reasoning
1585
- * attached — which is what the previous five each lacked.
1586
- *
1587
- * Order matters and is deliberate. The own-echo check comes first because it
1588
- * is the only one that holds regardless of what the sender believes: the two
1589
- * defences that ought to catch an echo both miss it. The origin filter
1590
- * compares the payload's origin to this connector's, and a bootstrap carries
1591
- * the SERVER as origin rather than the client the ref came from; the
1592
- * staleness check then measures the server's sequence, which did advance, so
1593
- * the echo reads as news.
1594
- *
1595
- * KNOWN LIMIT, stated because the next person will meet it: this compares
1596
- * against the LAST ref this agent sent, so an echo of an OLDER
1597
- * self-originated ref still gets through. Widening it to a set would also
1598
- * suppress a peer's legitimate revert to a state this agent once held. The
1599
- * real fix is for the bootstrap to carry the originating client, so the
1600
- * origin filter works and this check stops being needed at all.
1601
- * @param treeRef - The inbound ref.
1602
- * @param isNewestFromSender - Whether the connector judged it the newest
1603
- * thing its sender has advertised. Unknown answers `true`.
1604
- * @returns `apply`, or the reason it is not news.
1605
- */
1606
- private _inboundRefVerdict;
1607
- /**
1608
- * Records the files an announcement carried.
1609
- *
1610
- * Called wherever this agent commits to a state as "what peers know" —
1611
- * its own pushes, and the states it adopts from theirs.
1612
- * @param tree - The tree that just went out, or was adopted as ours.
1613
- */
1614
- /**
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
924
  /**
1695
925
  * What joining actually does to the folder.
1696
926
  * @param db - The route's database.
@@ -1709,357 +939,364 @@ export declare class FsAgent {
1709
939
  * nothing else will ever tell anybody it stopped working.
1710
940
  * @param path - The file to move, relative to the root, `/`-separated.
1711
941
  * @param name - Where to move it, same form.
942
+ * @param copies - Where each file that WAS moved went, `path → name`: what
943
+ * the join signal tells a host. A file that could not be moved is left out,
944
+ * because its own version is gone once the restore overwrites it.
1712
945
  */
1713
946
  private _setAside;
947
+ /** The chain entry this node stands on, persisted across restarts. */
948
+ private _ownHead?;
949
+ /** The own head's tree, `path → blob`: what the folder is diffed against. */
950
+ private _ownContent;
951
+ /** Paths the watcher saw deleted since the own head was authored. */
952
+ private readonly _watched;
953
+ /** Every chain entry's stamp, as this node learned it. */
954
+ private _stamps?;
955
+ /** The route this agent syncs, once a sync started. */
956
+ private _route?;
957
+ /** The newest head heard and not yet received. */
958
+ private _heard?;
959
+ /** Stamps heard, recorded in arrival order before anything decides. */
960
+ private _stamping;
961
+ /** The lock the send and receive sides share. */
962
+ private _lock;
963
+ /** The receive loop, while it runs. */
964
+ private _receiving?;
965
+ /** A joining folder's wait for the network's head, while it lasts. */
966
+ private _joinWait?;
967
+ /** Authors again shortly, once the watcher has caught up. */
968
+ private _authorSoon?;
969
+ /** The merge that waited for a stamp last, so a second wait is told. */
970
+ private _deferral?;
971
+ /** The last time this node announced its head to learn its stamp. */
972
+ private _stampAsk?;
973
+ /** What the last state the hub announced made this node do. */
974
+ private _hubStatus;
975
+ /** How many receive sides were started; the newest one owns the status. */
976
+ private _receivers;
977
+ /**
978
+ * What an apply that stopped partway — a locked file, an unreachable blob —
979
+ * had already written, path → blob. Not this node's work: authoring does not
980
+ * claim it, and the next apply recognises it. Cleared when the own head
981
+ * moves.
982
+ */
983
+ private _partiallyApplied;
984
+ /** The chain entry this node stands on, if any. */
985
+ get ownHead(): string | undefined;
986
+ /**
987
+ * The entry this folder stands on, with its stamp: what a host shows as the
988
+ * folder's current revision.
989
+ * @returns The entry, or `undefined` while no sync runs or the folder has no
990
+ * head yet.
991
+ */
992
+ headInfo(): Promise<FsHistoryEntry | undefined>;
993
+ /**
994
+ * One page of the folder's history, newest first: every edit, merge and
995
+ * root below the own head, whichever node made it — see `fs-history.ts` for
996
+ * the order.
997
+ *
998
+ * A host whose agent runs in another process reads the same pages from the
999
+ * store with `readFsHistory`.
1000
+ * @param options - Where to start (default: the own head), or the cursor of
1001
+ * the previous page, and how many entries.
1002
+ * @returns The page; empty while no sync runs or the folder has no head.
1003
+ */
1004
+ history(options?: FsHistoryOptions): Promise<FsHistoryPage>;
1005
+ /**
1006
+ * How this folder's head stands to another — the hub's, a peer's: the same
1007
+ * (`same`), behind it, ahead of it, forked from it, or not decidable from
1008
+ * what this node can read (`incomplete`).
1009
+ *
1010
+ * Two different heads can hold the same files — after two nodes merged the
1011
+ * same fork, say. Whether they do is a question for the tree refs, not this.
1012
+ * @param head - The other head.
1013
+ * @returns The relation, or `undefined` while no sync runs or the folder has
1014
+ * no head.
1015
+ */
1016
+ relationTo(head: string): Promise<Relation | undefined>;
1017
+ /**
1018
+ * Puts the folder back to a revision of its history, EXACTLY, and makes that
1019
+ * the newest edit, so every node follows.
1020
+ *
1021
+ * Exactly: what the revision holds is written, and what it lacks is
1022
+ * deleted. An older `restore` or `loadFromDb` of the same tree only adds and
1023
+ * overwrites, so files made after the revision stay and the folder ends up
1024
+ * in a state no revision ever had.
1025
+ *
1026
+ * Nothing is lost by it. Whatever the folder holds beyond its head is
1027
+ * recorded first, and the revision being left stays in the history, from
1028
+ * where it can be restored in turn.
1029
+ *
1030
+ * Rejects while no sync runs or the folder has no head; with a
1031
+ * `MassDeleteRefusedError`, changing nothing, when the revision would delete
1032
+ * a large part of the folder — the guard every prune has; and with a
1033
+ * `RestoreIncompleteError` when a file could not be written, the rest of the
1034
+ * revision in place.
1035
+ * @param head - The revision: a chain entry from {@link history}.
1036
+ * @returns `restored`; `unknown` when this node cannot read the entry or its
1037
+ * tree; `busy` while a file in the folder is still being written — nothing
1038
+ * was changed in either case, and a busy folder can be asked again.
1039
+ */
1040
+ restoreRevision(head: string): Promise<'restored' | 'unknown' | 'busy'>;
1041
+ /**
1042
+ * Records what the folder holds before something writes over it, waiting
1043
+ * out a file the scan will not read yet.
1044
+ *
1045
+ * A pass leaves out a file it has never read and one written to while it
1046
+ * ran, and reads them once they settle — right for a sync, which only ever
1047
+ * adds a later version. A restore overwrites and prunes, and a file no entry
1048
+ * holds yet is somebody's work with no copy anywhere: measured, a file
1049
+ * saved just before a restore was deleted by it.
1050
+ * @returns Whether everything was recorded; `false` while a file is still
1051
+ * being written after {@link RESTORE_SETTLE_PASSES} passes.
1052
+ */
1053
+ private _recordFolder;
1054
+ /** When this agent last finished something that may write to the folder. */
1055
+ private _wroteAt;
1056
+ /**
1057
+ * Runs `work`, which may write to the folder, and notes when it ended —
1058
+ * inside the lock, so nothing queued behind it can read an older note.
1059
+ * @param work - A receive or a join.
1060
+ * @returns What `work` returned.
1061
+ */
1062
+ private _writing;
1063
+ /**
1064
+ * The folder for authoring a local change: a pass that began after this
1065
+ * agent last wrote to it.
1066
+ *
1067
+ * A pass that overlapped an apply may have read the apply half-done, and
1068
+ * authoring from it announced the version before the apply — a revert
1069
+ * (F9). After a write, then, the folder is scanned afresh. Without one, the
1070
+ * watcher's last pass already is such a pass, and scanning again only looks
1071
+ * at a file mid-copy one more time: a copy that stalls hashed a truncated
1072
+ * version for every extra look, two to five times as many as before.
1073
+ * @returns The tree.
1074
+ */
1075
+ private _passAfterOwnWrites;
1076
+ /**
1077
+ * Runs `work` alone: the send and receive sides never interleave.
1078
+ * @param work - What to run.
1079
+ * @returns What `work` returned.
1080
+ */
1081
+ private _exclusive;
1714
1082
  /**
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.
1785
- */
1786
- private _agreeOnEntryFor;
1787
- /**
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.
1795
- */
1796
- private _rememberAnnouncedHead;
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.
1083
+ * Opens the chain and the stamp store for a route, once.
1816
1084
  * @param db - The route's database.
1817
1085
  * @param treeKey - The trees table key.
1818
1086
  */
1819
1087
  private _ensureChain;
1820
1088
  /**
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.
1089
+ * The head `.fsagent-state.json` names, if it names one.
1090
+ * @returns The head, or `undefined`.
1836
1091
  */
1837
- private _announceAs;
1092
+ private _persistedHead;
1838
1093
  /**
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.
1094
+ * Makes `head` this node's head, and remembers it across a restart.
1095
+ * @param head - The chain entry.
1096
+ * @param content - The tree it names, `path → blob`.
1097
+ */
1098
+ private _setOwn;
1099
+ /** Writes {@link AGENT_STATE_FILE}: the own head and the stamp epochs. */
1100
+ private _writeState;
1101
+ /** The stamp epochs the state file holds, as written. */
1102
+ private _writtenEpochs;
1103
+ /**
1104
+ * The tree a chain entry names.
1105
+ * @param head - The chain entry.
1106
+ * @returns Its tree ref and tree, or `undefined` when either cannot be read.
1846
1107
  */
1847
- private _resolveAnnouncement;
1108
+ private _treeOf;
1109
+ /** Announces the own head, with its stamp when this node knows it. */
1110
+ private _announceOwn;
1848
1111
  /**
1849
- * What the chain says about an announced head, for the decision.
1112
+ * Announces the own head so the hub stamps it — at once the first time,
1113
+ * then less and less often while the stamp does not come.
1850
1114
  *
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.
1115
+ * Bounded because nothing else bounds it: on a hub that does not stamp,
1116
+ * three nodes deferring the same conflict answered each other's
1117
+ * announcements with announcements, 245 000 merge attempts in one test.
1118
+ * @param head - The own head.
1860
1119
  */
1861
- private _reachabilityOf;
1120
+ private _askForStamp;
1862
1121
  /**
1863
- * Builds the bucket-sync host and the conversation that drives it.
1122
+ * Authors an edit for the folder as `tree` describes it, if it moved past
1123
+ * the own head and the edit is honest — see `planAuthoring`.
1124
+ * @param tree - The folder, as just scanned.
1125
+ */
1126
+ private _author;
1127
+ /**
1128
+ * Stores a tree and its blobs for the route.
1129
+ * @param tree - The tree.
1130
+ * @returns Its ref.
1131
+ */
1132
+ private _storeTree;
1133
+ /**
1134
+ * Watches the folder and keeps the chain in step with it.
1864
1135
  *
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.
1136
+ * On start, a folder with a head continues it; a folder without one joins
1137
+ * the network (`planJoin`) or, when nobody answers, becomes its origin.
1138
+ * @param db - The route's database.
1869
1139
  * @param connector - The transport.
1870
- * @param db - The route's database, for fetching what the plan asks for.
1871
1140
  * @param treeKey - The trees table key.
1872
- * @returns The conversation.
1141
+ * @returns Stops watching.
1873
1142
  */
1874
- private _makeBucketSync;
1143
+ syncToDb(db: Db, connector: Connector, treeKey: string): Promise<() => void>;
1875
1144
  /**
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.
1145
+ * Waits up to `joinWaitMs` for the network's head before this folder says
1146
+ * anything about itself.
1884
1147
  */
1885
- private _manifest;
1148
+ private _startJoinWait;
1149
+ /** Ends a join wait without acting on it. */
1150
+ private _endJoinWait;
1886
1151
  /**
1887
- * Performs what a bucket-sync round concluded.
1152
+ * Joins the network's head, or — when none came — makes this folder the
1153
+ * origin of its history.
1888
1154
  *
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.
1155
+ * **The chain applies first; the filesystem only then.** What the folder
1156
+ * holds beyond the head is judged by the history: a path the history never
1157
+ * named is new work and is authored on top of the head; a path it removed is
1158
+ * a stale copy and is set aside, not announced; a path both hold with
1159
+ * different bytes keeps the head's version and the local one as a copy.
1160
+ * @param head - The network's head, or `undefined`.
1897
1161
  */
1898
- private _applyReconcilePlan;
1162
+ private _join;
1899
1163
  /**
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.
1164
+ * Hears a head — from an announcement, a bootstrap or a state beacon.
1165
+ * @param head - The head.
1166
+ * @param stamp - The stamp it arrived with, if any.
1167
+ * @param fromHub - Whether the hub said it: what `antiEntropyStatus` reports.
1927
1168
  */
1928
- private _tombstoneDeleted;
1169
+ private _hear;
1170
+ /** The head the hub said last. */
1171
+ private _hubHead?;
1929
1172
  /**
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.
1173
+ * Records the stamp a head arrived with, in arrival order.
1174
+ * @param head - The head.
1175
+ * @param stamp - Its stamp, if any.
1941
1176
  */
1942
- private _refuseDeletion;
1177
+ private _recordStamp;
1178
+ /** Receives the newest head heard, one at a time, until none is left. */
1179
+ private _drain;
1943
1180
  /**
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.
1181
+ * Keeps `antiEntropyStatus` true to what the last head from the hub made
1182
+ * this node do.
1183
+ * @param head - The head that was received.
1184
+ * @param outcome - What was done.
1958
1185
  */
1959
- private _bucketRoundAgreed;
1186
+ private _noteOutcome;
1960
1187
  /**
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.
1188
+ * How often in a row an apply found the folder moved under this node's own
1189
+ * head. Counted per own head, not per incoming one: two heads arriving in
1190
+ * turn must not reset each other's count.
1967
1191
  */
1968
- private _collectRemovalsForTreeRef;
1192
+ private _movedAgain?;
1969
1193
  /**
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.
1194
+ * Receives a head once more after the folder moved under an apply — the
1195
+ * local work is authored first then, which turns the apply into a merge.
1196
+ * Bounded, so a cache that never catches up cannot loop; the next head the
1197
+ * hub says tries again.
1198
+ * @param head - The head.
1985
1199
  */
1986
- private _collectIncomingRemovals;
1200
+ private _receiveAgain;
1987
1201
  /**
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`.
1202
+ * What `receive` needs from this agent.
1203
+ * @returns The agent's side of a receive.
1204
+ */
1205
+ private _receiveDeps;
1206
+ /**
1207
+ * Makes a head this node's own without touching the folder: its content
1208
+ * is what the folder already holds.
1209
+ * @param head - The head.
1210
+ */
1211
+ private _adopt;
1212
+ /**
1213
+ * Applies a head that descends from the own one: writes what it changed,
1214
+ * deletes what it removed — every absence in it is a deletion its author
1215
+ * chose, because its author held this node's state.
2005
1216
  *
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.
1217
+ * Only what changed between the two heads is touched, and only while the
1218
+ * folder still holds the own head's version of it. A file the user changed
1219
+ * since is never overwritten: the apply stops, that work is authored, and
1220
+ * the head is received again — as a fork, which merges.
1221
+ * @param head - The head.
1222
+ * A deletion beyond the receiver's floors is the exception: the files stay,
1223
+ * the head is adopted all the same, and the files are authored again on top
1224
+ * of it — which is what refills a node that lost them.
1225
+ * @returns `applied`, or `refused` when the head cannot be read or local
1226
+ * work stopped it.
2010
1227
  */
2011
- private _applyIncomingRemovals;
1228
+ private _applyBehind;
2012
1229
  /**
2013
- * Appends one entry to this folder's history. Best-effort.
1230
+ * Moves the folder from the own content to `target`: writes what differs,
1231
+ * deletes what `target` lacks.
2014
1232
  *
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.
1233
+ * The receiver guard: a deletion that would lose more than the floors allow
1234
+ * — content `target` holds nowhere else — is not made. Everything else is,
1235
+ * and the files kept become this node's work, so the folder never holds a
1236
+ * state the chain does not describe.
1237
+ * @param target - Where the folder should end up, `path → blob`.
1238
+ * @param write - Writes the given paths' `target` versions.
1239
+ * @returns `applied`; `kept` when the guard kept files `target` lacks;
1240
+ * `moved` when the folder had moved past the own head.
2022
1241
  */
2023
- private _recordChainEntry;
2024
- private _adoptAppliedRef;
1242
+ private _applyContent;
2025
1243
  /**
2026
- * Derives a deterministic content key from an FsTree.
2027
- * @param tree - Tree structure to derive content key from
1244
+ * Whether every given path still holds what the own head says — or what a
1245
+ * cut-short apply already wrote there: no local change the watcher has not
1246
+ * reported yet.
1247
+ * @param paths - Relative paths.
1248
+ * @returns `true` when none of them changed since the own head.
2028
1249
  */
2029
- private _contentKeyFromTree;
1250
+ private _unchangedSinceOwn;
2030
1251
  /**
2031
- * Compares two trees by file content (relativePath + blobId).
2032
- * Ignores mtime differences — trees are equivalent if they have the same
2033
- * files with the same content. This prevents bounce-back restores from
2034
- * destroying locally-created files during bidirectional sync.
2035
- * @param a - First tree to compare
2036
- * @param b - Second tree to compare
1252
+ * The blob a file holds, as far as this agent knows without reading it: what
1253
+ * it last wrote there, or what the scanner last read — whichever a `stat`
1254
+ * confirms. Both, because either goes stale on its own: a restore's record
1255
+ * once anything else rewrites the file, the scanner's until its next pass.
1256
+ * @param path - Relative path.
1257
+ * @returns The blob; `null` when no file is there; `undefined` when the file
1258
+ * changed since this agent last knew it.
2037
1259
  */
2038
- private _treesHaveEquivalentContent;
1260
+ private _blobOnDisk;
2039
1261
  /**
2040
- * Builds the dependency surface a {@link FsConflictResolver} needs, wiring it
2041
- * to this agent's db, blob store, scanner, and working directory.
2042
- *
2043
- * The merge store records the merged ref/content key as the last-sent state,
2044
- * so the watcher-driven re-scan that follows the on-disk materialisation
2045
- * settles to a no-op instead of re-broadcasting.
2046
- * @param db - Database instance
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.
1262
+ * Writes the given paths of a tree into the folder, with everything a
1263
+ * restore does for a write: streams, locks, impossible names, a full disk.
1264
+ * @param tree - The tree.
1265
+ * @param paths - The relative paths to write.
2051
1266
  */
2052
- private _buildConflictResolverDeps;
1267
+ private _restorePaths;
2053
1268
  /**
2054
- * Watches database for tree changes and syncs to filesystem
2055
- * Uses Connector for socket-based notifications
2056
- * @param db - Database instance
2057
- * @param connector - Connector instance for socket-based sync
2058
- * @param treeKey - Tree table key
2059
- * @param restoreOptions - Restore options (e.g., cleanTarget)
2060
- * @returns Function to stop watching
1269
+ * Merges a forked head into the own one against their common base — the
1270
+ * conflict table in `fs-merge.ts` — and authors the merge.
1271
+ * @param theirs - The forked head.
1272
+ * @param base - Their common ancestor, if any.
1273
+ * @returns `merged`; `deferred` when a stamp the verdict needs is not known
1274
+ * yet; `refused` when the merge could not be applied.
1275
+ */
1276
+ private _merge;
1277
+ /**
1278
+ * Hears the network: announcements, the stamps of this node's own, and the
1279
+ * hub's state beacon.
1280
+ * @param db - The route's database.
1281
+ * @param connector - The transport.
1282
+ * @param treeKey - The trees table key.
1283
+ * @returns Stops listening.
1284
+ */
1285
+ syncFromDb(db: Db, connector: Connector, treeKey: string): Promise<() => void>;
1286
+ /**
1287
+ * Says, once, that a deletion was refused — in the log and as one
1288
+ * `deletion/refused` signal.
1289
+ *
1290
+ * Three call sites had three copies of this, which is how they came to say
1291
+ * three different things about the same decision. A client reading one of
1292
+ * them saw a third of the picture.
1293
+ * @param route - Which rule refused it.
1294
+ * @param wouldRemove - How many paths it would have deleted.
1295
+ * @param held - How many this folder holds.
1296
+ * @param paths - The paths, of which the first few are kept.
1297
+ * @param detail - Extra wording for the log line, where a route has some.
2061
1298
  */
2062
- syncFromDb(db: Db, connector: Connector, treeKey: string, restoreOptions?: RestoreOptions): Promise<() => void>;
1299
+ private _refuseDeletion;
2063
1300
  /**
2064
1301
  * Creates a fully configured FsAgent from a Client instance.
2065
1302
  * This factory method provides a simplified API where sync methods don't