@rljson/fs-agent 0.2.2 → 0.2.3

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.
package/dist/fs-agent.js CHANGED
@@ -443,6 +443,183 @@ var FsBlobAdapter = class FsBlobAdapter {
443
443
  }
444
444
  };
445
445
  //#endregion
446
+ //#region src/fs-carry.ts
447
+ // @license
448
+ /**
449
+ * A node's path, `.` for the root.
450
+ * @param node - The node.
451
+ * @returns Its relative path.
452
+ */
453
+ var pathOf = (node) => node.meta.relativePath;
454
+ /**
455
+ * Whether a node is a directory.
456
+ * @param node - The node.
457
+ * @returns True for a directory.
458
+ */
459
+ var isDirectory = (node) => node.meta.type === "directory";
460
+ /**
461
+ * The directory holding a path, `.` for a top-level one.
462
+ * @param path - A relative path other than `.`.
463
+ * @returns Its parent.
464
+ */
465
+ var parentOf = (path) => {
466
+ const slash = path.lastIndexOf("/");
467
+ return slash < 0 ? "." : path.slice(0, slash);
468
+ };
469
+ /**
470
+ * How deep a path is: `.` is 0, a top-level path 1.
471
+ * @param path - A relative path.
472
+ * @returns Its depth.
473
+ */
474
+ var depthOf = (path) => path === "." ? 0 : path.split("/").length;
475
+ /**
476
+ * The nodes of a tree a scan with this ignore rule leaves out.
477
+ *
478
+ * Walked from the root, as the scanner walks the folder: an ignored directory
479
+ * is taken whole, with everything below it, and nothing below it is asked.
480
+ * @param tree - The tree, typically a head's.
481
+ * @param ignores - The scanner's rule: a path, and whether it is a directory.
482
+ * @returns The left-out nodes, files and directories, by path.
483
+ */
484
+ var carriedNodes = (tree, ignores) => {
485
+ const carried = /* @__PURE__ */ new Map();
486
+ const childrenOf = (node) => node?.children ?? [];
487
+ const take = (node) => {
488
+ carried.set(pathOf(node), node);
489
+ for (const hash of childrenOf(node)) {
490
+ const child = tree.trees.get(hash);
491
+ if (child) take(child);
492
+ }
493
+ };
494
+ const visit = (node) => {
495
+ for (const hash of childrenOf(node)) {
496
+ const child = tree.trees.get(hash);
497
+ if (!child) continue;
498
+ if (ignores(pathOf(child), isDirectory(child))) take(child);
499
+ else if (isDirectory(child)) visit(child);
500
+ }
501
+ };
502
+ visit(tree.trees.get(tree.rootHash));
503
+ return carried;
504
+ };
505
+ /**
506
+ * A file node holding a version of another file under a new path — a merge
507
+ * keeping both versions of one file.
508
+ * @param path - Where the version is kept.
509
+ * @param blobId - The version.
510
+ * @param size - Its size in bytes.
511
+ * @returns The node, hashed, in the scanner's own format.
512
+ */
513
+ var fileNode = (path, blobId, size) => {
514
+ const name = path.slice(path.lastIndexOf("/") + 1);
515
+ const node = {
516
+ id: name,
517
+ isParent: false,
518
+ meta: {
519
+ name,
520
+ type: "file",
521
+ relativePath: path,
522
+ size,
523
+ blobId
524
+ },
525
+ children: null
526
+ };
527
+ hip(node);
528
+ return node;
529
+ };
530
+ /**
531
+ * A tree holding what `tree` holds and the carried nodes besides — built as
532
+ * the scanner builds one, so a folder that holds its carried paths after all
533
+ * gives the same ref either way.
534
+ *
535
+ * The folder's own entries come first: a carried path the scan holds itself
536
+ * is not carried, and neither is one below a path the scan holds as a file.
537
+ * A directory a carried path needs and the scan lacks — the folder lost it
538
+ * around a file it does not see — is put back, holding just that.
539
+ * @param tree - The folder, as scanned.
540
+ * @param carried - What to carry, by path — see {@link carriedNodes}. A file
541
+ * node is used as it is; every directory is rebuilt from its children.
542
+ * @returns The tree, and the carried paths it holds; `tree` itself when it
543
+ * holds none of them.
544
+ */
545
+ var graftTree = (tree, carried) => {
546
+ const added = /* @__PURE__ */ new Map();
547
+ if (carried.size === 0) return {
548
+ tree,
549
+ carried: added
550
+ };
551
+ const scanned = /* @__PURE__ */ new Map();
552
+ for (const node of tree.trees.values()) scanned.set(pathOf(node), node);
553
+ for (const path of [...carried.keys()].sort((a, b) => depthOf(a) - depthOf(b))) {
554
+ if (scanned.has(path)) continue;
555
+ let fits = true;
556
+ for (let at = parentOf(path); at !== "."; at = parentOf(at)) {
557
+ const holder = scanned.get(at) ?? added.get(at);
558
+ if (holder !== void 0 && !isDirectory(holder)) {
559
+ fits = false;
560
+ break;
561
+ }
562
+ }
563
+ if (fits) added.set(path, carried.get(path));
564
+ }
565
+ if (added.size === 0) return {
566
+ tree,
567
+ carried: added
568
+ };
569
+ const touched = /* @__PURE__ */ new Set();
570
+ for (const [path, node] of added) {
571
+ if (isDirectory(node)) touched.add(path);
572
+ for (let at = parentOf(path);; at = parentOf(at)) {
573
+ touched.add(at);
574
+ if (at === ".") break;
575
+ }
576
+ }
577
+ const members = /* @__PURE__ */ new Map();
578
+ const enter = (path) => {
579
+ if (path === ".") return;
580
+ const parent = parentOf(path);
581
+ if (!touched.has(parent)) return;
582
+ const list = members.get(parent);
583
+ if (list) list.push(path);
584
+ else members.set(parent, [path]);
585
+ };
586
+ for (const path of scanned.keys()) enter(path);
587
+ for (const path of added.keys()) if (!touched.has(path)) enter(path);
588
+ for (const path of touched) if (!scanned.has(path)) enter(path);
589
+ const trees = new Map(tree.trees);
590
+ for (const path of touched) {
591
+ const old = scanned.get(path);
592
+ if (old) trees.delete(old._hash);
593
+ }
594
+ for (const node of added.values()) if (!isDirectory(node)) trees.set(node._hash, node);
595
+ const rebuilt = /* @__PURE__ */ new Map();
596
+ for (const path of [...touched].sort((a, b) => depthOf(b) - depthOf(a))) {
597
+ const children = (members.get(path) ?? []).map((child) => (rebuilt.get(child) ?? scanned.get(child) ?? added.get(child))?._hash).sort();
598
+ const name = path === "." ? "." : path.slice(path.lastIndexOf("/") + 1);
599
+ const meta = {
600
+ name,
601
+ type: "directory",
602
+ relativePath: path
603
+ };
604
+ const node = {
605
+ id: name,
606
+ isParent: children.length > 0,
607
+ meta,
608
+ children: children.length > 0 ? children : null
609
+ };
610
+ hip(node);
611
+ rebuilt.set(path, node);
612
+ trees.set(node._hash, node);
613
+ }
614
+ return {
615
+ tree: {
616
+ rootHash: rebuilt.get(".")?._hash,
617
+ trees
618
+ },
619
+ carried: added
620
+ };
621
+ };
622
+ //#endregion
446
623
  //#region src/fs-db-adapter.ts
447
624
  // @license
448
625
  /**
@@ -969,6 +1146,153 @@ var planJoin = (q) => {
969
1146
  };
970
1147
  };
971
1148
  //#endregion
1149
+ //#region src/fs-ignore.ts
1150
+ // @license
1151
+ /** Characters whose presence makes a pattern a glob rather than a prefix. */
1152
+ var GLOB_CHARS = /[*?/\\]/;
1153
+ /**
1154
+ * Escapes the regular-expression metacharacters that are NOT glob syntax.
1155
+ *
1156
+ * `*` and `?` are handled by the translator and must not reach this.
1157
+ * @param text - A run of literal characters from a glob.
1158
+ * @returns The same text, safe to embed in a regular expression.
1159
+ */
1160
+ var escapeLiteral = (text) => text.replace(/[.+^${}()|[\]\\\-]/g, "\\$&");
1161
+ /**
1162
+ * Translates a glob into an anchored, case-insensitive regular expression.
1163
+ *
1164
+ * `*` and `?` stop at a separator, `**` crosses them. A `**` followed by `/`
1165
+ * also matches ZERO directories, so `**\/x` matches `x` at the root as well as
1166
+ * at any depth — the one piece of gitignore's behaviour that is not obvious
1167
+ * from the characters.
1168
+ * @param glob - The pattern, separators already normalised to `/`.
1169
+ * @returns A regular expression matching the whole string.
1170
+ */
1171
+ var globToRegExp = (glob) => {
1172
+ let out = "";
1173
+ for (let i = 0; i < glob.length; i++) {
1174
+ const char = glob[i];
1175
+ if (char === "*") {
1176
+ if (glob[i + 1] === "*") {
1177
+ i++;
1178
+ if (glob[i + 1] === "/") {
1179
+ out += "(?:[^/]+/)*";
1180
+ i++;
1181
+ } else out += ".*";
1182
+ } else out += "[^/]*";
1183
+ } else if (char === "?") out += "[^/]";
1184
+ else out += escapeLiteral(char);
1185
+ }
1186
+ return new RegExp(`^${out}$`, "i");
1187
+ };
1188
+ /**
1189
+ * Normalises a path the way every comparison here expects it.
1190
+ *
1191
+ * Windows separators become `/`, a leading `./` or `/` goes, and a trailing
1192
+ * `/` goes — so one path has one spelling whichever side produced it. The
1193
+ * watcher reports `sub\dir\file` on Windows and `sub/dir/file` elsewhere for
1194
+ * the same file.
1195
+ * @param path - A path relative to the sync root.
1196
+ * @returns The normalised form.
1197
+ */
1198
+ var normalise = (path) => {
1199
+ const slashed = path.replace(/\\/g, "/").replace(/^\.\//, "").replace(/^\/+/, "").replace(/\/+$/, "");
1200
+ return slashed === "." ? "" : slashed;
1201
+ };
1202
+ /**
1203
+ * Compiles one line of an ignore list.
1204
+ * @param pattern - The line, as the user or the product wrote it.
1205
+ * @returns The rule, or undefined for a blank line or a `#` comment.
1206
+ */
1207
+ var compileRule = (pattern) => {
1208
+ const trimmed = pattern.trim();
1209
+ if (trimmed === "" || trimmed.startsWith("#")) return void 0;
1210
+ const negated = trimmed.startsWith("!");
1211
+ const body = negated ? trimmed.slice(1) : trimmed;
1212
+ if (!negated && !GLOB_CHARS.test(body)) return {
1213
+ negated: false,
1214
+ dirOnly: false,
1215
+ kind: "literal",
1216
+ literal: body,
1217
+ re: void 0
1218
+ };
1219
+ const dirOnly = /[/\\]$/.test(body);
1220
+ const glob = normalise(body);
1221
+ if (glob === "") return void 0;
1222
+ return {
1223
+ negated,
1224
+ dirOnly,
1225
+ kind: glob.includes("/") ? "path" : "segment",
1226
+ literal: glob,
1227
+ re: globToRegExp(glob)
1228
+ };
1229
+ };
1230
+ /**
1231
+ * Whether one rule covers a path.
1232
+ * @param rule - The compiled rule.
1233
+ * @param path - The normalised relative path.
1234
+ * @param segments - That path, split on `/`.
1235
+ * @param isDirectory - True, false, or undefined when the caller cannot say.
1236
+ * @returns True when the rule matches.
1237
+ */
1238
+ var ruleMatches = (rule, path, segments, isDirectory) => {
1239
+ if (rule.kind === "literal") return segments.some((segment) => segment === rule.literal || segment.startsWith(rule.literal));
1240
+ const re = rule.re;
1241
+ if (rule.kind === "segment") {
1242
+ const last = segments.length - 1;
1243
+ return segments.some((segment, index) => {
1244
+ if (!re.test(segment)) return false;
1245
+ if (!rule.dirOnly) return true;
1246
+ return index < last || isDirectory !== false;
1247
+ });
1248
+ }
1249
+ if (re.test(path) && !(rule.dirOnly && isDirectory === false)) return true;
1250
+ let ancestor = "";
1251
+ for (const segment of segments.slice(0, -1)) {
1252
+ ancestor = ancestor === "" ? segment : `${ancestor}/${segment}`;
1253
+ if (re.test(ancestor)) return true;
1254
+ }
1255
+ return false;
1256
+ };
1257
+ /**
1258
+ * Compiles an ignore list into a matcher.
1259
+ *
1260
+ * **Order matters, and the LAST match decides** — the gitignore rule, and the
1261
+ * only one under which `!` can mean anything: `['*.log', '!keep.log']` keeps
1262
+ * `keep.log` and `['!keep.log', '*.log']` does not. One caveat inherited with
1263
+ * the semantics: the scanner does not descend into an ignored directory, so a
1264
+ * `!` line cannot rescue a file inside one.
1265
+ * @param patterns - The ignore list, in the order it was written.
1266
+ * @returns A matcher over those patterns.
1267
+ */
1268
+ var compileIgnore = (patterns) => {
1269
+ const rules = [];
1270
+ for (const pattern of patterns ?? []) {
1271
+ const rule = compileRule(pattern);
1272
+ if (rule !== void 0) rules.push(rule);
1273
+ }
1274
+ const ignores = (relativePath, isDirectory) => {
1275
+ const path = normalise(relativePath);
1276
+ if (path === "") return false;
1277
+ const segments = path.split("/").filter((s) => s !== "");
1278
+ let ignored = false;
1279
+ for (const rule of rules) if (ruleMatches(rule, path, segments, isDirectory)) ignored = !rule.negated;
1280
+ return ignored;
1281
+ };
1282
+ return {
1283
+ ignores,
1284
+ excludes: (relativePath, isDirectory) => {
1285
+ const segments = normalise(relativePath).split("/").filter((s) => s !== "");
1286
+ let above = "";
1287
+ for (const segment of segments.slice(0, -1)) {
1288
+ above = above === "" ? segment : `${above}/${segment}`;
1289
+ if (ignores(above, true)) return true;
1290
+ }
1291
+ return ignores(relativePath, isDirectory);
1292
+ }
1293
+ };
1294
+ };
1295
+ //#endregion
972
1296
  //#region src/fs-merge.ts
973
1297
  // @license
974
1298
  /** The value a directory has in a {@link ContentMap}. */
@@ -1668,141 +1992,6 @@ var planAuthoring = (q) => {
1668
1992
  };
1669
1993
  };
1670
1994
  //#endregion
1671
- //#region src/fs-ignore.ts
1672
- // @license
1673
- /** Characters whose presence makes a pattern a glob rather than a prefix. */
1674
- var GLOB_CHARS = /[*?/\\]/;
1675
- /**
1676
- * Escapes the regular-expression metacharacters that are NOT glob syntax.
1677
- *
1678
- * `*` and `?` are handled by the translator and must not reach this.
1679
- * @param text - A run of literal characters from a glob.
1680
- * @returns The same text, safe to embed in a regular expression.
1681
- */
1682
- var escapeLiteral = (text) => text.replace(/[.+^${}()|[\]\\\-]/g, "\\$&");
1683
- /**
1684
- * Translates a glob into an anchored, case-insensitive regular expression.
1685
- *
1686
- * `*` and `?` stop at a separator, `**` crosses them. A `**` followed by `/`
1687
- * also matches ZERO directories, so `**\/x` matches `x` at the root as well as
1688
- * at any depth — the one piece of gitignore's behaviour that is not obvious
1689
- * from the characters.
1690
- * @param glob - The pattern, separators already normalised to `/`.
1691
- * @returns A regular expression matching the whole string.
1692
- */
1693
- var globToRegExp = (glob) => {
1694
- let out = "";
1695
- for (let i = 0; i < glob.length; i++) {
1696
- const char = glob[i];
1697
- if (char === "*") {
1698
- if (glob[i + 1] === "*") {
1699
- i++;
1700
- if (glob[i + 1] === "/") {
1701
- out += "(?:[^/]+/)*";
1702
- i++;
1703
- } else out += ".*";
1704
- } else out += "[^/]*";
1705
- } else if (char === "?") out += "[^/]";
1706
- else out += escapeLiteral(char);
1707
- }
1708
- return new RegExp(`^${out}$`, "i");
1709
- };
1710
- /**
1711
- * Normalises a path the way every comparison here expects it.
1712
- *
1713
- * Windows separators become `/`, a leading `./` or `/` goes, and a trailing
1714
- * `/` goes — so one path has one spelling whichever side produced it. The
1715
- * watcher reports `sub\dir\file` on Windows and `sub/dir/file` elsewhere for
1716
- * the same file.
1717
- * @param path - A path relative to the sync root.
1718
- * @returns The normalised form.
1719
- */
1720
- var normalise = (path) => {
1721
- const slashed = path.replace(/\\/g, "/").replace(/^\.\//, "").replace(/^\/+/, "").replace(/\/+$/, "");
1722
- return slashed === "." ? "" : slashed;
1723
- };
1724
- /**
1725
- * Compiles one line of an ignore list.
1726
- * @param pattern - The line, as the user or the product wrote it.
1727
- * @returns The rule, or undefined for a blank line or a `#` comment.
1728
- */
1729
- var compileRule = (pattern) => {
1730
- const trimmed = pattern.trim();
1731
- if (trimmed === "" || trimmed.startsWith("#")) return void 0;
1732
- const negated = trimmed.startsWith("!");
1733
- const body = negated ? trimmed.slice(1) : trimmed;
1734
- if (!negated && !GLOB_CHARS.test(body)) return {
1735
- negated: false,
1736
- dirOnly: false,
1737
- kind: "literal",
1738
- literal: body,
1739
- re: void 0
1740
- };
1741
- const dirOnly = /[/\\]$/.test(body);
1742
- const glob = normalise(body);
1743
- if (glob === "") return void 0;
1744
- return {
1745
- negated,
1746
- dirOnly,
1747
- kind: glob.includes("/") ? "path" : "segment",
1748
- literal: glob,
1749
- re: globToRegExp(glob)
1750
- };
1751
- };
1752
- /**
1753
- * Whether one rule covers a path.
1754
- * @param rule - The compiled rule.
1755
- * @param path - The normalised relative path.
1756
- * @param segments - That path, split on `/`.
1757
- * @param isDirectory - True, false, or undefined when the caller cannot say.
1758
- * @returns True when the rule matches.
1759
- */
1760
- var ruleMatches = (rule, path, segments, isDirectory) => {
1761
- if (rule.kind === "literal") return segments.some((segment) => segment === rule.literal || segment.startsWith(rule.literal));
1762
- const re = rule.re;
1763
- if (rule.kind === "segment") {
1764
- const last = segments.length - 1;
1765
- return segments.some((segment, index) => {
1766
- if (!re.test(segment)) return false;
1767
- if (!rule.dirOnly) return true;
1768
- return index < last || isDirectory !== false;
1769
- });
1770
- }
1771
- if (re.test(path) && !(rule.dirOnly && isDirectory === false)) return true;
1772
- let ancestor = "";
1773
- for (const segment of segments.slice(0, -1)) {
1774
- ancestor = ancestor === "" ? segment : `${ancestor}/${segment}`;
1775
- if (re.test(ancestor)) return true;
1776
- }
1777
- return false;
1778
- };
1779
- /**
1780
- * Compiles an ignore list into a matcher.
1781
- *
1782
- * **Order matters, and the LAST match decides** — the gitignore rule, and the
1783
- * only one under which `!` can mean anything: `['*.log', '!keep.log']` keeps
1784
- * `keep.log` and `['!keep.log', '*.log']` does not. One caveat inherited with
1785
- * the semantics: the scanner does not descend into an ignored directory, so a
1786
- * `!` line cannot rescue a file inside one.
1787
- * @param patterns - The ignore list, in the order it was written.
1788
- * @returns A matcher over those patterns.
1789
- */
1790
- var compileIgnore = (patterns) => {
1791
- const rules = [];
1792
- for (const pattern of patterns ?? []) {
1793
- const rule = compileRule(pattern);
1794
- if (rule !== void 0) rules.push(rule);
1795
- }
1796
- return { ignores: (relativePath, isDirectory) => {
1797
- const path = normalise(relativePath);
1798
- if (path === "") return false;
1799
- const segments = path.split("/").filter((s) => s !== "");
1800
- let ignored = false;
1801
- for (const rule of rules) if (ruleMatches(rule, path, segments, isDirectory)) ignored = !rule.negated;
1802
- return ignored;
1803
- } };
1804
- };
1805
- //#endregion
1806
1995
  //#region src/fs-scanner.ts
1807
1996
  // @license
1808
1997
  /**
@@ -1934,6 +2123,10 @@ var FsScanner = class FsScanner {
1934
2123
  this._bs = options.bs || new BsMem();
1935
2124
  this._scanCachePath = options.scanCachePath;
1936
2125
  }
2126
+ /** The ignore list this scanner applies, in order, as it was given. */
2127
+ get ignore() {
2128
+ return this._options.ignore;
2129
+ }
1937
2130
  get tree() {
1938
2131
  return this._tree;
1939
2132
  }
@@ -2244,10 +2437,21 @@ var FsScanner = class FsScanner {
2244
2437
  * Whether the sync never sees a path: the ignore list, as the scan applies
2245
2438
  * it.
2246
2439
  * @param relativePath - Relative to the root, either separator.
2440
+ * @param isDirectory - Whether the path is a directory, when known.
2247
2441
  * @returns `true` when no tree of this folder can hold the path.
2248
2442
  */
2249
- ignores(relativePath) {
2250
- return this._shouldIgnorePath(relativePath);
2443
+ ignores(relativePath, isDirectory) {
2444
+ return this._shouldIgnorePath(relativePath, isDirectory);
2445
+ }
2446
+ /**
2447
+ * Whether a scan leaves a path out: the path, or a directory above it — see
2448
+ * {@link IgnoreMatcher.excludes}.
2449
+ * @param relativePath - Relative to the root, either separator.
2450
+ * @param isDirectory - Whether the path is a directory.
2451
+ * @returns `true` when no scan of this folder holds the path.
2452
+ */
2453
+ excludes(relativePath, isDirectory) {
2454
+ return this._ignoreMatcher.excludes(relativePath, isDirectory);
2251
2455
  }
2252
2456
  async watch() {
2253
2457
  if (this._watcher) throw new Error("Already watching. Call stopWatch() first.");
@@ -2752,6 +2956,14 @@ var REPAIR_ACTION = {
2752
2956
  deferred: "blocked",
2753
2957
  blocked: "blocked"
2754
2958
  };
2959
+ /**
2960
+ * Whether two ignore lists are the same list: the same patterns in the same
2961
+ * order — order decides what a `!` line rescues.
2962
+ * @param a - One list.
2963
+ * @param b - The other.
2964
+ * @returns True when they are equal.
2965
+ */
2966
+ var sameList = (a, b) => a.length === b.length && a.every((pattern, i) => pattern === b[i]);
2755
2967
  /** The longest a node waits between two announcements asking for its stamp. */
2756
2968
  var STAMP_ASK_MAX_MS = 3e4;
2757
2969
  /**
@@ -3019,6 +3231,7 @@ var FsAgent = class FsAgent {
3019
3231
  ],
3020
3232
  bs: this._bs
3021
3233
  });
3234
+ this._ignoreOnRecord = this._scanner.ignore;
3022
3235
  this._adapter = new FsBlobAdapter(this._bs);
3023
3236
  }
3024
3237
  /**
@@ -3160,8 +3373,10 @@ var FsAgent = class FsAgent {
3160
3373
  * @param conflicted - Paths edited here while away and changed elsewhere.
3161
3374
  * @param copies - Where each moved file went, `path → name`; a path the
3162
3375
  * join could not move has no entry.
3376
+ * @param why - `away`: the machine joined the network; `ignore`: it sees
3377
+ * paths again that its ignore list had left out.
3163
3378
  */
3164
- _signalJoinOutcome(recovered, conflicted, copies) {
3379
+ _signalJoinOutcome(recovered, conflicted, copies, why = "away") {
3165
3380
  if (recovered.length > 0) this._signal({
3166
3381
  kind: "join/recovered",
3167
3382
  paths: recovered,
@@ -3176,7 +3391,7 @@ var FsAgent = class FsAgent {
3176
3391
  copies,
3177
3392
  action: "review",
3178
3393
  decidedBy: "chain",
3179
- detail: `${conflicted.length} file(s) were edited on this machine while it was away and also changed on the network; both versions were kept`
3394
+ detail: why === "away" ? `${conflicted.length} file(s) were edited on this machine while it was away and also changed on the network; both versions were kept` : `${conflicted.length} file(s) this machine had left out of the sync differ from the network's; both versions were kept`
3180
3395
  });
3181
3396
  }
3182
3397
  /**
@@ -3438,8 +3653,12 @@ var FsAgent = class FsAgent {
3438
3653
  this._restoreImpossible.push(meta.relativePath);
3439
3654
  return;
3440
3655
  }
3656
+ if (this._leavesOut(meta, isOwnRoot)) return;
3441
3657
  const filePath = join(targetPath, meta.relativePath);
3442
- await this._makeRoomFor(filePath, "file");
3658
+ if (!await this._makeRoomFor(filePath, "file", isOwnRoot ? meta.relativePath : void 0)) {
3659
+ this._restoreImpossible.push(meta.relativePath);
3660
+ return;
3661
+ }
3443
3662
  /* v8 ignore else -- @preserve */
3444
3663
  if (meta.blobId) {
3445
3664
  if (await this._alreadyOnDisk(filePath, meta, isOwnRoot)) {
@@ -3513,8 +3732,12 @@ var FsAgent = class FsAgent {
3513
3732
  this._restoreImpossible.push(meta.relativePath);
3514
3733
  return;
3515
3734
  }
3735
+ if (this._leavesOut(meta, isOwnRoot)) return;
3516
3736
  const dirPath = meta.relativePath === "." ? targetPath : join(targetPath, meta.relativePath);
3517
- if (meta.relativePath !== ".") await this._makeRoomFor(dirPath, "directory");
3737
+ if (meta.relativePath !== "." && !await this._makeRoomFor(dirPath, "directory", isOwnRoot ? meta.relativePath : void 0)) {
3738
+ this._restoreImpossible.push(meta.relativePath);
3739
+ return;
3740
+ }
3518
3741
  await mkdir(dirPath, { recursive: true });
3519
3742
  /* v8 ignore else -- @preserve */
3520
3743
  if (treeNode.children && Array.isArray(treeNode.children)) {
@@ -3606,7 +3829,10 @@ var FsAgent = class FsAgent {
3606
3829
  * followed to decide what to remove.
3607
3830
  * @param path - Where the node is to be written.
3608
3831
  * @param want - What the tree says should be there.
3609
- * @returns Whether something had to be removed.
3832
+ * @param relativePath - The path in the folder, when restoring into this
3833
+ * node's own: an entry there this node ignores is never removed.
3834
+ * @returns Whether the place is free for the node now; `false` when an
3835
+ * entry this node ignores holds it.
3610
3836
  */
3611
3837
  /**
3612
3838
  * Whether a path the prune is about to delete is actually the expected file
@@ -3630,11 +3856,27 @@ var FsAgent = class FsAgent {
3630
3856
  if (same) console.warn(`${this._tag} restore: kept "${fullPath}" — the tree spells it "${expected}" and this filesystem treats them as one file`);
3631
3857
  return same;
3632
3858
  }
3633
- async _makeRoomFor(path, want) {
3859
+ /**
3860
+ * Whether a restore leaves a node out: what this node does not see, it does
3861
+ * not write into its folder — a directory with everything below it. Another
3862
+ * node's version of such a path is carried in its edits, never put on its
3863
+ * disk. Anywhere else a tree is just a tree.
3864
+ * @param meta - The node's meta.
3865
+ * @param isOwnRoot - Whether the restore writes into this node's folder.
3866
+ * @returns True when the node is not to be written.
3867
+ */
3868
+ _leavesOut(meta, isOwnRoot) {
3869
+ return isOwnRoot && meta.relativePath !== "." && this._scanner.ignores(meta.relativePath, meta.type === "directory");
3870
+ }
3871
+ async _makeRoomFor(path, want, relativePath) {
3634
3872
  const existing = await lstat(path).catch(() => void 0);
3635
- if (existing === void 0) return false;
3873
+ if (existing === void 0) return true;
3636
3874
  const isDir = existing.isDirectory();
3637
- if (isDir === (want === "directory")) return false;
3875
+ if (isDir === (want === "directory")) return true;
3876
+ if (relativePath !== void 0 && this._scanner.excludes(relativePath, isDir)) {
3877
+ console.warn(`${this._tag} restore: "${path}" is a ${isDir ? "directory" : "file"} this node ignores and the tree says ${want} — left as it is`);
3878
+ return false;
3879
+ }
3638
3880
  await rm(path, {
3639
3881
  recursive: true,
3640
3882
  force: true
@@ -3969,6 +4211,26 @@ var FsAgent = class FsAgent {
3969
4211
  * restart the floors judge what is gone afresh, as before.
3970
4212
  */
3971
4213
  _heldBack = /* @__PURE__ */ new Set();
4214
+ /**
4215
+ * The own head's nodes at the paths this node does not see — see
4216
+ * `fs-carry.ts`. Carried into every edit it authors; an apply neither writes
4217
+ * nor deletes them. Empty while the head names nothing this node ignores.
4218
+ */
4219
+ _carried = /* @__PURE__ */ new Map();
4220
+ /**
4221
+ * Paths this node sees again since a pattern left its ignore list, whose
4222
+ * version the own head holds is not in the folder yet. Carried until it is —
4223
+ * see {@link FsAgent._uncover}.
4224
+ */
4225
+ _uncovered = /* @__PURE__ */ new Set();
4226
+ /** A restart found its ignore list changed, and `_uncover` has not run. */
4227
+ _uncoverDue = false;
4228
+ /**
4229
+ * The ignore list the state file records: the one the folder is in step
4230
+ * with. It becomes the scanner's list once nothing a change of the list
4231
+ * uncovered is still missing.
4232
+ */
4233
+ _ignoreOnRecord = [];
3972
4234
  /** Every chain entry's stamp, as this node learned it. */
3973
4235
  _stamps;
3974
4236
  /** The route this agent syncs, once a sync started. */
@@ -4180,9 +4442,25 @@ var FsAgent = class FsAgent {
4180
4442
  * @returns The head, or `undefined`.
4181
4443
  */
4182
4444
  _persistedHead() {
4445
+ const state = this._persistedState();
4446
+ return typeof state?.ownHead === "string" && state.ownHead !== "" ? state.ownHead : void 0;
4447
+ }
4448
+ /**
4449
+ * The ignore list `.fsagent-state.json` records, if it records one — the
4450
+ * list the folder was in step with when this node last ran.
4451
+ * @returns The list, or `undefined`.
4452
+ */
4453
+ _persistedIgnore() {
4454
+ const ignore = this._persistedState()?.ignore;
4455
+ return Array.isArray(ignore) && ignore.every((pattern) => typeof pattern === "string") ? ignore : void 0;
4456
+ }
4457
+ /**
4458
+ * `.fsagent-state.json`, read.
4459
+ * @returns What it holds, or `undefined` when it cannot be read.
4460
+ */
4461
+ _persistedState() {
4183
4462
  try {
4184
- const state = JSON.parse(readFileSync(join(this._rootPath, AGENT_STATE_FILE), "utf-8"));
4185
- return typeof state?.ownHead === "string" && state.ownHead !== "" ? state.ownHead : void 0;
4463
+ return JSON.parse(readFileSync(join(this._rootPath, AGENT_STATE_FILE), "utf-8"));
4186
4464
  } catch {
4187
4465
  return;
4188
4466
  }
@@ -4191,21 +4469,43 @@ var FsAgent = class FsAgent {
4191
4469
  * Makes `head` this node's head, and remembers it across a restart.
4192
4470
  * @param head - The chain entry.
4193
4471
  * @param content - The tree it names, `path → blob`.
4472
+ * @param carried - Its nodes at the paths this node does not see.
4194
4473
  */
4195
- _setOwn(head, content) {
4474
+ _setOwn(head, content, carried) {
4196
4475
  this._ownHead = head;
4197
4476
  this._ownContent = content;
4477
+ this._carried = carried;
4478
+ for (const path of this._uncovered) if (!content.has(path)) this._uncovered.delete(path);
4479
+ if (this._uncovered.size === 0 && !this._uncoverDue) this._ignoreOnRecord = this._scanner.ignore;
4198
4480
  this._partiallyApplied.clear();
4199
4481
  this._writeState();
4200
4482
  }
4201
- /** Writes {@link AGENT_STATE_FILE}: the own head and the stamp epochs. */
4483
+ /**
4484
+ * What a head's tree holds at the paths this node does not see: those its
4485
+ * ignore list leaves out, and those it sees again and does not hold yet.
4486
+ * @param tree - The tree.
4487
+ * @returns The nodes, by path.
4488
+ */
4489
+ _carriedOf(tree) {
4490
+ const carried = carriedNodes(tree, (path, isDirectory) => this._scanner.ignores(path, isDirectory));
4491
+ if (this._uncovered.size > 0) for (const node of tree.trees.values()) {
4492
+ const path = node.meta.relativePath;
4493
+ if (this._uncovered.has(path)) carried.set(path, node);
4494
+ }
4495
+ return carried;
4496
+ }
4497
+ /**
4498
+ * Writes {@link AGENT_STATE_FILE}: the own head, the stamp epochs, and the
4499
+ * ignore list the folder is in step with.
4500
+ */
4202
4501
  _writeState() {
4203
4502
  const stampEpochs = this._stamps.epochs;
4204
4503
  this._writtenEpochs = JSON.stringify(stampEpochs);
4205
4504
  try {
4206
4505
  atomicWriteFileSync(join(this._rootPath, AGENT_STATE_FILE), JSON.stringify({
4207
4506
  ownHead: this._ownHead,
4208
- stampEpochs
4507
+ stampEpochs,
4508
+ ignore: this._ignoreOnRecord
4209
4509
  }));
4210
4510
  } catch (err) {
4211
4511
  this._writeSyncError("state/write", err);
@@ -4264,12 +4564,14 @@ var FsAgent = class FsAgent {
4264
4564
  this._announceOwn();
4265
4565
  }
4266
4566
  /**
4267
- * Authors an edit for the folder as `tree` describes it, if it moved past
4268
- * the own head and the edit is honest — see `planAuthoring`.
4269
- * @param tree - The folder, as just scanned.
4567
+ * Authors an edit for the folder as `scanned` describes it, if it moved past
4568
+ * the own head and the edit is honest — see `planAuthoring`. The paths this
4569
+ * node does not see are carried as the own head holds them.
4570
+ * @param scanned - The folder, as just scanned.
4270
4571
  */
4271
- async _author(tree) {
4572
+ async _author(scanned) {
4272
4573
  if (this._joinWait || !this._route || !this._chain) return;
4574
+ const { tree, carried } = graftTree(scanned, this._carried);
4273
4575
  const folder = this._getFileContentMap(tree);
4274
4576
  if (this._ownHead === void 0) {
4275
4577
  if (folder.size === 0) return;
@@ -4278,14 +4580,16 @@ var FsAgent = class FsAgent {
4278
4580
  treeRef,
4279
4581
  previous: []
4280
4582
  });
4281
- this._setOwn(root.head, folder);
4583
+ this._setOwn(root.head, folder, carried);
4282
4584
  this._watched.clear();
4283
4585
  this._announceOwn();
4284
4586
  return;
4285
4587
  }
4588
+ const head = this._partiallyApplied.size === 0 ? this._ownContent : new Map([...this._ownContent, ...this._partiallyApplied]);
4589
+ const seen = (content) => carried.size === 0 ? content : new Map([...content].filter(([path]) => !carried.has(path)));
4286
4590
  const plan = planAuthoring({
4287
- folder,
4288
- head: this._partiallyApplied.size === 0 ? this._ownContent : new Map([...this._ownContent, ...this._partiallyApplied]),
4591
+ folder: seen(folder),
4592
+ head: seen(head),
4289
4593
  watched: this._watched,
4290
4594
  minFiles: 100,
4291
4595
  maxRatio: MASS_DELETE_MAX_RATIO,
@@ -4310,7 +4614,7 @@ var FsAgent = class FsAgent {
4310
4614
  removed: plan.removed,
4311
4615
  previous: [this._ownHead]
4312
4616
  });
4313
- this._setOwn(entry.head, folder);
4617
+ this._setOwn(entry.head, folder, carried);
4314
4618
  this._watched.clear();
4315
4619
  this._announceOwn();
4316
4620
  }
@@ -4344,8 +4648,16 @@ var FsAgent = class FsAgent {
4344
4648
  const persisted = this._persistedHead();
4345
4649
  const resumed = persisted !== void 0 && await this._treeOf(persisted);
4346
4650
  if (resumed) {
4347
- this._setOwn(persisted, this._getFileContentMap(resumed.tree));
4348
- await this._exclusive(() => this._author(initial));
4651
+ const recorded = this._persistedIgnore();
4652
+ if (recorded !== void 0 && !sameList(recorded, this._scanner.ignore)) {
4653
+ this._ignoreOnRecord = recorded;
4654
+ this._uncoverDue = true;
4655
+ }
4656
+ this._setOwn(persisted, this._getFileContentMap(resumed.tree), this._carriedOf(resumed.tree));
4657
+ await this._exclusive(async () => {
4658
+ const moved = this._uncoverDue && await this._writing(() => this._uncover(persisted, resumed.tree, initial));
4659
+ await this._author(moved ? await this._scanner.scanFresh() : initial);
4660
+ });
4349
4661
  this._announceOwn();
4350
4662
  } else if (this._joinWaitMs > 0) this._startJoinWait();
4351
4663
  else await this._exclusive(() => this._author(initial));
@@ -4421,11 +4733,88 @@ var FsAgent = class FsAgent {
4421
4733
  for (const path of plan.conflict) await this._setAside(path, joinCopyName(path, Date.now(), taken), copies);
4422
4734
  this._signalJoinOutcome(plan.recover, plan.conflict, copies);
4423
4735
  await this.restore(joined.tree, void 0, { cleanTarget: false });
4424
- this._setOwn(head, headContent);
4736
+ this._setOwn(head, headContent, this._carriedOf(joined.tree));
4425
4737
  await this._author(await this._scanner.scanFresh());
4426
4738
  this._announceOwn();
4427
4739
  }
4428
4740
  /**
4741
+ * Joins the paths this node sees again: a pattern left its ignore list
4742
+ * since it last ran.
4743
+ *
4744
+ * While a path was ignored, this node neither wrote it nor deleted it, so
4745
+ * the folder can lack what the head holds there, or hold a version of its
4746
+ * own that never went anywhere. Authored as they stand, the first would
4747
+ * delete the network's files and the second overwrite them. So these paths
4748
+ * are joined as a joining folder is (`planJoin`): a version of this node's
4749
+ * own is set aside as a copy, one the history removed goes to
4750
+ * {@link RECOVERED_DIR}, one the history never named is new work — and the
4751
+ * head's version is written, and carried until it is there.
4752
+ * @param head - The own head.
4753
+ * @param headTree - Its tree.
4754
+ * @param folderTree - The folder, as just scanned.
4755
+ * @returns Whether anything in the folder was moved aside.
4756
+ */
4757
+ async _uncover(head, headTree, folderTree) {
4758
+ const was = compileIgnore(this._ignoreOnRecord);
4759
+ const seenAgain = (content) => new Map([...content].filter(([path, value]) => !this._carried.has(path) && was.excludes(path, value === "<dir>")));
4760
+ const folder = this._getFileContentMap(folderTree);
4761
+ const inHead = seenAgain(this._ownContent);
4762
+ const inFolder = seenAgain(folder);
4763
+ let changed = false;
4764
+ if (inHead.size > 0 || inFolder.size > 0) {
4765
+ const walk = await this._chain.collectRemovals(head, void 0).catch(() => void 0);
4766
+ const plan = planJoin({
4767
+ haveHead: true,
4768
+ head: inHead,
4769
+ folder: inFolder,
4770
+ removedEver: new Set(walk?.complete ? walk.removed : [])
4771
+ });
4772
+ const taken = /* @__PURE__ */ new Set([...folder.keys(), ...this._ownContent.keys()]);
4773
+ const copies = {};
4774
+ for (const path of plan.recover) await this._setAside(path, `${RECOVERED_DIR}/${recoveredName(path, taken)}`, copies);
4775
+ for (const path of plan.conflict) await this._setAside(path, joinCopyName(path, Date.now(), taken), copies);
4776
+ this._signalJoinOutcome(plan.recover, plan.conflict, copies, "ignore");
4777
+ for (const path of [...plan.write, ...plan.conflict]) this._uncovered.add(path);
4778
+ this._carried = this._carriedOf(headTree);
4779
+ changed = plan.recover.length + plan.conflict.length > 0;
4780
+ }
4781
+ this._uncoverDue = false;
4782
+ if (this._uncovered.size === 0) this._ignoreOnRecord = this._scanner.ignore;
4783
+ this._writeState();
4784
+ return changed;
4785
+ }
4786
+ /**
4787
+ * Writes the head's version of every path `_uncover` is waiting for that is
4788
+ * not in the folder — and stops carrying each one that is, whichever
4789
+ * version: a file somebody saved there meanwhile is their work, and the
4790
+ * next edit says so.
4791
+ *
4792
+ * Asked again with every head this node hears, so a version that could not
4793
+ * be fetched — this node started offline — arrives once it can be.
4794
+ */
4795
+ async _takeUncovered() {
4796
+ if (this._uncovered.size === 0) return;
4797
+ const there = (path) => lstat(join(this._rootPath, ...path.split("/"))).then(() => true, () => false);
4798
+ const missing = [];
4799
+ for (const path of this._uncovered) if (!await there(path)) missing.push(path);
4800
+ if (missing.length > 0) try {
4801
+ const own = await this._treeOf(this._ownHead);
4802
+ if (!own) throw new Error("the own head cannot be read");
4803
+ await this._restorePaths(own.tree, missing);
4804
+ } catch (err) {
4805
+ this._writeSyncError("uncover", err);
4806
+ }
4807
+ const arrived = /* @__PURE__ */ new Set();
4808
+ for (const path of this._uncovered) if (await there(path)) arrived.add(path);
4809
+ if (arrived.size === 0) return;
4810
+ for (const path of arrived) this._uncovered.delete(path);
4811
+ this._carried = new Map([...this._carried].filter(([path]) => !arrived.has(path)));
4812
+ if (this._uncovered.size === 0) {
4813
+ this._ignoreOnRecord = this._scanner.ignore;
4814
+ this._writeState();
4815
+ }
4816
+ }
4817
+ /**
4429
4818
  * Hears a head — from an announcement, a bootstrap or a state beacon.
4430
4819
  * @param head - The head.
4431
4820
  * @param stamp - The stamp it arrived with, if any.
@@ -4540,7 +4929,10 @@ var FsAgent = class FsAgent {
4540
4929
  const chain = this._chain;
4541
4930
  return {
4542
4931
  ownHead: () => this._ownHead,
4543
- flushLocal: async () => this._author(await this._scanner.scanFresh()),
4932
+ flushLocal: async () => {
4933
+ await this._takeUncovered();
4934
+ await this._author(await this._scanner.scanFresh());
4935
+ },
4544
4936
  relate: (ours, theirs) => chain.relate(ours, theirs),
4545
4937
  treeRefOf: async (head) => (await chain.entry(head))?.treeRef,
4546
4938
  applyBehind: (head) => this._applyBehind(head),
@@ -4562,7 +4954,7 @@ var FsAgent = class FsAgent {
4562
4954
  * @param head - The head.
4563
4955
  */
4564
4956
  async _adopt(head) {
4565
- this._setOwn(head, this._ownContent);
4957
+ this._setOwn(head, this._ownContent, this._carried);
4566
4958
  }
4567
4959
  /**
4568
4960
  * Applies a head that descends from the own one: writes what it changed,
@@ -4584,12 +4976,13 @@ var FsAgent = class FsAgent {
4584
4976
  const theirs = await this._treeOf(head);
4585
4977
  if (!theirs) return "refused";
4586
4978
  const target = this._getFileContentMap(theirs.tree);
4587
- const applied = await this._applyContent(target, (paths) => this._restorePaths(theirs.tree, paths));
4979
+ const carried = this._carriedOf(theirs.tree);
4980
+ const applied = await this._applyContent(target, (paths) => this._restorePaths(theirs.tree, paths), carried);
4588
4981
  if (applied === "moved") {
4589
4982
  this._receiveAgain(head);
4590
4983
  return "refused";
4591
4984
  }
4592
- this._setOwn(head, target);
4985
+ this._setOwn(head, target, carried);
4593
4986
  if (applied === "kept") await this._author(await this._scanner.scanFresh());
4594
4987
  return "applied";
4595
4988
  }
@@ -4601,22 +4994,33 @@ var FsAgent = class FsAgent {
4601
4994
  * — content `target` holds nowhere else — is not made. Everything else is,
4602
4995
  * and the files kept become this node's work, so the folder never holds a
4603
4996
  * state the chain does not describe.
4997
+ * The paths this node does not see are neither written nor deleted, and
4998
+ * the guard counts only what the folder holds.
4604
4999
  * @param target - Where the folder should end up, `path → blob`.
4605
5000
  * @param write - Writes the given paths' `target` versions.
5001
+ * @param carried - `target`'s nodes at the paths this node does not see.
4606
5002
  * @returns `applied`; `kept` when the guard kept files `target` lacks;
4607
5003
  * `moved` when the folder had moved past the own head.
4608
5004
  */
4609
- async _applyContent(target, write) {
5005
+ async _applyContent(target, write, carried) {
4610
5006
  const own = this._ownContent;
4611
5007
  const landed = this._partiallyApplied;
4612
- const writes = [...target.keys()].filter((p) => target.get(p) !== own.get(p) && target.get(p) !== landed.get(p));
4613
- const deletes = [...own.keys()].filter((p) => !target.has(p));
5008
+ const anyCarried = this._carried.size > 0 || carried.size > 0;
5009
+ const seen = (p) => !anyCarried || !this._carried.has(p) && !carried.has(p);
5010
+ const writes = [...target.keys()].filter((p) => target.get(p) !== own.get(p) && target.get(p) !== landed.get(p) && seen(p));
5011
+ const deletes = [...own.keys()].filter((p) => !target.has(p) && seen(p));
4614
5012
  const isFile = (v) => v !== void 0 && v !== "<dir>";
4615
- const held = [...own.values()].filter(isFile).length;
5013
+ const filesIn = (content) => {
5014
+ const blobs = [];
5015
+ for (const [p, v] of content) if (isFile(v) && seen(p)) blobs.push(v);
5016
+ return blobs;
5017
+ };
5018
+ const held = filesIn(own).length;
4616
5019
  const deletedFiles = deletes.filter((p) => isFile(own.get(p)));
4617
- const stillThere = new Set([...target.values()].filter(isFile));
5020
+ const targetFiles = filesIn(target);
5021
+ const stillThere = new Set(targetFiles);
4618
5022
  const lost = deletedFiles.filter((p) => !stillThere.has(own.get(p)));
4619
- const keep = new Set(lost.length > 100 && lost.length / held > .3 || lost.length > 0 && held > 10 && [...target.values()].filter(isFile).length <= 10 ? lost : []);
5023
+ const keep = new Set(lost.length > 100 && lost.length / held > .3 || lost.length > 0 && held > 10 && targetFiles.length <= 10 ? lost : []);
4620
5024
  const deleting = deletes.filter((p) => !keep.has(p));
4621
5025
  if (!await this._unchangedSinceOwn([...writes, ...deleting])) return "moved";
4622
5026
  if (writes.length > 0) try {
@@ -4760,6 +5164,7 @@ var FsAgent = class FsAgent {
4760
5164
  this._deferral = key;
4761
5165
  return "deferred";
4762
5166
  }
5167
+ const theirCarried = this._carriedOf(theirTree.tree);
4763
5168
  if (await this._applyContent(outcome.merged, async (paths) => {
4764
5169
  const fromTheirs = paths.filter((p) => outcome.merged.get(p) === theirContent.get(p));
4765
5170
  if (fromTheirs.length > 0) await this._restorePaths(theirTree.tree, fromTheirs);
@@ -4771,11 +5176,11 @@ var FsAgent = class FsAgent {
4771
5176
  const st = await stat(full);
4772
5177
  this._scanner.noteWrite(path, blob, st.size, st.mtime.getTime());
4773
5178
  }
4774
- }) === "moved") {
5179
+ }, theirCarried) === "moved") {
4775
5180
  this._receiveAgain(theirs);
4776
5181
  return "refused";
4777
5182
  }
4778
- const merged = await this._scanner.scanFresh();
5183
+ const { tree: merged, carried } = graftTree(await this._scanner.scanFresh(), await this._mergeCarried(outcome.merged, theirContent, theirCarried));
4779
5184
  const mergedContent = this._getFileContentMap(merged);
4780
5185
  const treeRef = await this._storeTree(merged);
4781
5186
  const touched = [.../* @__PURE__ */ new Set([
@@ -4795,7 +5200,7 @@ var FsAgent = class FsAgent {
4795
5200
  _hash: ""
4796
5201
  })._hash}`
4797
5202
  });
4798
- this._setOwn(entry.head, mergedContent);
5203
+ this._setOwn(entry.head, mergedContent, carried);
4799
5204
  for (const conflict of outcome.conflicts) this._signal({
4800
5205
  kind: conflict.kind,
4801
5206
  paths: [conflict.path],
@@ -4809,6 +5214,31 @@ var FsAgent = class FsAgent {
4809
5214
  return "merged";
4810
5215
  }
4811
5216
  /**
5217
+ * What a merge's result holds at the paths this node does not see: the node
5218
+ * of whichever side's version it kept there — and, for a copy a conflict
5219
+ * made at such a path, a node for the version the copy keeps, which the
5220
+ * merge wrote like any other copy.
5221
+ * @param merged - The merge's result, `path → blob`.
5222
+ * @param theirs - The forked head's content.
5223
+ * @param theirCarried - Its nodes at the paths this node does not see.
5224
+ * @returns The nodes to carry, by path.
5225
+ */
5226
+ async _mergeCarried(merged, theirs, theirCarried) {
5227
+ const ours = this._ownContent;
5228
+ const carried = /* @__PURE__ */ new Map();
5229
+ for (const [path, value] of merged) {
5230
+ const yours = theirCarried.get(path);
5231
+ const mine = this._carried.get(path);
5232
+ if (yours && value === theirs.get(path)) carried.set(path, yours);
5233
+ else if (mine && value === ours.get(path)) carried.set(path, mine);
5234
+ else if (!ours.has(path) && !theirs.has(path) && this._scanner.excludes(path, false)) {
5235
+ const st = await stat(join(this._rootPath, ...path.split("/"))).catch(() => void 0);
5236
+ if (st?.isFile()) carried.set(path, fileNode(path, value, st.size));
5237
+ }
5238
+ }
5239
+ return carried;
5240
+ }
5241
+ /**
4812
5242
  * Hears the network: announcements, the stamps of this node's own, and the
4813
5243
  * hub's state beacon.
4814
5244
  * @param db - The route's database.
@@ -4826,14 +5256,16 @@ var FsAgent = class FsAgent {
4826
5256
  await this._ensureWatching();
4827
5257
  connector.resetReceived?.();
4828
5258
  const generation = ++this._receivers;
5259
+ let listening = true;
4829
5260
  connector.listen(async (ref, _predecessors, info) => {
4830
- this._hear(ref, info?.stamp);
5261
+ if (listening) this._hear(ref, info?.stamp);
4831
5262
  });
4832
5263
  const offStamp = connector.onStamp((ref, stamp) => this._recordStamp(ref, stamp));
4833
5264
  const beacon = (payload) => this._hear(payload?.r, payload?.stamp, true);
4834
5265
  const events = [connector.events.bootstrap, stateBeaconEvent(connector.route.flat)];
4835
5266
  for (const event of events) connector.socket.on(event, beacon);
4836
5267
  return () => {
5268
+ listening = false;
4837
5269
  offStamp();
4838
5270
  for (const event of events) connector.socket.off(event, beacon);
4839
5271
  connector.tearDown();