@rljson/fs-agent 0.0.85 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,8 +1,10 @@
1
1
  import { Bs } from '@rljson/bs';
2
2
  import { ClientId, SyncConfig } from '@rljson/rljson';
3
- import { AntiEntropyOptions, AntiEntropyStatus } from './fs-anti-entropy.ts';
3
+ import { ATOMIC_TMP_PREFIX } from './fs-atomic-write.ts';
4
4
  import { FsBlobAdapter } from './fs-blob-adapter.ts';
5
5
  import { StoreFsTreeOptions } from './fs-db-adapter.ts';
6
+ import { FsSignal } from './fs-signals.ts';
7
+ import { AntiEntropyStatus } from './fs-receive.ts';
6
8
  import { FsScanner, FsTree } from './fs-scanner.ts';
7
9
  import { Connector, Db } from '@rljson/db';
8
10
  /**
@@ -16,22 +18,13 @@ export interface FsAgentOptions {
16
18
  /** Follow symlinks (default: false) */
17
19
  followSymlinks?: boolean;
18
20
  /**
19
- * Persist a path→(mtime, size, blobId) scan cache at this file path so a RESTART
20
- * does not re-read + re-hash the whole folder (a cold scan of an 80 GB catalog
21
- * is ~48 min). Forwarded to the {@link FsScanner}. Requires a PERSISTENT blob
22
- * store (e.g. `@rljson/bs-fs`). See {@link FsScanOptions.scanCachePath}.
21
+ * Persist a path→(mtime, size, blobId) scan cache at this file path so a
22
+ * RESTART does not re-read + re-hash the whole folder (a cold scan of an 80
23
+ * GB catalog is ~48 min). Forwarded to the {@link FsScanner}. Requires a
24
+ * PERSISTENT blob store (e.g. `@rljson/bs-fs`). See
25
+ * {@link FsScanOptions.scanCachePath}.
23
26
  */
24
27
  scanCachePath?: string;
25
- /** Database instance for automatic syncing */
26
- db?: Db;
27
- /** Tree key for database storage */
28
- treeKey?: string;
29
- /** Storage options for database operations */
30
- storageOptions?: StoreFsTreeOptions;
31
- /** Enable bidirectional sync (both fs→db and db→fs) */
32
- bidirectional?: boolean;
33
- /** Restore options applied when syncing from DB */
34
- restoreOptions?: RestoreOptions;
35
28
  /** Timeout configuration for async operations */
36
29
  timeouts?: TimeoutConfig;
37
30
  /**
@@ -53,26 +46,79 @@ export interface FsAgentOptions {
53
46
  */
54
47
  clientIdentity?: ClientId;
55
48
  /**
56
- * Enable Nextcloud-style conflict resolution. When true, {@link syncFromDb}
57
- * registers a DAG-branch conflict observer that resolves forks into a single
58
- * merge revision (winner keeps the path, loser is renamed). This is a
59
- * **client-only** behaviour — hubs are dumb relays and must leave it off
60
- * (the default). See `doc/conflict-resolution-design.md`.
49
+ * Told about everything that happened to this folder that a person might
50
+ * care about — see {@link FsSignal}. The one output channel: a same-file
51
+ * merge, a joining machine moving files aside, a deletion the guard refused,
52
+ * a path that could not be written. Each signal says which paths it touched,
53
+ * how the outcome was chosen, and whether a PERSON still has to do
54
+ * something. {@link signals} holds the same, for a host that starts later.
61
55
  */
62
- resolveConflicts?: boolean;
56
+ onSignal?: (signal: FsSignal) => void;
63
57
  /**
64
- * Repair a divergence from the hub that no message is going to fix — a
65
- * push the hub never received, a forward this node never received, an
66
- * apply that gave up. Driven by the hub's periodic announcement: the state
67
- * beacon (`stateBeaconMs` on the server — the one to use) or the bootstrap
68
- * heartbeat (`syncConfig.bootstrapHeartbeatMs`). Without either it never
69
- * fires. On by default. See `src/fs-anti-entropy.ts`.
58
+ * How long a folder with files and NO history waits for the network's state
59
+ * before saying anything about its own, in milliseconds. Default
60
+ * {@link DEFAULT_JOIN_WAIT_MS}; `0` makes the folder the origin of its
61
+ * history at once.
62
+ *
63
+ * **The chain applies first; the filesystem only then.** A starting agent
64
+ * authors a lineage root from whatever it happens to hold and announces it
65
+ * as the network's newest claim, and that is one defect wearing two faces:
66
+ * every node gets its own lineage root, so every announcement ever made is
67
+ * a fork; and a node restored from a backup pushes
68
+ * deleted files back to the whole fleet. With a wait set, such a node defers
69
+ * instead, reconciles against the first head it hears (`planJoin` — write
70
+ * what the head has, keep what the history never named, set aside what it
71
+ * REMOVED, treat a path live on both sides as a conflict) and speaks
72
+ * afterwards.
73
+ *
74
+ * **Bounded, and that is not a detail.** If no head arrives this folder IS
75
+ * the origin and its contents are the first state — a brand-new network has
76
+ * to be startable, so the wait is a deferral and never a refusal. It also
77
+ * cannot deadlock a fleet whose nodes all start with files: they all time
78
+ * out, they all announce, and their roots agree by content.
79
+ *
80
+ * **Off by default, deliberately.** It changes what a node says in its first
81
+ * seconds, which is the class of change this package has reverted four times
82
+ * for being shipped on reasoning. It is proven at the mesh tier
83
+ * (`fs-mesh-matrix.spec.ts`, `J4+J5`) and belongs on after an integration
84
+ * run — see `README.architecture.md`, "Joining a Network".
70
85
  */
71
- antiEntropy?: AntiEntropyOptions;
86
+ joinWaitMs?: number;
87
+ /**
88
+ * A short name for this agent, shown in every line it logs.
89
+ *
90
+ * **Because a log without it cannot be read when more than one agent runs.**
91
+ * Four nodes in one process produced three identical
92
+ * `applied 3 peer deletions: …` lines with nothing saying who, and a
93
+ * convergence investigation stopped there: the three nodes that applied a
94
+ * removal and the one that stayed silent were indistinguishable. The One
95
+ * Client has the same problem for a different reason — several routes, one
96
+ * console.
97
+ *
98
+ * Omitted, every line reads `[FsAgent]` exactly as before.
99
+ */
100
+ logName?: string;
72
101
  }
73
102
  /** Restore options */
74
103
  export interface RestoreOptions {
75
- /** Remove files/dirs on target that are not present in the tree */
104
+ /**
105
+ * Remove files and directories on the target that the tree does not contain.
106
+ *
107
+ * **Destructive, and the peer-apply path never sets it.** Deleting what a
108
+ * tree happens to lack is an INFERENCE, and it is the one this package spent
109
+ * its whole history getting wrong: a tree lacks a path because the sender
110
+ * removed it, or because the sender never had it, and a content hash cannot
111
+ * say which. `syncFromDb` therefore applies additively and takes deletions
112
+ * from the chain, where they are STATED — see `_applyIncomingRemovals`.
113
+ *
114
+ * Still honoured by a direct {@link FsAgent.restore} call, which is a caller
115
+ * saying "make this folder be exactly this tree". That is a different
116
+ * question, and its answer is one the caller already knows.
117
+ *
118
+ * `syncFromDb` still ACCEPTS it, so a configuration carrying
119
+ * `cleanTarget: true` keeps working unchanged; it no longer authorises a
120
+ * prune there.
121
+ */
76
122
  cleanTarget?: boolean;
77
123
  }
78
124
  /**
@@ -87,40 +133,20 @@ export interface TimeoutConfig {
87
133
  fetchTree?: number;
88
134
  /** Timeout for a filesystem extract / scan. Default: 15 000 ms */
89
135
  extract?: number;
90
- /** Timeout for a filesystem restore. Default: 15 000 ms */
91
- restore?: number;
92
- /** Timeout for the overall syncFromDb callback. Default: 25 000 ms */
93
- syncCallback?: number;
94
- /**
95
- * Debounce delay for sync callbacks (milliseconds). Default: 300 ms.
96
- * Rapid filesystem events (e.g. macOS Finder "Keep Both" copy+rename)
97
- * are coalesced into a single sync operation after this quiet period.
98
- * Also applies to incoming database refs in syncFromDb.
99
- */
100
- debounceMs?: number;
101
136
  /**
102
- * Number of retries for processRef in syncFromDb. Default: 3.
103
- * When a ref fails to process (e.g. db.get timeout because the IoPeer
104
- * transport hasn't connected yet), the ref is retried this many times
105
- * with increasing delay before being dropped.
137
+ * Timeout for writing one received head into the folder. Default: 15 000 ms.
138
+ * The receive and send sides share one lock, so an apply that hangs on a
139
+ * blob nobody serves would keep this node from authoring its own work. A
140
+ * timed-out apply changes nothing it had not written yet, and the next time
141
+ * the hub says the head it is tried again.
106
142
  */
107
- processRefRetries?: number;
108
- /**
109
- * Base delay between processRef retries (milliseconds). Default: 5 000 ms.
110
- * Each retry waits `attempt * processRefRetryDelayMs` (i.e. 5s, 10s, 15s).
111
- */
112
- processRefRetryDelayMs?: number;
143
+ restore?: number;
113
144
  /**
114
- * Number of **recovery re-queues** for a ref whose per-cycle retries were
115
- * all exhausted (e.g. `db.get` kept timing out because the transport was
116
- * disconnected/contended during a hub crash, reconnect or restart). Instead
117
- * of permanently dropping the ref — which loses the file written in that
118
- * window — it is re-queued up to this many times so it is eventually applied
119
- * once the transport recovers. A newer incoming ref supersedes a pending
120
- * recovery; `tearDown()` stops it. Default: 10. Set 0 to restore the old
121
- * drop-on-exhaustion behaviour.
145
+ * Debounce delay for authoring (milliseconds). Default: 300 ms. Rapid
146
+ * filesystem events (e.g. macOS Finder "Keep Both" copy+rename) are
147
+ * coalesced into a single edit after this quiet period.
122
148
  */
123
- recoveryRetries?: number;
149
+ debounceMs?: number;
124
150
  }
125
151
  /**
126
152
  * Longest a disconnect may keep the watcher paused.
@@ -133,40 +159,41 @@ export declare const DISCONNECT_PAUSE_MAX_MS = 30000;
133
159
  /** Filename for sync error log written to the sync folder */
134
160
  export declare const SYNC_ERROR_FILE = ".sync-errors.log";
135
161
  /**
136
- * Filename prefix for the staging files used by atomic writes. The scanner
137
- * ignores anything starting with this so the transient temp + rename never
138
- * pollutes the tree or churns the watcher.
139
- */
140
- export declare const ATOMIC_TMP_PREFIX = ".fsagent-tmp-";
141
- /**
142
- * Filename for the agent's own state, kept beside the synced folder's content
143
- * and ignored by the scanner like the other two above.
162
+ * Where a file the history had DELETED is kept when this node joins.
144
163
  *
145
- * It holds one thing: the ref this folder was last known to be at. That
146
- * survives a restart, which is the whole point — a process that comes back
147
- * with no idea what it descends from cannot declare ancestry, and a push with
148
- * no ancestry is one every peer has to treat as untrustworthy for deletion.
149
- */
150
- export declare const AGENT_STATE_FILE = ".fsagent-state.json";
151
- /**
152
- * Orchestrates filesystem operations with tree structures and blob storage
164
+ * **Outside the synced tree, and that is the whole point.** A recovered file
165
+ * must not be announced — it is content the fleet deliberately removed, and a
166
+ * folder restored from last month's backup would otherwise push every one of
167
+ * those deletions back to every node. But leaving it in the folder cannot
168
+ * achieve that: a tree ref carries CONTENT, so the file travels whatever the
169
+ * entry claims about it. Measured exactly that way — the set-aside copy
170
+ * arrived on a peer while the chain entry said nothing about it.
171
+ *
172
+ * So it goes in an ignored directory, which is local by construction, and the
173
+ * user can see it and move it back if they want it. Visible, keepable, and
174
+ * silent.
153
175
  */
176
+ export declare const RECOVERED_DIR = ".fsagent-recovered";
154
177
  /**
155
- * A prune smaller than this many files is always allowed through.
178
+ * How long a joining node asks before concluding it is the origin.
156
179
  *
157
- * Below it, "most of the folder" is not a meaningful statement: emptying a
158
- * three-file folder is an ordinary edit, and a guard that blocked it would
159
- * fire constantly on small trees and be turned off.
180
+ * The default for every route. Long enough for a hub's bootstrap to arrive on
181
+ * a real connection, short enough that the first client of a brand-new network
182
+ * is not kept waiting — and it is a deferral, never a refusal: when it expires
183
+ * the folder IS the origin and its contents are the first state.
160
184
  */
185
+ export declare const DEFAULT_JOIN_WAIT_MS = 1500;
186
+ export { ATOMIC_TMP_PREFIX };
161
187
  /**
162
- * How long an agent waits before answering another refusal.
188
+ * Filename for the agent's own state, kept beside the synced folder's content
189
+ * and ignored by the scanner like the other two above.
163
190
  *
164
- * Two nodes can refuse each other — each holding files the other lacks — and an
165
- * unthrottled answer to every refusal is a loop. Long enough that a genuine
166
- * catch-up (a restore of the answered ref) completes inside it, short enough
167
- * that a node joining an idle network is not left waiting.
191
+ * `ownHead` — the chain entry this folder stands on, so a restart continues the
192
+ * history rather than starting one. `stampEpochs` — the highest stamp epoch
193
+ * heard, per domain: a hub taking office on this machine passes it as
194
+ * `minEpoch`, so its stamps order after every stamp the fleet has seen.
168
195
  */
169
- export declare const REFUSAL_ANSWER_COOLDOWN_MS = 5000;
196
+ export declare const AGENT_STATE_FILE = ".fsagent-state.json";
170
197
  /**
171
198
  * How many tree nodes are fetched at once while walking a tree.
172
199
  *
@@ -192,7 +219,7 @@ export declare const RESTORED_BLOB_MEMORY_MAX = 50000;
192
219
  * A restore's cost is dominated by `getBlob`, and a blob this node does not
193
220
  * already hold is a socket round trip. Walking the tree strictly sequentially
194
221
  * makes the whole restore `files × RTT` — invisible on localhost, and about
195
- * sixteen files a second on the lab, where a 1 200-file folder then takes
222
+ * sixteen files a second on a real fleet, where a 1 200-file folder then takes
196
223
  * minutes and reads as a stalled node.
197
224
  *
198
225
  * Sixteen rather than sixty-four: blobs carry file CONTENT, so the ceiling is
@@ -200,26 +227,19 @@ export declare const RESTORED_BLOB_MEMORY_MAX = 50000;
200
227
  * high concurrency is how a client runs out of heap.
201
228
  */
202
229
  export declare const RESTORE_FETCH_CONCURRENCY = 16;
230
+ export declare const MASS_DELETE_MIN_FILES = 100;
203
231
  /**
204
- * How many of its own past states a node remembers.
205
- *
206
- * Used to recognise a sender that is BEHIND this node — one that declares a
207
- * state this node has held and left. A burst on a large folder produces a few
208
- * dozen states, so this is generous; forgetting the oldest costs only the
209
- * ability to spot a very stale sender, which the mass-delete guard still
210
- * catches.
232
+ * How often one head is received again because the folder moved under its
233
+ * apply, before the next announcement has to bring it back.
211
234
  */
212
- export declare const STATE_HISTORY_MAX = 1000;
235
+ export declare const RECEIVE_AGAIN_MAX = 3;
213
236
  /**
214
- * What an agent concluded about an inbound ref.
215
- *
216
- * See `FsAgent._inboundRefVerdict` for why this is one decision rather than
217
- * several conditions.
237
+ * How soon a node announces its head again when a merge still lacks its own
238
+ * stamp — doubling each time, up to {@link STAMP_ASK_MAX_MS}.
218
239
  */
219
- export type InboundRefVerdict = 'apply' | 'own-echo' | 'stale';
220
- /** How each non-applying verdict reads in a log line. */
221
- export declare const VERDICT_REASON: Record<Exclude<InboundRefVerdict, 'apply'>, string>;
222
- export declare const MASS_DELETE_MIN_FILES = 100;
240
+ export declare const STAMP_ASK_MIN_MS = 500;
241
+ /** The longest a node waits between two announcements asking for its stamp. */
242
+ export declare const STAMP_ASK_MAX_MS = 30000;
223
243
  /**
224
244
  * Above this share of the folder, a prune is treated as suspicious rather than
225
245
  * intentional.
@@ -260,8 +280,8 @@ export declare class PartialRestoreError extends RestoreIncompleteError {
260
280
  * the fetch.
261
281
  *
262
282
  * **Size is no longer one of those reasons.** The case that produced this class
263
- * was a file larger than the transport's `maxHttpBufferSize`, where no number of
264
- * retries made 63 MB fit through a 50 MB socket. Since `@rljson/bs` 0.0.27 a
283
+ * was a file larger than the transport's `maxHttpBufferSize`, where no number
284
+ * of retries made 63 MB fit through a 50 MB socket. Since `@rljson/bs` 0.0.27 a
265
285
  * blob crosses as a series of ranged pulls, so no single message carries the
266
286
  * whole file and the cap no longer bounds file size. The class stays, because a
267
287
  * blob can still be genuinely unreachable; the reason it was first needed is
@@ -277,10 +297,10 @@ export declare class PartialRestoreError extends RestoreIncompleteError {
277
297
  * silently ignoring every delete.
278
298
  *
279
299
  * Measured on four nodes: one 63 MB file (120% of the cap) left three of them
280
- * holding a file the fourth had deleted, permanently, and `projekte-shape`'s
281
- * deletion had still not propagated after 300 seconds. The customer's largest
282
- * file was 45.9 MB against the same 50 MB cap — close enough that the next
283
- * revision of one document would have reproduced it in production.
300
+ * holding a file the fourth had deleted, permanently, and the large-folder
301
+ * shape's deletion had still not propagated after 300 seconds. The largest
302
+ * observed file was 45.9 MB against the same 50 MB cap — close enough that the
303
+ * next revision of one document would have reproduced it in production.
284
304
  */
285
305
  export declare class BlobUnavailableError extends RestoreIncompleteError {
286
306
  readonly unavailablePaths: string[];
@@ -298,95 +318,71 @@ export declare class BlobUnavailableError extends RestoreIncompleteError {
298
318
  * judgement has to be made here, and it is deliberately biased: refusing a
299
319
  * real mass delete costs one manual step, applying a false one costs the data.
300
320
  */
321
+ /**
322
+ * A restore could not write a path this filesystem will not accept.
323
+ *
324
+ * Its own class rather than a {@link BlobUnavailableError}, because the
325
+ * message is what somebody reads in a support request and "could not fetch
326
+ * blob" for a 300-character filename sends them to the network when the
327
+ * problem is the name. The bytes arrived; the path cannot exist here.
328
+ *
329
+ * Not retryable, unlike {@link PartialRestoreError}: a name does not become
330
+ * legal by waiting. The rest of the tree is applied around it.
331
+ */
332
+ export declare class UnwritablePathError extends RestoreIncompleteError {
333
+ readonly impossiblePaths: string[];
334
+ constructor(impossiblePaths: string[]);
335
+ }
336
+ /**
337
+ * The volume ran out of space mid-restore.
338
+ *
339
+ * Its own class because it is the one restore failure that is not about the
340
+ * tree at all, and because retrying it is pointless until a person acts. It
341
+ * aborts rather than skipping the file: a folder being filled on a full disk
342
+ * would otherwise lose a different file on every attempt.
343
+ */
344
+ export declare class DiskFullError extends RestoreIncompleteError {
345
+ readonly path: string;
346
+ constructor(path: string);
347
+ }
301
348
  export declare class MassDeleteRefusedError extends RestoreIncompleteError {
302
349
  readonly wouldPrune: number;
303
350
  readonly totalFiles: number;
304
351
  readonly incomingFiles: number;
305
352
  constructor(wouldPrune: number, totalFiles: number, incomingFiles: number);
306
353
  }
354
+ /** What one push changed, against the state announced before it. */
355
+ export interface FsTreeDelta {
356
+ /** Relative paths added or modified, `/`-separated. */
357
+ changed: string[];
358
+ /** Relative paths removed, `/`-separated. */
359
+ removed: string[];
360
+ }
307
361
  export declare class FsAgent {
362
+ /**
363
+ * The prefix on every line this agent logs — see {@link FsAgentOptions.logName}.
364
+ *
365
+ * `[FsAgent]` when unnamed, so an unnamed agent's output is byte-identical
366
+ * to what it was before this existed.
367
+ */
368
+ private readonly _tag;
308
369
  private _scanner;
309
370
  private _adapter;
310
371
  private _rootPath;
311
372
  private _bs;
312
- private _db?;
313
- private _treeKey?;
314
- private _stopSync?;
315
- private _stopSyncFromDb?;
316
- private _lastSentRef?;
317
- /**
318
- * The ref this agent last pushed as its OWN work.
319
- *
320
- * Not the same as {@link _lastSentRef}, which an apply also sets when it
321
- * leaves the folder equal to — or short of — what it applied. Only a state
322
- * this agent authored may be re-announced by the anti-entropy: re-announcing
323
- * one it is still catching up to would roll its peers back.
324
- */
325
- private _lastPushedRef?;
326
- /** Tuning for the anti-entropy, as passed in. */
327
- private readonly _antiEntropyOptions?;
328
- /** The running anti-entropy, while {@link syncFromDb} is active. */
329
- private _antiEntropy?;
330
- /**
331
- * The incoming ref most recently applied. Retired from the connector's dedup
332
- * sets when the next one supersedes it, so a peer returning the tree to that
333
- * state can still reach this agent.
334
- */
335
- private _lastAppliedRef?;
336
- /** When this agent last answered a refusal, for the cooldown. */
337
- private _lastRefusalAnswerMs;
338
- /** Content fingerprint of the last tree we broadcasted (paths+blobIds) */
339
- private _lastSentContentKey?;
340
- /**
341
- * True while a ref received from a peer is being applied to disk.
342
- *
343
- * The safety rescan cannot tell a local change the watcher missed (which it
344
- * must broadcast) from a remote change not yet applied here (which it must
345
- * not). The agent can: while this is set, the disk is mid-way through
346
- * someone else's revision, so a rescan-driven push would re-assert our stale
347
- * view — and undo a deletion the peer just made.
348
- */
349
- private _remoteApplyInFlight;
350
- /**
351
- * Whether a safety rescan was suppressed while a remote apply was running.
352
- *
353
- * The rescan is what covers a watcher that drops or coalesces events, so a
354
- * suppressed one has to be re-run rather than forgotten — see the deferral in
355
- * `syncToDb`'s change handler.
356
- */
357
- private _rescanDeferred;
358
- /** Re-runs a deferred rescan once the apply that blocked it has finished. */
359
- private _flushDeferredRescan;
360
373
  /** Files written vs left alone by the current {@link restore}. */
361
374
  private _restoreWritten;
362
375
  private _restoreSkipped;
363
376
  /**
364
- * Absolute paths deleted here since the last announcement.
377
+ * This folder's history: one entry per state this node pushed.
365
378
  *
366
- * The mirror of {@link _announcedFiles}. Between a local unlink and the push
367
- * that announces it, this node's advertised state still CONTAINS the file —
368
- * so a peer pushing in that window descends from a state the file is in, and
369
- * an apply re-creates it. The local scan then sees the file present, and the
370
- * deletion is never announced at all: silently undone, everywhere.
379
+ * Created on the first `syncToDb`, and BEST-EFFORT throughout — a chain that
380
+ * cannot be written must never stop a folder syncing. Nothing consumes it
381
+ * yet; see `src/fs-edit-chain.ts`.
371
382
  */
372
- private readonly _pendingDeletes;
373
- /**
374
- * The states this node has held, oldest first.
375
- *
376
- * A push declaring one of these — but not the current one — comes from a
377
- * sender that is behind this node. Applying such a tree is what puts a
378
- * deleted file back, so it is ignored outright rather than applied
379
- * additively.
380
- */
381
- private readonly _stateHistory;
382
- /**
383
- * Absolute paths of the files this agent has actually TOLD anyone about.
384
- *
385
- * A prune may only remove a file that peers could know exists. Anything
386
- * written since the last announcement is invisible to every sender, so a
387
- * tree that lacks it is not deleting it — it simply predates it.
388
- */
389
- private readonly _announcedFiles;
383
+ private _chain?;
384
+ /** See {@link FsAgentOptions.joinWaitMs}. */
385
+ private readonly _joinWaitMs;
390
386
  /**
391
387
  * Files this restore DELETED.
392
388
  *
@@ -405,21 +401,65 @@ export declare class FsAgent {
405
401
  * cannot abandon the rest of the tree and, above all, cannot stop the prune.
406
402
  */
407
403
  private _restoreUnavailable;
404
+ /** Paths this filesystem rejected outright. See {@link UnwritablePathError}. */
405
+ private _restoreImpossible;
406
+ /**
407
+ * Paths whose KIND changed — a file where a directory was, or the reverse.
408
+ *
409
+ * Counted and reported because such a change removes whatever was there,
410
+ * and a restore that silently deletes a subtree is one nobody can audit
411
+ * afterwards.
412
+ */
413
+ private _restoreRetyped;
414
+ /**
415
+ * How long each stage of the last push and the last apply took, in ms.
416
+ *
417
+ * measured on a real fleet: *"im Schnitt 3 Sekunden, im schlechtesten Fall
418
+ * 84. Alle Zeitbudgets der Testsuite hängen an dieser Zahl."* And the reason
419
+ * nobody could say more than that: *"bisher wird nur die Gesamtzeit
420
+ * gemessen. Die einzelnen Schritte mitmessen — Scan, Prüfsumme, Ablage,
421
+ * Meldung, Abholen, Schreiben —, sonst rät man."* (`the weakness register`
422
+ * F5/C7.)
423
+ *
424
+ * A total tells you a sync was slow. It does not tell you whether the folder
425
+ * was being hashed, a blob was crossing the network, or a disk was writing —
426
+ * and those have different people to talk to. Kept as a plain record so a
427
+ * host can log or display it without this agent deciding how.
428
+ */
429
+ private readonly _stageMs;
430
+ /**
431
+ * Times one stage into {@link _stageMs}.
432
+ *
433
+ * Overwrites rather than accumulates: the question is "what did the last
434
+ * cycle cost", and a running total answers a different one and never resets.
435
+ * @param stage - The stage name.
436
+ * @param work - What to time.
437
+ * @returns Whatever `work` returned.
438
+ */
439
+ private _timed;
440
+ /**
441
+ * What each stage of the last push and apply cost, in milliseconds.
442
+ *
443
+ * A snapshot, safe to keep: `push.*` is the send side, `apply.*` the receive
444
+ * side, and a stage absent simply has not run yet in this process.
445
+ */
446
+ get stageTimings(): Readonly<Record<string, number>>;
408
447
  /**
409
448
  * What this agent last wrote to each absolute path, so a repeat restore can
410
449
  * recognise its own work without re-reading the file.
411
450
  */
412
451
  private _restoredBlobs;
413
452
  private _timeouts;
414
- /** Client-only: resolve DAG-branch conflicts into merge revisions. */
415
- private _resolveConflicts;
416
453
  /**
417
- * Ancestry head: the content ref of the revision currently representing the
418
- * filesystem state. New local revisions descend from it; received revisions
419
- * advance it. Only tracked when `resolveConflicts` is enabled, so the
420
- * InsertHistory predecessor DAG forms only where conflict resolution is on.
454
+ * Everything this folder has signalled, bounded and countable.
455
+ *
456
+ * Seeded from {@link SIGNAL_LOG_FILE} on the first write rather than in the
457
+ * constructor, because the constructor does no I/O and a host may construct
458
+ * an agent for a folder that does not exist yet.
421
459
  */
422
- private _currentRef?;
460
+ private readonly _signals;
461
+ /** Whether {@link SIGNAL_LOG_FILE} has been read back yet this process. */
462
+ private _signalsRestored;
423
463
  constructor(rootPath: string, bs?: Bs, options?: FsAgentOptions);
424
464
  /**
425
465
  * Gets the root path
@@ -448,6 +488,41 @@ export declare class FsAgent {
448
488
  * A divergence that lasts is the one thing a lost message leaves behind, and
449
489
  * until now nothing reported it: this is what a diagnostics view should show.
450
490
  */
491
+ /**
492
+ * Everything that happened to this folder that a person might care about,
493
+ * oldest first — see {@link FsSignal}.
494
+ *
495
+ * Seeded from {@link SIGNAL_LOG_FILE} the first time it is read, so a host
496
+ * that starts after the event still sees it. Bounded; {@link signalTotals}
497
+ * keeps the count of what was dropped.
498
+ * @returns The signals kept.
499
+ */
500
+ get signals(): readonly FsSignal[];
501
+ /**
502
+ * The signals a person still has to act on — `action: 'required'`.
503
+ *
504
+ * The list a UI should surface. Everything else is a record of something the
505
+ * agent already dealt with.
506
+ * @returns The unresolved signals.
507
+ */
508
+ get signalsNeedingAction(): readonly FsSignal[];
509
+ /**
510
+ * How many signals of each kind this folder has EVER produced.
511
+ *
512
+ * Not bounded by the log, so a folder that produced two thousand refusals
513
+ * still says two thousand after the oldest are dropped.
514
+ * @returns Counts keyed by {@link FsSignalKind}.
515
+ */
516
+ get signalTotals(): Readonly<Record<string, number>>;
517
+ /**
518
+ * Subscribes to signals as they happen.
519
+ *
520
+ * The same channel as the `onSignal` option, for a host that wants to attach
521
+ * later or more than once.
522
+ * @param listener - Called once per signal.
523
+ * @returns Unsubscribes.
524
+ */
525
+ onSignal(listener: (signal: FsSignal) => void): () => void;
451
526
  get antiEntropyStatus(): AntiEntropyStatus | null;
452
527
  /**
453
528
  * Records the ref this folder is now at, so a restart can still say what it
@@ -469,16 +544,49 @@ export declare class FsAgent {
469
544
  * A crash is a poor reason to choose an unsafe order.
470
545
  */
471
546
  private _ensureWatching;
472
- private _persistCurrentRef;
473
547
  /**
474
- * The ref this folder was last recorded at, from a previous run.
548
+ * Records one signal, tells subscribers, and persists the log.
475
549
  *
476
- * Absent, unreadable and malformed all mean the same thing — this process
477
- * cannot vouch for what it descends from — and all answer `undefined`, which
478
- * the caller treats as "declare no ancestry".
479
- * @returns The persisted ref, or `undefined`.
550
+ * **Never throws.** A notification that cannot be filed must not take the
551
+ * operation it describes with it. Nothing about a sync depends on anybody
552
+ * being told.
553
+ * @param input - What happened; see {@link FsSignal}.
480
554
  */
481
- private _loadPersistedRef;
555
+ private _signal;
556
+ /**
557
+ * Reports what joining a network did to this folder.
558
+ *
559
+ * **The case a person is most likely to ask about**, and it had no channel at
560
+ * all: a machine rejoining with files the network has since deleted, or with
561
+ * its own edits of paths that moved on — a restored backup, a laptop back
562
+ * from a fortnight away. Nothing is lost either way, because the files are
563
+ * moved aside rather than removed. But a folder that quietly grows a
564
+ * `.fsagent-recovered/` directory is unexplainable from outside the machine,
565
+ * and a line in that machine's console is not an answer.
566
+ *
567
+ * Extracted from the join body so it can be tested without standing up a
568
+ * chain, a db and a peer — the emission is a separate concern from deciding
569
+ * what to emit about.
570
+ * @param recovered - Paths moved aside because the history removed them.
571
+ * @param conflicted - Paths edited here while away and changed elsewhere.
572
+ */
573
+ private _signalJoinOutcome;
574
+ /**
575
+ * Records a standing condition at most once per agent.
576
+ * @param key - What is being reported once.
577
+ * @param input - What happened.
578
+ */
579
+ private _signalOnce;
580
+ /**
581
+ * Reads {@link SIGNAL_LOG_FILE} back, once.
582
+ *
583
+ * Lazily rather than in the constructor, which does no I/O: a host may
584
+ * construct an agent for a folder that is created later, and a signal log is
585
+ * never worth failing a construction over.
586
+ */
587
+ private _restoreSignals;
588
+ /** Writes the signal log, best effort. */
589
+ private _persistSignals;
482
590
  /**
483
591
  * Appends a sync error entry to the error log file in the sync folder.
484
592
  * Uses synchronous I/O to guarantee the write completes even in catch blocks.
@@ -487,33 +595,12 @@ export declare class FsAgent {
487
595
  */
488
596
  _writeSyncError(context: string, err: unknown): void;
489
597
  /**
490
- * Extracts a human-readable message from a thrown value. The non-`Error`
491
- * branch is defensive (the DB/transport always throw `Error`s).
492
- * @param err - The caught value.
493
- * @returns A message string.
494
- */
495
- private static _errMessage;
496
- /**
497
- * Retries an async operation up to `attempts` times with exponential backoff
498
- * (each delay doubles from `baseDelayMs`). For transient failures — a file
499
- * briefly locked by antivirus or a save-and-rename editor, a peer briefly
500
- * unreachable. Non-final failures are logged once at warn level so retry
501
- * pressure is visible without log-spam.
502
- * @param fn - The operation to run
503
- * @param attempts - Maximum number of attempts
504
- * @param baseDelayMs - Initial backoff delay (doubles each retry)
505
- * @param label - Human-readable label for log messages
506
- * @returns The operation's resolved value
507
- */
508
- private static _withRetry;
509
- /**
510
- * Atomically writes a file: stages the content in a sibling `.<rand>.tmp`,
511
- * then renames over the target. The rename is atomic, so a crash mid-write
512
- * leaves only the temp behind — never a half-written target file. (We do not
513
- * `fsync` the temp: it adds significant per-file latency under bursty
514
- * restores, and durability-on-power-loss is secondary here since the content
515
- * is replicated and re-synced.) The random suffix keeps concurrent restores
516
- * of the same path from trampling each other.
598
+ * Writes a file through a staging file and a rename.
599
+ *
600
+ * Kept as a thin named wrapper because the restore path reads as a pair with
601
+ * {@link FsAgent._atomicWriteStream}. The rule, and the byte-level
602
+ * corruption that made it a rule on every platform rather than on Windows
603
+ * only, are in `fs-atomic-write.ts`.
517
604
  * @param filePath - Destination path
518
605
  * @param content - Bytes to write
519
606
  */
@@ -523,10 +610,11 @@ export declare class FsAgent {
523
610
  *
524
611
  * The two have different answers. A blob that cannot be fetched costs one
525
612
  * file and the tree applies without it; a file that cannot be written is
526
- * usually a CARAT document a user still has open, and that one must not abort
527
- * the rest of the restore either. Conflating them would report an offline peer
528
- * as a locked file, and the field reports are read by people who act on that
529
- * distinction.
613
+ * usually a document the host application still has open for a user, and that
614
+ * one must not abort
615
+ * the rest of the restore either. Conflating them would report an offline
616
+ * peer as a locked file, and the field reports are read by people who act on
617
+ * that distinction.
530
618
  * @param error - The error thrown while writing the file.
531
619
  * @returns Whether it came from the blob source.
532
620
  */
@@ -534,12 +622,12 @@ export declare class FsAgent {
534
622
  /**
535
623
  * Writes a file from a stream, holding one chunk at a time.
536
624
  *
537
- * The twin of {@link FsAgent._atomicWriteFile}, with the same platform rule
538
- * and the same reason for it, but never materialising the whole file. A 500 MB
539
- * file used to cost 500 MB of Buffer on the receiving agent, another copy in
540
- * the socket parser, and — on the serving hub — the same again. That is the
541
- * shape that killed the cloud EventHub: memory that is work in flight rather
542
- * than garbage, so no collection can reclaim any of it.
625
+ * The twin of {@link FsAgent._atomicWriteFile} — temp and rename on every
626
+ * platform, for the same reasons — but never materialising the whole file. A
627
+ * 500 MB file used to cost 500 MB of Buffer on the receiving agent, another
628
+ * copy in the socket parser, and — on the serving hub — the same again. That
629
+ * is the shape that exhausted a cloud relay: memory that is work in flight
630
+ * rather than garbage, so no collection can reclaim any of it.
543
631
  *
544
632
  * Read failures are tagged, because from here on the bytes arrive during the
545
633
  * write rather than before it, and {@link FsAgent._isBlobReadError} is what
@@ -558,31 +646,24 @@ export declare class FsAgent {
558
646
  */
559
647
  private static _withTimeout;
560
648
  /**
561
- * Sends a ref through the connector.
562
- * Uses `sendWithAck()` when the connector has `requireAck` enabled,
563
- * otherwise falls back to fire-and-forget `send()`.
564
- * @param connector - The Connector to send through
565
- * @param ref - The ref to broadcast
566
- * @param predecessorRefs - Causal predecessor content refs to attach (for
567
- * conflict ancestry); set explicitly here because the FsAgent broadcasts
568
- * via an explicit send, which pre-empts the Connector's db-observer path.
569
- */
570
- private _sendRef;
571
- /**
572
- * Starts automatic syncing to database
573
- * Note: Auto-sync requires Connector which is not available in constructor.
574
- * Consider using syncToDb() directly instead of constructor options.
575
- */
576
- private _startAutoSync;
577
- /**
578
- * Starts automatic syncing from database
579
- * @param bidirectional - Whether bidirectional sync is enabled
580
- * Note: Auto-sync requires Connector which is not available in constructor.
581
- * Consider using syncFromDb() directly instead of constructor options.
582
- */
583
- private _startAutoSyncFromDb;
584
- /**
585
- * Stops automatic syncing and cleans up resources
649
+ * Abandons a join this agent is still waiting on.
650
+ *
651
+ * **This method used to do nothing at all**, and the host application calls
652
+ * it in
653
+ * six places on shutdown. It read two fields that were never assigned —
654
+ * leftovers of the constructor auto-sync pattern, which was removed — each
655
+ * behind a `v8 ignore` that hid the fact. The real stopping is done by the
656
+ * functions `syncToDb` and `syncFromDb` return, which the client already
657
+ * calls first.
658
+ *
659
+ * What it does now is the one thing those cannot: cancel a pending join. A
660
+ * folder that deferred its first announcement keeps asking the network for a
661
+ * head every {@link JOIN_ASK_INTERVAL_MS} until the wait expires, and a
662
+ * `stop()` does not end it — so a node shut down mid-join went on asking a
663
+ * connector that was being torn down, and every refusal reached the sync
664
+ * error log. The timers are `unref`'d, so this was never a reason the
665
+ * process stayed alive; it was noise at exactly the moment a shutdown is
666
+ * being diagnosed.
586
667
  */
587
668
  dispose(): void;
588
669
  /**
@@ -625,6 +706,89 @@ export declare class FsAgent {
625
706
  * @param err - The caught value.
626
707
  * @returns `true` for a lock-shaped error.
627
708
  */
709
+ /**
710
+ * Whether a write failed because the PATH is impossible here, rather than
711
+ * because the file is busy.
712
+ *
713
+ * The rules differ per platform and this agent must not encode them: Windows
714
+ * refuses a component over 255, a total path over 260, the reserved device
715
+ * names (`CON`, `PRN`, `AUX`, `NUL`, `COM1`…), a trailing space or dot;
716
+ * POSIX refuses a component over 255 and an embedded NUL. What they share is
717
+ * the errno, so the errno is what this reads.
718
+ *
719
+ * Deliberately NOT retried, unlike a lock: a name does not become legal by
720
+ * waiting. The file is reported as unavailable and the tree is applied
721
+ * around it.
722
+ * @param err - The caught value.
723
+ * @returns Whether the path itself is the problem.
724
+ */
725
+ /**
726
+ * Whether a tree's path stays inside the folder being restored.
727
+ *
728
+ * A tree is DATA FROM ANOTHER MACHINE. Nothing has checked where its paths
729
+ * point, and `join(target, '../escaped.txt')` resolves outside the target —
730
+ * so a peer, or one corrupted node, could write anywhere this process can.
731
+ * Measured before this existed: a tree carrying `../escaped.txt` put a file
732
+ * next to the sync folder, and the restore reported success.
733
+ *
734
+ * It needs no malice to matter. A relative path assembled wrongly, a
735
+ * `relativePath` left absolute by a future scanner, a tree edited by hand to
736
+ * reproduce a bug — all of them become an arbitrary file write on every node
737
+ * that applies the tree.
738
+ *
739
+ * Checked by RESOLVING rather than by looking for `..`, because `a/../../b`,
740
+ * a symlinked parent and an absolute path are all the same question and only
741
+ * one of them contains the obvious substring.
742
+ * @param target - The folder being restored into.
743
+ * @param relativePath - The path the tree claims.
744
+ * @returns Whether it is safe to write.
745
+ */
746
+ /**
747
+ * Clears whatever is at a path so a node of a DIFFERENT KIND can be written
748
+ * there.
749
+ *
750
+ * A path does not only change its contents; it changes what it IS. A user
751
+ * replaces a stray file with the folder it should have been, an export
752
+ * writes a single document where an unpacked directory used to sit. Both
753
+ * mature comparable projects test exactly these transitions —
754
+ * Syncthing as `filetype_test.go`, Unison as "file replacement" and
755
+ * "directory replacement" — and this agent did neither.
756
+ *
757
+ * Measured before this existed, all three aborting the WHOLE restore with a
758
+ * raw errno, so a single type change stopped the folder syncing:
759
+ *
760
+ * file → directory EEXIST: file already exists, mkdir
761
+ * empty directory → file EISDIR: illegal operation on a directory
762
+ * directory with files → file the same
763
+ *
764
+ * Nothing is destroyed that the tree does not already say is gone, and the
765
+ * mass-delete guard has already counted it: the subtree's files are in
766
+ * `preRestore` and absent from `expectedFiles`, which is exactly the
767
+ * population it judges. So a type change that would empty a folder is still
768
+ * refused before the walk reaches here.
769
+ *
770
+ * `lstat`, not `stat`: a symlink is a third kind of thing and must not be
771
+ * followed to decide what to remove.
772
+ * @param path - Where the node is to be written.
773
+ * @param want - What the tree says should be there.
774
+ * @returns Whether something had to be removed.
775
+ */
776
+ /**
777
+ * Whether a path the prune is about to delete is actually the expected file
778
+ * under another spelling of its name.
779
+ *
780
+ * On a case-insensitive filesystem `Angebot.docx` and `angebot.docx` are one
781
+ * file, so the two paths share an inode. On a case-sensitive one they are
782
+ * two files with two inodes, and the entry really is extraneous. Comparing
783
+ * the inode answers both without knowing which kind of filesystem this is.
784
+ * @param fullPath - The entry the prune found on disk.
785
+ * @param expectedByLowerCase - Expected paths indexed by lower case.
786
+ * @returns Whether the entry must be kept.
787
+ */
788
+ private _isSameFileAsExpected;
789
+ private _makeRoomFor;
790
+ static _isInsideRoot(target: string, relativePath: string): boolean;
791
+ private static _isImpossiblePath;
628
792
  private static _isLocked;
629
793
  /**
630
794
  * The content identity this agent believes is on disk at `filePath`, or
@@ -731,213 +895,326 @@ export declare class FsAgent {
731
895
  * @param expectedDirs - Allowed directory paths
732
896
  * @param expectedFiles - Allowed file paths
733
897
  * @param preRestore - Files present before the restore (prune candidates)
898
+ * @param expectedByLowerCase - Expected paths indexed by lower case, so a
899
+ * file the tree spells with different capitalisation is recognised as the
900
+ * same file rather than pruned.
734
901
  */
735
902
  private _pruneExtraneous;
736
903
  /**
737
- * Watches filesystem for changes and syncs to database
738
- * Uses Connector for socket-based broadcast
739
- * @param db - Database instance
740
- * @param connector - Connector instance for socket-based sync
741
- * @param treeKey - Tree table key
742
- * @param options - Storage options (e.g., skipNotification)
743
- * @returns Function to stop watching
904
+ * Builds a map of relativePath → blobId for all files in a tree.
905
+ * Used to compare trees by content rather than by hash (which includes mtime).
906
+ * @param tree - Tree structure to extract file content map from
907
+ */
908
+ private _getFileContentMap;
909
+ /**
910
+ * What joining actually does to the folder.
911
+ * @param db - The route's database.
912
+ * @param treeKey - The trees table key.
913
+ * @param entry - The head this node is joining onto.
744
914
  */
745
- syncToDb(db: Db, connector: Connector, treeKey: string, options?: StoreFsTreeOptions): Promise<() => void>;
746
915
  /**
747
- * Resolves the `previous` (InsertHistory predecessor timeIds) for a new
748
- * revision from the parent's shared content refs. timeIds are per-db, so we
749
- * map each shared parent ref to *this* db's local timeId(s). Returns undefined
750
- * when ancestry tracking is off (default) or no parent is known — in which
751
- * case the store behaves exactly as before.
752
- * @param db - Database instance
753
- * @param treeKey - Tree table key
754
- * @param parentRefs - Parent content refs (local head, or received predecessors)
916
+ * Moves one file out of the way of the state this node is joining onto.
917
+ *
918
+ * A method rather than a closure inside the join so that the failure can be
919
+ * TESTED. A rename that cannot be performed — the source gone between the
920
+ * scan and the move, the destination occupied by a directory — leaves the
921
+ * file where it is, and the restore then overwrites it. That loses less than
922
+ * refusing to join, which is why it is recorded rather than thrown; and a
923
+ * path that is only ever recorded is a path that needs a test, because
924
+ * nothing else will ever tell anybody it stopped working.
925
+ * @param path - The file to move, relative to the root, `/`-separated.
926
+ * @param name - Where to move it, same form.
927
+ */
928
+ private _setAside;
929
+ /** The chain entry this node stands on, persisted across restarts. */
930
+ private _ownHead?;
931
+ /** The own head's tree, `path → blob`: what the folder is diffed against. */
932
+ private _ownContent;
933
+ /** Paths the watcher saw deleted since the own head was authored. */
934
+ private readonly _watched;
935
+ /** Every chain entry's stamp, as this node learned it. */
936
+ private _stamps?;
937
+ /** The route this agent syncs, once a sync started. */
938
+ private _route?;
939
+ /** The newest head heard and not yet received. */
940
+ private _heard?;
941
+ /** Stamps heard, recorded in arrival order before anything decides. */
942
+ private _stamping;
943
+ /** The lock the send and receive sides share. */
944
+ private _lock;
945
+ /** The receive loop, while it runs. */
946
+ private _receiving?;
947
+ /** A joining folder's wait for the network's head, while it lasts. */
948
+ private _joinWait?;
949
+ /** Authors again shortly, once the watcher has caught up. */
950
+ private _authorSoon?;
951
+ /** The merge that waited for a stamp last, so a second wait is told. */
952
+ private _deferral?;
953
+ /** The last time this node announced its head to learn its stamp. */
954
+ private _stampAsk?;
955
+ /** What the last state the hub announced made this node do. */
956
+ private _hubStatus;
957
+ /** How many receive sides were started; the newest one owns the status. */
958
+ private _receivers;
959
+ /**
960
+ * What an apply that stopped partway — a locked file, an unreachable blob —
961
+ * had already written, path → blob. Not this node's work: authoring does not
962
+ * claim it, and the next apply recognises it. Cleared when the own head
963
+ * moves.
964
+ */
965
+ private _partiallyApplied;
966
+ /** The chain entry this node stands on, if any. */
967
+ get ownHead(): string | undefined;
968
+ /** When this agent last finished something that may write to the folder. */
969
+ private _wroteAt;
970
+ /**
971
+ * Runs `work`, which may write to the folder, and notes when it ended —
972
+ * inside the lock, so nothing queued behind it can read an older note.
973
+ * @param work - A receive or a join.
974
+ * @returns What `work` returned.
975
+ */
976
+ private _writing;
977
+ /**
978
+ * The folder for authoring a local change: a pass that began after this
979
+ * agent last wrote to it.
980
+ *
981
+ * A pass that overlapped an apply may have read the apply half-done, and
982
+ * authoring from it announced the version before the apply — a revert
983
+ * (F9). After a write, then, the folder is scanned afresh. Without one, the
984
+ * watcher's last pass already is such a pass, and scanning again only looks
985
+ * at a file mid-copy one more time: a copy that stalls hashed a truncated
986
+ * version for every extra look, two to five times as many as before.
987
+ * @returns The tree.
755
988
  */
756
- private _ancestryPrevious;
989
+ private _passAfterOwnWrites;
757
990
  /**
758
- * Classifies an incoming revision relative to our current head using the
759
- * local InsertHistory DAG (keyed on shared content refs):
760
- * - `behind` → incoming descends from our head → fast-forward (restore).
761
- * - `ahead` → our head descends from incoming (e.g. a reconnect bootstrap
762
- * re-sending an older ancestor) → ignore; we are newer.
763
- * - `diverged` → siblings produced by concurrent edits → resolve the fork.
764
- * @param db - Database instance
765
- * @param treeKey - Tree table key
766
- * @param currentRef - Our current head's content ref
767
- * @param incomingRef - The incoming revision's content ref
768
- * @param incomingPredecessorRefs - The incoming revision's predecessor refs
991
+ * Runs `work` alone: the send and receive sides never interleave.
992
+ * @param work - What to run.
993
+ * @returns What `work` returned.
769
994
  */
770
- private _ancestryRelation;
995
+ private _exclusive;
771
996
  /**
772
- * Resolves a divergent incoming revision inline (called from `processRef`
773
- * with the watcher paused, so resolution cannot race the sync loop). Records
774
- * the incoming revision as a fork tip without clobbering local content, then
775
- * merges our head and the incoming tip into a single merge revision D that is
776
- * materialised to disk and broadcast.
777
- * @param db - Database instance
778
- * @param treeKey - Tree table key
779
- * @param incomingRef - The incoming revision's content ref
780
- * @param incomingTree - The fetched incoming tree
781
- * @param predecessorRefs - The incoming revision's predecessor content refs
997
+ * Opens the chain and the stamp store for a route, once.
998
+ * @param db - The route's database.
999
+ * @param treeKey - The trees table key.
782
1000
  */
783
- private _resolveConflictInline;
1001
+ private _ensureChain;
784
1002
  /**
785
- * Builds a map of relativePath → blobId for all files in a tree.
786
- * Used to compare trees by content rather than by hash (which includes mtime).
787
- * @param tree - Tree structure to extract file content map from
1003
+ * The head `.fsagent-state.json` names, if it names one.
1004
+ * @returns The head, or `undefined`.
788
1005
  */
789
- private _getFileContentMap;
1006
+ private _persistedHead;
790
1007
  /**
791
- * Derives a deterministic string key from a content map so that two trees
792
- * with identical file paths + blobIds produce the same key regardless of
793
- * mtime differences.
794
- * @param map - Content map (relativePath → blobId)
1008
+ * Makes `head` this node's head, and remembers it across a restart.
1009
+ * @param head - The chain entry.
1010
+ * @param content - The tree it names, `path → blob`.
795
1011
  */
796
- private _contentKeyFromMap;
797
- /**
798
- * Records `treeRef` as the ref describing this folder's current state, and
799
- * retires the one it supersedes from the connector's dedup sets.
800
- *
801
- * A tree ref is a pure content hash, so a folder that returns to an earlier
802
- * state re-derives that state's exact ref. The connector drops an incoming
803
- * ref it has already received, which assumes a state is reached once and
804
- * never returned to — false for content-addressed state, and false in the
805
- * most ordinary way possible: create a file, then delete it again.
806
- *
807
- * Retiring the SUPERSEDED ref is what keeps the return trip deliverable.
808
- * The ref just adopted stays deduped, so a peer re-advertising the state
809
- * this folder is actually in is still suppressed as the echo it is. That
810
- * only works if every adopted state passes through here — a state adopted
811
- * silently is never retired and blocks its own return for good.
812
- * @param connector - Connector whose dedup sets to retire from.
813
- * @param treeRef - The ref that now describes this folder.
1012
+ private _setOwn;
1013
+ /** Writes {@link AGENT_STATE_FILE}: the own head and the stamp epochs. */
1014
+ private _writeState;
1015
+ /** The stamp epochs the state file holds, as written. */
1016
+ private _writtenEpochs;
1017
+ /**
1018
+ * The tree a chain entry names.
1019
+ * @param head - The chain entry.
1020
+ * @returns Its tree ref and tree, or `undefined` when either cannot be read.
814
1021
  */
1022
+ private _treeOf;
1023
+ /** Announces the own head, with its stamp when this node knows it. */
1024
+ private _announceOwn;
815
1025
  /**
816
- * Re-announce this folder's current state after refusing an incoming tree.
817
- *
818
- * A refusal means the sender holds less than this node does, so it is the one
819
- * that needs telling. Without this the network settles into a state that is
820
- * stable and wrong: the sparse node cannot push, the full node has nothing
821
- * new to push, and nothing moves until an unrelated edit happens somewhere.
1026
+ * Announces the own head so the hub stamps it — at once the first time,
1027
+ * then less and less often while the stamp does not come.
822
1028
  *
823
- * Rate-limited because two nodes can refuse each other — each holding files
824
- * the other lacks — and an unthrottled answer to every refusal is a loop.
825
- * @param connector - Connector to broadcast on.
1029
+ * Bounded because nothing else bounds it: on a hub that does not stamp,
1030
+ * three nodes deferring the same conflict answered each other's
1031
+ * announcements with announcements, 245 000 merge attempts in one test.
1032
+ * @param head - The own head.
826
1033
  */
827
- private _readvertiseAfterRefusal;
1034
+ private _askForStamp;
828
1035
  /**
829
- * Whether a tree describes a folder holding nothing whatsoever.
830
- *
831
- * Deliberately conservative: an empty DIRECTORY counts as content. A user who
832
- * creates a folder and puts a directory in it has made a statement about what
833
- * should be there, and the silence this gates is only correct for an agent
834
- * that has established nothing at all. Being wrong in that direction would
835
- * mean a folder that never advertises until something else happens to change.
836
- * @param tree - The tree to inspect.
837
- * @returns `true` when the tree carries no entries at all.
1036
+ * Authors an edit for the folder as `tree` describes it, if it moved past
1037
+ * the own head and the edit is honest — see `planAuthoring`.
1038
+ * @param tree - The folder, as just scanned.
838
1039
  */
839
- private _treeIsEmpty;
1040
+ private _author;
840
1041
  /**
841
- * Whether an inbound ref is news to this agent, and if not, why.
842
- *
843
- * "Is this ref news to me" is the question this subsystem keeps getting
844
- * wrong. It has been answered in five separate places — the connector's sent
845
- * and received dedup sets, `_lastSentContentKey`, `_lastSentRef`,
846
- * `_lastAppliedRef` — and each has been wrong at least once:
847
- *
848
- * - an agent applied its OWN last advertisement over its own newer edit,
849
- * destroying it and then declining to re-send (fixed 0.0.30);
850
- * - a delete propagated only from the client that had created the file,
851
- * because the send path never retired the state it left (0.0.31);
852
- * - a refusal consumed the ref it refused, so the same emptiness arriving
853
- * twice was silent the second time (0.0.33);
854
- * - a restarted agent inherited its predecessor's conclusions (0.0.34);
855
- * - a quiet join announced anyway, because the connector broadcasts on
856
- * local insert and the gate was on the send (0.0.38).
857
- *
858
- * Collecting the pre-fetch gates here does not fix a sixth. It makes the
859
- * question answerable in one place, in one order, with the reasoning
860
- * attached — which is what the previous five each lacked.
861
- *
862
- * Order matters and is deliberate. The own-echo check comes first because it
863
- * is the only one that holds regardless of what the sender believes: the two
864
- * defences that ought to catch an echo both miss it. The origin filter
865
- * compares the payload's origin to this connector's, and a bootstrap carries
866
- * the SERVER as origin rather than the client the ref came from; the
867
- * staleness check then measures the server's sequence, which did advance, so
868
- * the echo reads as news.
1042
+ * Stores a tree and its blobs for the route.
1043
+ * @param tree - The tree.
1044
+ * @returns Its ref.
1045
+ */
1046
+ private _storeTree;
1047
+ /**
1048
+ * Watches the folder and keeps the chain in step with it.
869
1049
  *
870
- * KNOWN LIMIT, stated because the next person will meet it: this compares
871
- * against the LAST ref this agent sent, so an echo of an OLDER
872
- * self-originated ref still gets through. Widening it to a set would also
873
- * suppress a peer's legitimate revert to a state this agent once held. The
874
- * real fix is for the bootstrap to carry the originating client, so the
875
- * origin filter works and this check stops being needed at all.
876
- * @param treeRef - The inbound ref.
877
- * @param isNewestFromSender - Whether the connector judged it the newest
878
- * thing its sender has advertised. Unknown answers `true`.
879
- * @returns `apply`, or the reason it is not news.
1050
+ * On start, a folder with a head continues it; a folder without one joins
1051
+ * the network (`planJoin`) or, when nobody answers, becomes its origin.
1052
+ * @param db - The route's database.
1053
+ * @param connector - The transport.
1054
+ * @param treeKey - The trees table key.
1055
+ * @returns Stops watching.
1056
+ */
1057
+ syncToDb(db: Db, connector: Connector, treeKey: string): Promise<() => void>;
1058
+ /**
1059
+ * Waits up to `joinWaitMs` for the network's head before this folder says
1060
+ * anything about itself.
880
1061
  */
881
- private _inboundRefVerdict;
1062
+ private _startJoinWait;
1063
+ /** Ends a join wait without acting on it. */
1064
+ private _endJoinWait;
882
1065
  /**
883
- * Records the files an announcement carried.
1066
+ * Joins the network's head, or — when none came — makes this folder the
1067
+ * origin of its history.
884
1068
  *
885
- * Called wherever this agent commits to a state as "what peers know" —
886
- * its own pushes, and the states it adopts from theirs.
887
- * @param tree - The tree that just went out, or was adopted as ours.
1069
+ * **The chain applies first; the filesystem only then.** What the folder
1070
+ * holds beyond the head is judged by the history: a path the history never
1071
+ * named is new work and is authored on top of the head; a path it removed is
1072
+ * a stale copy and is set aside, not announced; a path both hold with
1073
+ * different bytes keeps the head's version and the local one as a copy.
1074
+ * @param head - The network's head, or `undefined`.
888
1075
  */
1076
+ private _join;
889
1077
  /**
890
- * Records a state this node is now in.
891
- * @param ref - The content ref of that state.
1078
+ * Hears a head — from an announcement, a bootstrap or a state beacon.
1079
+ * @param head - The head.
1080
+ * @param stamp - The stamp it arrived with, if any.
1081
+ * @param fromHub - Whether the hub said it: what `antiEntropyStatus` reports.
892
1082
  */
893
- private _rememberState;
1083
+ private _hear;
1084
+ /** The head the hub said last. */
1085
+ private _hubHead?;
894
1086
  /**
895
- * Whether a push comes from a sender this node has already moved past.
896
- * @param predecessorRefs - What the push declares it descends from.
897
- * @returns True when every declared parent is a state this node has left.
898
- */
899
- private _senderIsBehind;
900
- private _rememberAnnounced;
901
- private _adoptAppliedRef;
902
- /**
903
- * Derives a deterministic content key from an FsTree.
904
- * @param tree - Tree structure to derive content key from
1087
+ * Records the stamp a head arrived with, in arrival order.
1088
+ * @param head - The head.
1089
+ * @param stamp - Its stamp, if any.
905
1090
  */
906
- private _contentKeyFromTree;
907
- /**
908
- * Compares two trees by file content (relativePath + blobId).
909
- * Ignores mtime differences — trees are equivalent if they have the same
910
- * files with the same content. This prevents bounce-back restores from
911
- * destroying locally-created files during bidirectional sync.
912
- * @param a - First tree to compare
913
- * @param b - Second tree to compare
1091
+ private _recordStamp;
1092
+ /** Receives the newest head heard, one at a time, until none is left. */
1093
+ private _drain;
1094
+ /**
1095
+ * Keeps `antiEntropyStatus` true to what the last head from the hub made
1096
+ * this node do.
1097
+ * @param head - The head that was received.
1098
+ * @param outcome - What was done.
914
1099
  */
915
- private _treesHaveEquivalentContent;
1100
+ private _noteOutcome;
916
1101
  /**
917
- * Builds the dependency surface a {@link FsConflictResolver} needs, wiring it
918
- * to this agent's db, blob store, scanner, and working directory.
919
- *
920
- * The merge store records the merged ref/content key as the last-sent state,
921
- * so the watcher-driven re-scan that follows the on-disk materialisation
922
- * settles to a no-op instead of re-broadcasting.
923
- * @param db - Database instance
924
- * @param treeKey - Tree table key
1102
+ * How often in a row an apply found the folder moved under this node's own
1103
+ * head. Counted per own head, not per incoming one: two heads arriving in
1104
+ * turn must not reset each other's count.
925
1105
  */
926
- private _buildConflictResolverDeps;
1106
+ private _movedAgain?;
927
1107
  /**
928
- * Watches database for tree changes and syncs to filesystem
929
- * Uses Connector for socket-based notifications
930
- * @param db - Database instance
931
- * @param connector - Connector instance for socket-based sync
932
- * @param treeKey - Tree table key
933
- * @param restoreOptions - Restore options (e.g., cleanTarget)
934
- * @returns Function to stop watching
1108
+ * Receives a head once more after the folder moved under an apply — the
1109
+ * local work is authored first then, which turns the apply into a merge.
1110
+ * Bounded, so a cache that never catches up cannot loop; the next head the
1111
+ * hub says tries again.
1112
+ * @param head - The head.
1113
+ */
1114
+ private _receiveAgain;
1115
+ /**
1116
+ * What `receive` needs from this agent.
1117
+ * @returns The agent's side of a receive.
1118
+ */
1119
+ private _receiveDeps;
1120
+ /**
1121
+ * Makes a head this node's own without touching the folder: its content
1122
+ * is what the folder already holds.
1123
+ * @param head - The head.
1124
+ */
1125
+ private _adopt;
1126
+ /**
1127
+ * Applies a head that descends from the own one: writes what it changed,
1128
+ * deletes what it removed — every absence in it is a deletion its author
1129
+ * chose, because its author held this node's state.
1130
+ *
1131
+ * Only what changed between the two heads is touched, and only while the
1132
+ * folder still holds the own head's version of it. A file the user changed
1133
+ * since is never overwritten: the apply stops, that work is authored, and
1134
+ * the head is received again — as a fork, which merges.
1135
+ * @param head - The head.
1136
+ * A deletion beyond the receiver's floors is the exception: the files stay,
1137
+ * the head is adopted all the same, and the files are authored again on top
1138
+ * of it — which is what refills a node that lost them.
1139
+ * @returns `applied`, or `refused` when the head cannot be read or local
1140
+ * work stopped it.
1141
+ */
1142
+ private _applyBehind;
1143
+ /**
1144
+ * Moves the folder from the own content to `target`: writes what differs,
1145
+ * deletes what `target` lacks.
1146
+ *
1147
+ * The receiver guard: a deletion that would lose more than the floors allow
1148
+ * — content `target` holds nowhere else — is not made. Everything else is,
1149
+ * and the files kept become this node's work, so the folder never holds a
1150
+ * state the chain does not describe.
1151
+ * @param target - Where the folder should end up, `path → blob`.
1152
+ * @param write - Writes the given paths' `target` versions.
1153
+ * @returns `applied`; `kept` when the guard kept files `target` lacks;
1154
+ * `moved` when the folder had moved past the own head.
1155
+ */
1156
+ private _applyContent;
1157
+ /**
1158
+ * Whether every given path still holds what the own head says — or what a
1159
+ * cut-short apply already wrote there: no local change the watcher has not
1160
+ * reported yet.
1161
+ * @param paths - Relative paths.
1162
+ * @returns `true` when none of them changed since the own head.
1163
+ */
1164
+ private _unchangedSinceOwn;
1165
+ /**
1166
+ * The blob a file holds, as far as this agent knows without reading it: what
1167
+ * it last wrote there, or what the scanner last read — whichever a `stat`
1168
+ * confirms. Both, because either goes stale on its own: a restore's record
1169
+ * once anything else rewrites the file, the scanner's until its next pass.
1170
+ * @param path - Relative path.
1171
+ * @returns The blob; `null` when no file is there; `undefined` when the file
1172
+ * changed since this agent last knew it.
1173
+ */
1174
+ private _blobOnDisk;
1175
+ /**
1176
+ * Writes the given paths of a tree into the folder, with everything a
1177
+ * restore does for a write: streams, locks, impossible names, a full disk.
1178
+ * @param tree - The tree.
1179
+ * @param paths - The relative paths to write.
1180
+ */
1181
+ private _restorePaths;
1182
+ /**
1183
+ * Merges a forked head into the own one against their common base — the
1184
+ * conflict table in `fs-merge.ts` — and authors the merge.
1185
+ * @param theirs - The forked head.
1186
+ * @param base - Their common ancestor, if any.
1187
+ * @returns `merged`; `deferred` when a stamp the verdict needs is not known
1188
+ * yet; `refused` when the merge could not be applied.
1189
+ */
1190
+ private _merge;
1191
+ /**
1192
+ * Hears the network: announcements, the stamps of this node's own, and the
1193
+ * hub's state beacon.
1194
+ * @param db - The route's database.
1195
+ * @param connector - The transport.
1196
+ * @param treeKey - The trees table key.
1197
+ * @returns Stops listening.
1198
+ */
1199
+ syncFromDb(db: Db, connector: Connector, treeKey: string): Promise<() => void>;
1200
+ /**
1201
+ * Says, once, that a deletion was refused — in the log and as one
1202
+ * `deletion/refused` signal.
1203
+ *
1204
+ * Three call sites had three copies of this, which is how they came to say
1205
+ * three different things about the same decision. A client reading one of
1206
+ * them saw a third of the picture.
1207
+ * @param route - Which rule refused it.
1208
+ * @param wouldRemove - How many paths it would have deleted.
1209
+ * @param held - How many this folder holds.
1210
+ * @param paths - The paths, of which the first few are kept.
1211
+ * @param detail - Extra wording for the log line, where a route has some.
935
1212
  */
936
- syncFromDb(db: Db, connector: Connector, treeKey: string, restoreOptions?: RestoreOptions): Promise<() => void>;
1213
+ private _refuseDeletion;
937
1214
  /**
938
1215
  * Creates a fully configured FsAgent from a Client instance.
939
- * This factory method provides a simplified API where sync methods don't require
940
- * db, connector, and treeKey parameters - they are stored internally.
1216
+ * This factory method provides a simplified API where sync methods don't
1217
+ * require db, connector, and treeKey parameters - they are stored internally.
941
1218
  * @param filePath - Directory path to sync
942
1219
  * @param treeKey - Tree table key (route will be `/${treeKey}`)
943
1220
  * @param client - Client instance with io and bs properties