@rljson/fs-agent 0.0.84 → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,582 @@
1
+ import { Db } from '@rljson/db';
2
+ import { Json } from '@rljson/json';
3
+ /** The `EditAction.type` every fs chain entry carries. */
4
+ export declare const FS_EDIT_ACTION = "putFsTree";
5
+ /**
6
+ * How far back a walk goes before it gives up.
7
+ *
8
+ * A walk this deep is a cold replay of a whole lineage rather than a
9
+ * catch-up, and left unbounded it pins a core on a long chain.
10
+ *
11
+ * Exhausting it is NOT the same as failing to read a row — see
12
+ * {@link FsEditChain.classify}. Conflating the two made any node more than this
13
+ * many pushes into its own history stop repairing, permanently and silently.
14
+ */
15
+ export declare const DEFAULT_MAX_WALK = 500;
16
+ /** What one chain entry says happened. */
17
+ export interface FsEditData extends Json {
18
+ /** The tree ref the folder ended up at. */
19
+ treeRef: string;
20
+ /** Relative paths added or modified, `/`-separated, sorted. */
21
+ changed: string[];
22
+ /**
23
+ * Relative paths REMOVED, `/`-separated, sorted.
24
+ *
25
+ * The whole reason the chain carries more than a ref. A tree records what a
26
+ * folder holds; only this records what it deliberately stopped holding.
27
+ */
28
+ removed: string[];
29
+ }
30
+ /** What {@link FsEditChain.append} records. */
31
+ export interface FsAppendOptions {
32
+ /** The state the folder ended up at. */
33
+ treeRef: string;
34
+ /** Relative paths added or modified. Default: none. */
35
+ changed?: readonly string[];
36
+ /** Relative paths removed. Default: none. */
37
+ removed?: readonly string[];
38
+ /**
39
+ * What this entry was made from.
40
+ *
41
+ * Defaults to the current head. Passed explicitly only for a MERGE entry,
42
+ * which has two parents — the one shape `MultiEditManager` refuses and the
43
+ * reason these rows are written by hand.
44
+ */
45
+ previous?: readonly string[];
46
+ }
47
+ /** One entry of the chain, as read back. */
48
+ export interface FsChainEntry {
49
+ /** The `EditHistory` ref — this entry's identity, and the head to announce. */
50
+ head: string;
51
+ /** Fleet-wide order. Minted once, by the node that made the change. */
52
+ timeId: string;
53
+ /** The tree ref the folder ended up at. */
54
+ treeRef: string;
55
+ /** The entries this one was made from. Empty for a lineage root. */
56
+ previous: string[];
57
+ /** Relative paths added or modified. */
58
+ changed: string[];
59
+ /** Relative paths removed. */
60
+ removed: string[];
61
+ }
62
+ /**
63
+ * Creates the three tables an fs chain needs, idempotently.
64
+ *
65
+ * **fs-agent creates its own tables.** The host application creates the trees
66
+ * table
67
+ * (in its own server and client entry points), and an agent that expected
68
+ * tables its host had never created would fail at runtime on any node whose
69
+ * host is one release behind — exactly the mixed-version case a rollout
70
+ * guarantees. `@rljson/db`'s `createTable` is `createOrExtendTable`, so calling
71
+ * this on every init costs nothing and removes the coupling rather than
72
+ * versioning it.
73
+ * @param db - The route's database.
74
+ * @param treeKey - The trees table key, e.g. `fileTree`.
75
+ */
76
+ export declare const createFsChainTables: (db: Db, treeKey: string) => Promise<void>;
77
+ /**
78
+ * The append-only chain for one folder.
79
+ *
80
+ * Append-only and never merged: each node keeps its own lineage, exactly as
81
+ * mongo does. Nothing here rewrites or prunes an entry — that is WP5's job.
82
+ */
83
+ export declare class FsEditChain {
84
+ private readonly _db;
85
+ private readonly _treeKey;
86
+ private _head;
87
+ /** The last own-lineage walk, keyed by the head it was computed for. */
88
+ private _lineageCache;
89
+ private _ready;
90
+ constructor(_db: Db, _treeKey: string);
91
+ /** The entry this node's lineage currently ends at. */
92
+ get head(): string | undefined;
93
+ /** Whether {@link init} has completed. */
94
+ get ready(): boolean;
95
+ /**
96
+ * Creates the tables and continues this node's lineage where it left off.
97
+ *
98
+ * A process that came back and started a fresh root would orphan everything
99
+ * it wrote before, so the tip is read from the store rather than assumed
100
+ * absent.
101
+ */
102
+ init(): Promise<void>;
103
+ /**
104
+ * Re-reads the tip, for a node waiting to learn the network's state.
105
+ *
106
+ * `init` reads it once. A joining node has none of its own and is waiting
107
+ * for the fleet's to replicate, so it has to be able to look again — the
108
+ * rows arrive after the connection, not before it.
109
+ * @returns The tip now, or `undefined` while nothing has arrived.
110
+ */
111
+ refreshHead(): Promise<string | undefined>;
112
+ /**
113
+ * Appends one entry.
114
+ * @param opts - What the change was; see {@link FsAppendOptions}.
115
+ * @returns The entry that was written.
116
+ */
117
+ append(opts: FsAppendOptions): Promise<FsChainEntry>;
118
+ /**
119
+ * Reads one entry back.
120
+ * @param head - The `EditHistory` ref to read.
121
+ * @returns The entry, or `undefined` when this node cannot resolve it — a
122
+ * ref a peer holds and we do not is the ordinary case, not an error.
123
+ */
124
+ entry(head: string): Promise<FsChainEntry | undefined>;
125
+ /**
126
+ * The newest entry that produced a given tree ref.
127
+ *
128
+ * **The migration bridge.** A build that predates the `~H~` announcement
129
+ * sends a plain tree ref, and a receiver holding one cannot find its chain
130
+ * row by hash — `dataRef` is the field, but finding a row BY a field is a
131
+ * query rather than a content read. Measured across a real relay
132
+ * (`test/fs-chain-crosses-the-wire.spec.ts`): the query is served, so an
133
+ * older peer's push can still carry ancestry.
134
+ *
135
+ * **Ambiguous by nature, which is why it is the fallback and not the
136
+ * primary.** A tree ref is a content hash, so a folder that returns to an
137
+ * earlier state produces a SECOND entry with the same `dataRef` — §2.1,
138
+ * exactly the ambiguity the chain exists to remove. The newest by `timeId`
139
+ * is the right pick: it is the entry that most recently produced this
140
+ * content, and the one whose ancestry describes how the folder got here now.
141
+ *
142
+ * Never called on the apply path. A query is a peer read, and awaiting one
143
+ * before scheduling an apply is how a late joiner's bootstrap was lost.
144
+ * @param treeRef - The state announced.
145
+ * @returns The newest entry producing it, or `undefined` if none is found.
146
+ */
147
+ /**
148
+ * The OLDEST entry that produced a given tree ref.
149
+ *
150
+ * **How a fleet agrees on one name for one state.** Every node authors an
151
+ * entry for the state it starts in, and those states are usually identical —
152
+ * peers already in sync hold the same bytes, so they derive the same tree
153
+ * ref. Each node then sits on its own lineage root and `classify` answers
154
+ * `fork` to every announcement forever.
155
+ *
156
+ * The oldest entry is the one to converge on because the choice is the same
157
+ * for everybody who can see the rows, and because adoption that only ever
158
+ * moves BACKWARDS in time is monotone: it cannot oscillate as rows arrive.
159
+ * Whoever reached this content first described it first.
160
+ *
161
+ * The counterpart of {@link entryForTreeRef}, which answers the opposite
162
+ * question — *"how did this folder get here NOW"* — and therefore wants the
163
+ * newest.
164
+ * @param treeRef - The state to name.
165
+ * @returns The oldest entry producing it, or `undefined` if none is found.
166
+ */
167
+ oldestEntryForTreeRef(treeRef: string): Promise<FsChainEntry | undefined>;
168
+ entryForTreeRef(treeRef: string): Promise<FsChainEntry | undefined>;
169
+ /**
170
+ * Where two heads stand relative to each other.
171
+ *
172
+ * `behind` — theirs descends from ours, so we are the one missing work.
173
+ * `ahead` — ours descends from theirs; they are missing ours.
174
+ * `fork` — neither descends from the other. Both sides have work.
175
+ * `incomplete` — an entry could not be RESOLVED, so nothing may be concluded.
176
+ *
177
+ * **A hole and the walk bound are not the same truncation**, and treating
178
+ * them alike was a latent permanent failure. A hole means an entry exists and
179
+ * this node cannot read it: the ref it was looking for may be inside the part
180
+ * it could not reach, so the honest answer is "I do not know". Exhausting the
181
+ * walk bound means the opposite — everything asked for WAS readable, and no
182
+ * relation was found within {@link DEFAULT_MAX_WALK} entries of history.
183
+ *
184
+ * Conflating them meant any node more than `DEFAULT_MAX_WALK` pushes into its
185
+ * own history answered `incomplete` forever, which the decision turns into
186
+ * `blocked`, which never repairs. A long-lived node would simply stop
187
+ * healing, silently. Measured on the growth run that was meant to be about
188
+ * storage.
189
+ *
190
+ * A bounded walk with no relation therefore answers `fork`: both sides keep
191
+ * their work and reconciliation is additive. Less precise than the truth and
192
+ * never destructive, which is the right direction to be wrong in.
193
+ * @param ourHead - This node's head, or `undefined` when it has none.
194
+ * @param theirHead - The head that arrived.
195
+ * @returns How the two histories stand.
196
+ */
197
+ classify(ourHead: string | undefined, theirHead: string): Promise<'behind' | 'ahead' | 'fork' | 'incomplete'>;
198
+ /**
199
+ * Every entry reachable from `head`, itself included.
200
+ *
201
+ * `holed` — an entry could not be RESOLVED. The caller must conclude
202
+ * nothing: the unreachable part may contain the very ref it was looking for,
203
+ * and a walk that answers "not an ancestor" on that basis is how a node
204
+ * decides it is ahead of a peer it is actually behind.
205
+ *
206
+ * `bounded` — the walk ran out of budget with everything it asked for
207
+ * readable. A different statement, and a usable one: no relation within this
208
+ * many entries of history. See {@link classify}.
209
+ * @param head - Where to start.
210
+ * @param maxWalk - Give up past this many entries.
211
+ * @returns The refs reached, whether anything was unreadable, and whether
212
+ * the budget ran out.
213
+ */
214
+ private _ancestorsOf;
215
+ /**
216
+ * Every entry this node's own head descends from, itself included.
217
+ *
218
+ * Cached on the head it was computed for. Announcements arrive in bursts and
219
+ * this node's head changes only when it records an entry, so the walk is
220
+ * done once per state rather than once per announcement.
221
+ * @param ourHead - This node's head, or `undefined` when it has none.
222
+ * @param maxWalk - Give up past this many entries.
223
+ * @returns The refs reached, or `undefined` when the walk could not be
224
+ * trusted — an unreadable entry means the stop set is unknown, not empty.
225
+ */
226
+ private _ourLineage;
227
+ /**
228
+ * The newest edit on this lineage that CHANGED or REMOVED a given path.
229
+ *
230
+ * **The per-path question, and the one the conflict resolver could not ask.**
231
+ * `compareTips` orders a BRANCH by its tip, and the caller then uses that one
232
+ * verdict for every path the two branches disagree about — so a tip wins
233
+ * paths it never touched. Measured: a node that had been offline came back,
234
+ * wrote one file of its own, and that newer tip took `doc.txt` as well,
235
+ * rolling the writer's own folder from v8 back to v5.
236
+ *
237
+ * Asking per path answers it exactly: the last edit naming `doc.txt` is the
238
+ * writer's, and the returning node's entry does not name it at all, so it
239
+ * does not count for it. No clock is involved — the answer is read out of the
240
+ * shared history, so every node computes the same winner on its own.
241
+ *
242
+ * **A removal counts as touching the path.** An edit/delete conflict is still
243
+ * two people acting on one file, and the one who acted later decides it.
244
+ *
245
+ * `undefined` means "cannot say": either nothing on this lineage ever named
246
+ * the path, or the walk could not be read to the end. The caller must not
247
+ * read that as "nobody edited it" — it falls back to the branch-level order.
248
+ * @param head - The lineage's tip.
249
+ * @param path - The relative path being decided.
250
+ * @param maxWalk - Give up past this many entries.
251
+ * @returns The newest entry naming `path`, or `undefined`.
252
+ */
253
+ lastEditOf(head: string, path: string, maxWalk?: number): Promise<FsChainEntry | undefined>;
254
+ /**
255
+ * The NET removals between a peer's head and a state this node knows.
256
+ *
257
+ * **Why a walk is needed at all, and it cost a red run to see.** A removal is
258
+ * stated ONCE, in the entry that made it. A node that was partitioned when it
259
+ * deleted a file states the removal in an entry nobody received; its next
260
+ * entry, after it rejoins, computes its `changed`/`removed` against its own
261
+ * last announcement and therefore says nothing about that deletion. So a peer
262
+ * reading only the head learns nothing, and the file survives on every node
263
+ * except the one that deleted it — which is the measured failure.
264
+ *
265
+ * Walking `previous` back to a state the receiver recognises closes exactly
266
+ * that gap, and the ancestry is reachable by hash alone (proven in
267
+ * `test/fs-chain-crosses-the-wire.spec.ts`).
268
+ *
269
+ * **Replayed oldest-first, so a re-add cancels a removal.** A path deleted
270
+ * and then created again inside the walked range is not a removal at all,
271
+ * and taking the union of `removed` would delete it. Order is the whole
272
+ * correctness of this function.
273
+ *
274
+ * **`complete` is mongo's contract, and it matters more than the result.**
275
+ * When an entry cannot be resolved the walk is truncated, and the caller MUST
276
+ * NOT treat the answer as authoritative — ancestors beyond the missing row
277
+ * are unknown, and one of them may be the re-add that cancels a removal we
278
+ * did collect. `@rljson/mongo-agent` states it as: *"a caller must not latch
279
+ * the head; ancestors beyond the missing row would otherwise be lost
280
+ * forever"*.
281
+ * **Where the walk stops is THIS NODE'S OWN LINEAGE, asked of the chain.**
282
+ * It used to be a set of content refs: the current one, the last applied one,
283
+ * and a thousand remembered past states. That set approximated "everywhere I
284
+ * have been" — capped, so a long-lived node forgot its oldest states, and
285
+ * matched BY CONTENT, so an entry on a lineage this node never travelled
286
+ * stopped the walk whenever it happened to produce bytes this node also
287
+ * holds. Identical content across nodes was rare while mtime was in the
288
+ * identity; now it is the norm.
289
+ *
290
+ * Neither is a measured data loss — stopping early collects FEWER removals,
291
+ * which is the safe direction, and content equality does mean the folder was
292
+ * in that state. It is a heuristic standing in for a question the chain can
293
+ * answer exactly, which is the whole reason the chain exists.
294
+ * @param head - The peer's head.
295
+ * @param ourHead - This node's own head, or `undefined` when it has none —
296
+ * a node with no history of its own recognises no state, so nothing stops
297
+ * the walk short of `maxWalk`.
298
+ * @param maxWalk - Give up past this many entries. A walk this deep is a
299
+ * cold replay rather than a catch-up, and left unbounded it pins a core on
300
+ * a long chain.
301
+ * **Both halves of the net delta are returned**, and the second one is not
302
+ * bookkeeping. A receiver holds a TOMBSTONE for every path it has deleted,
303
+ * including the ones a peer told it to delete, and that tombstone refuses
304
+ * the path if anyone writes it again. Only a peer that STATES it created
305
+ * the path may lift it — a tree merely containing the path states nothing,
306
+ * since every tree that predates the deletion contains it too. Measured: a
307
+ * file created, deleted and created again at the same path never reached the
308
+ * second node, in three runs of three, because nothing could clear the
309
+ * tombstone the node had set on its peer's authority.
310
+ * @returns The net removals, the net changes, the newest `timeId` seen, and
311
+ * whether the walk resolved completely.
312
+ */
313
+ collectRemovals(head: string, ourHead: string | undefined, maxWalk?: number): Promise<{
314
+ removed: string[];
315
+ changed: string[];
316
+ timeId?: string;
317
+ complete: boolean;
318
+ }>;
319
+ /**
320
+ * The newest entry nothing else descends from.
321
+ *
322
+ * **A single slot, and that is a known limit.** Every node keeps its own
323
+ * lineage and chains are never merged, so once the walk starts pulling peers'
324
+ * rows (WP3) this table holds several tips and "the newest" can be somebody
325
+ * else's. `@rljson/mongo-agent` had exactly this bug — lost updates
326
+ * root-caused to a single `_lastApplied` slot rather than per-node lineages —
327
+ * and fixed it by tracking lineages. Nothing reads this chain yet, so the
328
+ * limit is not reachable; WP3 must replace it rather than build on it.
329
+ *
330
+ * "Newest" is by `timeId`, which is `<millis>:<nanoid>` — so two entries
331
+ * minted in the same millisecond are separated by a random tail. That order
332
+ * is arbitrary in wall-clock terms and IDENTICAL on every node, which is the
333
+ * property that matters; nothing may depend on it meaning "later in time".
334
+ * @returns The tip's ref, or `undefined` on an empty chain.
335
+ */
336
+ private _tip;
337
+ /**
338
+ * Pulls the generated ref out of an insert result.
339
+ * @param result - What `db.add*` returned.
340
+ * @param suffix - The table suffix, e.g. `Edits`.
341
+ * @returns The ref.
342
+ */
343
+ private _refOf;
344
+ }
345
+ /**
346
+ * Orders two `timeId`s (`<millis>:<nanoid>`).
347
+ *
348
+ * Compares the millisecond part numerically and breaks ties on the random
349
+ * suffix, so the order is TOTAL and IDENTICAL on every node — which is the
350
+ * property that makes convergence a guarantee rather than a matter of who
351
+ * spoke last. It is not "later in wall-clock time": two ids minted in the same
352
+ * millisecond are separated by a random tail, and nothing may read the result
353
+ * as a timestamp comparison.
354
+ *
355
+ * A missing or malformed id orders as "not comparable" (`0`), so a caller
356
+ * cannot accidentally treat "unknown" as "older".
357
+ *
358
+ * Same semantics as `@rljson/mongo-agent`'s `compareTimeId`, restated here
359
+ * rather than depended on: fs must not take a dependency on mongo-agent, which
360
+ * already depends on fs-agent.
361
+ * @param a - The first timeId, or `undefined`.
362
+ * @param b - The second timeId, or `undefined`.
363
+ * @returns `-1` if `a` is older, `1` if newer, `0` when equal or not
364
+ * comparable.
365
+ */
366
+ export declare const compareTimeId: (a: string | undefined, b: string | undefined) => number;
367
+ /** What {@link planRemovals} is asked. */
368
+ export interface RemovalQuestion {
369
+ /** Relative paths the peer says it deleted. */
370
+ removed: readonly string[];
371
+ /** The `timeId` of the edit carrying them. */
372
+ timeId: string;
373
+ /**
374
+ * `path → timeId` of the newest LOCAL edit that touched each path.
375
+ *
376
+ * A path absent from this map has no local claim, and a removal for it is
377
+ * applied — "unknown" must never read as "older".
378
+ */
379
+ localTimeIds: ReadonlyMap<string, string>;
380
+ /**
381
+ * `path → timeId` of the last edit the CHAIN knows for that path.
382
+ *
383
+ * Consulted only where {@link localTimeIds} has nothing, which is the case
384
+ * that matters: a node holding a file it RECEIVED rather than authored has
385
+ * no claim on it — a receiver adopts and never authors, deliberately — so
386
+ * without this the ordering question had no answer and an old removal won
387
+ * by default.
388
+ *
389
+ * Optional, because the chain is best effort. Absent, the behaviour is
390
+ * exactly what it was: only this node's own claims can outrank a removal.
391
+ */
392
+ chainTimeIds?: ReadonlyMap<string, string>;
393
+ /** Relative paths this node currently holds. */
394
+ held: ReadonlySet<string>;
395
+ /**
396
+ * Paths this node HOLDS but has never told anyone about — local work made
397
+ * since its last announcement.
398
+ *
399
+ * **A removal cannot be about a file its author has never seen.** A peer's
400
+ * stated removal travels with the chain and is re-collected by every later
401
+ * walk, so it keeps arriving after it was first applied. If this node
402
+ * re-creates the path in the meantime, that creation has no `localTimeIds`
403
+ * entry yet — claims are recorded by the PUSH, which has not happened — so
404
+ * the recency rule above cannot see it and the removal deletes a file the
405
+ * user has just made.
406
+ *
407
+ * Measured as `I7b`: three nodes, a deletion everyone applied, then a
408
+ * different node re-creates the path. The re-created file was removed again
409
+ * before its author could announce it, and the fleet ended up split, with
410
+ * the deleter holding the file and the author who re-made it without it.
411
+ * Found by the random-churn fuzzer at roughly one run in eight; the named
412
+ * reproduction is deterministic in 33 seconds.
413
+ *
414
+ * Absent means "ask the rules below", so an omitted set changes nothing.
415
+ */
416
+ unannounced?: ReadonlySet<string>;
417
+ /**
418
+ * How many paths the SAME edit claims.
419
+ *
420
+ * It counts towards what the folder would be left with, because a rename
421
+ * drops every old name and claims every new one — a folder that is renamed
422
+ * does not shrink, and reading the removals alone makes one look like a
423
+ * wipe. Default 0, which is what a pure deletion is.
424
+ */
425
+ claims?: number;
426
+ /** Below this many removals, nothing is bounded. */
427
+ minFiles: number;
428
+ /**
429
+ * Above `minFiles`, the largest fraction of `held` one removal may take.
430
+ */
431
+ maxRatio: number;
432
+ }
433
+ /** What {@link planRemovals} decided about a peer's deletions. */
434
+ export interface RemovalPlan {
435
+ /** Paths to delete here. */
436
+ apply: string[];
437
+ /**
438
+ * Paths refused because this node has NEWER work on them.
439
+ *
440
+ * A removal is a statement about a state. A node that has since re-created
441
+ * the path has moved past that state, and applying the removal would undo
442
+ * newer work on the authority of an older edit.
443
+ */
444
+ staler: string[];
445
+ /**
446
+ * Whether the whole set was refused for being too large.
447
+ *
448
+ * The mass-delete circuit breaker, applied here for the same reason
449
+ * `@rljson/mongo-agent` applies it to tombstone application: an explicit
450
+ * removal list bypasses the ancestry check by design, so it must not also
451
+ * bypass the bound on how much one message may destroy.
452
+ */
453
+ blocked: boolean;
454
+ }
455
+ /**
456
+ * Which of a peer's deletions to apply here.
457
+ *
458
+ * **Why an explicit list is needed at all.** A tree records what a folder
459
+ * holds, so a deletion reaches a peer only as an absence — and an absence is
460
+ * indistinguishable from a state that merely predates the file. fs infers the
461
+ * difference from ancestry (`senderSawMyState`), which works only while the
462
+ * ancestor can be resolved. A partitioned node's ancestor cannot, and that is
463
+ * the measured data loss: the deleted file comes back on the node that deleted
464
+ * it. A removal carried in the chain is a FACT rather than an inference, and it
465
+ * is the authorisation ancestry could not supply.
466
+ *
467
+ * **Which is exactly why it is bounded twice.** It deletes without asking the
468
+ * ancestry rule, so recency and volume are the only guards left:
469
+ *
470
+ * - **recency**, by `timeId`. Minted once by the node that made the edit, so
471
+ * every node orders the same pair the same way. A removal older than this
472
+ * node's own newest edit to that path is refused.
473
+ * - **volume**, by the mass-delete circuit breaker. Below
474
+ * `minFiles` nothing is bounded — emptying a three-file folder is an
475
+ * ordinary edit — and above it a removal of more than `maxRatio` of what
476
+ * this node holds is refused wholesale.
477
+ * @param opts - The removal and this node's state; see
478
+ * {@link RemovalQuestion}.
479
+ * @returns What to delete, what was refused as stale, and whether the whole
480
+ * set was blocked.
481
+ */
482
+ export declare const planRemovals: (opts: RemovalQuestion) => RemovalPlan;
483
+ /**
484
+ * Above this many files, a removal covering the WHOLE folder is refused.
485
+ *
486
+ * The user's rule — *protect whenever ALL files would vanish* — against the
487
+ * reason the ratio guard has a floor at all: a folder of one or four files
488
+ * loses all of them as ordinary work, and so does a rename, which removes
489
+ * every path it holds and adds them back under new names.
490
+ *
491
+ * Ten is the line between those two facts. Below it, "the whole folder" is a
492
+ * handful of files and emptying it is an edit; above it, one peer's loss
493
+ * taking everybody's copy is the measured failure
494
+ * (`a small folder survives a wiped peer too`, 40 files).
495
+ *
496
+ * It is a refusal and not a question, because the agent has no one to ask.
497
+ * The decision called for *"protect, and ask"*; the asking belongs to a host
498
+ * that can show a user a dialogue, and until one does this errs towards
499
+ * keeping files.
500
+ */
501
+ export declare const ALL_GONE_MIN_FILES = 10;
502
+ /** What {@link planJoin} is asked. */
503
+ export interface JoinQuestion {
504
+ /**
505
+ * The hub head's tree, `path → content hash`.
506
+ *
507
+ * Materialised VIRTUALLY — nothing is written until the plan says so. The
508
+ * point of the whole exercise is to decide before touching the folder.
509
+ */
510
+ head: ReadonlyMap<string, string>;
511
+ /** This folder as it stands, `path → content hash`. */
512
+ folder: ReadonlyMap<string, string>;
513
+ /**
514
+ * Paths the history states were REMOVED and never re-added.
515
+ *
516
+ * The net removals over the WHOLE history — `collectRemovals` with no stop
517
+ * state, which walks to the root and lets a re-add cancel a removal in
518
+ * order. This is the one fact that separates a stale copy from new work, and
519
+ * no filesystem can supply it.
520
+ */
521
+ removedEver: ReadonlySet<string>;
522
+ /**
523
+ * Whether a head was found at all.
524
+ *
525
+ * No head means no history exists anywhere, so this folder IS the origin and
526
+ * its contents are its first state. Absence of a head is NOT the same as an
527
+ * empty head: an empty head is a fleet that has agreed the folder is empty,
528
+ * and its emptiness is a fact to be applied.
529
+ */
530
+ haveHead: boolean;
531
+ }
532
+ /** What {@link planJoin} concluded, per path. */
533
+ export interface JoinPlan {
534
+ /** In the head and missing or differing here — write the head's bytes. */
535
+ write: string[];
536
+ /**
537
+ * Here, unknown to the history — new local work. Announce it.
538
+ *
539
+ * A file nobody has ever mentioned cannot be a deletion anybody made, and
540
+ * dropping it is how a node loses its own work on joining.
541
+ */
542
+ announce: string[];
543
+ /**
544
+ * Here, and REMOVED by the history — a stale copy. Rename aside; do NOT
545
+ * announce.
546
+ *
547
+ * The restored-backup case. Announcing these would push content the fleet
548
+ * deliberately deleted back to every node, one file at a time, under names
549
+ * nobody deleted — for a folder restored from last month's backup that is
550
+ * thousands of files. So the bytes are kept where their owner can see them
551
+ * and nothing is said about them. **That is a deliberate, visible local
552
+ * divergence**, chosen over resurrecting a deletion or destroying a file.
553
+ */
554
+ recover: string[];
555
+ /**
556
+ * In the head AND here with different bytes — a real conflict.
557
+ *
558
+ * The case the stated algorithm does not name, because it is neither
559
+ * "missing here" nor "additional here": the path is live on both sides and
560
+ * was edited while this node was away. The head's bytes are written (the
561
+ * chain wins on what it states) and the local bytes are kept aside as an
562
+ * ordinary conflict copy, which IS announced — an edit to a live path is
563
+ * exactly what conflict copies exist for.
564
+ */
565
+ conflict: string[];
566
+ }
567
+ /**
568
+ * Decides what joining a network does to a folder, before anything is written.
569
+ *
570
+ * **The chain applies first; the filesystem only then.** A joining node used to
571
+ * author a lineage root from whatever it happened to hold and push it as the
572
+ * network's newest claim. That is one defect wearing two faces: every node got
573
+ * its own lineage root, so `classify` answered `fork` to every announcement
574
+ * ever made; and a node restored from a backup pushed deleted files back to the
575
+ * whole fleet.
576
+ *
577
+ * Every question here is answered against the chain. The folder is consulted
578
+ * only for what it holds — never for what that means.
579
+ * @param q - The head, the folder, and what the history says was removed.
580
+ * @returns The per-path plan; every path appears in at most one bucket.
581
+ */
582
+ export declare const planJoin: (q: JoinQuestion) => JoinPlan;
@@ -0,0 +1,32 @@
1
+ /**
2
+ * Translates a glob into an anchored, case-insensitive regular expression.
3
+ *
4
+ * `*` and `?` stop at a separator, `**` crosses them. A `**` followed by `/`
5
+ * also matches ZERO directories, so `**\/x` matches `x` at the root as well as
6
+ * at any depth — the one piece of gitignore's behaviour that is not obvious
7
+ * from the characters.
8
+ * @param glob - The pattern, separators already normalised to `/`.
9
+ * @returns A regular expression matching the whole string.
10
+ */
11
+ export declare const globToRegExp: (glob: string) => RegExp;
12
+ /** Decides whether a path is ignored. Compiled once, asked many times. */
13
+ export interface IgnoreMatcher {
14
+ /**
15
+ * @param relativePath - Path relative to the sync root, either separator.
16
+ * @param isDirectory - Pass it when known; a directory-only pattern needs it.
17
+ * @returns True when the sync must not see this path.
18
+ */
19
+ ignores(relativePath: string, isDirectory?: boolean): boolean;
20
+ }
21
+ /**
22
+ * Compiles an ignore list into a matcher.
23
+ *
24
+ * **Order matters, and the LAST match decides** — the gitignore rule, and the
25
+ * only one under which `!` can mean anything: `['*.log', '!keep.log']` keeps
26
+ * `keep.log` and `['!keep.log', '*.log']` does not. One caveat inherited with
27
+ * the semantics: the scanner does not descend into an ignored directory, so a
28
+ * `!` line cannot rescue a file inside one.
29
+ * @param patterns - The ignore list, in the order it was written.
30
+ * @returns A matcher over those patterns.
31
+ */
32
+ export declare const compileIgnore: (patterns: readonly string[] | undefined) => IgnoreMatcher;