zen-fs-config 0.7.5 → 0.7.7

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/index.js CHANGED
@@ -97,6 +97,17 @@ async function wrapZenFSFileSystem(config) {
97
97
  const notifyChange = () => {
98
98
  if (changeCallback) changeCallback();
99
99
  };
100
+ const writeQueues = /* @__PURE__ */ new Map();
101
+ const runExclusive = async (path, task) => {
102
+ const prev = writeQueues.get(path);
103
+ const run = (prev ?? Promise.resolve()).catch(() => void 0).then(task);
104
+ writeQueues.set(path, run);
105
+ try {
106
+ await run;
107
+ } finally {
108
+ if (writeQueues.get(path) === run) writeQueues.delete(path);
109
+ }
110
+ };
100
111
  const backend = {
101
112
  async readFile(path, ...args) {
102
113
  const st = await isolatedFS.stat(path);
@@ -107,31 +118,28 @@ async function wrapZenFSFileSystem(config) {
107
118
  return buf;
108
119
  },
109
120
  async writeFile(path, data, _options) {
110
- const bytes = data instanceof ArrayBuffer ? new Uint8Array(data) : data instanceof Uint8Array ? data : new TextEncoder().encode(data);
111
- const parts = path.split("/").filter(Boolean);
112
- parts.pop();
113
- let dir = "";
114
- for (const p of parts) {
115
- dir += "/" + p;
116
- if (!await isolatedFS.exists(dir)) {
117
- await isolatedFS.mkdir(dir, { uid: 0, gid: 0, mode: 493 });
121
+ const source = data instanceof ArrayBuffer ? new Uint8Array(data) : data instanceof Uint8Array ? data : new TextEncoder().encode(data);
122
+ const bytes = new Uint8Array(source);
123
+ await runExclusive(path, async () => {
124
+ const parts = path.split("/").filter(Boolean);
125
+ parts.pop();
126
+ let dir = "";
127
+ for (const p of parts) {
128
+ dir += "/" + p;
129
+ if (!await isolatedFS.exists(dir)) {
130
+ await isolatedFS.mkdir(dir, { uid: 0, gid: 0, mode: 493 });
131
+ }
132
+ }
133
+ if (await isolatedFS.exists(path)) {
134
+ await isolatedFS.unlink(path);
118
135
  }
119
- }
120
- let currentSize = 0;
121
- if (await isolatedFS.exists(path)) {
122
- currentSize = (await isolatedFS.stat(path)).size;
123
- } else {
124
- await isolatedFS.createFile(path, { uid: 0, gid: 0, mode: 420 });
125
- }
126
- if (currentSize > 0) {
127
- await isolatedFS.unlink(path);
128
136
  await isolatedFS.createFile(path, { uid: 0, gid: 0, mode: 420 });
129
- }
130
- await isolatedFS.write(path, bytes, 0);
131
- try {
132
- await isolatedFS.touch(path, { size: bytes.byteLength, mtimeMs: _options?.mtime ?? Date.now() });
133
- } catch {
134
- }
137
+ await isolatedFS.write(path, bytes, 0);
138
+ try {
139
+ await isolatedFS.touch(path, { size: bytes.byteLength, mtimeMs: _options?.mtime ?? Date.now() });
140
+ } catch {
141
+ }
142
+ });
135
143
  notifyChange();
136
144
  },
137
145
  async readdir(path) {
@@ -1195,7 +1203,7 @@ function deleteDataGroupLocalStore(appId, groupId, options = {}) {
1195
1203
  }
1196
1204
 
1197
1205
  // src/config-repo.ts
1198
- var import_localstorage_logger4 = require("@richard432/localstorage-logger");
1206
+ var import_localstorage_logger5 = require("@richard432/localstorage-logger");
1199
1207
 
1200
1208
  // src/version.ts
1201
1209
  function versionPathFor(configFilePath) {
@@ -1438,343 +1446,164 @@ async function verifyOrRepairVersion(fs, configFilePath, author) {
1438
1446
  }
1439
1447
  }
1440
1448
 
1441
- // src/mtime-cleanup.ts
1442
- function isMtimeSidecar(fileName) {
1443
- return fileName.endsWith(".mtime");
1449
+ // src/group-meta.ts
1450
+ var import_localstorage_logger3 = require("@richard432/localstorage-logger");
1451
+
1452
+ // src/canonical-json.ts
1453
+ var FEATURE_ORDER = ["tombstones", "versions", "conflicts", "configHost", "appData"];
1454
+ var GROUP_DESCRIPTOR_ORDER = ["schemaVersion", "kind", "id", "instanceId", "name", "features"];
1455
+ var APP_DATA_GROUP_ORDER = ["id", "groupType", "instanceId", "name", "features", "backends"];
1456
+ var BACKEND_ORDER = ["id", "type", "options", "accountBackendId", "description", "createdAt"];
1457
+ function compareKeys(a, b) {
1458
+ return a < b ? -1 : a > b ? 1 : 0;
1444
1459
  }
1445
- var S_IFDIR = 16384;
1446
- function isDirectory(stat) {
1447
- return typeof stat.mode === "number" && (stat.mode & S_IFDIR) === S_IFDIR;
1460
+ function isPlainObject(value) {
1461
+ return typeof value === "object" && value !== null && !Array.isArray(value);
1448
1462
  }
1449
- function joinPath(dir, entry) {
1450
- if (dir === "/" || dir === "") return `/${entry}`;
1451
- return `${dir.replace(/\/+$/, "")}/${entry}`;
1463
+ function canonicalObject(value, order = []) {
1464
+ const out = {};
1465
+ for (const key of order) {
1466
+ if (value[key] !== void 0) out[key] = canonicalField(key, value[key]);
1467
+ }
1468
+ for (const key of Object.keys(value).sort(compareKeys)) {
1469
+ if (order.includes(key) || value[key] === void 0) continue;
1470
+ out[key] = canonicalField(key, value[key]);
1471
+ }
1472
+ return out;
1452
1473
  }
1453
- async function purgeMtimeSidecars(fs, options = {}) {
1454
- const root = options.root && options.root !== "" ? options.root : "/";
1455
- const dryRun = options.dryRun ?? false;
1456
- const result = { scanned: 0, removed: [], failed: [] };
1457
- const stack = [root];
1458
- while (stack.length > 0) {
1459
- const dir = stack.pop();
1460
- let entries;
1461
- try {
1462
- entries = await fs.readdir(dir);
1463
- } catch {
1464
- continue;
1465
- }
1466
- for (const entry of entries) {
1467
- const fullPath = joinPath(dir, entry);
1468
- let stat;
1469
- try {
1470
- stat = await fs.stat(fullPath);
1471
- } catch {
1472
- continue;
1473
- }
1474
- if (isDirectory(stat)) {
1475
- stack.push(fullPath);
1476
- continue;
1477
- }
1478
- result.scanned++;
1479
- if (!isMtimeSidecar(entry)) continue;
1480
- if (dryRun) {
1481
- result.removed.push(fullPath);
1482
- continue;
1483
- }
1484
- try {
1485
- await fs.unlink(fullPath);
1486
- result.removed.push(fullPath);
1487
- } catch {
1488
- result.failed.push(fullPath);
1489
- }
1474
+ function canonicalField(key, value) {
1475
+ if (Array.isArray(value)) {
1476
+ if (key === "backends") {
1477
+ return value.map((item) => isPlainObject(item) ? canonicalObject(item, BACKEND_ORDER) : item).sort(
1478
+ (a, b) => compareKeys(String(a?.id ?? ""), String(b?.id ?? ""))
1479
+ );
1490
1480
  }
1481
+ return value.map((item) => canonicalField("", item));
1491
1482
  }
1492
- return result;
1483
+ if (isPlainObject(value)) {
1484
+ if (key === "features") return canonicalObject(value, FEATURE_ORDER);
1485
+ return canonicalObject(value);
1486
+ }
1487
+ return value;
1493
1488
  }
1494
-
1495
- // src/keep-cleanup.ts
1496
- function isKeepFile(fileName) {
1497
- return fileName === ".keep";
1489
+ function stringify(value) {
1490
+ return JSON.stringify(value, null, 2);
1498
1491
  }
1499
- var S_IFDIR2 = 16384;
1500
- var DEFAULT_PROTECTED_DIRS = ["/.meta/backends/.keep"];
1501
- function isDirectory2(stat) {
1502
- return typeof stat.mode === "number" && (stat.mode & S_IFDIR2) === S_IFDIR2;
1492
+ function serializeGroupDescriptor(descriptor) {
1493
+ const { updatedAt: _ignored, ...rest } = descriptor;
1494
+ return stringify(canonicalObject(rest, GROUP_DESCRIPTOR_ORDER));
1503
1495
  }
1504
- function joinPath2(dir, entry) {
1505
- if (dir === "/" || dir === "") return `/${entry}`;
1506
- return `${dir.replace(/\/+$/, "")}/${entry}`;
1496
+ function serializeBackendDescriptor(descriptor) {
1497
+ return stringify(canonicalObject(descriptor, BACKEND_ORDER));
1507
1498
  }
1508
- function isProtected(fullPath, protectedDirs) {
1509
- return protectedDirs.some((d) => {
1510
- const dir = d.endsWith("/") ? d.slice(0, -1) : d;
1511
- return fullPath === dir || fullPath.startsWith(dir + "/");
1512
- });
1499
+ function serializeAppDataGroupDescriptor(descriptor) {
1500
+ return stringify(canonicalObject(descriptor, APP_DATA_GROUP_ORDER));
1513
1501
  }
1514
- async function purgeKeepFiles(fs, options = {}) {
1515
- const root = options.root && options.root !== "" ? options.root : "/";
1516
- const dryRun = options.dryRun ?? false;
1517
- const protectedDirs = options.protectedDirs ?? DEFAULT_PROTECTED_DIRS;
1518
- const result = { scanned: 0, removed: [], failed: [] };
1519
- const stack = [root];
1520
- while (stack.length > 0) {
1521
- const dir = stack.pop();
1522
- if (isProtected(dir, protectedDirs)) continue;
1523
- let entries;
1524
- try {
1525
- entries = await fs.readdir(dir);
1526
- } catch {
1527
- continue;
1528
- }
1529
- for (const entry of entries) {
1530
- const fullPath = joinPath2(dir, entry);
1531
- if (isProtected(fullPath, protectedDirs)) continue;
1532
- let stat;
1533
- try {
1534
- stat = await fs.stat(fullPath);
1535
- } catch {
1536
- continue;
1537
- }
1538
- if (isDirectory2(stat)) {
1539
- stack.push(fullPath);
1540
- continue;
1541
- }
1542
- result.scanned++;
1543
- if (!isKeepFile(entry)) continue;
1544
- if (dryRun) {
1545
- result.removed.push(fullPath);
1546
- continue;
1547
- }
1548
- try {
1549
- await fs.unlink(fullPath);
1550
- result.removed.push(fullPath);
1551
- } catch {
1552
- result.failed.push(fullPath);
1553
- }
1554
- }
1555
- }
1556
- return result;
1502
+ function stripBackendCreatedAt(descriptor) {
1503
+ const { createdAt: _ignored, ...rest } = descriptor;
1504
+ return rest;
1557
1505
  }
1558
-
1559
- // src/version-migration.ts
1560
- var S_IFDIR3 = 16384;
1561
- function isDir(stat) {
1562
- return typeof stat.mode === "number" && (stat.mode & S_IFDIR3) === S_IFDIR3;
1506
+ function mergeBackendDescriptor(existing, incoming) {
1507
+ const existingCreatedAt = typeof existing?.createdAt === "number" ? existing.createdAt : void 0;
1508
+ const incomingCreatedAt = typeof incoming.createdAt === "number" ? incoming.createdAt : void 0;
1509
+ const createdAt = existingCreatedAt === void 0 ? incomingCreatedAt : incomingCreatedAt === void 0 ? existingCreatedAt : Math.min(existingCreatedAt, incomingCreatedAt);
1510
+ return createdAt === void 0 ? stripBackendCreatedAt(incoming) : { ...incoming, createdAt };
1563
1511
  }
1564
- function joinPath3(dir, entry) {
1565
- if (dir === "/" || dir === "") return `/${entry}`;
1566
- return `${dir.replace(/\/+$/, "")}/${entry}`;
1512
+ function mergeBackendCreatedAt(incoming, existing) {
1513
+ if (!existing || existing.length === 0) return incoming;
1514
+ const byId = new Map(existing.map((d) => [d.id, d]));
1515
+ return incoming.map((desc) => mergeBackendDescriptor(byId.get(desc.id), desc));
1567
1516
  }
1568
- async function existsPath(fs, p) {
1569
- try {
1570
- await fs.stat(p);
1571
- return true;
1572
- } catch {
1573
- return false;
1517
+ function mergeDescriptorCreatedAt(descriptor, existing) {
1518
+ return {
1519
+ ...descriptor,
1520
+ backends: mergeBackendCreatedAt(descriptor.backends, existing?.backends)
1521
+ };
1522
+ }
1523
+
1524
+ // src/group-meta.ts
1525
+ var log3 = (0, import_localstorage_logger3.createLogger)("zen-fs-config:tombstones");
1526
+ var META_DIR = "/.meta";
1527
+ var GROUP_DESCRIPTOR_FILE2 = `${META_DIR}/group.json`;
1528
+ var META_BACKENDS_DIR = `${META_DIR}/backends`;
1529
+ var TOMBSTONES_DIR = `${META_DIR}/tombstones`;
1530
+ var RECREATE_AFTER_DELETE_SKEW_MS = 3e3;
1531
+ var TOMBSTONE_RETENTION_MS = 24 * 60 * 60 * 1e3;
1532
+ var TOMBSTONE_PLACEHOLDER_RETENTION_MS = 10 * 60 * 1e3;
1533
+ function tombstoneRetentionMs(tombstonePath) {
1534
+ if (tombstonePath.endsWith(".mtime") || tombstonePath === "/.keep" || tombstonePath.endsWith("/.keep")) {
1535
+ return TOMBSTONE_PLACEHOLDER_RETENTION_MS;
1574
1536
  }
1537
+ return TOMBSTONE_RETENTION_MS;
1575
1538
  }
1576
- function configNameFromLegacy(entry) {
1577
- const noMtime = entry.endsWith(".version.mtime") ? entry.slice(0, -".version.mtime".length) : entry.slice(0, -".version".length);
1578
- return noMtime.slice(1);
1539
+ function isTombstoneRetentionElapsed(tombstone, now = Date.now()) {
1540
+ const deletedAt = Number(tombstone.deletedAt);
1541
+ if (!Number.isFinite(deletedAt)) return true;
1542
+ return now - deletedAt >= tombstoneRetentionMs(tombstone.path);
1579
1543
  }
1580
- async function resolveTarget(fs, dir, entry) {
1581
- const configName = configNameFromLegacy(entry);
1582
- const configPath = joinPath3(dir, configName);
1583
- const dotConfigPath = joinPath3(dir, `.${configName}`);
1584
- if (await existsPath(fs, dotConfigPath)) {
1585
- return { action: "skip" };
1586
- }
1587
- if (await existsPath(fs, configPath)) {
1588
- return { action: "rename", newPath: versionPathFor(configPath) ?? `${configName}.version` };
1589
- }
1590
- return { action: "delete" };
1544
+ function isDirectoryTombstone(tombstone) {
1545
+ return tombstone.type === "directory";
1591
1546
  }
1592
- async function migrateVersionSidecars(fs, options = {}) {
1593
- const root = options.root && options.root !== "" ? options.root : "/";
1594
- const dryRun = options.dryRun ?? false;
1595
- const replicas = options.replicas ?? [];
1596
- const result = {
1597
- renamed: [],
1598
- deleted: [],
1599
- remoteDeleted: [],
1600
- failed: []
1547
+ function serializeTombstone(tombstone) {
1548
+ const ordered = {
1549
+ path: tombstone.path,
1550
+ deletedAt: tombstone.deletedAt,
1551
+ deletedBy: tombstone.deletedBy,
1552
+ confirmedBy: tombstone.confirmedBy
1601
1553
  };
1602
- const stack = [root];
1603
- while (stack.length > 0) {
1604
- const dir = stack.pop();
1605
- let entries;
1554
+ if (tombstone.type) ordered.type = tombstone.type;
1555
+ return JSON.stringify(ordered, null, 2);
1556
+ }
1557
+ async function purgeTombstonedTree(fs, targetPath) {
1558
+ let isDir2 = false;
1559
+ try {
1560
+ const stat = await fs.stat?.(targetPath);
1561
+ if (stat) {
1562
+ if (typeof stat.isDirectory === "function") isDir2 = stat.isDirectory();
1563
+ else {
1564
+ const mode = Number(stat.mode ?? 0);
1565
+ isDir2 = mode > 0 && (mode & 61440) === 16384;
1566
+ }
1567
+ }
1568
+ } catch {
1569
+ isDir2 = false;
1570
+ }
1571
+ if (!isDir2) {
1606
1572
  try {
1607
- entries = await fs.readdir(dir);
1573
+ await fs.readdir(targetPath);
1574
+ isDir2 = true;
1608
1575
  } catch {
1609
- continue;
1576
+ isDir2 = false;
1610
1577
  }
1611
- for (const entry of entries) {
1612
- const full = joinPath3(dir, entry);
1613
- let stat;
1614
- try {
1615
- stat = await fs.stat(full);
1616
- } catch {
1617
- continue;
1618
- }
1619
- if (isDir(stat)) {
1620
- stack.push(full);
1621
- continue;
1622
- }
1623
- const isLegacyVersion = entry.startsWith(".") && (entry.endsWith(".version") || entry.endsWith(".version.mtime"));
1624
- if (!isLegacyVersion) continue;
1625
- const legacyVerPath = entry.endsWith(".version.mtime") ? full.slice(0, -".mtime".length) : full;
1626
- const target = await resolveTarget(fs, dir, entry);
1627
- if (target.action === "skip") continue;
1628
- const legacyMtimePath = `${legacyVerPath}.mtime`;
1629
- const newMtimePath = target.newPath ? `${target.newPath}.mtime` : null;
1630
- if (dryRun) {
1631
- if (target.action === "rename") result.renamed.push(full);
1632
- else result.deleted.push(full);
1633
- continue;
1634
- }
1635
- try {
1636
- if (target.action === "rename") {
1637
- if (await existsPath(fs, target.newPath)) {
1638
- await fs.unlink(legacyVerPath);
1639
- result.deleted.push(full);
1640
- } else {
1641
- const content = await fs.readFile(legacyVerPath);
1642
- const bytes = typeof content === "string" ? new TextEncoder().encode(content) : content;
1643
- await fs.writeFile(target.newPath, bytes);
1644
- await fs.unlink(legacyVerPath);
1645
- result.renamed.push(full);
1646
- }
1647
- if (newMtimePath && await existsPath(fs, legacyMtimePath)) {
1648
- try {
1649
- const mc = await fs.readFile(legacyMtimePath);
1650
- const mb = typeof mc === "string" ? new TextEncoder().encode(mc) : mc;
1651
- await fs.writeFile(newMtimePath, mb);
1652
- await fs.unlink(legacyMtimePath);
1653
- } catch {
1654
- }
1655
- }
1656
- } else {
1657
- await fs.unlink(legacyVerPath);
1658
- result.deleted.push(full);
1659
- if (await existsPath(fs, legacyMtimePath)) {
1660
- try {
1661
- await fs.unlink(legacyMtimePath);
1662
- } catch {
1663
- }
1664
- }
1665
- }
1666
- } catch (e) {
1667
- result.failed.push(full);
1668
- continue;
1669
- }
1670
- for (const rep of replicas) {
1671
- for (const rp of [legacyVerPath, legacyMtimePath]) {
1672
- try {
1673
- await rep.unlink(rp);
1674
- result.remoteDeleted.push(rp);
1675
- } catch {
1676
- }
1677
- }
1678
- }
1679
- }
1680
- }
1681
- return result;
1682
- }
1683
-
1684
- // src/group-meta.ts
1685
- var import_localstorage_logger3 = require("@richard432/localstorage-logger");
1686
-
1687
- // src/canonical-json.ts
1688
- var FEATURE_ORDER = ["tombstones", "versions", "conflicts", "configHost", "appData"];
1689
- var GROUP_DESCRIPTOR_ORDER = ["schemaVersion", "kind", "id", "name", "features"];
1690
- var APP_DATA_GROUP_ORDER = ["id", "groupType", "name", "features", "backends"];
1691
- var BACKEND_ORDER = ["id", "type", "options", "accountBackendId", "description", "createdAt"];
1692
- function compareKeys(a, b) {
1693
- return a < b ? -1 : a > b ? 1 : 0;
1694
- }
1695
- function isPlainObject(value) {
1696
- return typeof value === "object" && value !== null && !Array.isArray(value);
1697
- }
1698
- function canonicalObject(value, order = []) {
1699
- const out = {};
1700
- for (const key of order) {
1701
- if (value[key] !== void 0) out[key] = canonicalField(key, value[key]);
1702
1578
  }
1703
- for (const key of Object.keys(value).sort(compareKeys)) {
1704
- if (order.includes(key) || value[key] === void 0) continue;
1705
- out[key] = canonicalField(key, value[key]);
1579
+ if (!isDir2) {
1580
+ try {
1581
+ await fs.unlink(targetPath);
1582
+ } catch {
1583
+ }
1584
+ return;
1706
1585
  }
1707
- return out;
1708
- }
1709
- function canonicalField(key, value) {
1710
- if (Array.isArray(value)) {
1711
- if (key === "backends") {
1712
- return value.map((item) => isPlainObject(item) ? canonicalObject(item, BACKEND_ORDER) : item).sort(
1713
- (a, b) => compareKeys(String(a?.id ?? ""), String(b?.id ?? ""))
1714
- );
1586
+ for (const placeholder of [`${targetPath}/.keep`, `${targetPath}/.keep.mtime`]) {
1587
+ try {
1588
+ await fs.unlink(placeholder);
1589
+ } catch {
1715
1590
  }
1716
- return value.map((item) => canonicalField("", item));
1717
1591
  }
1718
- if (isPlainObject(value)) {
1719
- if (key === "features") return canonicalObject(value, FEATURE_ORDER);
1720
- return canonicalObject(value);
1592
+ let children = [];
1593
+ try {
1594
+ children = await fs.readdir(targetPath);
1595
+ } catch {
1721
1596
  }
1722
- return value;
1723
- }
1724
- function stringify(value) {
1725
- return JSON.stringify(value, null, 2);
1726
- }
1727
- function serializeGroupDescriptor(descriptor) {
1728
- const { updatedAt: _ignored, ...rest } = descriptor;
1729
- return stringify(canonicalObject(rest, GROUP_DESCRIPTOR_ORDER));
1730
- }
1731
- function serializeBackendDescriptor(descriptor) {
1732
- return stringify(canonicalObject(descriptor, BACKEND_ORDER));
1733
- }
1734
- function serializeAppDataGroupDescriptor(descriptor) {
1735
- return stringify(canonicalObject(descriptor, APP_DATA_GROUP_ORDER));
1736
- }
1737
- function stripBackendCreatedAt(descriptor) {
1738
- const { createdAt: _ignored, ...rest } = descriptor;
1739
- return rest;
1740
- }
1741
- function mergeBackendDescriptor(existing, incoming) {
1742
- const existingCreatedAt = typeof existing?.createdAt === "number" ? existing.createdAt : void 0;
1743
- const incomingCreatedAt = typeof incoming.createdAt === "number" ? incoming.createdAt : void 0;
1744
- const createdAt = existingCreatedAt === void 0 ? incomingCreatedAt : incomingCreatedAt === void 0 ? existingCreatedAt : Math.min(existingCreatedAt, incomingCreatedAt);
1745
- return createdAt === void 0 ? stripBackendCreatedAt(incoming) : { ...incoming, createdAt };
1746
- }
1747
- function mergeBackendCreatedAt(incoming, existing) {
1748
- if (!existing || existing.length === 0) return incoming;
1749
- const byId = new Map(existing.map((d) => [d.id, d]));
1750
- return incoming.map((desc) => mergeBackendDescriptor(byId.get(desc.id), desc));
1751
- }
1752
- function mergeDescriptorCreatedAt(descriptor, existing) {
1753
- return {
1754
- ...descriptor,
1755
- backends: mergeBackendCreatedAt(descriptor.backends, existing?.backends)
1756
- };
1757
- }
1758
-
1759
- // src/group-meta.ts
1760
- var log3 = (0, import_localstorage_logger3.createLogger)("zen-fs-config:tombstones");
1761
- var META_DIR = "/.meta";
1762
- var GROUP_DESCRIPTOR_FILE2 = `${META_DIR}/group.json`;
1763
- var META_BACKENDS_DIR = `${META_DIR}/backends`;
1764
- var TOMBSTONES_DIR = `${META_DIR}/tombstones`;
1765
- var RECREATE_AFTER_DELETE_SKEW_MS = 3e3;
1766
- var TOMBSTONE_RETENTION_MS = 24 * 60 * 60 * 1e3;
1767
- var TOMBSTONE_PLACEHOLDER_RETENTION_MS = 10 * 60 * 1e3;
1768
- function tombstoneRetentionMs(tombstonePath) {
1769
- if (tombstonePath.endsWith(".mtime") || tombstonePath === "/.keep" || tombstonePath.endsWith("/.keep")) {
1770
- return TOMBSTONE_PLACEHOLDER_RETENTION_MS;
1597
+ for (const child of children) await purgeTombstonedTree(fs, `${targetPath}/${child}`);
1598
+ try {
1599
+ if (typeof fs.rmdir === "function") await fs.rmdir(targetPath);
1600
+ else await fs.unlink(targetPath);
1601
+ } catch {
1602
+ try {
1603
+ await fs.unlink(targetPath);
1604
+ } catch {
1605
+ }
1771
1606
  }
1772
- return TOMBSTONE_RETENTION_MS;
1773
- }
1774
- function isTombstoneRetentionElapsed(tombstone, now = Date.now()) {
1775
- const deletedAt = Number(tombstone.deletedAt);
1776
- if (!Number.isFinite(deletedAt)) return true;
1777
- return now - deletedAt >= tombstoneRetentionMs(tombstone.path);
1778
1607
  }
1779
1608
  var LEGACY_TOMBSTONES_DIR = `${META_DIR}/.deleted`;
1780
1609
  var VERSIONS_DIR = `${META_DIR}/versions`;
@@ -1838,6 +1667,9 @@ async function existsSafe(fs, path) {
1838
1667
  function isMtimeSidecarPath(path) {
1839
1668
  return path.endsWith(".mtime");
1840
1669
  }
1670
+ function isHiddenPlaceholderPath(path) {
1671
+ return isMtimeSidecarPath(path) || path === "/.keep" || path.endsWith("/.keep");
1672
+ }
1841
1673
  function encodeMetaPath(filePath) {
1842
1674
  const normalized = filePath.startsWith("/") ? filePath : `/${filePath}`;
1843
1675
  return normalized.replace(/^\//, "").replace(/\//g, "__").replace(/\./g, "++");
@@ -1856,15 +1688,21 @@ function normalizeTombstoneRecord(value, fallbackPath) {
1856
1688
  const record = value;
1857
1689
  const rawPath = typeof record.path === "string" ? record.path : fallbackPath;
1858
1690
  if (!rawPath) return null;
1859
- const path = rawPath.startsWith("/") ? rawPath : `/${rawPath}`;
1691
+ const path = normalizeTombstonePath(rawPath);
1860
1692
  const confirmedBy = Array.isArray(record.confirmedBy) ? record.confirmedBy.filter((id) => typeof id === "string") : [];
1693
+ const type = record.type === "directory" ? "directory" : record.type === "file" ? "file" : void 0;
1861
1694
  return {
1862
1695
  path,
1863
1696
  deletedAt: typeof record.deletedAt === "number" ? record.deletedAt : 0,
1864
1697
  deletedBy: typeof record.deletedBy === "string" ? record.deletedBy : "unknown",
1865
- confirmedBy
1698
+ confirmedBy,
1699
+ ...type ? { type } : {}
1866
1700
  };
1867
1701
  }
1702
+ function normalizeTombstonePath(rawPath) {
1703
+ const withLeading = rawPath.startsWith("/") ? rawPath : `/${rawPath}`;
1704
+ return withLeading.length > 1 ? withLeading.replace(/\/+$/, "") || "/" : withLeading;
1705
+ }
1868
1706
  function extractJsonObjects(raw) {
1869
1707
  const objects = [];
1870
1708
  let depth = 0;
@@ -1945,6 +1783,7 @@ function mergeTombstone(byPath, tombstone) {
1945
1783
  for (const id of tombstone.confirmedBy) {
1946
1784
  if (!prev.confirmedBy.includes(id)) prev.confirmedBy.push(id);
1947
1785
  }
1786
+ if (isDirectoryTombstone(tombstone) && !isDirectoryTombstone(prev)) prev.type = "directory";
1948
1787
  }
1949
1788
  async function readTombstonesFromFs(fs, warn) {
1950
1789
  const byPath = /* @__PURE__ */ new Map();
@@ -2050,6 +1889,14 @@ var TombstoneStore = class {
2050
1889
  }
2051
1890
  fs;
2052
1891
  author;
1892
+ /**
1893
+ * 本轮 `process()` 真正核对过"确实不存在"的(路径 → 目标 id)。
1894
+ *
1895
+ * 只有出现在这里的副本才会被写进 `confirmedBy`(见 {@link confirm}),与
1896
+ * 配置组 `ConfigRepo.updateTombstoneConfirmations` 的保守语义一致:副本删除
1897
+ * 失败(网络、后端限制、只剩占位目录)时绝不算已确认。
1898
+ */
1899
+ verifiedAbsent = /* @__PURE__ */ new Map();
2053
1900
  pathFor(filePath) {
2054
1901
  return `${TOMBSTONES_DIR}/${encodeMetaPath(filePath)}.json`;
2055
1902
  }
@@ -2059,14 +1906,14 @@ var TombstoneStore = class {
2059
1906
  }
2060
1907
  /** Write a tombstone. */
2061
1908
  async write(tombstone) {
2062
- const bytes = new TextEncoder().encode(JSON.stringify(tombstone, null, 2));
1909
+ const bytes = new TextEncoder().encode(serializeTombstone(tombstone));
2063
1910
  const p = this.pathFor(tombstone.path);
2064
1911
  await ensureParentDir2(this.fs, p);
2065
1912
  await this.fs.writeFile(p, bytes);
2066
1913
  }
2067
1914
  /** Persist an updated tombstone (confirmations) when it still exists. */
2068
1915
  async save(tombstone) {
2069
- const bytes = new TextEncoder().encode(JSON.stringify(tombstone, null, 2));
1916
+ const bytes = new TextEncoder().encode(serializeTombstone(tombstone));
2070
1917
  const p = this.pathFor(tombstone.path);
2071
1918
  if (!await existsSafe(this.fs, p)) return;
2072
1919
  await this.fs.writeFile(p, bytes);
@@ -2093,14 +1940,20 @@ var TombstoneStore = class {
2093
1940
  async process(targets = []) {
2094
1941
  const tombstones = await this.list();
2095
1942
  const expired = [];
1943
+ this.verifiedAbsent.clear();
2096
1944
  for (const tombstone of tombstones) {
2097
1945
  if (await this.wasRecreatedAfterDeletion(tombstone)) {
2098
1946
  expired.push(tombstone);
2099
1947
  continue;
2100
1948
  }
2101
- await this.deleteEverywhere(this.fs, tombstone.path);
1949
+ await this.deleteEverywhere(this.fs, tombstone);
1950
+ for (const target of targets) {
1951
+ await this.deleteEverywhere(target.fs, tombstone);
1952
+ }
2102
1953
  for (const target of targets) {
2103
- await this.deleteEverywhere(target.fs, tombstone.path);
1954
+ if (await this.absentOnTarget(target.fs, tombstone)) {
1955
+ this.markVerified(tombstone.path, target.id);
1956
+ }
2104
1957
  }
2105
1958
  }
2106
1959
  for (const tombstone of expired) {
@@ -2110,6 +1963,36 @@ var TombstoneStore = class {
2110
1963
  );
2111
1964
  }
2112
1965
  }
1966
+ markVerified(path, targetId) {
1967
+ let ids = this.verifiedAbsent.get(path);
1968
+ if (!ids) {
1969
+ ids = /* @__PURE__ */ new Set();
1970
+ this.verifiedAbsent.set(path, ids);
1971
+ }
1972
+ ids.add(targetId);
1973
+ }
1974
+ /**
1975
+ * 目标上该路径当前是否确实不存在。
1976
+ *
1977
+ * `.mtime` 侧车与 `.keep` 占位对部分后端不可见(`exists()` 恒为 false),这类
1978
+ * 路径只能相信本轮 unlink 没有报错,因此按"不可见即可信"处理(与配置组的
1979
+ * `allReplicasConfirmAbsent` 一致)。
1980
+ */
1981
+ async absentOnTarget(fs, tombstone) {
1982
+ if (!isDirectoryTombstone(tombstone) && isHiddenPlaceholderPath(tombstone.path)) {
1983
+ return true;
1984
+ }
1985
+ try {
1986
+ const stat = await fs.stat?.(tombstone.path);
1987
+ if (stat) return false;
1988
+ } catch {
1989
+ }
1990
+ try {
1991
+ if (typeof fs.exists === "function") return !await fs.exists(tombstone.path);
1992
+ } catch {
1993
+ }
1994
+ return true;
1995
+ }
2113
1996
  /**
2114
1997
  * 本地存储上该路径的 mtime 是否晚于墓碑的删除时刻。
2115
1998
  *
@@ -2130,24 +2013,38 @@ var TombstoneStore = class {
2130
2013
  return null;
2131
2014
  }
2132
2015
  }
2133
- async deleteEverywhere(fs, filePath) {
2134
- if (!isMtimeSidecarPath(filePath) && !await existsSafe(fs, filePath)) return;
2016
+ async deleteEverywhere(fs, tombstone) {
2017
+ if (isDirectoryTombstone(tombstone)) {
2018
+ await purgeTombstonedTree(fs, tombstone.path);
2019
+ return;
2020
+ }
2021
+ if (!isMtimeSidecarPath(tombstone.path) && !await existsSafe(fs, tombstone.path)) return;
2135
2022
  try {
2136
- await fs.unlink(filePath);
2023
+ await fs.unlink(tombstone.path);
2137
2024
  } catch {
2138
2025
  }
2139
2026
  }
2140
- /** Add the given backend ids to every tombstone's confirmation set. */
2141
- async confirm(backendIds) {
2027
+ /**
2028
+ * 把本轮真正核对过"确实不存在"的目标写进墓碑的 `confirmedBy`。
2029
+ *
2030
+ * 旧实现把传入的后端 id 无条件写入,等于"跑过一轮就算所有副本都清干净了";
2031
+ * 副本删除失败时墓碑仍会被 GC,下一轮同步再把残留拉回本地。现在只确认
2032
+ * {@link process} 中现场核对通过的目标(与配置组语义一致),并支持只传 id
2033
+ * 的旧调用方式(此时沿用同一份核对结果)。
2034
+ */
2035
+ async confirm(targets) {
2036
+ const isTargetList = (value) => value.length > 0 && typeof value[0] === "object";
2037
+ const ids = isTargetList(targets) ? targets.map((t) => t.id) : targets;
2142
2038
  const tombstones = await this.list();
2143
2039
  let modified = 0;
2144
2040
  for (const tombstone of tombstones) {
2041
+ const verified = this.verifiedAbsent.get(tombstone.path);
2145
2042
  let changed = false;
2146
- for (const id of backendIds) {
2147
- if (!tombstone.confirmedBy.includes(id)) {
2148
- tombstone.confirmedBy.push(id);
2149
- changed = true;
2150
- }
2043
+ for (const id of ids) {
2044
+ if (tombstone.confirmedBy.includes(id)) continue;
2045
+ if (!verified?.has(id)) continue;
2046
+ tombstone.confirmedBy.push(id);
2047
+ changed = true;
2151
2048
  }
2152
2049
  if (!changed) continue;
2153
2050
  try {
@@ -2165,6 +2062,14 @@ var TombstoneStore = class {
2165
2062
  if (!isTombstoneRetentionElapsed(tombstone)) continue;
2166
2063
  const allConfirmed = allBackendIds.every((id) => tombstone.confirmedBy.includes(id));
2167
2064
  if (!allConfirmed) continue;
2065
+ let stillAbsent = true;
2066
+ for (const target of targets) {
2067
+ if (!await this.absentOnTarget(target.fs, tombstone)) {
2068
+ stillAbsent = false;
2069
+ break;
2070
+ }
2071
+ }
2072
+ if (!stillAbsent) continue;
2168
2073
  const p = this.pathFor(tombstone.path);
2169
2074
  if (await existsSafe(this.fs, p)) {
2170
2075
  try {
@@ -2266,55 +2171,365 @@ var ConflictStore = class {
2266
2171
  for (const dir of [CONFLICTS_DIR, LEGACY_CONFLICTS_DIR]) {
2267
2172
  let entries;
2268
2173
  try {
2269
- entries = await this.fs.readdir(dir);
2174
+ entries = await this.fs.readdir(dir);
2175
+ } catch {
2176
+ continue;
2177
+ }
2178
+ for (const entry of entries) {
2179
+ if (seen.has(entry)) continue;
2180
+ const archive = await readJson(this.fs, `${dir}/${entry}/meta.json`);
2181
+ if (!archive) continue;
2182
+ seen.add(entry);
2183
+ archives.push(archive);
2184
+ }
2185
+ }
2186
+ return archives.sort((a, b) => a.timestamp - b.timestamp);
2187
+ }
2188
+ candidatesFor(conflictId) {
2189
+ const id = conflictId.replace(/\/meta\.json$/, "");
2190
+ return [`${CONFLICTS_DIR}/${id}`, `${LEGACY_CONFLICTS_DIR}/${id}`];
2191
+ }
2192
+ async readBackup(conflictId, fileType) {
2193
+ for (const dir of this.candidatesFor(conflictId)) {
2194
+ const p = `${dir}/${fileType}`;
2195
+ try {
2196
+ return new TextDecoder().decode(toBytes(await this.fs.readFile(p)));
2197
+ } catch {
2198
+ }
2199
+ }
2200
+ throw new Error(`Conflict backup not found: ${conflictId}/${fileType}`);
2201
+ }
2202
+ /** Resolve a conflict with raw (already serialized) content. */
2203
+ async resolve(conflictId, mergedContent) {
2204
+ for (const dir of this.candidatesFor(conflictId)) {
2205
+ const metaPath = `${dir}/meta.json`;
2206
+ const archive = await readJson(this.fs, metaPath);
2207
+ if (!archive) continue;
2208
+ const bytes = typeof mergedContent === "string" ? new TextEncoder().encode(mergedContent) : mergedContent;
2209
+ await ensureParentDir2(this.fs, archive.conflictPath);
2210
+ await this.fs.writeFile(archive.conflictPath, bytes);
2211
+ await this.versions.record(archive.conflictPath, bytes);
2212
+ await this.fs.writeFile(`${dir}/resolved`, bytes);
2213
+ archive.resolvedBackupPath = "./resolved";
2214
+ await writeJson(this.fs, metaPath, archive);
2215
+ return;
2216
+ }
2217
+ throw new Error(`Failed to resolve conflict ${conflictId}: archive not found`);
2218
+ }
2219
+ };
2220
+
2221
+ // src/group-identity.ts
2222
+ var import_localstorage_logger4 = require("@richard432/localstorage-logger");
2223
+ var log4 = (0, import_localstorage_logger4.createLogger)("zen-fs-config:group-identity");
2224
+ var INSTANCE_ID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
2225
+ function newGroupInstanceId() {
2226
+ const cryptoObj = globalThis?.crypto;
2227
+ if (cryptoObj?.randomUUID) return cryptoObj.randomUUID();
2228
+ const bytes = new Uint8Array(16);
2229
+ if (cryptoObj?.getRandomValues) {
2230
+ cryptoObj.getRandomValues(bytes);
2231
+ } else {
2232
+ for (let i = 0; i < bytes.length; i += 1) bytes[i] = Math.floor(Math.random() * 256);
2233
+ }
2234
+ bytes[6] = bytes[6] & 15 | 64;
2235
+ bytes[8] = bytes[8] & 63 | 128;
2236
+ const hex = Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join("");
2237
+ return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
2238
+ }
2239
+ function isValidGroupInstanceId(value) {
2240
+ return typeof value === "string" && INSTANCE_ID_RE.test(value.trim());
2241
+ }
2242
+ async function bindRemoteGroupIdentity(remoteFS, identity) {
2243
+ let remote = null;
2244
+ try {
2245
+ remote = await readGroupDescriptor(remoteFS);
2246
+ } catch (err) {
2247
+ log4.warn(`[GroupIdentity] failed to read remote ${identity.kind}/"${identity.id}" group.json:`, err);
2248
+ throw err;
2249
+ }
2250
+ const current = remote?.instanceId;
2251
+ if (isValidGroupInstanceId(current)) {
2252
+ if (current === identity.instanceId) return "match";
2253
+ log4.warn(
2254
+ `[GroupIdentity] backend belongs to another sync group (remote instanceId=${current}, this group=${identity.instanceId}, kind ${remote?.kind ?? "?"}/"${remote?.id ?? "?"}") \u2014 sync pair NOT created`
2255
+ );
2256
+ return "conflict";
2257
+ }
2258
+ const next = {
2259
+ schemaVersion: 2,
2260
+ kind: remote?.kind ?? identity.kind,
2261
+ id: remote?.id ?? identity.id,
2262
+ instanceId: identity.instanceId,
2263
+ ...remote?.name ?? identity.name ? { name: remote?.name ?? identity.name } : {},
2264
+ ...remote?.features ?? identity.features ? { features: remote?.features ?? identity.features } : {}
2265
+ };
2266
+ if (next.kind !== identity.kind) {
2267
+ log4.warn(
2268
+ `[GroupIdentity] remote kind "${next.kind}" \u2260 this group kind "${identity.kind}" \u2014 sync pair NOT created`
2269
+ );
2270
+ return "conflict";
2271
+ }
2272
+ try {
2273
+ await writeGroupDescriptor(remoteFS, next);
2274
+ } catch (err) {
2275
+ log4.warn(`[GroupIdentity] failed to claim remote root for "${identity.id}":`, err);
2276
+ return "conflict";
2277
+ }
2278
+ log4.log(
2279
+ `[GroupIdentity] claimed remote root for ${identity.kind}/"${identity.id}" (instanceId=${identity.instanceId})`
2280
+ );
2281
+ return "claimed";
2282
+ }
2283
+ function pickInstanceId(descriptor) {
2284
+ const value = descriptor?.instanceId;
2285
+ return isValidGroupInstanceId(value) ? value : void 0;
2286
+ }
2287
+
2288
+ // src/mtime-cleanup.ts
2289
+ function isMtimeSidecar(fileName) {
2290
+ return fileName.endsWith(".mtime");
2291
+ }
2292
+ var S_IFDIR = 16384;
2293
+ function isDirectory(stat) {
2294
+ return typeof stat.mode === "number" && (stat.mode & S_IFDIR) === S_IFDIR;
2295
+ }
2296
+ function joinPath(dir, entry) {
2297
+ if (dir === "/" || dir === "") return `/${entry}`;
2298
+ return `${dir.replace(/\/+$/, "")}/${entry}`;
2299
+ }
2300
+ async function purgeMtimeSidecars(fs, options = {}) {
2301
+ const root = options.root && options.root !== "" ? options.root : "/";
2302
+ const dryRun = options.dryRun ?? false;
2303
+ const result = { scanned: 0, removed: [], failed: [] };
2304
+ const stack = [root];
2305
+ while (stack.length > 0) {
2306
+ const dir = stack.pop();
2307
+ let entries;
2308
+ try {
2309
+ entries = await fs.readdir(dir);
2310
+ } catch {
2311
+ continue;
2312
+ }
2313
+ for (const entry of entries) {
2314
+ const fullPath = joinPath(dir, entry);
2315
+ let stat;
2316
+ try {
2317
+ stat = await fs.stat(fullPath);
2318
+ } catch {
2319
+ continue;
2320
+ }
2321
+ if (isDirectory(stat)) {
2322
+ stack.push(fullPath);
2323
+ continue;
2324
+ }
2325
+ result.scanned++;
2326
+ if (!isMtimeSidecar(entry)) continue;
2327
+ if (dryRun) {
2328
+ result.removed.push(fullPath);
2329
+ continue;
2330
+ }
2331
+ try {
2332
+ await fs.unlink(fullPath);
2333
+ result.removed.push(fullPath);
2334
+ } catch {
2335
+ result.failed.push(fullPath);
2336
+ }
2337
+ }
2338
+ }
2339
+ return result;
2340
+ }
2341
+
2342
+ // src/keep-cleanup.ts
2343
+ function isKeepFile(fileName) {
2344
+ return fileName === ".keep";
2345
+ }
2346
+ var S_IFDIR2 = 16384;
2347
+ var DEFAULT_PROTECTED_DIRS = ["/.meta/backends/.keep"];
2348
+ function isDirectory2(stat) {
2349
+ return typeof stat.mode === "number" && (stat.mode & S_IFDIR2) === S_IFDIR2;
2350
+ }
2351
+ function joinPath2(dir, entry) {
2352
+ if (dir === "/" || dir === "") return `/${entry}`;
2353
+ return `${dir.replace(/\/+$/, "")}/${entry}`;
2354
+ }
2355
+ function isProtected(fullPath, protectedDirs) {
2356
+ return protectedDirs.some((d) => {
2357
+ const dir = d.endsWith("/") ? d.slice(0, -1) : d;
2358
+ return fullPath === dir || fullPath.startsWith(dir + "/");
2359
+ });
2360
+ }
2361
+ async function purgeKeepFiles(fs, options = {}) {
2362
+ const root = options.root && options.root !== "" ? options.root : "/";
2363
+ const dryRun = options.dryRun ?? false;
2364
+ const protectedDirs = options.protectedDirs ?? DEFAULT_PROTECTED_DIRS;
2365
+ const result = { scanned: 0, removed: [], failed: [] };
2366
+ const stack = [root];
2367
+ while (stack.length > 0) {
2368
+ const dir = stack.pop();
2369
+ if (isProtected(dir, protectedDirs)) continue;
2370
+ let entries;
2371
+ try {
2372
+ entries = await fs.readdir(dir);
2373
+ } catch {
2374
+ continue;
2375
+ }
2376
+ for (const entry of entries) {
2377
+ const fullPath = joinPath2(dir, entry);
2378
+ if (isProtected(fullPath, protectedDirs)) continue;
2379
+ let stat;
2380
+ try {
2381
+ stat = await fs.stat(fullPath);
2382
+ } catch {
2383
+ continue;
2384
+ }
2385
+ if (isDirectory2(stat)) {
2386
+ stack.push(fullPath);
2387
+ continue;
2388
+ }
2389
+ result.scanned++;
2390
+ if (!isKeepFile(entry)) continue;
2391
+ if (dryRun) {
2392
+ result.removed.push(fullPath);
2393
+ continue;
2394
+ }
2395
+ try {
2396
+ await fs.unlink(fullPath);
2397
+ result.removed.push(fullPath);
2398
+ } catch {
2399
+ result.failed.push(fullPath);
2400
+ }
2401
+ }
2402
+ }
2403
+ return result;
2404
+ }
2405
+
2406
+ // src/version-migration.ts
2407
+ var S_IFDIR3 = 16384;
2408
+ function isDir(stat) {
2409
+ return typeof stat.mode === "number" && (stat.mode & S_IFDIR3) === S_IFDIR3;
2410
+ }
2411
+ function joinPath3(dir, entry) {
2412
+ if (dir === "/" || dir === "") return `/${entry}`;
2413
+ return `${dir.replace(/\/+$/, "")}/${entry}`;
2414
+ }
2415
+ async function existsPath(fs, p) {
2416
+ try {
2417
+ await fs.stat(p);
2418
+ return true;
2419
+ } catch {
2420
+ return false;
2421
+ }
2422
+ }
2423
+ function configNameFromLegacy(entry) {
2424
+ const noMtime = entry.endsWith(".version.mtime") ? entry.slice(0, -".version.mtime".length) : entry.slice(0, -".version".length);
2425
+ return noMtime.slice(1);
2426
+ }
2427
+ async function resolveTarget(fs, dir, entry) {
2428
+ const configName = configNameFromLegacy(entry);
2429
+ const configPath = joinPath3(dir, configName);
2430
+ const dotConfigPath = joinPath3(dir, `.${configName}`);
2431
+ if (await existsPath(fs, dotConfigPath)) {
2432
+ return { action: "skip" };
2433
+ }
2434
+ if (await existsPath(fs, configPath)) {
2435
+ return { action: "rename", newPath: versionPathFor(configPath) ?? `${configName}.version` };
2436
+ }
2437
+ return { action: "delete" };
2438
+ }
2439
+ async function migrateVersionSidecars(fs, options = {}) {
2440
+ const root = options.root && options.root !== "" ? options.root : "/";
2441
+ const dryRun = options.dryRun ?? false;
2442
+ const replicas = options.replicas ?? [];
2443
+ const result = {
2444
+ renamed: [],
2445
+ deleted: [],
2446
+ remoteDeleted: [],
2447
+ failed: []
2448
+ };
2449
+ const stack = [root];
2450
+ while (stack.length > 0) {
2451
+ const dir = stack.pop();
2452
+ let entries;
2453
+ try {
2454
+ entries = await fs.readdir(dir);
2455
+ } catch {
2456
+ continue;
2457
+ }
2458
+ for (const entry of entries) {
2459
+ const full = joinPath3(dir, entry);
2460
+ let stat;
2461
+ try {
2462
+ stat = await fs.stat(full);
2270
2463
  } catch {
2271
2464
  continue;
2272
2465
  }
2273
- for (const entry of entries) {
2274
- if (seen.has(entry)) continue;
2275
- const archive = await readJson(this.fs, `${dir}/${entry}/meta.json`);
2276
- if (!archive) continue;
2277
- seen.add(entry);
2278
- archives.push(archive);
2466
+ if (isDir(stat)) {
2467
+ stack.push(full);
2468
+ continue;
2469
+ }
2470
+ const isLegacyVersion = entry.startsWith(".") && (entry.endsWith(".version") || entry.endsWith(".version.mtime"));
2471
+ if (!isLegacyVersion) continue;
2472
+ const legacyVerPath = entry.endsWith(".version.mtime") ? full.slice(0, -".mtime".length) : full;
2473
+ const target = await resolveTarget(fs, dir, entry);
2474
+ if (target.action === "skip") continue;
2475
+ const legacyMtimePath = `${legacyVerPath}.mtime`;
2476
+ const newMtimePath = target.newPath ? `${target.newPath}.mtime` : null;
2477
+ if (dryRun) {
2478
+ if (target.action === "rename") result.renamed.push(full);
2479
+ else result.deleted.push(full);
2480
+ continue;
2279
2481
  }
2280
- }
2281
- return archives.sort((a, b) => a.timestamp - b.timestamp);
2282
- }
2283
- candidatesFor(conflictId) {
2284
- const id = conflictId.replace(/\/meta\.json$/, "");
2285
- return [`${CONFLICTS_DIR}/${id}`, `${LEGACY_CONFLICTS_DIR}/${id}`];
2286
- }
2287
- async readBackup(conflictId, fileType) {
2288
- for (const dir of this.candidatesFor(conflictId)) {
2289
- const p = `${dir}/${fileType}`;
2290
2482
  try {
2291
- return new TextDecoder().decode(toBytes(await this.fs.readFile(p)));
2292
- } catch {
2483
+ if (target.action === "rename") {
2484
+ if (await existsPath(fs, target.newPath)) {
2485
+ await fs.unlink(legacyVerPath);
2486
+ result.deleted.push(full);
2487
+ } else {
2488
+ const content = await fs.readFile(legacyVerPath);
2489
+ const bytes = typeof content === "string" ? new TextEncoder().encode(content) : content;
2490
+ await fs.writeFile(target.newPath, bytes);
2491
+ await fs.unlink(legacyVerPath);
2492
+ result.renamed.push(full);
2493
+ }
2494
+ if (newMtimePath && await existsPath(fs, legacyMtimePath)) {
2495
+ try {
2496
+ const mc = await fs.readFile(legacyMtimePath);
2497
+ const mb = typeof mc === "string" ? new TextEncoder().encode(mc) : mc;
2498
+ await fs.writeFile(newMtimePath, mb);
2499
+ await fs.unlink(legacyMtimePath);
2500
+ } catch {
2501
+ }
2502
+ }
2503
+ } else {
2504
+ await fs.unlink(legacyVerPath);
2505
+ result.deleted.push(full);
2506
+ if (await existsPath(fs, legacyMtimePath)) {
2507
+ try {
2508
+ await fs.unlink(legacyMtimePath);
2509
+ } catch {
2510
+ }
2511
+ }
2512
+ }
2513
+ } catch (e) {
2514
+ result.failed.push(full);
2515
+ continue;
2516
+ }
2517
+ for (const rep of replicas) {
2518
+ for (const rp of [legacyVerPath, legacyMtimePath]) {
2519
+ try {
2520
+ await rep.unlink(rp);
2521
+ result.remoteDeleted.push(rp);
2522
+ } catch {
2523
+ }
2524
+ }
2293
2525
  }
2294
2526
  }
2295
- throw new Error(`Conflict backup not found: ${conflictId}/${fileType}`);
2296
- }
2297
- /** Resolve a conflict with raw (already serialized) content. */
2298
- async resolve(conflictId, mergedContent) {
2299
- for (const dir of this.candidatesFor(conflictId)) {
2300
- const metaPath = `${dir}/meta.json`;
2301
- const archive = await readJson(this.fs, metaPath);
2302
- if (!archive) continue;
2303
- const bytes = typeof mergedContent === "string" ? new TextEncoder().encode(mergedContent) : mergedContent;
2304
- await ensureParentDir2(this.fs, archive.conflictPath);
2305
- await this.fs.writeFile(archive.conflictPath, bytes);
2306
- await this.versions.record(archive.conflictPath, bytes);
2307
- await this.fs.writeFile(`${dir}/resolved`, bytes);
2308
- archive.resolvedBackupPath = "./resolved";
2309
- await writeJson(this.fs, metaPath, archive);
2310
- return;
2311
- }
2312
- throw new Error(`Failed to resolve conflict ${conflictId}: archive not found`);
2313
2527
  }
2314
- };
2528
+ return result;
2529
+ }
2315
2530
 
2316
2531
  // src/config-repo.ts
2317
- var log4 = (0, import_localstorage_logger4.createLogger)("zen-fs-config:config-repo");
2532
+ var log5 = (0, import_localstorage_logger5.createLogger)("zen-fs-config:config-repo");
2318
2533
  var GROUP_DESCRIPTOR_FILE3 = `${META_DIR}/group.json`;
2319
2534
  var GROUP_TYPE_FILE = `${CONFIG_DIR}/group-type`;
2320
2535
  var LEGACY_GROUP_TYPE_FILE = `${META_DIR}/group-type`;
@@ -2347,81 +2562,6 @@ async function isDirectoryPath(fs, absolutePath) {
2347
2562
  return false;
2348
2563
  }
2349
2564
  }
2350
- async function collectFilesUnder(fs, dir, out = []) {
2351
- const entries = await fs.readdir(dir);
2352
- for (const entry of entries) {
2353
- const child = dir === "/" ? `/${entry}` : `${dir}/${entry}`;
2354
- if (await isDirectoryPath(fs, child)) {
2355
- await collectFilesUnder(fs, child, out);
2356
- } else {
2357
- out.push(child);
2358
- }
2359
- }
2360
- return out;
2361
- }
2362
- async function collectDirectoriesUnder(fs, dir, out = []) {
2363
- out.push(dir);
2364
- let entries;
2365
- try {
2366
- entries = await fs.readdir(dir);
2367
- } catch {
2368
- return out;
2369
- }
2370
- for (const entry of entries) {
2371
- const child = dir === "/" ? `/${entry}` : `${dir}/${entry}`;
2372
- if (await isDirectoryPath(fs, child)) await collectDirectoriesUnder(fs, child, out);
2373
- }
2374
- return out;
2375
- }
2376
- async function removeDirectoryTree(fs, dir) {
2377
- let entries;
2378
- try {
2379
- entries = await fs.readdir(dir);
2380
- } catch {
2381
- return;
2382
- }
2383
- for (const entry of entries) {
2384
- const child = dir === "/" ? `/${entry}` : `${dir}/${entry}`;
2385
- if (await isDirectoryPath(fs, child)) await removeDirectoryTree(fs, child);
2386
- }
2387
- try {
2388
- await fs.rmdir?.(dir);
2389
- } catch {
2390
- }
2391
- }
2392
- async function collectFilesUnderAny(surfaces, dir, onError) {
2393
- const merged = /* @__PURE__ */ new Set();
2394
- for (const surface of surfaces) {
2395
- try {
2396
- for (const file of await collectFilesUnder(surface.fs, dir)) merged.add(file);
2397
- } catch (error) {
2398
- onError(surface.label, error);
2399
- }
2400
- }
2401
- return [...merged];
2402
- }
2403
- async function collectDirectoriesUnderStrict(fs, dir, out = []) {
2404
- out.push(dir);
2405
- const entries = await fs.readdir(dir);
2406
- for (const entry of entries) {
2407
- const child = dir === "/" ? `/${entry}` : `${dir}/${entry}`;
2408
- if (await isDirectoryPath(fs, child)) await collectDirectoriesUnderStrict(fs, child, out);
2409
- }
2410
- return out;
2411
- }
2412
- async function collectDirectoriesUnderAny(surfaces, dir, onError) {
2413
- const merged = /* @__PURE__ */ new Set();
2414
- for (const surface of surfaces) {
2415
- const found = [];
2416
- try {
2417
- await collectDirectoriesUnderStrict(surface.fs, dir, found);
2418
- } catch (error) {
2419
- onError(surface.label, error);
2420
- }
2421
- for (const child of found) merged.add(child);
2422
- }
2423
- return [...merged];
2424
- }
2425
2565
  async function isDirectoryAny(surfaces, path) {
2426
2566
  for (const surface of surfaces) {
2427
2567
  if (await isDirectoryPath(surface.fs, path)) return true;
@@ -2558,6 +2698,15 @@ var ConfigRepo = class {
2558
2698
  tombstoneConfirmations = /* @__PURE__ */ new Map();
2559
2699
  /** Per-backend sync state (successful pairs + connect failures). */
2560
2700
  backendStates = /* @__PURE__ */ new Map();
2701
+ /**
2702
+ * 本组的实例身份(UUID,见 `group-identity.ts`)。
2703
+ *
2704
+ * 它同时是同步边界:连接任何远端副本前先比对对方 `.meta/group.json` 里的
2705
+ * `instanceId`,不一致就不建同步对 —— 两个不同的同步组永不互相同步。
2706
+ */
2707
+ instanceId;
2708
+ /** 因归属他人而被跳过的后端 id → 原因,供 UI 展示。 */
2709
+ skippedBackends = /* @__PURE__ */ new Map();
2561
2710
  /** Last known backend descriptors, for the synchronous unified handle API. */
2562
2711
  backendDescriptorCache = [];
2563
2712
  /**
@@ -2629,7 +2778,7 @@ var ConfigRepo = class {
2629
2778
  const bytes = this.serializer.serialize(data, fullPath);
2630
2779
  this.configCache.set(fullPath, data);
2631
2780
  this.persistConfig(fullPath, bytes).catch((err) => {
2632
- log4.error(`[zen-fs-config] Failed to persist ${fullPath}:`, err);
2781
+ log5.error(`[zen-fs-config] Failed to persist ${fullPath}:`, err);
2633
2782
  });
2634
2783
  }
2635
2784
  // -----------------------------------------------------------------------
@@ -2746,19 +2895,22 @@ var ConfigRepo = class {
2746
2895
  // Tombstone (Deletion Tracking)
2747
2896
  // -----------------------------------------------------------------------
2748
2897
  /**
2749
- * Write the tombstone record for `filePath` under `.meta/tombstones/`.
2750
- * Records only metadata — it never creates the deleted file locally, and the
2898
+ * Write the tombstone record for `path` under `.meta/tombstones/`.
2899
+ * Records only metadata — it never creates the deleted path locally, and the
2751
2900
  * legacy `/.meta/.deleted/` archive is neither read nor written.
2901
+ *
2902
+ * `type: 'directory'` 表示这是一条目录墓碑:应用时按整棵树清理。
2752
2903
  */
2753
- async writeTombstoneFor(filePath) {
2754
- const normalizedPath = filePath.startsWith("/") ? filePath : "/" + filePath;
2904
+ async writeTombstoneFor(path, type) {
2905
+ const normalizedPath = normalizeTombstonePath(path);
2755
2906
  const tombstone = {
2756
2907
  path: normalizedPath,
2757
2908
  deletedAt: Date.now(),
2758
2909
  deletedBy: this.primaryBackendId,
2759
- confirmedBy: [this.primaryBackendId]
2910
+ confirmedBy: [this.primaryBackendId],
2911
+ ...type ? { type } : {}
2760
2912
  };
2761
- const tombstoneBytes = new TextEncoder().encode(JSON.stringify(tombstone, null, 2));
2913
+ const tombstoneBytes = new TextEncoder().encode(serializeTombstone(tombstone));
2762
2914
  const tombstonePath = tombstonePathFor(normalizedPath, TOMBSTONES_DIR);
2763
2915
  await this.ensureDir(tombstonePath);
2764
2916
  await this.cachedFS.writeFile(tombstonePath, tombstoneBytes);
@@ -2769,29 +2921,17 @@ var ConfigRepo = class {
2769
2921
  */
2770
2922
  async deleteFile(path) {
2771
2923
  this.assertNotDisposed();
2772
- const normalizedPath = path.startsWith("/") ? path : "/" + path;
2924
+ const normalizedPath = normalizeTombstonePath(path);
2773
2925
  const surfaces = [{ label: "local-cache", fs: this.cachedFS }];
2774
2926
  for (const [id, replica] of this.replicaBackends) {
2775
2927
  surfaces.push({ label: id, fs: replica.instance });
2776
2928
  }
2777
- const onEnumerateError = (label, error) => {
2778
- const reason = error?.message ?? String(error);
2779
- log4.warn(
2780
- `[ConfigRepo] deleteFile(directory): cannot enumerate "${label}" under ${normalizedPath}: ${reason}`
2781
- );
2782
- };
2783
2929
  if (await isDirectoryAny(surfaces, normalizedPath)) {
2784
- const files = await collectFilesUnderAny(surfaces, normalizedPath, onEnumerateError);
2785
- for (const file of files) await this.deleteFile(file);
2786
- for (const dir of await collectDirectoriesUnderAny(surfaces, normalizedPath, onEnumerateError)) {
2787
- const keepPath = dir === "/" ? "/.keep" : `${dir}/.keep`;
2788
- await this.writeTombstoneFor(keepPath);
2789
- await this.writeTombstoneFor(`${keepPath}.mtime`);
2790
- }
2791
- await removeDirectoryTree(this.cachedFS, normalizedPath);
2930
+ await this.writeTombstoneFor(normalizedPath, "directory");
2931
+ await this.purgePathOnBackend(this.cachedFS, normalizedPath);
2792
2932
  this.invalidateTombstoneCache();
2793
2933
  this.schedulePostDeleteSync();
2794
- log4.log(`[ConfigRepo] deleteFile(directory): ${normalizedPath} (${files.length} file(s))`);
2934
+ log5.log(`[ConfigRepo] deleteFile(directory): ${normalizedPath} (single directory tombstone)`);
2795
2935
  return;
2796
2936
  }
2797
2937
  await this.writeTombstoneFor(normalizedPath);
@@ -2812,7 +2952,7 @@ var ConfigRepo = class {
2812
2952
  } catch {
2813
2953
  }
2814
2954
  }
2815
- log4.log(`[ConfigRepo] deleteFile: ${normalizedPath} (tombstone at ${tombstonePathFor(normalizedPath)})`);
2955
+ log5.log(`[ConfigRepo] deleteFile: ${normalizedPath} (tombstone at ${tombstonePathFor(normalizedPath)})`);
2816
2956
  this.invalidateTombstoneCache();
2817
2957
  this.schedulePostDeleteSync();
2818
2958
  }
@@ -2830,7 +2970,7 @@ var ConfigRepo = class {
2830
2970
  this.postDeleteSyncTimer = void 0;
2831
2971
  if (this.disposed) return;
2832
2972
  this.syncEngine.syncAll().catch((err) => {
2833
- log4.warn("[ConfigRepo] post-delete sync failed:", err);
2973
+ log5.warn("[ConfigRepo] post-delete sync failed:", err);
2834
2974
  });
2835
2975
  }, 500);
2836
2976
  }
@@ -2842,7 +2982,7 @@ var ConfigRepo = class {
2842
2982
  if (this.tombstoneCache !== null) {
2843
2983
  return this.tombstoneCache;
2844
2984
  }
2845
- this.tombstoneCache = await readTombstonesFromFs(this.cachedFS, (message) => log4.warn(message));
2985
+ this.tombstoneCache = await readTombstonesFromFs(this.cachedFS, (message) => log5.warn(message));
2846
2986
  this.refreshSyncExclusions(this.tombstoneCache);
2847
2987
  return this.tombstoneCache;
2848
2988
  }
@@ -2915,7 +3055,8 @@ var ConfigRepo = class {
2915
3055
  for (const tombstone of tombstones) {
2916
3056
  const isKeepPlaceholder = tombstone.path === "/.keep" || tombstone.path.endsWith("/.keep");
2917
3057
  const forceDelete = isMtimeSidecar(tombstone.path) || isKeepPlaceholder;
2918
- const tVersionPath = forceDelete ? null : versionPathFor(tombstone.path);
3058
+ const isDirTombstone = isDirectoryTombstone(tombstone);
3059
+ const tVersionPath = forceDelete || isDirTombstone ? null : versionPathFor(tombstone.path);
2919
3060
  if (!forceDelete && await this.isPathRecreatedAfterTombstone(tombstone)) {
2920
3061
  expired.push(tombstone);
2921
3062
  continue;
@@ -2973,7 +3114,7 @@ var ConfigRepo = class {
2973
3114
  confirmed.add(replicaId);
2974
3115
  } else {
2975
3116
  unresolved++;
2976
- log4.warn(
3117
+ log5.warn(
2977
3118
  `[ConfigRepo] tombstone kept: ${tombstone.path} still present on replica ${replicaId}`
2978
3119
  );
2979
3120
  }
@@ -2988,12 +3129,12 @@ var ConfigRepo = class {
2988
3129
  }
2989
3130
  this.invalidateTombstoneCache();
2990
3131
  await this.readTombstones();
2991
- log4.log(
3132
+ log5.log(
2992
3133
  `[ConfigRepo] processTombstones: expired ${expired.length} tombstone(s) \u2014 path recreated after deletion`
2993
3134
  );
2994
3135
  }
2995
3136
  if (processed > 0 || alreadyDeleted > 0 || unresolved > 0) {
2996
- log4.log(
3137
+ log5.log(
2997
3138
  `[ConfigRepo] processTombstones: ${tombstones.length} tombstone(s), ${processed} deleted, ${alreadyDeleted} already gone, ${unresolved} unresolved`
2998
3139
  );
2999
3140
  }
@@ -3094,21 +3235,21 @@ var ConfigRepo = class {
3094
3235
  const innerBackendName = fs?.inner?.backendName;
3095
3236
  const directBackendName = fs?.backendName;
3096
3237
  const backendLabel = innerBackendName ?? directBackendName ?? innerBackend ?? ctorName;
3097
- log4.log(`[TOMB-TRACE] safeExists(${path}): fs type=${ctorName} backend=${backendLabel} hasExists=${hasExists} hasStat=${hasStat} inner=${innerBackend ?? "N/A"}`);
3238
+ log5.log(`[TOMB-TRACE] safeExists(${path}): fs type=${ctorName} backend=${backendLabel} hasExists=${hasExists} hasStat=${hasStat} inner=${innerBackend ?? "N/A"}`);
3098
3239
  if (hasExists) {
3099
- log4.log(`[TOMB-TRACE] safeExists(${path}): \u2192 calling fs.exists() [backend=${backendLabel}]`);
3240
+ log5.log(`[TOMB-TRACE] safeExists(${path}): \u2192 calling fs.exists() [backend=${backendLabel}]`);
3100
3241
  const result = await fs.exists(path);
3101
- log4.log(`[TOMB-TRACE] safeExists(${path}): \u2190 fs.exists() [backend=${backendLabel}] \u2192 ${result}`);
3242
+ log5.log(`[TOMB-TRACE] safeExists(${path}): \u2190 fs.exists() [backend=${backendLabel}] \u2192 ${result}`);
3102
3243
  return result;
3103
3244
  }
3104
- log4.log(`[TOMB-TRACE] safeExists(${path}): no exists(), calling fs.stat() [backend=${backendLabel}]`);
3245
+ log5.log(`[TOMB-TRACE] safeExists(${path}): no exists(), calling fs.stat() [backend=${backendLabel}]`);
3105
3246
  await fs.stat(path);
3106
- log4.log(`[TOMB-TRACE] safeExists(${path}): \u2190 fs.stat() [backend=${backendLabel}] \u2192 OK (exists)`);
3247
+ log5.log(`[TOMB-TRACE] safeExists(${path}): \u2190 fs.stat() [backend=${backendLabel}] \u2192 OK (exists)`);
3107
3248
  return true;
3108
3249
  } catch (err) {
3109
3250
  const errCode = err?.code ?? err?.status ?? "";
3110
3251
  const errName = err?.constructor?.name ?? "";
3111
- log4.log(`[TOMB-TRACE] safeExists(${path}): \u2190 ERROR ${errName} ${errCode} ${err?.message ?? err}`);
3252
+ log5.log(`[TOMB-TRACE] safeExists(${path}): \u2190 ERROR ${errName} ${errCode} ${err?.message ?? err}`);
3112
3253
  return false;
3113
3254
  }
3114
3255
  }
@@ -3135,13 +3276,13 @@ var ConfigRepo = class {
3135
3276
  this.assertNotDisposed();
3136
3277
  const result = await purgeMtimeSidecars(this.cachedFS, options);
3137
3278
  if (result.removed.length > 0) {
3138
- log4.log(
3279
+ log5.log(
3139
3280
  `[ConfigRepo] purged ${result.removed.length} .mtime sidecar(s) from local primary` + (options?.dryRun ? " (dry run)" : ""),
3140
3281
  result.removed
3141
3282
  );
3142
3283
  }
3143
3284
  if (result.failed.length > 0) {
3144
- log4.warn(`[ConfigRepo] failed to purge ${result.failed.length} .mtime sidecar(s):`, result.failed);
3285
+ log5.warn(`[ConfigRepo] failed to purge ${result.failed.length} .mtime sidecar(s):`, result.failed);
3145
3286
  }
3146
3287
  return result;
3147
3288
  }
@@ -3161,13 +3302,13 @@ var ConfigRepo = class {
3161
3302
  this.assertNotDisposed();
3162
3303
  const result = await purgeKeepFiles(this.cachedFS, options);
3163
3304
  if (result.removed.length > 0) {
3164
- log4.log(
3305
+ log5.log(
3165
3306
  `[ConfigRepo] purged ${result.removed.length} .keep placeholder(s) from local primary` + (options?.dryRun ? " (dry run)" : ""),
3166
3307
  result.removed
3167
3308
  );
3168
3309
  }
3169
3310
  if (result.failed.length > 0) {
3170
- log4.warn(`[ConfigRepo] failed to purge ${result.failed.length} .keep placeholder(s):`, result.failed);
3311
+ log5.warn(`[ConfigRepo] failed to purge ${result.failed.length} .keep placeholder(s):`, result.failed);
3171
3312
  }
3172
3313
  return result;
3173
3314
  }
@@ -3186,24 +3327,24 @@ var ConfigRepo = class {
3186
3327
  }));
3187
3328
  const result = await migrateVersionSidecars(this.cachedFS, { replicas });
3188
3329
  if (result.renamed.length > 0) {
3189
- log4.log(
3330
+ log5.log(
3190
3331
  `[ConfigRepo] migrated ${result.renamed.length} legacy version sidecar(s) to new naming`,
3191
3332
  result.renamed
3192
3333
  );
3193
3334
  }
3194
3335
  if (result.deleted.length > 0) {
3195
- log4.log(
3336
+ log5.log(
3196
3337
  `[ConfigRepo] removed ${result.deleted.length} orphaned legacy version sidecar(s)`,
3197
3338
  result.deleted
3198
3339
  );
3199
3340
  }
3200
3341
  if (result.remoteDeleted.length > 0) {
3201
- log4.log(
3342
+ log5.log(
3202
3343
  `[ConfigRepo] removed ${result.remoteDeleted.length} remote residual legacy version sidecar(s)`
3203
3344
  );
3204
3345
  }
3205
3346
  if (result.failed.length > 0) {
3206
- log4.warn(`[ConfigRepo] failed to migrate ${result.failed.length} legacy version sidecar(s):`, result.failed);
3347
+ log5.warn(`[ConfigRepo] failed to migrate ${result.failed.length} legacy version sidecar(s):`, result.failed);
3207
3348
  }
3208
3349
  return result;
3209
3350
  }
@@ -3226,9 +3367,9 @@ var ConfigRepo = class {
3226
3367
  */
3227
3368
  startBackgroundSync() {
3228
3369
  this.initialSyncPromise = this.initialSyncAndDedup().then(() => {
3229
- log4.log("[ConfigRepo] Background initial sync complete");
3370
+ log5.log("[ConfigRepo] Background initial sync complete");
3230
3371
  }).catch((err) => {
3231
- log4.error("[ConfigRepo] Background initial sync failed:", err);
3372
+ log5.error("[ConfigRepo] Background initial sync failed:", err);
3232
3373
  }).finally(() => {
3233
3374
  this.initialSyncPromise = null;
3234
3375
  });
@@ -3257,7 +3398,7 @@ var ConfigRepo = class {
3257
3398
  }
3258
3399
  if (changed) {
3259
3400
  try {
3260
- const bytes = new TextEncoder().encode(JSON.stringify(tombstone, null, 2));
3401
+ const bytes = new TextEncoder().encode(serializeTombstone(tombstone));
3261
3402
  const tombstonePath = tombstonePathFor(tombstone.path, TOMBSTONES_DIR);
3262
3403
  if (await this.safeExists(this.cachedFS, tombstonePath)) {
3263
3404
  await this.cachedFS.writeFile(tombstonePath, bytes);
@@ -3267,7 +3408,7 @@ var ConfigRepo = class {
3267
3408
  }
3268
3409
  }
3269
3410
  }
3270
- log4.log(`[ConfigRepo] updateTombstoneConfirmations: ${modified} tombstone(s) updated`);
3411
+ log5.log(`[ConfigRepo] updateTombstoneConfirmations: ${modified} tombstone(s) updated`);
3271
3412
  if (modified > 0) this.invalidateTombstoneCache();
3272
3413
  }
3273
3414
  /**
@@ -3326,11 +3467,11 @@ var ConfigRepo = class {
3326
3467
  }
3327
3468
  }
3328
3469
  }
3329
- log4.log(`[ConfigRepo] gcTombstones: removed ${tombstonePath} (all ${allBackendIds.length} backends confirmed)`);
3470
+ log5.log(`[ConfigRepo] gcTombstones: removed ${tombstonePath} (all ${allBackendIds.length} backends confirmed)`);
3330
3471
  }
3331
3472
  }
3332
3473
  if (keptByRetention > 0) {
3333
- log4.log(`[ConfigRepo] gcTombstones: kept ${keptByRetention} tombstone(s) within retention window`);
3474
+ log5.log(`[ConfigRepo] gcTombstones: kept ${keptByRetention} tombstone(s) within retention window`);
3334
3475
  }
3335
3476
  }
3336
3477
  /**
@@ -3345,7 +3486,7 @@ var ConfigRepo = class {
3345
3486
  this.assertNotDisposed();
3346
3487
  const results = await this.flush();
3347
3488
  for (const result of results) {
3348
- log4.log(
3489
+ log5.log(
3349
3490
  `[ConfigRepo] syncMetaToReplicas: ${result.pairId} +${result.filesCreated}/~${result.filesUpdated}/-${result.filesDeleted} skip:${result.filesSkipped} ${result.durationMs}ms`
3350
3491
  );
3351
3492
  }
@@ -3518,21 +3659,29 @@ var ConfigRepo = class {
3518
3659
  // Internal — Setup
3519
3660
  // -----------------------------------------------------------------------
3520
3661
  async setupSync(backends, primaryBackendId, pollIntervalMs) {
3521
- log4.log(`[ConfigRepo] setupSync: ${backends.length} backends, primary=${primaryBackendId} pollInterval=${pollIntervalMs ?? "default"}ms`);
3662
+ log5.log(`[ConfigRepo] setupSync: ${backends.length} backends, primary=${primaryBackendId} pollInterval=${pollIntervalMs ?? "default"}ms`);
3522
3663
  for (const desc of backends) {
3523
3664
  if (desc.id === primaryBackendId) continue;
3524
3665
  if (desc.enabled === false) {
3525
- log4.log(`[ConfigRepo] Skipping disabled replica: ${desc.id}`);
3666
+ log5.log(`[ConfigRepo] Skipping disabled replica: ${desc.id}`);
3526
3667
  continue;
3527
3668
  }
3528
- log4.log(`[ConfigRepo] Creating replica backend: id=${desc.id}, type=${desc.type}`);
3669
+ log5.log(`[ConfigRepo] Creating replica backend: id=${desc.id}, type=${desc.type}`);
3529
3670
  try {
3530
3671
  const instance = await createBackend(desc);
3672
+ const owner = await this.bindBackendIdentity(instance, desc.id);
3673
+ if (owner === "conflict") {
3674
+ try {
3675
+ await instance.dispose?.();
3676
+ } catch {
3677
+ }
3678
+ continue;
3679
+ }
3531
3680
  let fsInstance = instance;
3532
3681
  if (this.cacheOptions) {
3533
3682
  const { wrapWithCache: wrapWithCache2 } = await Promise.resolve().then(() => (init_cache_wrapper(), cache_wrapper_exports));
3534
3683
  fsInstance = wrapWithCache2(instance, desc.id, this.cacheOptions);
3535
- log4.log(`[ConfigRepo] Replica ${desc.id} wrapped with CachedFileSystem (store=${this.cacheOptions.storeType ?? "IdbCacheStore"})`);
3684
+ log5.log(`[ConfigRepo] Replica ${desc.id} wrapped with CachedFileSystem (store=${this.cacheOptions.storeType ?? "IdbCacheStore"})`);
3536
3685
  }
3537
3686
  const syncable = backendToSyncableFS(fsInstance, `${desc.type}(${desc.id})`);
3538
3687
  const pair = this.syncEngine.addPair(
@@ -3550,7 +3699,7 @@ var ConfigRepo = class {
3550
3699
  this.invalidateTombstoneCache();
3551
3700
  await this.processTombstones();
3552
3701
  } catch (err) {
3553
- log4.warn("[ConfigRepo] preSyncHook processTombstones failed:", err);
3702
+ log5.warn("[ConfigRepo] preSyncHook processTombstones failed:", err);
3554
3703
  }
3555
3704
  },
3556
3705
  postSyncHook: async () => {
@@ -3559,7 +3708,7 @@ var ConfigRepo = class {
3559
3708
  await this.processTombstones();
3560
3709
  await this.updateTombstoneConfirmations();
3561
3710
  } catch (err) {
3562
- log4.warn("[ConfigRepo] postSyncHook tombstone processing failed:", err);
3711
+ log5.warn("[ConfigRepo] postSyncHook tombstone processing failed:", err);
3563
3712
  }
3564
3713
  }
3565
3714
  },
@@ -3572,9 +3721,9 @@ var ConfigRepo = class {
3572
3721
  };
3573
3722
  this.syncEngine.on(pair.pairId, "conflict", conflictHandler);
3574
3723
  this.trackSyncErrors(desc.id, pair.pairId);
3575
- log4.log(`[ConfigRepo] Replica ${desc.id} created, sync pair=${pair.pairId}`);
3724
+ log5.log(`[ConfigRepo] Replica ${desc.id} created, sync pair=${pair.pairId}`);
3576
3725
  } catch (err) {
3577
- log4.error(`[ConfigRepo] Failed to create replica ${desc.id} (${desc.type}):`, err);
3726
+ log5.error(`[ConfigRepo] Failed to create replica ${desc.id} (${desc.type}):`, err);
3578
3727
  this.backendStates.set(desc.id, {
3579
3728
  backendId: desc.id,
3580
3729
  error: {
@@ -3584,8 +3733,8 @@ var ConfigRepo = class {
3584
3733
  });
3585
3734
  }
3586
3735
  }
3587
- log4.log(`[ConfigRepo] setupSync complete. Replicas:`, Array.from(this.replicaBackends.keys()));
3588
- log4.log(`[ConfigRepo] Sync statuses:`, this.getSyncStatuses());
3736
+ log5.log(`[ConfigRepo] setupSync complete. Replicas:`, Array.from(this.replicaBackends.keys()));
3737
+ log5.log(`[ConfigRepo] Sync statuses:`, this.getSyncStatuses());
3589
3738
  }
3590
3739
  // -----------------------------------------------------------------------
3591
3740
  // Internal — Persistence
@@ -3597,12 +3746,12 @@ var ConfigRepo = class {
3597
3746
  try {
3598
3747
  const existing = await readVersion(this.fullFS, vPath);
3599
3748
  if (existing && existing.hash === version.hash) {
3600
- log4.log("[ConfigRepo] skip version sidecar (hash unchanged):", vPath);
3749
+ log5.log("[ConfigRepo] skip version sidecar (hash unchanged):", vPath);
3601
3750
  return;
3602
3751
  }
3603
3752
  } catch {
3604
3753
  }
3605
- log4.log("[ConfigRepo] write version sidecar:", vPath, "v" + version.version);
3754
+ log5.log("[ConfigRepo] write version sidecar:", vPath, "v" + version.version);
3606
3755
  await this.ensureDir(vPath);
3607
3756
  await writeVersion(this.fullFS, vPath, version);
3608
3757
  }
@@ -3706,7 +3855,7 @@ var ConfigRepo = class {
3706
3855
  await this.resolveConflict(`${conflictId}/meta.json`, customMerge);
3707
3856
  }
3708
3857
  } catch (err) {
3709
- log4.error("[zen-fs-config] Conflict handler error:", err);
3858
+ log5.error("[zen-fs-config] Conflict handler error:", err);
3710
3859
  }
3711
3860
  }
3712
3861
  }
@@ -3766,6 +3915,30 @@ var ConfigRepo = class {
3766
3915
  const version = await incrementVersion(this.fullFS, path, bytes, author);
3767
3916
  await this.writeVersionSidecar(path, version);
3768
3917
  }
3918
+ /**
3919
+ * 写仓库根级文件(`/.config/...`、`/.meta/...`、`/shared/...` 等,不是 app 载荷)。
3920
+ *
3921
+ * 与 `setConfig()` 的区别:`setConfig(path)` 会把路径拼成 `/${appId}${path}`,
3922
+ * 是给应用自己的配置键用的;根级文件必须落在 cachedFS 的真实路径上,否则编辑
3923
+ * 会写进 `/admin/.config/...` 之类的影子目录(读的地方看不到,文件"改了又没改")。
3924
+ *
3925
+ * 落盘后按同一套机制记录 `.version` 边车(作者为 `appId/nodeId`),
3926
+ * 与内部写描述符 / 元数据的行为一致。
3927
+ */
3928
+ async writeRepoFile(path, data) {
3929
+ this.assertNotDisposed();
3930
+ const p = path.startsWith("/") ? path : `/${path}`;
3931
+ const bytes = typeof data === "string" ? new TextEncoder().encode(data) : data;
3932
+ await this.ensureDir(p);
3933
+ await this.cachedFS.writeFile(p, bytes);
3934
+ const author = `${this.appId}/${this.nodeId}`;
3935
+ try {
3936
+ const version = await incrementVersion(this.fullFS, p, bytes, author);
3937
+ await this.writeVersionSidecar(p, version);
3938
+ } catch (err) {
3939
+ log5.warn(`[ConfigRepo] writeRepoFile: version sidecar failed for ${p}:`, err);
3940
+ }
3941
+ }
3769
3942
  async readMetaFile(path) {
3770
3943
  try {
3771
3944
  const raw = await this.cachedFS.readFile(path);
@@ -3822,11 +3995,11 @@ var ConfigRepo = class {
3822
3995
  }
3823
3996
  return { kind: "ok", desc, mtime };
3824
3997
  } else {
3825
- log4.warn(`[ConfigRepo] Backend descriptor ${entry} is missing id/type fields, marking for cleanup`);
3998
+ log5.warn(`[ConfigRepo] Backend descriptor ${entry} is missing id/type fields, marking for cleanup`);
3826
3999
  return { kind: "corrupt", filePath };
3827
4000
  }
3828
4001
  } catch (parseErr) {
3829
- log4.warn(`[ConfigRepo] Backend descriptor ${entry} has corrupted JSON: ${parseErr}. Marking for cleanup.`);
4002
+ log5.warn(`[ConfigRepo] Backend descriptor ${entry} has corrupted JSON: ${parseErr}. Marking for cleanup.`);
3830
4003
  return { kind: "corrupt", filePath };
3831
4004
  }
3832
4005
  })
@@ -3892,7 +4065,7 @@ var ConfigRepo = class {
3892
4065
  }
3893
4066
  }
3894
4067
  if (duplicates.length > 0) {
3895
- log4.log(
4068
+ log5.log(
3896
4069
  `[ConfigRepo] readAllBackendDescriptors: removing ${duplicates.length} duplicate(s): ${duplicates.join(", ")}`
3897
4070
  );
3898
4071
  for (const dupId of duplicates) {
@@ -4024,7 +4197,7 @@ var ConfigRepo = class {
4024
4197
  * Shared by addBackend() and replaceBackend().
4025
4198
  */
4026
4199
  async setupReplica(id, type, options, description) {
4027
- log4.log(`[ConfigRepo] addBackend: creating ${id} (${type})...`);
4200
+ log5.log(`[ConfigRepo] addBackend: creating ${id} (${type})...`);
4028
4201
  const instance = await createBackend({ type, options });
4029
4202
  const syncable = backendToSyncableFS(instance, `${type}(${id})`);
4030
4203
  const desc = { id, type, options, description };
@@ -4042,7 +4215,7 @@ var ConfigRepo = class {
4042
4215
  this.invalidateTombstoneCache();
4043
4216
  await this.processTombstones();
4044
4217
  } catch (err) {
4045
- log4.warn("[ConfigRepo] preSyncHook processTombstones failed:", err);
4218
+ log5.warn("[ConfigRepo] preSyncHook processTombstones failed:", err);
4046
4219
  }
4047
4220
  },
4048
4221
  postSyncHook: async () => {
@@ -4051,7 +4224,7 @@ var ConfigRepo = class {
4051
4224
  await this.processTombstones();
4052
4225
  await this.updateTombstoneConfirmations();
4053
4226
  } catch (err) {
4054
- log4.warn("[ConfigRepo] postSyncHook tombstone processing failed:", err);
4227
+ log5.warn("[ConfigRepo] postSyncHook tombstone processing failed:", err);
4055
4228
  }
4056
4229
  }
4057
4230
  },
@@ -4064,7 +4237,7 @@ var ConfigRepo = class {
4064
4237
  };
4065
4238
  this.syncEngine.on(pair.pairId, "conflict", conflictHandler);
4066
4239
  this.trackSyncErrors(id, pair.pairId);
4067
- log4.log(`[ConfigRepo] addBackend: ${id} (${type}) added, sync pair=${pair.pairId}`);
4240
+ log5.log(`[ConfigRepo] addBackend: ${id} (${type}) added, sync pair=${pair.pairId}`);
4068
4241
  await this.syncMetaToReplicas();
4069
4242
  this.syncEngine.watch(pair.pairId);
4070
4243
  return pair.pairId;
@@ -4090,13 +4263,13 @@ var ConfigRepo = class {
4090
4263
  }
4091
4264
  }
4092
4265
  this.syncEngine.removePair(replica.pairId);
4093
- log4.log(`[ConfigRepo] removeBackend: sync pair ${replica.pairId} removed`);
4266
+ log5.log(`[ConfigRepo] removeBackend: sync pair ${replica.pairId} removed`);
4094
4267
  this.replicaBackends.delete(id);
4095
4268
  if (replica.instance?.dispose) {
4096
4269
  await replica.instance.dispose();
4097
4270
  }
4098
4271
  } else {
4099
- log4.log(`[ConfigRepo] removeBackend: "${id}" not in replicaBackends, cleaning up descriptor only`);
4272
+ log5.log(`[ConfigRepo] removeBackend: "${id}" not in replicaBackends, cleaning up descriptor only`);
4100
4273
  for (const descPath of descPaths) {
4101
4274
  try {
4102
4275
  await this.deleteFile(descPath);
@@ -4107,7 +4280,7 @@ var ConfigRepo = class {
4107
4280
  }
4108
4281
  this.backendStates.delete(id);
4109
4282
  this.schedulePostDeleteSync();
4110
- log4.log(`[ConfigRepo] removeBackend: ${id} removed (tombstone written, remote cleaned)`);
4283
+ log5.log(`[ConfigRepo] removeBackend: ${id} removed (tombstone written, remote cleaned)`);
4111
4284
  }
4112
4285
  /**
4113
4286
  * Replace a config-sync backend's parameters in place (same id).
@@ -4154,11 +4327,11 @@ var ConfigRepo = class {
4154
4327
  await this.setupReplica(id, type, options, description ?? before.description);
4155
4328
  } catch (err) {
4156
4329
  const reason = err instanceof Error ? err.message : String(err);
4157
- log4.warn(`[ConfigRepo] replaceBackend: "${id}" failed, rolling back old options:`, err);
4330
+ log5.warn(`[ConfigRepo] replaceBackend: "${id}" failed, rolling back old options:`, err);
4158
4331
  try {
4159
4332
  await this.setupReplica(id, before.type, before.options, before.description);
4160
4333
  } catch (rollbackErr) {
4161
- log4.error(`[ConfigRepo] replaceBackend: rollback for "${id}" ALSO failed:`, rollbackErr);
4334
+ log5.error(`[ConfigRepo] replaceBackend: rollback for "${id}" ALSO failed:`, rollbackErr);
4162
4335
  }
4163
4336
  throw new Error(`\u66F4\u65B0\u540E\u7AEF\u53C2\u6570\u5931\u8D25\uFF1A${reason}\uFF08\u5DF2\u5C1D\u8BD5\u56DE\u6EDA\u65E7\u53C2\u6570\uFF09`);
4164
4337
  }
@@ -4166,6 +4339,80 @@ var ConfigRepo = class {
4166
4339
  // -----------------------------------------------------------------------
4167
4340
  // IConfigRepo — Group Type
4168
4341
  // -----------------------------------------------------------------------
4342
+ /**
4343
+ * 本组的同步身份(kind + id + 不可变 instanceId)。
4344
+ *
4345
+ * 首次调用时若 `.meta/group.json` 里还没有 `instanceId`(老部署),生成一个
4346
+ * 并就地写回 —— 只写一次,之后字节相同不再落盘。
4347
+ */
4348
+ async ensureGroupIdentity(kind = "config", id = CONFIG_GROUP_ID) {
4349
+ let existingFeatures;
4350
+ if (!this.instanceId) {
4351
+ let existing = null;
4352
+ try {
4353
+ existing = await readGroupDescriptor(this.cachedFS);
4354
+ } catch {
4355
+ }
4356
+ const known = pickInstanceId(existing);
4357
+ existingFeatures = existing?.features ?? CONFIG_GROUP_FEATURES;
4358
+ this.instanceId = known ?? newGroupInstanceId();
4359
+ if (!known) {
4360
+ try {
4361
+ await writeGroupDescriptor(this.cachedFS, {
4362
+ schemaVersion: 2,
4363
+ kind: existing?.kind ?? kind,
4364
+ id: existing?.id ?? id,
4365
+ instanceId: this.instanceId,
4366
+ ...existing?.name ?? this.name ? { name: existing?.name ?? this.name } : {},
4367
+ features: existing?.features ?? CONFIG_GROUP_FEATURES
4368
+ });
4369
+ log5.log(`[ConfigRepo] group instanceId assigned: ${this.instanceId} (kind=${existing?.kind ?? kind})`);
4370
+ } catch (err) {
4371
+ log5.warn("[ConfigRepo] failed to persist group instanceId:", err);
4372
+ }
4373
+ }
4374
+ }
4375
+ return {
4376
+ kind,
4377
+ id,
4378
+ instanceId: this.instanceId,
4379
+ ...this.name ? { name: this.name } : {},
4380
+ ...existingFeatures ? { features: existingFeatures } : {}
4381
+ };
4382
+ }
4383
+ /** 组实例身份(未初始化时先兜底生成并落盘)。 */
4384
+ async ensureGroupInstanceId() {
4385
+ return (await this.ensureGroupIdentity()).instanceId;
4386
+ }
4387
+ /** 组实例身份(同步读取;init 之前可能为 `undefined`)。 */
4388
+ getGroupInstanceId() {
4389
+ return this.instanceId;
4390
+ }
4391
+ /**
4392
+ * 连接远端前校验归属:属于别的组 → `conflict`(调用方必须跳过、不建同步对)。
4393
+ * 老仓库(无 instanceId)会被本组认领。
4394
+ */
4395
+ async bindBackendIdentity(instance, backendId) {
4396
+ try {
4397
+ const identity = await this.ensureGroupIdentity();
4398
+ const state = await bindRemoteGroupIdentity(instance, identity);
4399
+ if (state === "conflict") {
4400
+ this.skippedBackends.set(
4401
+ backendId,
4402
+ `\u8FDC\u7AEF\u6839\u5C5E\u4E8E\u53E6\u4E00\u4E2A\u540C\u6B65\u7EC4\uFF08instanceId \u4E0D\u4E00\u81F4\uFF09\uFF0C\u5DF2\u8DF3\u8FC7\u8BE5\u540E\u7AEF`
4403
+ );
4404
+ }
4405
+ return state;
4406
+ } catch (err) {
4407
+ log5.warn(`[ConfigRepo] identity check failed for backend "${backendId}", skipping it:`, err);
4408
+ this.skippedBackends.set(backendId, `\u5F52\u5C5E\u6821\u9A8C\u5931\u8D25\uFF1A${err?.message ?? String(err)}`);
4409
+ return "conflict";
4410
+ }
4411
+ }
4412
+ /** 因归属他人而被跳过的后端(id → 原因)。 */
4413
+ listSkippedBackends() {
4414
+ return Array.from(this.skippedBackends, ([backendId, reason]) => ({ backendId, reason }));
4415
+ }
4169
4416
  /** Write the group-type marker file if it doesn't exist. */
4170
4417
  async ensureGroupType(type) {
4171
4418
  this.assertNotDisposed();
@@ -4174,7 +4421,7 @@ var ConfigRepo = class {
4174
4421
  const existing = await this.cachedFS.readFile(path, "utf-8");
4175
4422
  const current = existing.trim();
4176
4423
  if (current && current !== type) {
4177
- log4.warn(`[ConfigRepo] group-type already set to "${current}" at ${path}, ignoring request to set "${type}"`);
4424
+ log5.warn(`[ConfigRepo] group-type already set to "${current}" at ${path}, ignoring request to set "${type}"`);
4178
4425
  return;
4179
4426
  }
4180
4427
  } catch {
@@ -4188,10 +4435,12 @@ var ConfigRepo = class {
4188
4435
  }
4189
4436
  const existingDescriptor = await readGroupDescriptor(this.cachedFS);
4190
4437
  if (!existingDescriptor) {
4438
+ this.instanceId = newGroupInstanceId();
4191
4439
  await writeGroupDescriptor(this.cachedFS, {
4192
4440
  schemaVersion: 2,
4193
4441
  kind: "config",
4194
4442
  id: CONFIG_GROUP_ID,
4443
+ instanceId: this.instanceId,
4195
4444
  ...this.name ? { name: this.name } : {},
4196
4445
  features: CONFIG_GROUP_FEATURES
4197
4446
  });
@@ -4205,7 +4454,22 @@ var ConfigRepo = class {
4205
4454
  features: existingDescriptor.features ?? CONFIG_GROUP_FEATURES
4206
4455
  });
4207
4456
  }
4208
- log4.log(`[ConfigRepo] group-type set to "${type}"`);
4457
+ const knownInstanceId = pickInstanceId(existingDescriptor);
4458
+ if (knownInstanceId) {
4459
+ this.instanceId = knownInstanceId;
4460
+ } else if (!this.instanceId) {
4461
+ this.instanceId = newGroupInstanceId();
4462
+ await writeGroupDescriptor(this.cachedFS, {
4463
+ schemaVersion: 2,
4464
+ kind: existingDescriptor?.kind ?? "config",
4465
+ id: existingDescriptor?.id ?? CONFIG_GROUP_ID,
4466
+ instanceId: this.instanceId,
4467
+ ...existingDescriptor?.name ?? this.name ? { name: existingDescriptor?.name ?? this.name } : {},
4468
+ ...existingDescriptor?.features ? { features: existingDescriptor.features } : {}
4469
+ });
4470
+ log5.log(`[ConfigRepo] assigned group instanceId ${this.instanceId} (kind=${existingDescriptor?.kind ?? "config"})`);
4471
+ }
4472
+ log5.log(`[ConfigRepo] group-type set to "${type}"`);
4209
4473
  }
4210
4474
  /** Read the group-type marker. Returns null if not set (new path, then legacy). */
4211
4475
  async getGroupType() {
@@ -4300,7 +4564,7 @@ var ConfigRepo = class {
4300
4564
  if (this.appDataGroups.has(id)) {
4301
4565
  throw new Error(`App data group "${id}" already exists. Use removeAppDataGroup() first.`);
4302
4566
  }
4303
- log4.log(`[ConfigRepo] createAppDataGroup: creating "${id}" with ${backends.length} backend(s)`);
4567
+ log5.log(`[ConfigRepo] createAppDataGroup: creating "${id}" with ${backends.length} backend(s)`);
4304
4568
  const resolvedBackends = [];
4305
4569
  for (const desc of backends) {
4306
4570
  assertValidBackendId(desc.id);
@@ -4308,6 +4572,7 @@ var ConfigRepo = class {
4308
4572
  resolvedBackends.push({ ...desc, options: mergedOptions });
4309
4573
  }
4310
4574
  await this.assertNoSharedRemote(resolvedBackends, id);
4575
+ const instanceId = newGroupInstanceId();
4311
4576
  const group = new AppDataGroupImpl(
4312
4577
  id,
4313
4578
  this.appId,
@@ -4315,19 +4580,25 @@ var ConfigRepo = class {
4315
4580
  this.pollIntervalMs,
4316
4581
  this,
4317
4582
  // 显式新拓扑:以参数为准并写入 `.meta/backends/`。
4318
- { name: options.name, features: options.features, backendsAreAuthoritative: true }
4583
+ {
4584
+ name: options.name,
4585
+ features: options.features,
4586
+ backendsAreAuthoritative: true,
4587
+ instanceId
4588
+ }
4319
4589
  );
4320
4590
  await group.init();
4321
4591
  const descriptor = {
4322
4592
  id,
4323
4593
  groupType: "data-sync",
4594
+ instanceId: group.getGroupInstanceId() ?? instanceId,
4324
4595
  ...options.name ? { name: options.name } : {},
4325
4596
  ...options.features ? { features: options.features } : {},
4326
4597
  backends: group.listDeclaredBackends()
4327
4598
  };
4328
4599
  await this.writeAppDataGroupDescriptorFile(id, descriptor);
4329
4600
  this.appDataGroups.set(id, group);
4330
- log4.log(`[ConfigRepo] createAppDataGroup: "${id}" created`);
4601
+ log5.log(`[ConfigRepo] createAppDataGroup: "${id}" created`);
4331
4602
  return group;
4332
4603
  }
4333
4604
  /**
@@ -4344,9 +4615,13 @@ var ConfigRepo = class {
4344
4615
  const existing = await this.readAppDataGroupDescriptor(id);
4345
4616
  const name = meta?.name ?? existing?.name;
4346
4617
  const features = meta?.features ?? existing?.features;
4618
+ const liveGroup = this.appDataGroups.get(id);
4619
+ const liveInstanceId = liveGroup?.getGroupInstanceId();
4620
+ const instanceId = pickInstanceId(existing) ?? (isValidGroupInstanceId(liveInstanceId) ? liveInstanceId : void 0);
4347
4621
  const descriptor = {
4348
4622
  id,
4349
4623
  groupType: "data-sync",
4624
+ ...instanceId ? { instanceId } : {},
4350
4625
  ...name ? { name } : {},
4351
4626
  ...features ? { features } : {},
4352
4627
  backends
@@ -4370,7 +4645,7 @@ var ConfigRepo = class {
4370
4645
  try {
4371
4646
  await live.writeOwnGroupDescriptor();
4372
4647
  } catch (err) {
4373
- log4.warn(`[ConfigRepo] updateAppDataGroupName: "${id}" group.json update failed:`, err);
4648
+ log5.warn(`[ConfigRepo] updateAppDataGroupName: "${id}" group.json update failed:`, err);
4374
4649
  }
4375
4650
  }
4376
4651
  const descriptor = {
@@ -4414,6 +4689,9 @@ var ConfigRepo = class {
4414
4689
  const nextBackends = declared.map(
4415
4690
  (b, i) => i === index ? { ...candidate, options: mergedOptions } : b
4416
4691
  );
4692
+ const descriptorNow = await this.readAppDataGroupDescriptor(groupId);
4693
+ const instanceIdFromLive = live?.getGroupInstanceId();
4694
+ const instanceId = pickInstanceId(descriptorNow) ?? (isValidGroupInstanceId(instanceIdFromLive) ? instanceIdFromLive : void 0);
4417
4695
  if (live) {
4418
4696
  await live.dispose();
4419
4697
  this.appDataGroups.delete(groupId);
@@ -4425,7 +4703,7 @@ var ConfigRepo = class {
4425
4703
  nextBackends,
4426
4704
  this.pollIntervalMs,
4427
4705
  this,
4428
- { backendsAreAuthoritative: true }
4706
+ { backendsAreAuthoritative: true, ...instanceId ? { instanceId } : {} }
4429
4707
  );
4430
4708
  await group.init();
4431
4709
  await this.updateAppDataGroupDescriptor(groupId, group.listDeclaredBackends());
@@ -4433,7 +4711,7 @@ var ConfigRepo = class {
4433
4711
  return group;
4434
4712
  } catch (err) {
4435
4713
  const reason = err instanceof Error ? err.message : String(err);
4436
- log4.warn(`[ConfigRepo] replaceAppDataGroupBackend: "${backendId}" failed, rolling back:`, err);
4714
+ log5.warn(`[ConfigRepo] replaceAppDataGroupBackend: "${backendId}" failed, rolling back:`, err);
4437
4715
  try {
4438
4716
  const restored = new AppDataGroupImpl(
4439
4717
  groupId,
@@ -4441,13 +4719,13 @@ var ConfigRepo = class {
4441
4719
  oldBackends,
4442
4720
  this.pollIntervalMs,
4443
4721
  this,
4444
- { backendsAreAuthoritative: true }
4722
+ { backendsAreAuthoritative: true, ...instanceId ? { instanceId } : {} }
4445
4723
  );
4446
4724
  await restored.init();
4447
4725
  await this.updateAppDataGroupDescriptor(groupId, restored.listDeclaredBackends());
4448
4726
  this.appDataGroups.set(groupId, restored);
4449
4727
  } catch (rollbackErr) {
4450
- log4.error("[ConfigRepo] replaceAppDataGroupBackend: rollback ALSO failed:", rollbackErr);
4728
+ log5.error("[ConfigRepo] replaceAppDataGroupBackend: rollback ALSO failed:", rollbackErr);
4451
4729
  }
4452
4730
  throw new Error(`\u66F4\u65B0\u540E\u7AEF\u53C2\u6570\u5931\u8D25\uFF1A${reason}\uFF08\u5DF2\u5C1D\u8BD5\u56DE\u6EDA\u65E7\u53C2\u6570\uFF09`);
4453
4731
  }
@@ -4485,10 +4763,12 @@ var ConfigRepo = class {
4485
4763
  const version = await incrementVersion(this.fullFS, path, bytes, author);
4486
4764
  await this.writeVersionSidecar(path, version);
4487
4765
  }
4766
+ const identity = await this.ensureGroupIdentity();
4488
4767
  await writeGroupDescriptor(this.cachedFS, {
4489
4768
  schemaVersion: 2,
4490
4769
  kind: "config",
4491
4770
  id: CONFIG_GROUP_ID,
4771
+ instanceId: identity.instanceId,
4492
4772
  name: normalized,
4493
4773
  features: CONFIG_GROUP_FEATURES
4494
4774
  });
@@ -4565,7 +4845,7 @@ var ConfigRepo = class {
4565
4845
  try {
4566
4846
  await this.deleteFile(descPath);
4567
4847
  } catch (err) {
4568
- log4.log(`[ConfigRepo] removeAppDataGroup: deleteFile failed for "${id}" at ${descPath}:`, err);
4848
+ log5.log(`[ConfigRepo] removeAppDataGroup: deleteFile failed for "${id}" at ${descPath}:`, err);
4569
4849
  try {
4570
4850
  await this.cachedFS.unlink(descPath);
4571
4851
  } catch {
@@ -4573,7 +4853,7 @@ var ConfigRepo = class {
4573
4853
  await this.unlinkVersionSidecar(this.cachedFS, descPath);
4574
4854
  }
4575
4855
  }
4576
- log4.log(`[ConfigRepo] removeAppDataGroup: "${id}" removed`);
4856
+ log5.log(`[ConfigRepo] removeAppDataGroup: "${id}" removed`);
4577
4857
  }
4578
4858
  async listAccountBackends() {
4579
4859
  this.assertNotDisposed();
@@ -4610,10 +4890,20 @@ var AppDataGroupImpl = class {
4610
4890
  versions;
4611
4891
  conflicts;
4612
4892
  postDeleteTimer;
4893
+ /**
4894
+ * 墓碑路径的同步排除表(与配置组同一套机制)。
4895
+ *
4896
+ * 保留期内的墓碑路径不参与同步:否则副本上的残留会被当作"远端内容"逐文件
4897
+ * 拉回本地,把已删除的目录复活。数组与各同步对共享同一实例(zen-fs-sync
4898
+ * 每次检测时实时读取 `filter.excludePrefixes`),原地更新即可生效。
4899
+ */
4900
+ tombstoneExcludePrefixes = [...CONFIG_ONLY_PREFIXES];
4901
+ syncFilter = { excludePrefixes: this.tombstoneExcludePrefixes };
4613
4902
  constructor(groupId, appId, backends, pollIntervalMs, parent, descriptor = {}) {
4614
4903
  this.groupId = groupId;
4615
4904
  this.appId = appId;
4616
4905
  this.name = descriptor.name;
4906
+ this.instanceId = isValidGroupInstanceId(descriptor.instanceId) ? descriptor.instanceId : void 0;
4617
4907
  this.features = {
4618
4908
  ...DATA_GROUP_DEFAULT_FEATURES,
4619
4909
  ...descriptor.features,
@@ -4631,6 +4921,13 @@ var AppDataGroupImpl = class {
4631
4921
  }
4632
4922
  parent;
4633
4923
  _backends;
4924
+ /**
4925
+ * 组实例身份(UUID)。同步边界:远端 `.meta/group.json` 的 `instanceId`
4926
+ * 不一致就不建同步对,因此不同同步组之间永不互相搬运数据。
4927
+ */
4928
+ instanceId;
4929
+ /** 因归属他人而被跳过的后端 id → 原因。 */
4930
+ skippedBackends = /* @__PURE__ */ new Map();
4634
4931
  _pollIntervalMs;
4635
4932
  _backendsAreAuthoritative;
4636
4933
  /** 引导副本(`.config/` 里的描述符)原有的能力位,用于回刷时不丢信息。 */
@@ -4727,14 +5024,64 @@ var AppDataGroupImpl = class {
4727
5024
  }
4728
5025
  /** Write this group's own `.meta/group.json` (idempotent: identical bytes → no write). */
4729
5026
  async writeOwnGroupDescriptor() {
5027
+ if (!this.instanceId) {
5028
+ this.instanceId = newGroupInstanceId();
5029
+ log5.log(`[AppDataGroup:${this.groupId}] assigned instanceId ${this.instanceId}`);
5030
+ }
4730
5031
  await writeGroupDescriptor(this.localFS, {
4731
5032
  schemaVersion: 2,
4732
5033
  kind: "data",
4733
5034
  id: this.groupId,
5035
+ instanceId: this.instanceId,
4734
5036
  ...this.name ? { name: this.name } : {},
4735
5037
  features: this.features
4736
5038
  });
4737
5039
  }
5040
+ /** 本组实例身份(初始化后可用)。 */
5041
+ getGroupInstanceId() {
5042
+ return this.instanceId;
5043
+ }
5044
+ /** 因归属他人而被跳过的后端(id → 原因)。 */
5045
+ listSkippedBackends() {
5046
+ return Array.from(this.skippedBackends, ([backendId, reason]) => ({ backendId, reason }));
5047
+ }
5048
+ /**
5049
+ * 连接数据后端前的归属校验。
5050
+ *
5051
+ * - `match`:远端 `.meta/group.json` 的 `instanceId` 与本组一致 → 建同步对;
5052
+ * - `claimed`:远端是老仓库(无身份)→ 本组认领并写入,再建同步对;
5053
+ * - `conflict`:远端属于另一个同步组(或类型不符 / 读不到)→ 跳过,
5054
+ * **绝不建立同步对**,因此跨组数据不会被搬运。
5055
+ */
5056
+ async checkBackendOwnership(instance, backendId) {
5057
+ if (!this.instanceId) {
5058
+ this.skippedBackends.set(backendId, "\u672C\u7EC4\u5C1A\u672A\u5206\u914D instanceId\uFF0C\u5DF2\u8DF3\u8FC7\u8BE5\u540E\u7AEF");
5059
+ return "conflict";
5060
+ }
5061
+ try {
5062
+ const state = await bindRemoteGroupIdentity(instance, {
5063
+ kind: "data",
5064
+ id: this.groupId,
5065
+ instanceId: this.instanceId,
5066
+ ...this.name ? { name: this.name } : {},
5067
+ features: this.features
5068
+ });
5069
+ if (state === "conflict") {
5070
+ this.skippedBackends.set(
5071
+ backendId,
5072
+ "\u8FDC\u7AEF\u6839\u5C5E\u4E8E\u53E6\u4E00\u4E2A\u540C\u6B65\u7EC4\uFF08instanceId \u4E0D\u4E00\u81F4\uFF09\uFF0C\u5DF2\u8DF3\u8FC7\u8BE5\u540E\u7AEF"
5073
+ );
5074
+ log5.warn(
5075
+ `[AppDataGroup:${this.groupId}] backend "${backendId}" belongs to another sync group \u2014 sync pair skipped`
5076
+ );
5077
+ }
5078
+ return state;
5079
+ } catch (err) {
5080
+ log5.warn(`[AppDataGroup:${this.groupId}] ownership check failed for "${backendId}":`, err);
5081
+ this.skippedBackends.set(backendId, `\u5F52\u5C5E\u6821\u9A8C\u5931\u8D25\uFF1A${err?.message ?? String(err)}`);
5082
+ return "conflict";
5083
+ }
5084
+ }
4738
5085
  async init() {
4739
5086
  const storeName = dataGroupLocalStoreName(this.appId, this.groupId);
4740
5087
  try {
@@ -4762,40 +5109,56 @@ var AppDataGroupImpl = class {
4762
5109
  try {
4763
5110
  const purged = await purgeMtimeSidecars(this.localFS);
4764
5111
  if (purged.removed.length > 0) {
4765
- log4.warn(
5112
+ log5.warn(
4766
5113
  `[AppDataGroup:${this.groupId}] purged ${purged.removed.length} leaked .mtime sidecar(s):`,
4767
5114
  purged.removed
4768
5115
  );
4769
5116
  }
4770
5117
  } catch (err) {
4771
- log4.warn(`[AppDataGroup:${this.groupId}] .mtime purge failed:`, err?.message ?? err);
5118
+ log5.warn(`[AppDataGroup:${this.groupId}] .mtime purge failed:`, err?.message ?? err);
4772
5119
  }
4773
5120
  try {
4774
5121
  const purgedKeep = await purgeKeepFiles(this.localFS);
4775
5122
  if (purgedKeep.removed.length > 0) {
4776
- log4.warn(
5123
+ log5.warn(
4777
5124
  `[AppDataGroup:${this.groupId}] purged ${purgedKeep.removed.length} leaked .keep placeholder(s):`,
4778
5125
  purgedKeep.removed
4779
5126
  );
4780
5127
  }
4781
5128
  } catch (err) {
4782
- log4.warn(`[AppDataGroup:${this.groupId}] .keep purge failed:`, err?.message ?? err);
5129
+ log5.warn(`[AppDataGroup:${this.groupId}] .keep purge failed:`, err?.message ?? err);
4783
5130
  }
4784
5131
  const localSyncable = backendToSyncableFS(this.localFS, `local(${this.groupId})`);
4785
5132
  this.tombstones = new TombstoneStore(this.localFS, this.localBackendId);
4786
5133
  this.versions = new VersionStore(this.localFS, `${this.appId}/${this.groupId}`);
4787
5134
  this.conflicts = new ConflictStore(this.localFS, this.appId, `${this.groupId}`, this.versions);
5135
+ try {
5136
+ this.refreshSyncExclusions(await this.tombstones.list());
5137
+ } catch (err) {
5138
+ log5.warn(`[AppDataGroup:${this.groupId}] failed to load tombstones for exclusions:`, err);
5139
+ }
4788
5140
  let backendsChanged = false;
4789
5141
  try {
4790
5142
  backendsChanged = await this.loadBackendDescriptors();
4791
5143
  } catch (err) {
4792
- log4.warn(`[AppDataGroup:${this.groupId}] failed to load .meta/backends:`, err);
5144
+ log5.warn(`[AppDataGroup:${this.groupId}] failed to load .meta/backends:`, err);
4793
5145
  this._backends = this._backends ?? [];
4794
5146
  }
5147
+ if (!this.instanceId) {
5148
+ try {
5149
+ const existing = await readGroupDescriptor(this.localFS);
5150
+ this.instanceId = pickInstanceId(existing);
5151
+ if (this.instanceId) {
5152
+ log5.log(`[AppDataGroup:${this.groupId}] adopted instanceId ${this.instanceId} from local group.json`);
5153
+ }
5154
+ } catch (err) {
5155
+ log5.warn(`[AppDataGroup:${this.groupId}] failed to read local group.json:`, err);
5156
+ }
5157
+ }
4795
5158
  try {
4796
5159
  await this.writeOwnGroupDescriptor();
4797
5160
  } catch (err) {
4798
- log4.warn(`[AppDataGroup:${this.groupId}] failed to write .meta/group.json:`, err);
5161
+ log5.warn(`[AppDataGroup:${this.groupId}] failed to write .meta/group.json:`, err);
4799
5162
  }
4800
5163
  this.fs = createChrootFS(this.localFS, "/", {
4801
5164
  hiddenPrefixes: [META_DIR, CONFIG_DIR],
@@ -4805,7 +5168,7 @@ var AppDataGroupImpl = class {
4805
5168
  });
4806
5169
  const { kept, removed } = dedupeAppDataBackends(this._backends);
4807
5170
  if (removed.length > 0) {
4808
- log4.warn(
5171
+ log5.warn(
4809
5172
  `[AppDataGroup:${this.groupId}] dedupe: removing ${removed.length} duplicate backend(s) (${removed.map((b) => b.id).join(", ")}) \u2014 keeping ${kept.map((b) => b.id).join(", ")}`
4810
5173
  );
4811
5174
  this._backends = kept;
@@ -4819,12 +5182,20 @@ var AppDataGroupImpl = class {
4819
5182
  features: this._declaredFeatures
4820
5183
  });
4821
5184
  } catch (err) {
4822
- log4.warn(`[AppDataGroup:${this.groupId}] failed to persist backend topology:`, err);
5185
+ log5.warn(`[AppDataGroup:${this.groupId}] failed to persist backend topology:`, err);
4823
5186
  }
4824
5187
  }
4825
5188
  for (const desc of this._backends) {
4826
5189
  try {
4827
5190
  const instance = await createBackend({ type: desc.type, options: desc.options });
5191
+ const owned = await this.checkBackendOwnership(instance, desc.id);
5192
+ if (owned === "conflict") {
5193
+ try {
5194
+ await instance.dispose?.();
5195
+ } catch {
5196
+ }
5197
+ continue;
5198
+ }
4828
5199
  const syncable = backendToSyncableFS(instance, `${desc.type}(${desc.id})`);
4829
5200
  const pair = this.syncEngine.addPair(
4830
5201
  localSyncable,
@@ -4835,7 +5206,8 @@ var AppDataGroupImpl = class {
4835
5206
  pollIntervalMs: this._pollIntervalMs,
4836
5207
  // `.meta/` is intentionally NOT excluded: tombstones, versions and
4837
5208
  // conflicts must sync, otherwise deletions resurrect on other devices.
4838
- filter: { excludePrefixes: CONFIG_ONLY_PREFIXES },
5209
+ // 但要排除"当前墓碑指向的路径"(与配置组同一张表,实时生效)。
5210
+ filter: this.syncFilter,
4839
5211
  preSyncHook: async () => {
4840
5212
  await this.runTombstonePass("preSync");
4841
5213
  },
@@ -4851,26 +5223,26 @@ var AppDataGroupImpl = class {
4851
5223
  if (this.features.conflicts) {
4852
5224
  const conflictHandler = (event) => {
4853
5225
  this.archiveConflict(event).catch((err) => {
4854
- log4.warn(`[AppDataGroup:${this.groupId}] conflict archive failed:`, err);
5226
+ log5.warn(`[AppDataGroup:${this.groupId}] conflict archive failed:`, err);
4855
5227
  });
4856
5228
  };
4857
5229
  this.syncEngine.on(pair.pairId, "conflict", conflictHandler);
4858
5230
  }
4859
5231
  this.trackSyncErrors(desc.id, pair.pairId);
4860
- log4.log(`[AppDataGroup:${this.groupId}] backend ${desc.id} (${desc.type}) connected, pair=${pair.pairId}`);
5232
+ log5.log(`[AppDataGroup:${this.groupId}] backend ${desc.id} (${desc.type}) connected, pair=${pair.pairId}`);
4861
5233
  } catch (err) {
4862
5234
  const message = err instanceof Error ? err.message : String(err);
4863
5235
  this.backendStates.set(desc.id, {
4864
5236
  backendId: desc.id,
4865
5237
  error: { message, timestamp: Date.now() }
4866
5238
  });
4867
- log4.error(`[AppDataGroup:${this.groupId}] Failed to create backend ${desc.id} (${desc.type}):`, err);
5239
+ log5.error(`[AppDataGroup:${this.groupId}] Failed to create backend ${desc.id} (${desc.type}):`, err);
4868
5240
  }
4869
5241
  }
4870
5242
  try {
4871
5243
  await this.syncEngine.syncAll();
4872
5244
  } catch (err) {
4873
- log4.warn(`[AppDataGroup:${this.groupId}] Initial sync failed:`, err);
5245
+ log5.warn(`[AppDataGroup:${this.groupId}] Initial sync failed:`, err);
4874
5246
  }
4875
5247
  this.syncEngine.watchAll();
4876
5248
  }
@@ -4885,7 +5257,7 @@ var AppDataGroupImpl = class {
4885
5257
  try {
4886
5258
  await this.tombstones.gc(this.allBackendIds(), this.tombstoneTargets());
4887
5259
  } catch (err) {
4888
- log4.warn(`[AppDataGroup:${this.groupId}] tombstone GC failed:`, err);
5260
+ log5.warn(`[AppDataGroup:${this.groupId}] tombstone GC failed:`, err);
4889
5261
  }
4890
5262
  return Array.from(results.values());
4891
5263
  }
@@ -4920,31 +5292,47 @@ var AppDataGroupImpl = class {
4920
5292
  const bytes = typeof data === "string" ? new TextEncoder().encode(data) : toUint8Array2(data);
4921
5293
  await this.versions.record(path, bytes);
4922
5294
  } catch (err) {
4923
- log4.warn(`[AppDataGroup:${this.groupId}] version record failed for ${path}:`, err);
5295
+ log5.warn(`[AppDataGroup:${this.groupId}] version record failed for ${path}:`, err);
4924
5296
  }
4925
5297
  }
4926
5298
  /** Delete tombstoned files on local + every connected backend before/after sync. */
4927
5299
  async runTombstonePass(stage) {
4928
5300
  try {
4929
5301
  await this.tombstones.process(this.tombstoneTargets());
5302
+ this.refreshSyncExclusions(await this.tombstones.list());
4930
5303
  } catch (err) {
4931
- log4.warn(`[AppDataGroup:${this.groupId}] ${stage} tombstone pass failed:`, err);
5304
+ log5.warn(`[AppDataGroup:${this.groupId}] ${stage} tombstone pass failed:`, err);
5305
+ }
5306
+ }
5307
+ /**
5308
+ * 把当前墓碑路径写进同步排除表(原地更新共享数组)。
5309
+ *
5310
+ * 目录墓碑的 `${path}/` 前缀是故意的:整棵树已删除,保留期内任何子路径都不
5311
+ * 参与同步。注意**不能**为 `.keep` 占位排除父目录,否则真实数据会被一起挡掉。
5312
+ */
5313
+ refreshSyncExclusions(tombstones) {
5314
+ this.tombstoneExcludePrefixes.length = 0;
5315
+ this.tombstoneExcludePrefixes.push(...CONFIG_ONLY_PREFIXES);
5316
+ for (const tombstone of tombstones) {
5317
+ if (!tombstone.path) continue;
5318
+ this.tombstoneExcludePrefixes.push(tombstone.path, `${tombstone.path}/`);
4932
5319
  }
4933
5320
  }
4934
5321
  async confirmTombstones() {
4935
5322
  try {
4936
- await this.tombstones.confirm(this.allBackendIds());
5323
+ await this.tombstones.confirm(this.tombstoneTargets());
4937
5324
  } catch (err) {
4938
- log4.warn(`[AppDataGroup:${this.groupId}] tombstone confirmations failed:`, err);
5325
+ log5.warn(`[AppDataGroup:${this.groupId}] tombstone confirmations failed:`, err);
4939
5326
  }
4940
5327
  }
4941
- /** Write a tombstone for `filePath`. Records metadata only — it never creates the file. */
4942
- async writeTombstoneFor(filePath) {
5328
+ /** Write a tombstone for `path`. Records metadata only — it never creates the path. */
5329
+ async writeTombstoneFor(path, type) {
4943
5330
  await this.tombstones.write({
4944
- path: filePath.startsWith("/") ? filePath : `/${filePath}`,
5331
+ path: normalizeTombstonePath(path),
4945
5332
  deletedAt: Date.now(),
4946
5333
  deletedBy: this.localBackendId,
4947
- confirmedBy: [this.localBackendId]
5334
+ confirmedBy: [this.localBackendId],
5335
+ ...type ? { type } : {}
4948
5336
  });
4949
5337
  }
4950
5338
  /**
@@ -4959,16 +5347,10 @@ var AppDataGroupImpl = class {
4959
5347
  throw new Error(`Cannot delete metadata path "${normalized}"`);
4960
5348
  }
4961
5349
  if (await isDirectoryPath(this.localFS, normalized)) {
4962
- const files = await collectFilesUnder(this.localFS, normalized);
4963
- for (const file of files) await this.deleteFile(file);
4964
- for (const dir of await collectDirectoriesUnder(this.localFS, normalized)) {
4965
- const keepPath = dir === "/" ? "/.keep" : `${dir}/.keep`;
4966
- await this.writeTombstoneFor(keepPath);
4967
- await this.writeTombstoneFor(`${keepPath}.mtime`);
4968
- }
4969
- await removeDirectoryTree(this.localFS, normalized);
5350
+ await this.writeTombstoneFor(normalized, "directory");
5351
+ await purgeTombstonedTree(this.localFS, normalized);
4970
5352
  this.schedulePostDeleteSync();
4971
- log4.log(`[AppDataGroup:${this.groupId}] deleteFile(directory): ${normalized} (${files.length} file(s))`);
5353
+ log5.log(`[AppDataGroup:${this.groupId}] deleteFile(directory): ${normalized} (single directory tombstone)`);
4972
5354
  return;
4973
5355
  }
4974
5356
  await this.writeTombstoneFor(normalized);
@@ -5007,7 +5389,7 @@ var AppDataGroupImpl = class {
5007
5389
  try {
5008
5390
  await this.syncEngine.syncAll();
5009
5391
  } catch (err) {
5010
- log4.warn(`[AppDataGroup:${this.groupId}] sync after conflict resolve failed:`, err);
5392
+ log5.warn(`[AppDataGroup:${this.groupId}] sync after conflict resolve failed:`, err);
5011
5393
  }
5012
5394
  }
5013
5395
  readConflictBackup(conflictId, fileType) {
@@ -5042,7 +5424,7 @@ var AppDataGroupImpl = class {
5042
5424
  if (this.dataBackends.has(id)) {
5043
5425
  throw new Error(`Backend "${id}" already exists in data group "${this.groupId}"`);
5044
5426
  }
5045
- log4.log(`[AppDataGroup:${this.groupId}] addBackend: creating ${id} (${type})...`);
5427
+ log5.log(`[AppDataGroup:${this.groupId}] addBackend: creating ${id} (${type})...`);
5046
5428
  const instance = await createBackend({ type, options });
5047
5429
  const syncable = backendToSyncableFS(instance, `${type}(${id})`);
5048
5430
  const localSyncable = backendToSyncableFS(this.localFS, `local(${this.groupId})`);
@@ -5053,7 +5435,7 @@ var AppDataGroupImpl = class {
5053
5435
  direction: import_zen_fs_sync.SyncDirection.BiDirectional,
5054
5436
  conflictStrategy: "source-wins",
5055
5437
  pollIntervalMs: this._pollIntervalMs,
5056
- filter: { excludePrefixes: CONFIG_ONLY_PREFIXES },
5438
+ filter: this.syncFilter,
5057
5439
  preSyncHook: async () => {
5058
5440
  await this.runTombstonePass("preSync");
5059
5441
  },
@@ -5070,13 +5452,13 @@ var AppDataGroupImpl = class {
5070
5452
  if (this.features.conflicts) {
5071
5453
  this.syncEngine.on(pair.pairId, "conflict", (event) => {
5072
5454
  this.archiveConflict(event).catch((err) => {
5073
- log4.warn(`[AppDataGroup:${this.groupId}] conflict archive failed:`, err);
5455
+ log5.warn(`[AppDataGroup:${this.groupId}] conflict archive failed:`, err);
5074
5456
  });
5075
5457
  });
5076
5458
  }
5077
5459
  this.trackSyncErrors(id, pair.pairId);
5078
5460
  this._backends = [...this._backends.filter((b) => b.id !== id), desc];
5079
- log4.log(`[AppDataGroup:${this.groupId}] addBackend: ${id} (${type}) connected, pair=${pair.pairId}`);
5461
+ log5.log(`[AppDataGroup:${this.groupId}] addBackend: ${id} (${type}) connected, pair=${pair.pairId}`);
5080
5462
  try {
5081
5463
  const stale = (await this.tombstones.list()).find(
5082
5464
  (t) => t.path === backendMetaFilePath(id)
@@ -5084,12 +5466,12 @@ var AppDataGroupImpl = class {
5084
5466
  if (stale) await this.tombstones.remove(stale);
5085
5467
  await writeBackendMetaDescriptor(this.localFS, desc);
5086
5468
  } catch (err) {
5087
- log4.warn(`[AppDataGroup:${this.groupId}] addBackend: failed to write .meta/backends/${id}.json:`, err);
5469
+ log5.warn(`[AppDataGroup:${this.groupId}] addBackend: failed to write .meta/backends/${id}.json:`, err);
5088
5470
  }
5089
5471
  try {
5090
5472
  await this.syncEngine.sync(pair.pairId);
5091
5473
  } catch (err) {
5092
- log4.warn(`[AppDataGroup:${this.groupId}] addBackend: initial sync failed for ${id}:`, err);
5474
+ log5.warn(`[AppDataGroup:${this.groupId}] addBackend: initial sync failed for ${id}:`, err);
5093
5475
  }
5094
5476
  this.syncEngine.watch(pair.pairId);
5095
5477
  await this.parent.updateAppDataGroupDescriptor(this.groupId, this._backends, {
@@ -5120,7 +5502,7 @@ var AppDataGroupImpl = class {
5120
5502
  if (backend?.instance?.dispose) {
5121
5503
  await backend.instance.dispose();
5122
5504
  }
5123
- log4.log(`[AppDataGroup:${this.groupId}] removeBackend: ${id} removed`);
5505
+ log5.log(`[AppDataGroup:${this.groupId}] removeBackend: ${id} removed`);
5124
5506
  }
5125
5507
  listBackends() {
5126
5508
  return Array.from(this.dataBackends.values()).map((b) => b.desc);
@@ -5162,44 +5544,44 @@ async function createConfigRepo(appId, options = {}) {
5162
5544
  idbStoreName: options.idbStoreName,
5163
5545
  folderPath: options.folderPath
5164
5546
  });
5165
- log4.log(`[createConfigRepo] Creating local primary (type: ${localPrimary.type})...`);
5547
+ log5.log(`[createConfigRepo] Creating local primary (type: ${localPrimary.type})...`);
5166
5548
  const primaryInstance = await createBackend(localPrimary);
5167
5549
  const cachedFS = primaryInstance;
5168
5550
  if (options.purgeMtimeSidecars !== false) {
5169
5551
  try {
5170
5552
  const purged = await purgeMtimeSidecars(cachedFS);
5171
5553
  if (purged.removed.length > 0) {
5172
- log4.warn(
5554
+ log5.warn(
5173
5555
  `[createConfigRepo] purged ${purged.removed.length} leaked .mtime sidecar(s) from local primary:`,
5174
5556
  purged.removed
5175
5557
  );
5176
5558
  }
5177
5559
  } catch (err) {
5178
- log4.warn(`[createConfigRepo] .mtime purge failed:`, err?.message ?? err);
5560
+ log5.warn(`[createConfigRepo] .mtime purge failed:`, err?.message ?? err);
5179
5561
  }
5180
5562
  }
5181
5563
  if (options.purgeKeepFiles !== false) {
5182
5564
  try {
5183
5565
  const purged = await purgeKeepFiles(cachedFS);
5184
5566
  if (purged.removed.length > 0) {
5185
- log4.warn(
5567
+ log5.warn(
5186
5568
  `[createConfigRepo] purged ${purged.removed.length} leaked .keep placeholder(s) from local primary:`,
5187
5569
  purged.removed
5188
5570
  );
5189
5571
  }
5190
5572
  } catch (err) {
5191
- log4.warn(`[createConfigRepo] .keep purge failed:`, err?.message ?? err);
5573
+ log5.warn(`[createConfigRepo] .keep purge failed:`, err?.message ?? err);
5192
5574
  }
5193
5575
  }
5194
5576
  const cacheOptions = options.cache === false ? void 0 : options.cache ?? {};
5195
5577
  try {
5196
5578
  await primaryInstance.mkdir(META_DIR);
5197
- log4.log(`[createConfigRepo] /.meta/ ready`);
5579
+ log5.log(`[createConfigRepo] /.meta/ ready`);
5198
5580
  } catch (err) {
5199
5581
  const msg = err.message || "";
5200
5582
  if (msg.includes("File exists") || msg.includes("EEXIST") || err.code === "EEXIST") {
5201
5583
  } else {
5202
- log4.error(`[createConfigRepo] Failed to ensure /.meta/:`, err.message);
5584
+ log5.error(`[createConfigRepo] Failed to ensure /.meta/:`, err.message);
5203
5585
  }
5204
5586
  }
5205
5587
  try {
@@ -5210,7 +5592,7 @@ async function createConfigRepo(appId, options = {}) {
5210
5592
  } catch {
5211
5593
  await ensureParentDir2(primaryInstance, path);
5212
5594
  await primaryInstance.writeFile(path, groupTypeBytes);
5213
- log4.log(`[createConfigRepo] group-type set to "config-sync" at ${path}`);
5595
+ log5.log(`[createConfigRepo] group-type set to "config-sync" at ${path}`);
5214
5596
  }
5215
5597
  }
5216
5598
  if (!await readGroupDescriptor(primaryInstance)) {
@@ -5218,11 +5600,12 @@ async function createConfigRepo(appId, options = {}) {
5218
5600
  schemaVersion: 2,
5219
5601
  kind: "config",
5220
5602
  id: CONFIG_GROUP_ID,
5603
+ instanceId: newGroupInstanceId(),
5221
5604
  features: CONFIG_GROUP_FEATURES
5222
5605
  });
5223
5606
  }
5224
5607
  } catch (err) {
5225
- log4.warn(`[createConfigRepo] Failed to write group metadata:`, err.message);
5608
+ log5.warn(`[createConfigRepo] Failed to write group metadata:`, err.message);
5226
5609
  }
5227
5610
  const tempRepo = new ConfigRepo(
5228
5611
  appId,
@@ -5236,11 +5619,11 @@ async function createConfigRepo(appId, options = {}) {
5236
5619
  );
5237
5620
  const oldBackendsMeta = await tempRepo.readMetaFile(BACKENDS_FILE);
5238
5621
  if (oldBackendsMeta && oldBackendsMeta.backends?.length > 0) {
5239
- log4.log(`[createConfigRepo] Migrating ${oldBackendsMeta.backends.length} backend(s) from backends.json to individual files...`);
5622
+ log5.log(`[createConfigRepo] Migrating ${oldBackendsMeta.backends.length} backend(s) from backends.json to individual files...`);
5240
5623
  await tempRepo.ensureDir(`${BACKENDS_DIR}/.keep`);
5241
5624
  for (const desc of oldBackendsMeta.backends) {
5242
5625
  if (desc.id === LOCAL_IDB_BACKEND_ID) {
5243
- log4.log(`[createConfigRepo] Skipping local backend ${desc.id} during migration`);
5626
+ log5.log(`[createConfigRepo] Skipping local backend ${desc.id} during migration`);
5244
5627
  continue;
5245
5628
  }
5246
5629
  await tempRepo.writeBackendDescriptor(desc);
@@ -5258,7 +5641,7 @@ async function createConfigRepo(appId, options = {}) {
5258
5641
  }
5259
5642
  }
5260
5643
  }
5261
- log4.log(`[createConfigRepo] Migration complete`);
5644
+ log5.log(`[createConfigRepo] Migration complete`);
5262
5645
  }
5263
5646
  let allBackends = await tempRepo.readAllBackendDescriptors();
5264
5647
  if (options.backendInfo) {
@@ -5276,19 +5659,19 @@ async function createConfigRepo(appId, options = {}) {
5276
5659
  type: options.backendInfo.type,
5277
5660
  options: options.backendInfo.options
5278
5661
  });
5279
- log4.log(`[createConfigRepo] Added replica backend: ${replicaId} (${options.backendInfo.type})`);
5662
+ log5.log(`[createConfigRepo] Added replica backend: ${replicaId} (${options.backendInfo.type})`);
5280
5663
  allBackends = [...allBackends, { id: replicaId, type: options.backendInfo.type, options: options.backendInfo.options }];
5281
5664
  } else if (dupConfig) {
5282
- log4.log(`[createConfigRepo] Replica with same config already registered as "${dupConfig.id}", skipping`);
5665
+ log5.log(`[createConfigRepo] Replica with same config already registered as "${dupConfig.id}", skipping`);
5283
5666
  } else {
5284
- log4.log(`[createConfigRepo] Replica ${replicaId} already registered`);
5667
+ log5.log(`[createConfigRepo] Replica ${replicaId} already registered`);
5285
5668
  }
5286
5669
  }
5287
- log4.log(`[createConfigRepo] Replica backends: ${allBackends.map((b) => b.id).join(", ") || "(none)"}`);
5670
+ log5.log(`[createConfigRepo] Replica backends: ${allBackends.map((b) => b.id).join(", ") || "(none)"}`);
5288
5671
  let nodeId = options.nodeId;
5289
5672
  if (!nodeId) {
5290
5673
  nodeId = `node-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`;
5291
- log4.log(`[createConfigRepo] Generated nodeId: ${nodeId}`);
5674
+ log5.log(`[createConfigRepo] Generated nodeId: ${nodeId}`);
5292
5675
  }
5293
5676
  const serializer = createSerializerChain(options.serializer);
5294
5677
  const repo = new ConfigRepo(
@@ -5311,19 +5694,19 @@ async function createConfigRepo(appId, options = {}) {
5311
5694
  try {
5312
5695
  const mig = await repo.migrateLegacyVersionSidecars();
5313
5696
  if (mig.renamed.length === 0 && mig.deleted.length === 0 && mig.remoteDeleted.length === 0) {
5314
- log4.log("[createConfigRepo] no legacy version sidecars to migrate");
5697
+ log5.log("[createConfigRepo] no legacy version sidecars to migrate");
5315
5698
  }
5316
5699
  } catch (err) {
5317
- log4.warn(`[createConfigRepo] version sidecar migration failed:`, err?.message ?? err);
5700
+ log5.warn(`[createConfigRepo] version sidecar migration failed:`, err?.message ?? err);
5318
5701
  }
5319
5702
  }
5320
5703
  await repo.load();
5321
5704
  if (repo.replicaCount > 0) {
5322
- log4.log("[createConfigRepo] Starting background initial sync + dedup...");
5705
+ log5.log("[createConfigRepo] Starting background initial sync + dedup...");
5323
5706
  repo.startBackgroundSync();
5324
5707
  }
5325
5708
  repo.syncMetaToReplicas().catch((err) => {
5326
- log4.error("[createConfigRepo] background syncMetaToReplicas failed:", err);
5709
+ log5.error("[createConfigRepo] background syncMetaToReplicas failed:", err);
5327
5710
  });
5328
5711
  return repo;
5329
5712
  }
@@ -5337,11 +5720,11 @@ function sidecarOwnerPath(path) {
5337
5720
 
5338
5721
  // src/connect.ts
5339
5722
  init_backend_registry();
5340
- var log5 = createLogger2("connect");
5723
+ var log6 = createLogger2("connect");
5341
5724
  var GROUP_TYPE_FILE2 = "/.config/group-type";
5342
5725
  var LEGACY_GROUP_TYPE_FILE2 = "/.meta/group-type";
5343
5726
  async function detectGroupType(type, options) {
5344
- log5(`detectGroupType: connecting to ${type}...`);
5727
+ log6(`detectGroupType: connecting to ${type}...`);
5345
5728
  const tempBackend = await createBackend({ type, options });
5346
5729
  try {
5347
5730
  for (const path of [GROUP_TYPE_FILE2, LEGACY_GROUP_TYPE_FILE2]) {
@@ -5349,15 +5732,15 @@ async function detectGroupType(type, options) {
5349
5732
  const raw = await tempBackend.readFile(path, "utf-8");
5350
5733
  const groupType = raw.trim();
5351
5734
  if (groupType === "config-sync" || groupType === "data-sync") {
5352
- log5(`detectGroupType: detected "${groupType}" at ${path}`);
5735
+ log6(`detectGroupType: detected "${groupType}" at ${path}`);
5353
5736
  return groupType;
5354
5737
  }
5355
- log5(`detectGroupType: unknown group-type value "${groupType}" at ${path}, treating as null`);
5738
+ log6(`detectGroupType: unknown group-type value "${groupType}" at ${path}, treating as null`);
5356
5739
  return null;
5357
5740
  } catch {
5358
5741
  }
5359
5742
  }
5360
- log5(`detectGroupType: no group-type file found (new backend)`);
5743
+ log6(`detectGroupType: no group-type file found (new backend)`);
5361
5744
  return null;
5362
5745
  } finally {
5363
5746
  if (tempBackend?.dispose) {
@@ -5366,7 +5749,7 @@ async function detectGroupType(type, options) {
5366
5749
  }
5367
5750
  }
5368
5751
  async function connect(appId, options = {}) {
5369
- log5(`connect: appId=${appId}`);
5752
+ log6(`connect: appId=${appId}`);
5370
5753
  if (!options.backendInfo) {
5371
5754
  const repo2 = await createConfigRepo(appId, {
5372
5755
  idbStoreName: options.idbStoreName,
@@ -5384,12 +5767,12 @@ async function connect(appId, options = {}) {
5384
5767
  try {
5385
5768
  appDataGroups2.push(await repo2.getAppDataGroup(d.id));
5386
5769
  } catch (err) {
5387
- log5(`connect: failed to load app data group "${d.id}":`, err);
5770
+ log6(`connect: failed to load app data group "${d.id}":`, err);
5388
5771
  }
5389
5772
  }
5390
5773
  const dataGroup2 = appDataGroups2[0];
5391
5774
  if (!dataGroup2 && descriptors2.length > 0) {
5392
- log5(
5775
+ log6(
5393
5776
  `connect: ${descriptors2.length} data group descriptor(s) found but none could be loaded; leaving them untouched (no empty group is created)`
5394
5777
  );
5395
5778
  }
@@ -5414,7 +5797,7 @@ async function connect(appId, options = {}) {
5414
5797
  groupType = detectedType;
5415
5798
  } else {
5416
5799
  groupType = options.groupType ?? "config-sync";
5417
- log5(`connect: new backend, using groupType="${groupType}"`);
5800
+ log6(`connect: new backend, using groupType="${groupType}"`);
5418
5801
  }
5419
5802
  const repo = await createConfigRepo(
5420
5803
  appId,
@@ -5443,14 +5826,14 @@ async function connect(appId, options = {}) {
5443
5826
  try {
5444
5827
  appDataGroups.push(await repo.getAppDataGroup(d.id));
5445
5828
  } catch (err) {
5446
- log5(`connect: failed to load app data group "${d.id}":`, err);
5829
+ log6(`connect: failed to load app data group "${d.id}":`, err);
5447
5830
  }
5448
5831
  }
5449
5832
  let dataGroup = appDataGroups[0];
5450
5833
  if (groupType === "data-sync") {
5451
5834
  if (!dataGroup) {
5452
5835
  if (descriptors.length > 0) {
5453
- log5(
5836
+ log6(
5454
5837
  `connect: ${descriptors.length} data group descriptor(s) exist but could not be loaded; refusing to create/overwrite "default"`
5455
5838
  );
5456
5839
  } else {