zen-fs-config 0.7.5 → 0.7.6

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);
2102
1950
  for (const target of targets) {
2103
- await this.deleteEverywhere(target.fs, tombstone.path);
1951
+ await this.deleteEverywhere(target.fs, tombstone);
1952
+ }
1953
+ for (const target of targets) {
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 {
@@ -2259,62 +2164,372 @@ var ConflictStore = class {
2259
2164
  await writeJson(this.fs, `${dir}/meta.json`, archive);
2260
2165
  return archive;
2261
2166
  }
2262
- /** All archives, new layout first, legacy entries only when not shadowed. */
2263
- async list() {
2264
- const seen = /* @__PURE__ */ new Set();
2265
- const archives = [];
2266
- for (const dir of [CONFLICTS_DIR, LEGACY_CONFLICTS_DIR]) {
2267
- let entries;
2167
+ /** All archives, new layout first, legacy entries only when not shadowed. */
2168
+ async list() {
2169
+ const seen = /* @__PURE__ */ new Set();
2170
+ const archives = [];
2171
+ for (const dir of [CONFLICTS_DIR, LEGACY_CONFLICTS_DIR]) {
2172
+ let entries;
2173
+ try {
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;
2268
2461
  try {
2269
- entries = await this.fs.readdir(dir);
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
  }
@@ -3822,11 +3971,11 @@ var ConfigRepo = class {
3822
3971
  }
3823
3972
  return { kind: "ok", desc, mtime };
3824
3973
  } else {
3825
- log4.warn(`[ConfigRepo] Backend descriptor ${entry} is missing id/type fields, marking for cleanup`);
3974
+ log5.warn(`[ConfigRepo] Backend descriptor ${entry} is missing id/type fields, marking for cleanup`);
3826
3975
  return { kind: "corrupt", filePath };
3827
3976
  }
3828
3977
  } catch (parseErr) {
3829
- log4.warn(`[ConfigRepo] Backend descriptor ${entry} has corrupted JSON: ${parseErr}. Marking for cleanup.`);
3978
+ log5.warn(`[ConfigRepo] Backend descriptor ${entry} has corrupted JSON: ${parseErr}. Marking for cleanup.`);
3830
3979
  return { kind: "corrupt", filePath };
3831
3980
  }
3832
3981
  })
@@ -3892,7 +4041,7 @@ var ConfigRepo = class {
3892
4041
  }
3893
4042
  }
3894
4043
  if (duplicates.length > 0) {
3895
- log4.log(
4044
+ log5.log(
3896
4045
  `[ConfigRepo] readAllBackendDescriptors: removing ${duplicates.length} duplicate(s): ${duplicates.join(", ")}`
3897
4046
  );
3898
4047
  for (const dupId of duplicates) {
@@ -4024,7 +4173,7 @@ var ConfigRepo = class {
4024
4173
  * Shared by addBackend() and replaceBackend().
4025
4174
  */
4026
4175
  async setupReplica(id, type, options, description) {
4027
- log4.log(`[ConfigRepo] addBackend: creating ${id} (${type})...`);
4176
+ log5.log(`[ConfigRepo] addBackend: creating ${id} (${type})...`);
4028
4177
  const instance = await createBackend({ type, options });
4029
4178
  const syncable = backendToSyncableFS(instance, `${type}(${id})`);
4030
4179
  const desc = { id, type, options, description };
@@ -4042,7 +4191,7 @@ var ConfigRepo = class {
4042
4191
  this.invalidateTombstoneCache();
4043
4192
  await this.processTombstones();
4044
4193
  } catch (err) {
4045
- log4.warn("[ConfigRepo] preSyncHook processTombstones failed:", err);
4194
+ log5.warn("[ConfigRepo] preSyncHook processTombstones failed:", err);
4046
4195
  }
4047
4196
  },
4048
4197
  postSyncHook: async () => {
@@ -4051,7 +4200,7 @@ var ConfigRepo = class {
4051
4200
  await this.processTombstones();
4052
4201
  await this.updateTombstoneConfirmations();
4053
4202
  } catch (err) {
4054
- log4.warn("[ConfigRepo] postSyncHook tombstone processing failed:", err);
4203
+ log5.warn("[ConfigRepo] postSyncHook tombstone processing failed:", err);
4055
4204
  }
4056
4205
  }
4057
4206
  },
@@ -4064,7 +4213,7 @@ var ConfigRepo = class {
4064
4213
  };
4065
4214
  this.syncEngine.on(pair.pairId, "conflict", conflictHandler);
4066
4215
  this.trackSyncErrors(id, pair.pairId);
4067
- log4.log(`[ConfigRepo] addBackend: ${id} (${type}) added, sync pair=${pair.pairId}`);
4216
+ log5.log(`[ConfigRepo] addBackend: ${id} (${type}) added, sync pair=${pair.pairId}`);
4068
4217
  await this.syncMetaToReplicas();
4069
4218
  this.syncEngine.watch(pair.pairId);
4070
4219
  return pair.pairId;
@@ -4090,13 +4239,13 @@ var ConfigRepo = class {
4090
4239
  }
4091
4240
  }
4092
4241
  this.syncEngine.removePair(replica.pairId);
4093
- log4.log(`[ConfigRepo] removeBackend: sync pair ${replica.pairId} removed`);
4242
+ log5.log(`[ConfigRepo] removeBackend: sync pair ${replica.pairId} removed`);
4094
4243
  this.replicaBackends.delete(id);
4095
4244
  if (replica.instance?.dispose) {
4096
4245
  await replica.instance.dispose();
4097
4246
  }
4098
4247
  } else {
4099
- log4.log(`[ConfigRepo] removeBackend: "${id}" not in replicaBackends, cleaning up descriptor only`);
4248
+ log5.log(`[ConfigRepo] removeBackend: "${id}" not in replicaBackends, cleaning up descriptor only`);
4100
4249
  for (const descPath of descPaths) {
4101
4250
  try {
4102
4251
  await this.deleteFile(descPath);
@@ -4107,7 +4256,7 @@ var ConfigRepo = class {
4107
4256
  }
4108
4257
  this.backendStates.delete(id);
4109
4258
  this.schedulePostDeleteSync();
4110
- log4.log(`[ConfigRepo] removeBackend: ${id} removed (tombstone written, remote cleaned)`);
4259
+ log5.log(`[ConfigRepo] removeBackend: ${id} removed (tombstone written, remote cleaned)`);
4111
4260
  }
4112
4261
  /**
4113
4262
  * Replace a config-sync backend's parameters in place (same id).
@@ -4154,11 +4303,11 @@ var ConfigRepo = class {
4154
4303
  await this.setupReplica(id, type, options, description ?? before.description);
4155
4304
  } catch (err) {
4156
4305
  const reason = err instanceof Error ? err.message : String(err);
4157
- log4.warn(`[ConfigRepo] replaceBackend: "${id}" failed, rolling back old options:`, err);
4306
+ log5.warn(`[ConfigRepo] replaceBackend: "${id}" failed, rolling back old options:`, err);
4158
4307
  try {
4159
4308
  await this.setupReplica(id, before.type, before.options, before.description);
4160
4309
  } catch (rollbackErr) {
4161
- log4.error(`[ConfigRepo] replaceBackend: rollback for "${id}" ALSO failed:`, rollbackErr);
4310
+ log5.error(`[ConfigRepo] replaceBackend: rollback for "${id}" ALSO failed:`, rollbackErr);
4162
4311
  }
4163
4312
  throw new Error(`\u66F4\u65B0\u540E\u7AEF\u53C2\u6570\u5931\u8D25\uFF1A${reason}\uFF08\u5DF2\u5C1D\u8BD5\u56DE\u6EDA\u65E7\u53C2\u6570\uFF09`);
4164
4313
  }
@@ -4166,6 +4315,80 @@ var ConfigRepo = class {
4166
4315
  // -----------------------------------------------------------------------
4167
4316
  // IConfigRepo — Group Type
4168
4317
  // -----------------------------------------------------------------------
4318
+ /**
4319
+ * 本组的同步身份(kind + id + 不可变 instanceId)。
4320
+ *
4321
+ * 首次调用时若 `.meta/group.json` 里还没有 `instanceId`(老部署),生成一个
4322
+ * 并就地写回 —— 只写一次,之后字节相同不再落盘。
4323
+ */
4324
+ async ensureGroupIdentity(kind = "config", id = CONFIG_GROUP_ID) {
4325
+ let existingFeatures;
4326
+ if (!this.instanceId) {
4327
+ let existing = null;
4328
+ try {
4329
+ existing = await readGroupDescriptor(this.cachedFS);
4330
+ } catch {
4331
+ }
4332
+ const known = pickInstanceId(existing);
4333
+ existingFeatures = existing?.features ?? CONFIG_GROUP_FEATURES;
4334
+ this.instanceId = known ?? newGroupInstanceId();
4335
+ if (!known) {
4336
+ try {
4337
+ await writeGroupDescriptor(this.cachedFS, {
4338
+ schemaVersion: 2,
4339
+ kind: existing?.kind ?? kind,
4340
+ id: existing?.id ?? id,
4341
+ instanceId: this.instanceId,
4342
+ ...existing?.name ?? this.name ? { name: existing?.name ?? this.name } : {},
4343
+ features: existing?.features ?? CONFIG_GROUP_FEATURES
4344
+ });
4345
+ log5.log(`[ConfigRepo] group instanceId assigned: ${this.instanceId} (kind=${existing?.kind ?? kind})`);
4346
+ } catch (err) {
4347
+ log5.warn("[ConfigRepo] failed to persist group instanceId:", err);
4348
+ }
4349
+ }
4350
+ }
4351
+ return {
4352
+ kind,
4353
+ id,
4354
+ instanceId: this.instanceId,
4355
+ ...this.name ? { name: this.name } : {},
4356
+ ...existingFeatures ? { features: existingFeatures } : {}
4357
+ };
4358
+ }
4359
+ /** 组实例身份(未初始化时先兜底生成并落盘)。 */
4360
+ async ensureGroupInstanceId() {
4361
+ return (await this.ensureGroupIdentity()).instanceId;
4362
+ }
4363
+ /** 组实例身份(同步读取;init 之前可能为 `undefined`)。 */
4364
+ getGroupInstanceId() {
4365
+ return this.instanceId;
4366
+ }
4367
+ /**
4368
+ * 连接远端前校验归属:属于别的组 → `conflict`(调用方必须跳过、不建同步对)。
4369
+ * 老仓库(无 instanceId)会被本组认领。
4370
+ */
4371
+ async bindBackendIdentity(instance, backendId) {
4372
+ try {
4373
+ const identity = await this.ensureGroupIdentity();
4374
+ const state = await bindRemoteGroupIdentity(instance, identity);
4375
+ if (state === "conflict") {
4376
+ this.skippedBackends.set(
4377
+ backendId,
4378
+ `\u8FDC\u7AEF\u6839\u5C5E\u4E8E\u53E6\u4E00\u4E2A\u540C\u6B65\u7EC4\uFF08instanceId \u4E0D\u4E00\u81F4\uFF09\uFF0C\u5DF2\u8DF3\u8FC7\u8BE5\u540E\u7AEF`
4379
+ );
4380
+ }
4381
+ return state;
4382
+ } catch (err) {
4383
+ log5.warn(`[ConfigRepo] identity check failed for backend "${backendId}", skipping it:`, err);
4384
+ this.skippedBackends.set(backendId, `\u5F52\u5C5E\u6821\u9A8C\u5931\u8D25\uFF1A${err?.message ?? String(err)}`);
4385
+ return "conflict";
4386
+ }
4387
+ }
4388
+ /** 因归属他人而被跳过的后端(id → 原因)。 */
4389
+ listSkippedBackends() {
4390
+ return Array.from(this.skippedBackends, ([backendId, reason]) => ({ backendId, reason }));
4391
+ }
4169
4392
  /** Write the group-type marker file if it doesn't exist. */
4170
4393
  async ensureGroupType(type) {
4171
4394
  this.assertNotDisposed();
@@ -4174,7 +4397,7 @@ var ConfigRepo = class {
4174
4397
  const existing = await this.cachedFS.readFile(path, "utf-8");
4175
4398
  const current = existing.trim();
4176
4399
  if (current && current !== type) {
4177
- log4.warn(`[ConfigRepo] group-type already set to "${current}" at ${path}, ignoring request to set "${type}"`);
4400
+ log5.warn(`[ConfigRepo] group-type already set to "${current}" at ${path}, ignoring request to set "${type}"`);
4178
4401
  return;
4179
4402
  }
4180
4403
  } catch {
@@ -4188,10 +4411,12 @@ var ConfigRepo = class {
4188
4411
  }
4189
4412
  const existingDescriptor = await readGroupDescriptor(this.cachedFS);
4190
4413
  if (!existingDescriptor) {
4414
+ this.instanceId = newGroupInstanceId();
4191
4415
  await writeGroupDescriptor(this.cachedFS, {
4192
4416
  schemaVersion: 2,
4193
4417
  kind: "config",
4194
4418
  id: CONFIG_GROUP_ID,
4419
+ instanceId: this.instanceId,
4195
4420
  ...this.name ? { name: this.name } : {},
4196
4421
  features: CONFIG_GROUP_FEATURES
4197
4422
  });
@@ -4205,7 +4430,22 @@ var ConfigRepo = class {
4205
4430
  features: existingDescriptor.features ?? CONFIG_GROUP_FEATURES
4206
4431
  });
4207
4432
  }
4208
- log4.log(`[ConfigRepo] group-type set to "${type}"`);
4433
+ const knownInstanceId = pickInstanceId(existingDescriptor);
4434
+ if (knownInstanceId) {
4435
+ this.instanceId = knownInstanceId;
4436
+ } else if (!this.instanceId) {
4437
+ this.instanceId = newGroupInstanceId();
4438
+ await writeGroupDescriptor(this.cachedFS, {
4439
+ schemaVersion: 2,
4440
+ kind: existingDescriptor?.kind ?? "config",
4441
+ id: existingDescriptor?.id ?? CONFIG_GROUP_ID,
4442
+ instanceId: this.instanceId,
4443
+ ...existingDescriptor?.name ?? this.name ? { name: existingDescriptor?.name ?? this.name } : {},
4444
+ ...existingDescriptor?.features ? { features: existingDescriptor.features } : {}
4445
+ });
4446
+ log5.log(`[ConfigRepo] assigned group instanceId ${this.instanceId} (kind=${existingDescriptor?.kind ?? "config"})`);
4447
+ }
4448
+ log5.log(`[ConfigRepo] group-type set to "${type}"`);
4209
4449
  }
4210
4450
  /** Read the group-type marker. Returns null if not set (new path, then legacy). */
4211
4451
  async getGroupType() {
@@ -4300,7 +4540,7 @@ var ConfigRepo = class {
4300
4540
  if (this.appDataGroups.has(id)) {
4301
4541
  throw new Error(`App data group "${id}" already exists. Use removeAppDataGroup() first.`);
4302
4542
  }
4303
- log4.log(`[ConfigRepo] createAppDataGroup: creating "${id}" with ${backends.length} backend(s)`);
4543
+ log5.log(`[ConfigRepo] createAppDataGroup: creating "${id}" with ${backends.length} backend(s)`);
4304
4544
  const resolvedBackends = [];
4305
4545
  for (const desc of backends) {
4306
4546
  assertValidBackendId(desc.id);
@@ -4308,6 +4548,7 @@ var ConfigRepo = class {
4308
4548
  resolvedBackends.push({ ...desc, options: mergedOptions });
4309
4549
  }
4310
4550
  await this.assertNoSharedRemote(resolvedBackends, id);
4551
+ const instanceId = newGroupInstanceId();
4311
4552
  const group = new AppDataGroupImpl(
4312
4553
  id,
4313
4554
  this.appId,
@@ -4315,19 +4556,25 @@ var ConfigRepo = class {
4315
4556
  this.pollIntervalMs,
4316
4557
  this,
4317
4558
  // 显式新拓扑:以参数为准并写入 `.meta/backends/`。
4318
- { name: options.name, features: options.features, backendsAreAuthoritative: true }
4559
+ {
4560
+ name: options.name,
4561
+ features: options.features,
4562
+ backendsAreAuthoritative: true,
4563
+ instanceId
4564
+ }
4319
4565
  );
4320
4566
  await group.init();
4321
4567
  const descriptor = {
4322
4568
  id,
4323
4569
  groupType: "data-sync",
4570
+ instanceId: group.getGroupInstanceId() ?? instanceId,
4324
4571
  ...options.name ? { name: options.name } : {},
4325
4572
  ...options.features ? { features: options.features } : {},
4326
4573
  backends: group.listDeclaredBackends()
4327
4574
  };
4328
4575
  await this.writeAppDataGroupDescriptorFile(id, descriptor);
4329
4576
  this.appDataGroups.set(id, group);
4330
- log4.log(`[ConfigRepo] createAppDataGroup: "${id}" created`);
4577
+ log5.log(`[ConfigRepo] createAppDataGroup: "${id}" created`);
4331
4578
  return group;
4332
4579
  }
4333
4580
  /**
@@ -4344,9 +4591,13 @@ var ConfigRepo = class {
4344
4591
  const existing = await this.readAppDataGroupDescriptor(id);
4345
4592
  const name = meta?.name ?? existing?.name;
4346
4593
  const features = meta?.features ?? existing?.features;
4594
+ const liveGroup = this.appDataGroups.get(id);
4595
+ const liveInstanceId = liveGroup?.getGroupInstanceId();
4596
+ const instanceId = pickInstanceId(existing) ?? (isValidGroupInstanceId(liveInstanceId) ? liveInstanceId : void 0);
4347
4597
  const descriptor = {
4348
4598
  id,
4349
4599
  groupType: "data-sync",
4600
+ ...instanceId ? { instanceId } : {},
4350
4601
  ...name ? { name } : {},
4351
4602
  ...features ? { features } : {},
4352
4603
  backends
@@ -4370,7 +4621,7 @@ var ConfigRepo = class {
4370
4621
  try {
4371
4622
  await live.writeOwnGroupDescriptor();
4372
4623
  } catch (err) {
4373
- log4.warn(`[ConfigRepo] updateAppDataGroupName: "${id}" group.json update failed:`, err);
4624
+ log5.warn(`[ConfigRepo] updateAppDataGroupName: "${id}" group.json update failed:`, err);
4374
4625
  }
4375
4626
  }
4376
4627
  const descriptor = {
@@ -4414,6 +4665,9 @@ var ConfigRepo = class {
4414
4665
  const nextBackends = declared.map(
4415
4666
  (b, i) => i === index ? { ...candidate, options: mergedOptions } : b
4416
4667
  );
4668
+ const descriptorNow = await this.readAppDataGroupDescriptor(groupId);
4669
+ const instanceIdFromLive = live?.getGroupInstanceId();
4670
+ const instanceId = pickInstanceId(descriptorNow) ?? (isValidGroupInstanceId(instanceIdFromLive) ? instanceIdFromLive : void 0);
4417
4671
  if (live) {
4418
4672
  await live.dispose();
4419
4673
  this.appDataGroups.delete(groupId);
@@ -4425,7 +4679,7 @@ var ConfigRepo = class {
4425
4679
  nextBackends,
4426
4680
  this.pollIntervalMs,
4427
4681
  this,
4428
- { backendsAreAuthoritative: true }
4682
+ { backendsAreAuthoritative: true, ...instanceId ? { instanceId } : {} }
4429
4683
  );
4430
4684
  await group.init();
4431
4685
  await this.updateAppDataGroupDescriptor(groupId, group.listDeclaredBackends());
@@ -4433,7 +4687,7 @@ var ConfigRepo = class {
4433
4687
  return group;
4434
4688
  } catch (err) {
4435
4689
  const reason = err instanceof Error ? err.message : String(err);
4436
- log4.warn(`[ConfigRepo] replaceAppDataGroupBackend: "${backendId}" failed, rolling back:`, err);
4690
+ log5.warn(`[ConfigRepo] replaceAppDataGroupBackend: "${backendId}" failed, rolling back:`, err);
4437
4691
  try {
4438
4692
  const restored = new AppDataGroupImpl(
4439
4693
  groupId,
@@ -4441,13 +4695,13 @@ var ConfigRepo = class {
4441
4695
  oldBackends,
4442
4696
  this.pollIntervalMs,
4443
4697
  this,
4444
- { backendsAreAuthoritative: true }
4698
+ { backendsAreAuthoritative: true, ...instanceId ? { instanceId } : {} }
4445
4699
  );
4446
4700
  await restored.init();
4447
4701
  await this.updateAppDataGroupDescriptor(groupId, restored.listDeclaredBackends());
4448
4702
  this.appDataGroups.set(groupId, restored);
4449
4703
  } catch (rollbackErr) {
4450
- log4.error("[ConfigRepo] replaceAppDataGroupBackend: rollback ALSO failed:", rollbackErr);
4704
+ log5.error("[ConfigRepo] replaceAppDataGroupBackend: rollback ALSO failed:", rollbackErr);
4451
4705
  }
4452
4706
  throw new Error(`\u66F4\u65B0\u540E\u7AEF\u53C2\u6570\u5931\u8D25\uFF1A${reason}\uFF08\u5DF2\u5C1D\u8BD5\u56DE\u6EDA\u65E7\u53C2\u6570\uFF09`);
4453
4707
  }
@@ -4485,10 +4739,12 @@ var ConfigRepo = class {
4485
4739
  const version = await incrementVersion(this.fullFS, path, bytes, author);
4486
4740
  await this.writeVersionSidecar(path, version);
4487
4741
  }
4742
+ const identity = await this.ensureGroupIdentity();
4488
4743
  await writeGroupDescriptor(this.cachedFS, {
4489
4744
  schemaVersion: 2,
4490
4745
  kind: "config",
4491
4746
  id: CONFIG_GROUP_ID,
4747
+ instanceId: identity.instanceId,
4492
4748
  name: normalized,
4493
4749
  features: CONFIG_GROUP_FEATURES
4494
4750
  });
@@ -4565,7 +4821,7 @@ var ConfigRepo = class {
4565
4821
  try {
4566
4822
  await this.deleteFile(descPath);
4567
4823
  } catch (err) {
4568
- log4.log(`[ConfigRepo] removeAppDataGroup: deleteFile failed for "${id}" at ${descPath}:`, err);
4824
+ log5.log(`[ConfigRepo] removeAppDataGroup: deleteFile failed for "${id}" at ${descPath}:`, err);
4569
4825
  try {
4570
4826
  await this.cachedFS.unlink(descPath);
4571
4827
  } catch {
@@ -4573,7 +4829,7 @@ var ConfigRepo = class {
4573
4829
  await this.unlinkVersionSidecar(this.cachedFS, descPath);
4574
4830
  }
4575
4831
  }
4576
- log4.log(`[ConfigRepo] removeAppDataGroup: "${id}" removed`);
4832
+ log5.log(`[ConfigRepo] removeAppDataGroup: "${id}" removed`);
4577
4833
  }
4578
4834
  async listAccountBackends() {
4579
4835
  this.assertNotDisposed();
@@ -4610,10 +4866,20 @@ var AppDataGroupImpl = class {
4610
4866
  versions;
4611
4867
  conflicts;
4612
4868
  postDeleteTimer;
4869
+ /**
4870
+ * 墓碑路径的同步排除表(与配置组同一套机制)。
4871
+ *
4872
+ * 保留期内的墓碑路径不参与同步:否则副本上的残留会被当作"远端内容"逐文件
4873
+ * 拉回本地,把已删除的目录复活。数组与各同步对共享同一实例(zen-fs-sync
4874
+ * 每次检测时实时读取 `filter.excludePrefixes`),原地更新即可生效。
4875
+ */
4876
+ tombstoneExcludePrefixes = [...CONFIG_ONLY_PREFIXES];
4877
+ syncFilter = { excludePrefixes: this.tombstoneExcludePrefixes };
4613
4878
  constructor(groupId, appId, backends, pollIntervalMs, parent, descriptor = {}) {
4614
4879
  this.groupId = groupId;
4615
4880
  this.appId = appId;
4616
4881
  this.name = descriptor.name;
4882
+ this.instanceId = isValidGroupInstanceId(descriptor.instanceId) ? descriptor.instanceId : void 0;
4617
4883
  this.features = {
4618
4884
  ...DATA_GROUP_DEFAULT_FEATURES,
4619
4885
  ...descriptor.features,
@@ -4631,6 +4897,13 @@ var AppDataGroupImpl = class {
4631
4897
  }
4632
4898
  parent;
4633
4899
  _backends;
4900
+ /**
4901
+ * 组实例身份(UUID)。同步边界:远端 `.meta/group.json` 的 `instanceId`
4902
+ * 不一致就不建同步对,因此不同同步组之间永不互相搬运数据。
4903
+ */
4904
+ instanceId;
4905
+ /** 因归属他人而被跳过的后端 id → 原因。 */
4906
+ skippedBackends = /* @__PURE__ */ new Map();
4634
4907
  _pollIntervalMs;
4635
4908
  _backendsAreAuthoritative;
4636
4909
  /** 引导副本(`.config/` 里的描述符)原有的能力位,用于回刷时不丢信息。 */
@@ -4727,14 +5000,64 @@ var AppDataGroupImpl = class {
4727
5000
  }
4728
5001
  /** Write this group's own `.meta/group.json` (idempotent: identical bytes → no write). */
4729
5002
  async writeOwnGroupDescriptor() {
5003
+ if (!this.instanceId) {
5004
+ this.instanceId = newGroupInstanceId();
5005
+ log5.log(`[AppDataGroup:${this.groupId}] assigned instanceId ${this.instanceId}`);
5006
+ }
4730
5007
  await writeGroupDescriptor(this.localFS, {
4731
5008
  schemaVersion: 2,
4732
5009
  kind: "data",
4733
5010
  id: this.groupId,
5011
+ instanceId: this.instanceId,
4734
5012
  ...this.name ? { name: this.name } : {},
4735
5013
  features: this.features
4736
5014
  });
4737
5015
  }
5016
+ /** 本组实例身份(初始化后可用)。 */
5017
+ getGroupInstanceId() {
5018
+ return this.instanceId;
5019
+ }
5020
+ /** 因归属他人而被跳过的后端(id → 原因)。 */
5021
+ listSkippedBackends() {
5022
+ return Array.from(this.skippedBackends, ([backendId, reason]) => ({ backendId, reason }));
5023
+ }
5024
+ /**
5025
+ * 连接数据后端前的归属校验。
5026
+ *
5027
+ * - `match`:远端 `.meta/group.json` 的 `instanceId` 与本组一致 → 建同步对;
5028
+ * - `claimed`:远端是老仓库(无身份)→ 本组认领并写入,再建同步对;
5029
+ * - `conflict`:远端属于另一个同步组(或类型不符 / 读不到)→ 跳过,
5030
+ * **绝不建立同步对**,因此跨组数据不会被搬运。
5031
+ */
5032
+ async checkBackendOwnership(instance, backendId) {
5033
+ if (!this.instanceId) {
5034
+ this.skippedBackends.set(backendId, "\u672C\u7EC4\u5C1A\u672A\u5206\u914D instanceId\uFF0C\u5DF2\u8DF3\u8FC7\u8BE5\u540E\u7AEF");
5035
+ return "conflict";
5036
+ }
5037
+ try {
5038
+ const state = await bindRemoteGroupIdentity(instance, {
5039
+ kind: "data",
5040
+ id: this.groupId,
5041
+ instanceId: this.instanceId,
5042
+ ...this.name ? { name: this.name } : {},
5043
+ features: this.features
5044
+ });
5045
+ if (state === "conflict") {
5046
+ this.skippedBackends.set(
5047
+ backendId,
5048
+ "\u8FDC\u7AEF\u6839\u5C5E\u4E8E\u53E6\u4E00\u4E2A\u540C\u6B65\u7EC4\uFF08instanceId \u4E0D\u4E00\u81F4\uFF09\uFF0C\u5DF2\u8DF3\u8FC7\u8BE5\u540E\u7AEF"
5049
+ );
5050
+ log5.warn(
5051
+ `[AppDataGroup:${this.groupId}] backend "${backendId}" belongs to another sync group \u2014 sync pair skipped`
5052
+ );
5053
+ }
5054
+ return state;
5055
+ } catch (err) {
5056
+ log5.warn(`[AppDataGroup:${this.groupId}] ownership check failed for "${backendId}":`, err);
5057
+ this.skippedBackends.set(backendId, `\u5F52\u5C5E\u6821\u9A8C\u5931\u8D25\uFF1A${err?.message ?? String(err)}`);
5058
+ return "conflict";
5059
+ }
5060
+ }
4738
5061
  async init() {
4739
5062
  const storeName = dataGroupLocalStoreName(this.appId, this.groupId);
4740
5063
  try {
@@ -4762,40 +5085,56 @@ var AppDataGroupImpl = class {
4762
5085
  try {
4763
5086
  const purged = await purgeMtimeSidecars(this.localFS);
4764
5087
  if (purged.removed.length > 0) {
4765
- log4.warn(
5088
+ log5.warn(
4766
5089
  `[AppDataGroup:${this.groupId}] purged ${purged.removed.length} leaked .mtime sidecar(s):`,
4767
5090
  purged.removed
4768
5091
  );
4769
5092
  }
4770
5093
  } catch (err) {
4771
- log4.warn(`[AppDataGroup:${this.groupId}] .mtime purge failed:`, err?.message ?? err);
5094
+ log5.warn(`[AppDataGroup:${this.groupId}] .mtime purge failed:`, err?.message ?? err);
4772
5095
  }
4773
5096
  try {
4774
5097
  const purgedKeep = await purgeKeepFiles(this.localFS);
4775
5098
  if (purgedKeep.removed.length > 0) {
4776
- log4.warn(
5099
+ log5.warn(
4777
5100
  `[AppDataGroup:${this.groupId}] purged ${purgedKeep.removed.length} leaked .keep placeholder(s):`,
4778
5101
  purgedKeep.removed
4779
5102
  );
4780
5103
  }
4781
5104
  } catch (err) {
4782
- log4.warn(`[AppDataGroup:${this.groupId}] .keep purge failed:`, err?.message ?? err);
5105
+ log5.warn(`[AppDataGroup:${this.groupId}] .keep purge failed:`, err?.message ?? err);
4783
5106
  }
4784
5107
  const localSyncable = backendToSyncableFS(this.localFS, `local(${this.groupId})`);
4785
5108
  this.tombstones = new TombstoneStore(this.localFS, this.localBackendId);
4786
5109
  this.versions = new VersionStore(this.localFS, `${this.appId}/${this.groupId}`);
4787
5110
  this.conflicts = new ConflictStore(this.localFS, this.appId, `${this.groupId}`, this.versions);
5111
+ try {
5112
+ this.refreshSyncExclusions(await this.tombstones.list());
5113
+ } catch (err) {
5114
+ log5.warn(`[AppDataGroup:${this.groupId}] failed to load tombstones for exclusions:`, err);
5115
+ }
4788
5116
  let backendsChanged = false;
4789
5117
  try {
4790
5118
  backendsChanged = await this.loadBackendDescriptors();
4791
5119
  } catch (err) {
4792
- log4.warn(`[AppDataGroup:${this.groupId}] failed to load .meta/backends:`, err);
5120
+ log5.warn(`[AppDataGroup:${this.groupId}] failed to load .meta/backends:`, err);
4793
5121
  this._backends = this._backends ?? [];
4794
5122
  }
5123
+ if (!this.instanceId) {
5124
+ try {
5125
+ const existing = await readGroupDescriptor(this.localFS);
5126
+ this.instanceId = pickInstanceId(existing);
5127
+ if (this.instanceId) {
5128
+ log5.log(`[AppDataGroup:${this.groupId}] adopted instanceId ${this.instanceId} from local group.json`);
5129
+ }
5130
+ } catch (err) {
5131
+ log5.warn(`[AppDataGroup:${this.groupId}] failed to read local group.json:`, err);
5132
+ }
5133
+ }
4795
5134
  try {
4796
5135
  await this.writeOwnGroupDescriptor();
4797
5136
  } catch (err) {
4798
- log4.warn(`[AppDataGroup:${this.groupId}] failed to write .meta/group.json:`, err);
5137
+ log5.warn(`[AppDataGroup:${this.groupId}] failed to write .meta/group.json:`, err);
4799
5138
  }
4800
5139
  this.fs = createChrootFS(this.localFS, "/", {
4801
5140
  hiddenPrefixes: [META_DIR, CONFIG_DIR],
@@ -4805,7 +5144,7 @@ var AppDataGroupImpl = class {
4805
5144
  });
4806
5145
  const { kept, removed } = dedupeAppDataBackends(this._backends);
4807
5146
  if (removed.length > 0) {
4808
- log4.warn(
5147
+ log5.warn(
4809
5148
  `[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
5149
  );
4811
5150
  this._backends = kept;
@@ -4819,12 +5158,20 @@ var AppDataGroupImpl = class {
4819
5158
  features: this._declaredFeatures
4820
5159
  });
4821
5160
  } catch (err) {
4822
- log4.warn(`[AppDataGroup:${this.groupId}] failed to persist backend topology:`, err);
5161
+ log5.warn(`[AppDataGroup:${this.groupId}] failed to persist backend topology:`, err);
4823
5162
  }
4824
5163
  }
4825
5164
  for (const desc of this._backends) {
4826
5165
  try {
4827
5166
  const instance = await createBackend({ type: desc.type, options: desc.options });
5167
+ const owned = await this.checkBackendOwnership(instance, desc.id);
5168
+ if (owned === "conflict") {
5169
+ try {
5170
+ await instance.dispose?.();
5171
+ } catch {
5172
+ }
5173
+ continue;
5174
+ }
4828
5175
  const syncable = backendToSyncableFS(instance, `${desc.type}(${desc.id})`);
4829
5176
  const pair = this.syncEngine.addPair(
4830
5177
  localSyncable,
@@ -4835,7 +5182,8 @@ var AppDataGroupImpl = class {
4835
5182
  pollIntervalMs: this._pollIntervalMs,
4836
5183
  // `.meta/` is intentionally NOT excluded: tombstones, versions and
4837
5184
  // conflicts must sync, otherwise deletions resurrect on other devices.
4838
- filter: { excludePrefixes: CONFIG_ONLY_PREFIXES },
5185
+ // 但要排除"当前墓碑指向的路径"(与配置组同一张表,实时生效)。
5186
+ filter: this.syncFilter,
4839
5187
  preSyncHook: async () => {
4840
5188
  await this.runTombstonePass("preSync");
4841
5189
  },
@@ -4851,26 +5199,26 @@ var AppDataGroupImpl = class {
4851
5199
  if (this.features.conflicts) {
4852
5200
  const conflictHandler = (event) => {
4853
5201
  this.archiveConflict(event).catch((err) => {
4854
- log4.warn(`[AppDataGroup:${this.groupId}] conflict archive failed:`, err);
5202
+ log5.warn(`[AppDataGroup:${this.groupId}] conflict archive failed:`, err);
4855
5203
  });
4856
5204
  };
4857
5205
  this.syncEngine.on(pair.pairId, "conflict", conflictHandler);
4858
5206
  }
4859
5207
  this.trackSyncErrors(desc.id, pair.pairId);
4860
- log4.log(`[AppDataGroup:${this.groupId}] backend ${desc.id} (${desc.type}) connected, pair=${pair.pairId}`);
5208
+ log5.log(`[AppDataGroup:${this.groupId}] backend ${desc.id} (${desc.type}) connected, pair=${pair.pairId}`);
4861
5209
  } catch (err) {
4862
5210
  const message = err instanceof Error ? err.message : String(err);
4863
5211
  this.backendStates.set(desc.id, {
4864
5212
  backendId: desc.id,
4865
5213
  error: { message, timestamp: Date.now() }
4866
5214
  });
4867
- log4.error(`[AppDataGroup:${this.groupId}] Failed to create backend ${desc.id} (${desc.type}):`, err);
5215
+ log5.error(`[AppDataGroup:${this.groupId}] Failed to create backend ${desc.id} (${desc.type}):`, err);
4868
5216
  }
4869
5217
  }
4870
5218
  try {
4871
5219
  await this.syncEngine.syncAll();
4872
5220
  } catch (err) {
4873
- log4.warn(`[AppDataGroup:${this.groupId}] Initial sync failed:`, err);
5221
+ log5.warn(`[AppDataGroup:${this.groupId}] Initial sync failed:`, err);
4874
5222
  }
4875
5223
  this.syncEngine.watchAll();
4876
5224
  }
@@ -4885,7 +5233,7 @@ var AppDataGroupImpl = class {
4885
5233
  try {
4886
5234
  await this.tombstones.gc(this.allBackendIds(), this.tombstoneTargets());
4887
5235
  } catch (err) {
4888
- log4.warn(`[AppDataGroup:${this.groupId}] tombstone GC failed:`, err);
5236
+ log5.warn(`[AppDataGroup:${this.groupId}] tombstone GC failed:`, err);
4889
5237
  }
4890
5238
  return Array.from(results.values());
4891
5239
  }
@@ -4920,31 +5268,47 @@ var AppDataGroupImpl = class {
4920
5268
  const bytes = typeof data === "string" ? new TextEncoder().encode(data) : toUint8Array2(data);
4921
5269
  await this.versions.record(path, bytes);
4922
5270
  } catch (err) {
4923
- log4.warn(`[AppDataGroup:${this.groupId}] version record failed for ${path}:`, err);
5271
+ log5.warn(`[AppDataGroup:${this.groupId}] version record failed for ${path}:`, err);
4924
5272
  }
4925
5273
  }
4926
5274
  /** Delete tombstoned files on local + every connected backend before/after sync. */
4927
5275
  async runTombstonePass(stage) {
4928
5276
  try {
4929
5277
  await this.tombstones.process(this.tombstoneTargets());
5278
+ this.refreshSyncExclusions(await this.tombstones.list());
4930
5279
  } catch (err) {
4931
- log4.warn(`[AppDataGroup:${this.groupId}] ${stage} tombstone pass failed:`, err);
5280
+ log5.warn(`[AppDataGroup:${this.groupId}] ${stage} tombstone pass failed:`, err);
5281
+ }
5282
+ }
5283
+ /**
5284
+ * 把当前墓碑路径写进同步排除表(原地更新共享数组)。
5285
+ *
5286
+ * 目录墓碑的 `${path}/` 前缀是故意的:整棵树已删除,保留期内任何子路径都不
5287
+ * 参与同步。注意**不能**为 `.keep` 占位排除父目录,否则真实数据会被一起挡掉。
5288
+ */
5289
+ refreshSyncExclusions(tombstones) {
5290
+ this.tombstoneExcludePrefixes.length = 0;
5291
+ this.tombstoneExcludePrefixes.push(...CONFIG_ONLY_PREFIXES);
5292
+ for (const tombstone of tombstones) {
5293
+ if (!tombstone.path) continue;
5294
+ this.tombstoneExcludePrefixes.push(tombstone.path, `${tombstone.path}/`);
4932
5295
  }
4933
5296
  }
4934
5297
  async confirmTombstones() {
4935
5298
  try {
4936
- await this.tombstones.confirm(this.allBackendIds());
5299
+ await this.tombstones.confirm(this.tombstoneTargets());
4937
5300
  } catch (err) {
4938
- log4.warn(`[AppDataGroup:${this.groupId}] tombstone confirmations failed:`, err);
5301
+ log5.warn(`[AppDataGroup:${this.groupId}] tombstone confirmations failed:`, err);
4939
5302
  }
4940
5303
  }
4941
- /** Write a tombstone for `filePath`. Records metadata only — it never creates the file. */
4942
- async writeTombstoneFor(filePath) {
5304
+ /** Write a tombstone for `path`. Records metadata only — it never creates the path. */
5305
+ async writeTombstoneFor(path, type) {
4943
5306
  await this.tombstones.write({
4944
- path: filePath.startsWith("/") ? filePath : `/${filePath}`,
5307
+ path: normalizeTombstonePath(path),
4945
5308
  deletedAt: Date.now(),
4946
5309
  deletedBy: this.localBackendId,
4947
- confirmedBy: [this.localBackendId]
5310
+ confirmedBy: [this.localBackendId],
5311
+ ...type ? { type } : {}
4948
5312
  });
4949
5313
  }
4950
5314
  /**
@@ -4959,16 +5323,10 @@ var AppDataGroupImpl = class {
4959
5323
  throw new Error(`Cannot delete metadata path "${normalized}"`);
4960
5324
  }
4961
5325
  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);
5326
+ await this.writeTombstoneFor(normalized, "directory");
5327
+ await purgeTombstonedTree(this.localFS, normalized);
4970
5328
  this.schedulePostDeleteSync();
4971
- log4.log(`[AppDataGroup:${this.groupId}] deleteFile(directory): ${normalized} (${files.length} file(s))`);
5329
+ log5.log(`[AppDataGroup:${this.groupId}] deleteFile(directory): ${normalized} (single directory tombstone)`);
4972
5330
  return;
4973
5331
  }
4974
5332
  await this.writeTombstoneFor(normalized);
@@ -5007,7 +5365,7 @@ var AppDataGroupImpl = class {
5007
5365
  try {
5008
5366
  await this.syncEngine.syncAll();
5009
5367
  } catch (err) {
5010
- log4.warn(`[AppDataGroup:${this.groupId}] sync after conflict resolve failed:`, err);
5368
+ log5.warn(`[AppDataGroup:${this.groupId}] sync after conflict resolve failed:`, err);
5011
5369
  }
5012
5370
  }
5013
5371
  readConflictBackup(conflictId, fileType) {
@@ -5042,7 +5400,7 @@ var AppDataGroupImpl = class {
5042
5400
  if (this.dataBackends.has(id)) {
5043
5401
  throw new Error(`Backend "${id}" already exists in data group "${this.groupId}"`);
5044
5402
  }
5045
- log4.log(`[AppDataGroup:${this.groupId}] addBackend: creating ${id} (${type})...`);
5403
+ log5.log(`[AppDataGroup:${this.groupId}] addBackend: creating ${id} (${type})...`);
5046
5404
  const instance = await createBackend({ type, options });
5047
5405
  const syncable = backendToSyncableFS(instance, `${type}(${id})`);
5048
5406
  const localSyncable = backendToSyncableFS(this.localFS, `local(${this.groupId})`);
@@ -5053,7 +5411,7 @@ var AppDataGroupImpl = class {
5053
5411
  direction: import_zen_fs_sync.SyncDirection.BiDirectional,
5054
5412
  conflictStrategy: "source-wins",
5055
5413
  pollIntervalMs: this._pollIntervalMs,
5056
- filter: { excludePrefixes: CONFIG_ONLY_PREFIXES },
5414
+ filter: this.syncFilter,
5057
5415
  preSyncHook: async () => {
5058
5416
  await this.runTombstonePass("preSync");
5059
5417
  },
@@ -5070,13 +5428,13 @@ var AppDataGroupImpl = class {
5070
5428
  if (this.features.conflicts) {
5071
5429
  this.syncEngine.on(pair.pairId, "conflict", (event) => {
5072
5430
  this.archiveConflict(event).catch((err) => {
5073
- log4.warn(`[AppDataGroup:${this.groupId}] conflict archive failed:`, err);
5431
+ log5.warn(`[AppDataGroup:${this.groupId}] conflict archive failed:`, err);
5074
5432
  });
5075
5433
  });
5076
5434
  }
5077
5435
  this.trackSyncErrors(id, pair.pairId);
5078
5436
  this._backends = [...this._backends.filter((b) => b.id !== id), desc];
5079
- log4.log(`[AppDataGroup:${this.groupId}] addBackend: ${id} (${type}) connected, pair=${pair.pairId}`);
5437
+ log5.log(`[AppDataGroup:${this.groupId}] addBackend: ${id} (${type}) connected, pair=${pair.pairId}`);
5080
5438
  try {
5081
5439
  const stale = (await this.tombstones.list()).find(
5082
5440
  (t) => t.path === backendMetaFilePath(id)
@@ -5084,12 +5442,12 @@ var AppDataGroupImpl = class {
5084
5442
  if (stale) await this.tombstones.remove(stale);
5085
5443
  await writeBackendMetaDescriptor(this.localFS, desc);
5086
5444
  } catch (err) {
5087
- log4.warn(`[AppDataGroup:${this.groupId}] addBackend: failed to write .meta/backends/${id}.json:`, err);
5445
+ log5.warn(`[AppDataGroup:${this.groupId}] addBackend: failed to write .meta/backends/${id}.json:`, err);
5088
5446
  }
5089
5447
  try {
5090
5448
  await this.syncEngine.sync(pair.pairId);
5091
5449
  } catch (err) {
5092
- log4.warn(`[AppDataGroup:${this.groupId}] addBackend: initial sync failed for ${id}:`, err);
5450
+ log5.warn(`[AppDataGroup:${this.groupId}] addBackend: initial sync failed for ${id}:`, err);
5093
5451
  }
5094
5452
  this.syncEngine.watch(pair.pairId);
5095
5453
  await this.parent.updateAppDataGroupDescriptor(this.groupId, this._backends, {
@@ -5120,7 +5478,7 @@ var AppDataGroupImpl = class {
5120
5478
  if (backend?.instance?.dispose) {
5121
5479
  await backend.instance.dispose();
5122
5480
  }
5123
- log4.log(`[AppDataGroup:${this.groupId}] removeBackend: ${id} removed`);
5481
+ log5.log(`[AppDataGroup:${this.groupId}] removeBackend: ${id} removed`);
5124
5482
  }
5125
5483
  listBackends() {
5126
5484
  return Array.from(this.dataBackends.values()).map((b) => b.desc);
@@ -5162,44 +5520,44 @@ async function createConfigRepo(appId, options = {}) {
5162
5520
  idbStoreName: options.idbStoreName,
5163
5521
  folderPath: options.folderPath
5164
5522
  });
5165
- log4.log(`[createConfigRepo] Creating local primary (type: ${localPrimary.type})...`);
5523
+ log5.log(`[createConfigRepo] Creating local primary (type: ${localPrimary.type})...`);
5166
5524
  const primaryInstance = await createBackend(localPrimary);
5167
5525
  const cachedFS = primaryInstance;
5168
5526
  if (options.purgeMtimeSidecars !== false) {
5169
5527
  try {
5170
5528
  const purged = await purgeMtimeSidecars(cachedFS);
5171
5529
  if (purged.removed.length > 0) {
5172
- log4.warn(
5530
+ log5.warn(
5173
5531
  `[createConfigRepo] purged ${purged.removed.length} leaked .mtime sidecar(s) from local primary:`,
5174
5532
  purged.removed
5175
5533
  );
5176
5534
  }
5177
5535
  } catch (err) {
5178
- log4.warn(`[createConfigRepo] .mtime purge failed:`, err?.message ?? err);
5536
+ log5.warn(`[createConfigRepo] .mtime purge failed:`, err?.message ?? err);
5179
5537
  }
5180
5538
  }
5181
5539
  if (options.purgeKeepFiles !== false) {
5182
5540
  try {
5183
5541
  const purged = await purgeKeepFiles(cachedFS);
5184
5542
  if (purged.removed.length > 0) {
5185
- log4.warn(
5543
+ log5.warn(
5186
5544
  `[createConfigRepo] purged ${purged.removed.length} leaked .keep placeholder(s) from local primary:`,
5187
5545
  purged.removed
5188
5546
  );
5189
5547
  }
5190
5548
  } catch (err) {
5191
- log4.warn(`[createConfigRepo] .keep purge failed:`, err?.message ?? err);
5549
+ log5.warn(`[createConfigRepo] .keep purge failed:`, err?.message ?? err);
5192
5550
  }
5193
5551
  }
5194
5552
  const cacheOptions = options.cache === false ? void 0 : options.cache ?? {};
5195
5553
  try {
5196
5554
  await primaryInstance.mkdir(META_DIR);
5197
- log4.log(`[createConfigRepo] /.meta/ ready`);
5555
+ log5.log(`[createConfigRepo] /.meta/ ready`);
5198
5556
  } catch (err) {
5199
5557
  const msg = err.message || "";
5200
5558
  if (msg.includes("File exists") || msg.includes("EEXIST") || err.code === "EEXIST") {
5201
5559
  } else {
5202
- log4.error(`[createConfigRepo] Failed to ensure /.meta/:`, err.message);
5560
+ log5.error(`[createConfigRepo] Failed to ensure /.meta/:`, err.message);
5203
5561
  }
5204
5562
  }
5205
5563
  try {
@@ -5210,7 +5568,7 @@ async function createConfigRepo(appId, options = {}) {
5210
5568
  } catch {
5211
5569
  await ensureParentDir2(primaryInstance, path);
5212
5570
  await primaryInstance.writeFile(path, groupTypeBytes);
5213
- log4.log(`[createConfigRepo] group-type set to "config-sync" at ${path}`);
5571
+ log5.log(`[createConfigRepo] group-type set to "config-sync" at ${path}`);
5214
5572
  }
5215
5573
  }
5216
5574
  if (!await readGroupDescriptor(primaryInstance)) {
@@ -5218,11 +5576,12 @@ async function createConfigRepo(appId, options = {}) {
5218
5576
  schemaVersion: 2,
5219
5577
  kind: "config",
5220
5578
  id: CONFIG_GROUP_ID,
5579
+ instanceId: newGroupInstanceId(),
5221
5580
  features: CONFIG_GROUP_FEATURES
5222
5581
  });
5223
5582
  }
5224
5583
  } catch (err) {
5225
- log4.warn(`[createConfigRepo] Failed to write group metadata:`, err.message);
5584
+ log5.warn(`[createConfigRepo] Failed to write group metadata:`, err.message);
5226
5585
  }
5227
5586
  const tempRepo = new ConfigRepo(
5228
5587
  appId,
@@ -5236,11 +5595,11 @@ async function createConfigRepo(appId, options = {}) {
5236
5595
  );
5237
5596
  const oldBackendsMeta = await tempRepo.readMetaFile(BACKENDS_FILE);
5238
5597
  if (oldBackendsMeta && oldBackendsMeta.backends?.length > 0) {
5239
- log4.log(`[createConfigRepo] Migrating ${oldBackendsMeta.backends.length} backend(s) from backends.json to individual files...`);
5598
+ log5.log(`[createConfigRepo] Migrating ${oldBackendsMeta.backends.length} backend(s) from backends.json to individual files...`);
5240
5599
  await tempRepo.ensureDir(`${BACKENDS_DIR}/.keep`);
5241
5600
  for (const desc of oldBackendsMeta.backends) {
5242
5601
  if (desc.id === LOCAL_IDB_BACKEND_ID) {
5243
- log4.log(`[createConfigRepo] Skipping local backend ${desc.id} during migration`);
5602
+ log5.log(`[createConfigRepo] Skipping local backend ${desc.id} during migration`);
5244
5603
  continue;
5245
5604
  }
5246
5605
  await tempRepo.writeBackendDescriptor(desc);
@@ -5258,7 +5617,7 @@ async function createConfigRepo(appId, options = {}) {
5258
5617
  }
5259
5618
  }
5260
5619
  }
5261
- log4.log(`[createConfigRepo] Migration complete`);
5620
+ log5.log(`[createConfigRepo] Migration complete`);
5262
5621
  }
5263
5622
  let allBackends = await tempRepo.readAllBackendDescriptors();
5264
5623
  if (options.backendInfo) {
@@ -5276,19 +5635,19 @@ async function createConfigRepo(appId, options = {}) {
5276
5635
  type: options.backendInfo.type,
5277
5636
  options: options.backendInfo.options
5278
5637
  });
5279
- log4.log(`[createConfigRepo] Added replica backend: ${replicaId} (${options.backendInfo.type})`);
5638
+ log5.log(`[createConfigRepo] Added replica backend: ${replicaId} (${options.backendInfo.type})`);
5280
5639
  allBackends = [...allBackends, { id: replicaId, type: options.backendInfo.type, options: options.backendInfo.options }];
5281
5640
  } else if (dupConfig) {
5282
- log4.log(`[createConfigRepo] Replica with same config already registered as "${dupConfig.id}", skipping`);
5641
+ log5.log(`[createConfigRepo] Replica with same config already registered as "${dupConfig.id}", skipping`);
5283
5642
  } else {
5284
- log4.log(`[createConfigRepo] Replica ${replicaId} already registered`);
5643
+ log5.log(`[createConfigRepo] Replica ${replicaId} already registered`);
5285
5644
  }
5286
5645
  }
5287
- log4.log(`[createConfigRepo] Replica backends: ${allBackends.map((b) => b.id).join(", ") || "(none)"}`);
5646
+ log5.log(`[createConfigRepo] Replica backends: ${allBackends.map((b) => b.id).join(", ") || "(none)"}`);
5288
5647
  let nodeId = options.nodeId;
5289
5648
  if (!nodeId) {
5290
5649
  nodeId = `node-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`;
5291
- log4.log(`[createConfigRepo] Generated nodeId: ${nodeId}`);
5650
+ log5.log(`[createConfigRepo] Generated nodeId: ${nodeId}`);
5292
5651
  }
5293
5652
  const serializer = createSerializerChain(options.serializer);
5294
5653
  const repo = new ConfigRepo(
@@ -5311,19 +5670,19 @@ async function createConfigRepo(appId, options = {}) {
5311
5670
  try {
5312
5671
  const mig = await repo.migrateLegacyVersionSidecars();
5313
5672
  if (mig.renamed.length === 0 && mig.deleted.length === 0 && mig.remoteDeleted.length === 0) {
5314
- log4.log("[createConfigRepo] no legacy version sidecars to migrate");
5673
+ log5.log("[createConfigRepo] no legacy version sidecars to migrate");
5315
5674
  }
5316
5675
  } catch (err) {
5317
- log4.warn(`[createConfigRepo] version sidecar migration failed:`, err?.message ?? err);
5676
+ log5.warn(`[createConfigRepo] version sidecar migration failed:`, err?.message ?? err);
5318
5677
  }
5319
5678
  }
5320
5679
  await repo.load();
5321
5680
  if (repo.replicaCount > 0) {
5322
- log4.log("[createConfigRepo] Starting background initial sync + dedup...");
5681
+ log5.log("[createConfigRepo] Starting background initial sync + dedup...");
5323
5682
  repo.startBackgroundSync();
5324
5683
  }
5325
5684
  repo.syncMetaToReplicas().catch((err) => {
5326
- log4.error("[createConfigRepo] background syncMetaToReplicas failed:", err);
5685
+ log5.error("[createConfigRepo] background syncMetaToReplicas failed:", err);
5327
5686
  });
5328
5687
  return repo;
5329
5688
  }
@@ -5337,11 +5696,11 @@ function sidecarOwnerPath(path) {
5337
5696
 
5338
5697
  // src/connect.ts
5339
5698
  init_backend_registry();
5340
- var log5 = createLogger2("connect");
5699
+ var log6 = createLogger2("connect");
5341
5700
  var GROUP_TYPE_FILE2 = "/.config/group-type";
5342
5701
  var LEGACY_GROUP_TYPE_FILE2 = "/.meta/group-type";
5343
5702
  async function detectGroupType(type, options) {
5344
- log5(`detectGroupType: connecting to ${type}...`);
5703
+ log6(`detectGroupType: connecting to ${type}...`);
5345
5704
  const tempBackend = await createBackend({ type, options });
5346
5705
  try {
5347
5706
  for (const path of [GROUP_TYPE_FILE2, LEGACY_GROUP_TYPE_FILE2]) {
@@ -5349,15 +5708,15 @@ async function detectGroupType(type, options) {
5349
5708
  const raw = await tempBackend.readFile(path, "utf-8");
5350
5709
  const groupType = raw.trim();
5351
5710
  if (groupType === "config-sync" || groupType === "data-sync") {
5352
- log5(`detectGroupType: detected "${groupType}" at ${path}`);
5711
+ log6(`detectGroupType: detected "${groupType}" at ${path}`);
5353
5712
  return groupType;
5354
5713
  }
5355
- log5(`detectGroupType: unknown group-type value "${groupType}" at ${path}, treating as null`);
5714
+ log6(`detectGroupType: unknown group-type value "${groupType}" at ${path}, treating as null`);
5356
5715
  return null;
5357
5716
  } catch {
5358
5717
  }
5359
5718
  }
5360
- log5(`detectGroupType: no group-type file found (new backend)`);
5719
+ log6(`detectGroupType: no group-type file found (new backend)`);
5361
5720
  return null;
5362
5721
  } finally {
5363
5722
  if (tempBackend?.dispose) {
@@ -5366,7 +5725,7 @@ async function detectGroupType(type, options) {
5366
5725
  }
5367
5726
  }
5368
5727
  async function connect(appId, options = {}) {
5369
- log5(`connect: appId=${appId}`);
5728
+ log6(`connect: appId=${appId}`);
5370
5729
  if (!options.backendInfo) {
5371
5730
  const repo2 = await createConfigRepo(appId, {
5372
5731
  idbStoreName: options.idbStoreName,
@@ -5384,12 +5743,12 @@ async function connect(appId, options = {}) {
5384
5743
  try {
5385
5744
  appDataGroups2.push(await repo2.getAppDataGroup(d.id));
5386
5745
  } catch (err) {
5387
- log5(`connect: failed to load app data group "${d.id}":`, err);
5746
+ log6(`connect: failed to load app data group "${d.id}":`, err);
5388
5747
  }
5389
5748
  }
5390
5749
  const dataGroup2 = appDataGroups2[0];
5391
5750
  if (!dataGroup2 && descriptors2.length > 0) {
5392
- log5(
5751
+ log6(
5393
5752
  `connect: ${descriptors2.length} data group descriptor(s) found but none could be loaded; leaving them untouched (no empty group is created)`
5394
5753
  );
5395
5754
  }
@@ -5414,7 +5773,7 @@ async function connect(appId, options = {}) {
5414
5773
  groupType = detectedType;
5415
5774
  } else {
5416
5775
  groupType = options.groupType ?? "config-sync";
5417
- log5(`connect: new backend, using groupType="${groupType}"`);
5776
+ log6(`connect: new backend, using groupType="${groupType}"`);
5418
5777
  }
5419
5778
  const repo = await createConfigRepo(
5420
5779
  appId,
@@ -5443,14 +5802,14 @@ async function connect(appId, options = {}) {
5443
5802
  try {
5444
5803
  appDataGroups.push(await repo.getAppDataGroup(d.id));
5445
5804
  } catch (err) {
5446
- log5(`connect: failed to load app data group "${d.id}":`, err);
5805
+ log6(`connect: failed to load app data group "${d.id}":`, err);
5447
5806
  }
5448
5807
  }
5449
5808
  let dataGroup = appDataGroups[0];
5450
5809
  if (groupType === "data-sync") {
5451
5810
  if (!dataGroup) {
5452
5811
  if (descriptors.length > 0) {
5453
- log5(
5812
+ log6(
5454
5813
  `connect: ${descriptors.length} data group descriptor(s) exist but could not be loaded; refusing to create/overwrite "default"`
5455
5814
  );
5456
5815
  } else {