zen-fs-config 0.7.13 → 0.7.15

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.mjs CHANGED
@@ -1284,6 +1284,28 @@ async function readGroupDescriptor(fs) {
1284
1284
  const { updatedAt: _ignored, ...rest } = parsed;
1285
1285
  return rest;
1286
1286
  }
1287
+ function isNotFoundError(err) {
1288
+ const e = err;
1289
+ if (!e) return false;
1290
+ if (e.code === "ENOENT" || e.code === "ENOTDIR" || e.name === "NotFoundError" || e.errno === -2) return true;
1291
+ return /no such file|not found|不存在/i.test(String(e.message ?? ""));
1292
+ }
1293
+ async function readGroupDescriptorStrict(fs) {
1294
+ let raw;
1295
+ try {
1296
+ raw = new TextDecoder().decode(toBytes(await fs.readFile(GROUP_DESCRIPTOR_FILE2)));
1297
+ } catch (err) {
1298
+ if (isNotFoundError(err)) return null;
1299
+ throw err;
1300
+ }
1301
+ try {
1302
+ const parsed = JSON.parse(raw);
1303
+ const { updatedAt: _ignored, ...rest } = parsed;
1304
+ return rest;
1305
+ } catch {
1306
+ return null;
1307
+ }
1308
+ }
1287
1309
  async function writeGroupDescriptor(fs, descriptor) {
1288
1310
  const bytes = serializeGroupDescriptor(descriptor);
1289
1311
  if (await readText(fs, GROUP_DESCRIPTOR_FILE2) === bytes) return;
@@ -1701,20 +1723,62 @@ function isValidGroupInstanceId(value) {
1701
1723
  return typeof value === "string" && INSTANCE_ID_RE.test(value.trim());
1702
1724
  }
1703
1725
  async function bindRemoteGroupIdentity(remoteFS, identity) {
1726
+ const result = await bindRemoteGroupIdentityDetailed(remoteFS, identity);
1727
+ return result.state;
1728
+ }
1729
+ function summarizeIdentity(identity) {
1730
+ if (!identity) return "\uFF08\u65E0\u63CF\u8FF0\u7B26\uFF09";
1731
+ const parts = [
1732
+ `kind=${identity.kind ?? "?"}`,
1733
+ `id=${identity.id ?? "?"}`,
1734
+ `\u5B9E\u4F8B ID=${identity.instanceId ? shortInstanceId(identity.instanceId) : "\uFF08\u65E0\uFF09"}`
1735
+ ];
1736
+ return parts.join(" \xB7 ");
1737
+ }
1738
+ function shortInstanceId(instanceId) {
1739
+ return `${instanceId.slice(0, 8)}\u2026`;
1740
+ }
1741
+ function snapshotOf(descriptor) {
1742
+ if (!descriptor) return null;
1743
+ return {
1744
+ kind: descriptor.kind,
1745
+ id: descriptor.id,
1746
+ instanceId: pickInstanceId(descriptor),
1747
+ ...descriptor.name ? { name: descriptor.name } : {}
1748
+ };
1749
+ }
1750
+ async function bindRemoteGroupIdentityDetailed(remoteFS, identity) {
1704
1751
  let remote = null;
1705
1752
  try {
1706
- remote = await readGroupDescriptor(remoteFS);
1753
+ remote = await readGroupDescriptorStrict(remoteFS);
1707
1754
  } catch (err) {
1708
1755
  log4.warn(`[GroupIdentity] failed to read remote ${identity.kind}/"${identity.id}" group.json:`, err);
1709
- throw err;
1756
+ return {
1757
+ state: "conflict",
1758
+ remote: null,
1759
+ local: identity,
1760
+ conflict: "unreadable",
1761
+ unreadable: true,
1762
+ error: err?.message ?? String(err)
1763
+ };
1764
+ }
1765
+ const snapshot = snapshotOf(remote);
1766
+ const current = snapshot?.instanceId;
1767
+ if (snapshot?.kind && snapshot.kind !== identity.kind) {
1768
+ log4.warn(
1769
+ `[GroupIdentity] remote kind "${snapshot.kind}" \u2260 this group kind "${identity.kind}" \u2014 sync pair NOT created`
1770
+ );
1771
+ return { state: "conflict", remote: snapshot, local: identity, conflict: "kind-mismatch" };
1710
1772
  }
1711
- const current = remote?.instanceId;
1712
1773
  if (isValidGroupInstanceId(current)) {
1713
- if (current === identity.instanceId) return "match";
1774
+ if (current === identity.instanceId) {
1775
+ return { state: "match", remote: snapshot, local: identity };
1776
+ }
1777
+ const reason = snapshot?.id && snapshot.id !== identity.id ? "id-mismatch" : "instance-mismatch";
1714
1778
  log4.warn(
1715
- `[GroupIdentity] backend belongs to another sync group (remote instanceId=${current}, this group=${identity.instanceId}, kind ${remote?.kind ?? "?"}/"${remote?.id ?? "?"}") \u2014 sync pair NOT created`
1779
+ `[GroupIdentity] backend belongs to another sync group (remote ${summarizeIdentity(snapshot)}, this group ${summarizeIdentity(identity)}) \u2014 sync pair NOT created`
1716
1780
  );
1717
- return "conflict";
1781
+ return { state: "conflict", remote: snapshot, local: identity, conflict: reason };
1718
1782
  }
1719
1783
  const next = {
1720
1784
  schemaVersion: 2,
@@ -1724,22 +1788,79 @@ async function bindRemoteGroupIdentity(remoteFS, identity) {
1724
1788
  ...remote?.name ?? identity.name ? { name: remote?.name ?? identity.name } : {},
1725
1789
  ...remote?.features ?? identity.features ? { features: remote?.features ?? identity.features } : {}
1726
1790
  };
1727
- if (next.kind !== identity.kind) {
1728
- log4.warn(
1729
- `[GroupIdentity] remote kind "${next.kind}" \u2260 this group kind "${identity.kind}" \u2014 sync pair NOT created`
1730
- );
1731
- return "conflict";
1732
- }
1733
1791
  try {
1734
1792
  await writeGroupDescriptor(remoteFS, next);
1735
1793
  } catch (err) {
1736
1794
  log4.warn(`[GroupIdentity] failed to claim remote root for "${identity.id}":`, err);
1737
- return "conflict";
1795
+ return {
1796
+ state: "conflict",
1797
+ remote: snapshot,
1798
+ local: identity,
1799
+ conflict: "claim-failed",
1800
+ error: err?.message ?? String(err)
1801
+ };
1738
1802
  }
1739
1803
  log4.log(
1740
1804
  `[GroupIdentity] claimed remote root for ${identity.kind}/"${identity.id}" (instanceId=${identity.instanceId})`
1741
1805
  );
1742
- return "claimed";
1806
+ return { state: "claimed", remote: snapshot, local: identity };
1807
+ }
1808
+ async function resolveRemoteIdentity(remoteFS, identity, mode) {
1809
+ let remote = null;
1810
+ try {
1811
+ remote = await readGroupDescriptorStrict(remoteFS);
1812
+ } catch (err) {
1813
+ return { mode, ok: false, reason: `\u8FDC\u7AEF\u63CF\u8FF0\u7B26\u8BFB\u4E0D\u5230\uFF1A${err?.message ?? String(err)}` };
1814
+ }
1815
+ const snapshot = snapshotOf(remote);
1816
+ if (mode === "adopt-remote-instance") {
1817
+ const remoteInstanceId = snapshot?.instanceId;
1818
+ if (!isValidGroupInstanceId(remoteInstanceId)) {
1819
+ return { mode, ok: false, reason: "\u8FDC\u7AEF\u6CA1\u6709\u5B9E\u4F8B\u8EAB\u4EFD\uFF0C\u65E0\u9700\u5BF9\u9F50", remote: snapshot };
1820
+ }
1821
+ if (snapshot?.kind !== identity.kind) {
1822
+ return {
1823
+ mode,
1824
+ ok: false,
1825
+ reason: `\u8FDC\u7AEF kind=${snapshot?.kind ?? "?"}\uFF0C\u672C\u7EC4 kind=${identity.kind}\uFF1A\u7C7B\u578B\u4E0D\u540C\u4E0D\u80FD\u53EA\u5BF9\u9F50\u5B9E\u4F8B\u8EAB\u4EFD`,
1826
+ remote: snapshot
1827
+ };
1828
+ }
1829
+ if (snapshot?.id !== identity.id) {
1830
+ return {
1831
+ mode,
1832
+ ok: false,
1833
+ reason: `\u8FDC\u7AEF id=${snapshot?.id ?? "?"}\uFF0C\u672C\u7EC4 id=${identity.id}\uFF1A\u7EC4 id \u4E0D\u540C\u8BF4\u660E\u8FDC\u7AEF\u6839\u88AB\u53E6\u4E00\u4E2A\u903B\u8F91\u7EC4\u5360\u7528\uFF0C\u4E0D\u80FD\u5BF9\u9F50`,
1834
+ remote: snapshot
1835
+ };
1836
+ }
1837
+ return { mode, ok: true, instanceId: remoteInstanceId, remote: snapshot };
1838
+ }
1839
+ if (snapshot && snapshot.kind !== identity.kind) {
1840
+ return {
1841
+ mode,
1842
+ ok: false,
1843
+ reason: `\u8FDC\u7AEF kind=${snapshot.kind}\uFF0C\u672C\u7EC4 kind=${identity.kind}\uFF1A\u7C7B\u578B\u4E0D\u540C\u4E0D\u5141\u8BB8\u6539\u5199\u8FDC\u7AEF`,
1844
+ remote: snapshot
1845
+ };
1846
+ }
1847
+ const next = {
1848
+ schemaVersion: 2,
1849
+ kind: identity.kind,
1850
+ id: identity.id,
1851
+ instanceId: identity.instanceId,
1852
+ ...identity.name ? { name: identity.name } : {},
1853
+ ...identity.features ? { features: identity.features } : {}
1854
+ };
1855
+ try {
1856
+ await writeGroupDescriptor(remoteFS, next);
1857
+ } catch (err) {
1858
+ return { mode, ok: false, reason: `\u5199\u8FDC\u7AEF\u5931\u8D25\uFF1A${err?.message ?? String(err)}`, remote: snapshot };
1859
+ }
1860
+ log4.log(
1861
+ `[GroupIdentity] rewrote remote identity to ${identity.kind}/"${identity.id}" (instanceId=${identity.instanceId})`
1862
+ );
1863
+ return { mode, ok: true, remote: snapshot };
1743
1864
  }
1744
1865
  function pickInstanceId(descriptor) {
1745
1866
  const value = descriptor?.instanceId;
@@ -1990,6 +2111,24 @@ async function migrateVersionSidecars(fs, options = {}) {
1990
2111
  }
1991
2112
 
1992
2113
  // src/config-repo.ts
2114
+ function describeConflict(result) {
2115
+ const remote = summarizeIdentity(result.remote);
2116
+ const local = summarizeIdentity(result.local);
2117
+ switch (result.conflict) {
2118
+ case "kind-mismatch":
2119
+ return `\u7EC4\u7C7B\u578B\u4E0D\u4E00\u81F4\uFF1A\u8FDC\u7AEF ${remote}\uFF0C\u672C\u7EC4 ${local}\u3002\u8BE5\u8FDC\u7AEF\u6839\u5DF2\u88AB\u53E6\u4E00\u7C7B\u7EC4\u5360\u7528\uFF0C\u5DF2\u8DF3\u8FC7\u8BE5\u540E\u7AEF`;
2120
+ case "id-mismatch":
2121
+ return `\u7EC4 id \u4E0D\u4E00\u81F4\uFF1A\u8FDC\u7AEF ${remote}\uFF0C\u672C\u7EC4 ${local}\u3002\u540C\u4E00\u8FDC\u7AEF\u6839\u88AB\u53E6\u4E00\u4E2A\u903B\u8F91\u7EC4\u5360\u7528\uFF0C\u5DF2\u8DF3\u8FC7\u8BE5\u540E\u7AEF`;
2122
+ case "instance-mismatch":
2123
+ return `\u5B9E\u4F8B\u8EAB\u4EFD\u4E0D\u4E00\u81F4\uFF1A\u8FDC\u7AEF ${remote}\uFF0C\u672C\u7EC4 ${local}\u3002\u5DF2\u8DF3\u8FC7\u8BE5\u540E\u7AEF\uFF08\u786E\u8BA4\u540E\u53EF\u5728\u754C\u9762\u4E0A\u5BF9\u9F50\uFF09`;
2124
+ case "unreadable":
2125
+ return `\u8FDC\u7AEF group.json \u8BFB\u4E0D\u5230\uFF08${result.error ?? "\u672A\u77E5\u9519\u8BEF"}\uFF09\uFF0C\u65E0\u6CD5\u5224\u65AD\u5F52\u5C5E\uFF0C\u5DF2\u8DF3\u8FC7\u8BE5\u540E\u7AEF`;
2126
+ case "claim-failed":
2127
+ return `\u8BA4\u9886\u8FDC\u7AEF\u6839\u5931\u8D25\uFF08${result.error ?? "\u672A\u77E5\u9519\u8BEF"}\uFF09\uFF0C\u5DF2\u8DF3\u8FC7\u8BE5\u540E\u7AEF`;
2128
+ default:
2129
+ return `\u8FDC\u7AEF\u6839\u5F52\u5C5E\u51B2\u7A81\uFF1A\u8FDC\u7AEF ${remote}\uFF0C\u672C\u7EC4 ${local}`;
2130
+ }
2131
+ }
1993
2132
  var log5 = createLogger5("zen-fs-config:config-repo");
1994
2133
  var GROUP_DESCRIPTOR_FILE3 = `${META_DIR}/group.json`;
1995
2134
  var GROUP_TYPE_FILE = `${CONFIG_DIR}/group-type`;
@@ -2029,7 +2168,7 @@ async function isDirectoryAny(surfaces, path) {
2029
2168
  }
2030
2169
  return false;
2031
2170
  }
2032
- function isNotFoundError(err) {
2171
+ function isNotFoundError2(err) {
2033
2172
  const code = err?.code;
2034
2173
  if (code === "ENOENT" || code === "ENOTDIR") return true;
2035
2174
  const message = String(err?.message ?? err);
@@ -2168,6 +2307,8 @@ var ConfigRepo = class {
2168
2307
  instanceId;
2169
2308
  /** 因归属他人而被跳过的后端 id → 原因,供 UI 展示。 */
2170
2309
  skippedBackends = /* @__PURE__ */ new Map();
2310
+ /** 归属冲突的完整信息(两侧 kind / id / instanceId + 可执行动作)。 */
2311
+ backendConflicts = /* @__PURE__ */ new Map();
2171
2312
  /** Last known backend descriptors, for the synchronous unified handle API. */
2172
2313
  backendDescriptorCache = [];
2173
2314
  /**
@@ -2587,7 +2728,7 @@ var ConfigRepo = class {
2587
2728
  await replica.instance.unlink(tombstone.path);
2588
2729
  gone = true;
2589
2730
  } catch (err) {
2590
- gone = isNotFoundError(err);
2731
+ gone = isNotFoundError2(err);
2591
2732
  }
2592
2733
  if (gone) processed++;
2593
2734
  }
@@ -3892,17 +4033,37 @@ var ConfigRepo = class {
3892
4033
  async bindBackendIdentity(instance, backendId) {
3893
4034
  try {
3894
4035
  const identity = await this.ensureGroupIdentity();
3895
- const state = await bindRemoteGroupIdentity(instance, identity);
3896
- if (state === "conflict") {
3897
- this.skippedBackends.set(
4036
+ const result = await bindRemoteGroupIdentityDetailed(instance, identity);
4037
+ if (result.state === "conflict") {
4038
+ this.skippedBackends.set(backendId, describeConflict(result));
4039
+ this.backendConflicts.set(backendId, {
3898
4040
  backendId,
3899
- `\u8FDC\u7AEF\u6839\u5C5E\u4E8E\u53E6\u4E00\u4E2A\u540C\u6B65\u7EC4\uFF08instanceId \u4E0D\u4E00\u81F4\uFF09\uFF0C\u5DF2\u8DF3\u8FC7\u8BE5\u540E\u7AEF`
3900
- );
4041
+ reason: describeConflict(result),
4042
+ ...result.conflict ? { conflict: result.conflict } : {},
4043
+ remote: result.remote,
4044
+ local: { kind: identity.kind, id: identity.id, instanceId: identity.instanceId },
4045
+ canAdoptRemoteInstance: !!result.remote?.instanceId && result.remote.kind === identity.kind && result.remote.id === identity.id,
4046
+ canRewriteRemoteIdentity: result.remote ? result.remote.kind === identity.kind : false,
4047
+ ...result.unreadable ? { unreadable: true } : {},
4048
+ ...result.error ? { error: result.error } : {}
4049
+ });
4050
+ } else {
4051
+ this.skippedBackends.delete(backendId);
4052
+ this.backendConflicts.delete(backendId);
3901
4053
  }
3902
- return state;
4054
+ return result.state;
3903
4055
  } catch (err) {
3904
4056
  log5.warn(`[ConfigRepo] identity check failed for backend "${backendId}", skipping it:`, err);
3905
- this.skippedBackends.set(backendId, `\u5F52\u5C5E\u6821\u9A8C\u5931\u8D25\uFF1A${err?.message ?? String(err)}`);
4057
+ const message = err?.message ?? String(err);
4058
+ this.skippedBackends.set(backendId, `\u5F52\u5C5E\u6821\u9A8C\u5931\u8D25\uFF1A${message}`);
4059
+ this.backendConflicts.set(backendId, {
4060
+ backendId,
4061
+ reason: `\u5F52\u5C5E\u6821\u9A8C\u5931\u8D25\uFF1A${message}`,
4062
+ remote: null,
4063
+ local: { kind: "config", id: CONFIG_GROUP_ID, instanceId: this.instanceId },
4064
+ canAdoptRemoteInstance: false,
4065
+ canRewriteRemoteIdentity: false
4066
+ });
3906
4067
  return "conflict";
3907
4068
  }
3908
4069
  }
@@ -3910,6 +4071,53 @@ var ConfigRepo = class {
3910
4071
  listSkippedBackends() {
3911
4072
  return Array.from(this.skippedBackends, ([backendId, reason]) => ({ backendId, reason }));
3912
4073
  }
4074
+ /** 归属冲突的完整信息(配置组也会被别的组占用同一个根)。 */
4075
+ listBackendConflicts() {
4076
+ return Array.from(this.backendConflicts.values());
4077
+ }
4078
+ /** 用户确认后解决配置组某个后端的归属冲突。 */
4079
+ async resolveBackendConflict(backendId, mode) {
4080
+ const identity = await this.ensureGroupIdentity();
4081
+ const desc = (this.backendDescriptorCache ?? []).find((b) => b.id === backendId);
4082
+ if (!desc) {
4083
+ return { mode, ok: false, reason: `\u627E\u4E0D\u5230\u540E\u7AEF ${backendId}\uFF08\u53EF\u80FD\u5DF2\u88AB\u5220\u9664\uFF09` };
4084
+ }
4085
+ let instance;
4086
+ try {
4087
+ instance = await createBackend({ type: desc.type, options: desc.options });
4088
+ } catch (err) {
4089
+ return { mode, ok: false, reason: `\u521B\u5EFA\u540E\u7AEF\u5931\u8D25\uFF1A${err?.message ?? String(err)}` };
4090
+ }
4091
+ try {
4092
+ const result = await resolveRemoteIdentity(instance, identity, mode);
4093
+ if (!result.ok) return { mode, ok: false, ...result.reason ? { reason: result.reason } : {} };
4094
+ if (mode === "adopt-remote-instance" && result.instanceId) {
4095
+ this.instanceId = result.instanceId;
4096
+ try {
4097
+ await writeGroupDescriptor(this.cachedFS, {
4098
+ schemaVersion: 2,
4099
+ kind: identity.kind,
4100
+ id: identity.id,
4101
+ instanceId: this.instanceId,
4102
+ ...this.name ? { name: this.name } : {},
4103
+ features: CONFIG_GROUP_FEATURES
4104
+ });
4105
+ } catch (err) {
4106
+ log5.warn("[ConfigRepo] failed to persist adopted instanceId:", err);
4107
+ }
4108
+ }
4109
+ this.backendConflicts.delete(backendId);
4110
+ this.skippedBackends.delete(backendId);
4111
+ return { mode, ok: true, ...result.instanceId ? { instanceId: result.instanceId } : {} };
4112
+ } catch (err) {
4113
+ return { mode, ok: false, reason: `\u5BF9\u9F50\u5931\u8D25\uFF1A${err?.message ?? String(err)}` };
4114
+ } finally {
4115
+ try {
4116
+ await instance.dispose?.();
4117
+ } catch {
4118
+ }
4119
+ }
4120
+ }
3913
4121
  /** Write the group-type marker file if it doesn't exist. */
3914
4122
  async ensureGroupType(type) {
3915
4123
  this.assertNotDisposed();
@@ -4114,7 +4322,7 @@ var ConfigRepo = class {
4114
4322
  const features = meta?.features ?? existing?.features;
4115
4323
  const liveGroup = this.appDataGroups.get(id);
4116
4324
  const liveInstanceId = liveGroup?.getGroupInstanceId();
4117
- const instanceId = pickInstanceId(existing) ?? (isValidGroupInstanceId(liveInstanceId) ? liveInstanceId : void 0);
4325
+ const instanceId = isValidGroupInstanceId(meta?.instanceId) ? meta.instanceId : pickInstanceId(existing) ?? (isValidGroupInstanceId(liveInstanceId) ? liveInstanceId : void 0);
4118
4326
  const descriptor = {
4119
4327
  id,
4120
4328
  groupType: "data-sync",
@@ -4425,6 +4633,8 @@ var AppDataGroupImpl = class {
4425
4633
  instanceId;
4426
4634
  /** 因归属他人而被跳过的后端 id → 原因。 */
4427
4635
  skippedBackends = /* @__PURE__ */ new Map();
4636
+ /** 归属冲突的完整信息(两侧 kind / id / instanceId + 可执行动作)。 */
4637
+ backendConflicts = /* @__PURE__ */ new Map();
4428
4638
  _pollIntervalMs;
4429
4639
  _backendsAreAuthoritative;
4430
4640
  /** 引导副本(`.config/` 里的描述符)原有的能力位,用于回刷时不丢信息。 */
@@ -4553,32 +4763,126 @@ var AppDataGroupImpl = class {
4553
4763
  async checkBackendOwnership(instance, backendId) {
4554
4764
  if (!this.instanceId) {
4555
4765
  this.skippedBackends.set(backendId, "\u672C\u7EC4\u5C1A\u672A\u5206\u914D instanceId\uFF0C\u5DF2\u8DF3\u8FC7\u8BE5\u540E\u7AEF");
4766
+ this.backendConflicts.set(backendId, {
4767
+ backendId,
4768
+ reason: "\u672C\u7EC4\u5C1A\u672A\u5206\u914D instanceId\uFF0C\u5DF2\u8DF3\u8FC7\u8BE5\u540E\u7AEF",
4769
+ remote: null,
4770
+ local: { kind: "data", id: this.groupId, instanceId: void 0 },
4771
+ canAdoptRemoteInstance: false,
4772
+ canRewriteRemoteIdentity: false
4773
+ });
4556
4774
  return "conflict";
4557
4775
  }
4558
4776
  try {
4559
- const state = await bindRemoteGroupIdentity(instance, {
4777
+ const identity = {
4560
4778
  kind: "data",
4561
4779
  id: this.groupId,
4562
4780
  instanceId: this.instanceId,
4563
4781
  ...this.name ? { name: this.name } : {},
4564
4782
  features: this.features
4565
- });
4566
- if (state === "conflict") {
4567
- this.skippedBackends.set(
4783
+ };
4784
+ const result = await bindRemoteGroupIdentityDetailed(instance, identity);
4785
+ if (result.state === "conflict") {
4786
+ this.skippedBackends.set(backendId, describeConflict(result));
4787
+ this.backendConflicts.set(backendId, {
4568
4788
  backendId,
4569
- "\u8FDC\u7AEF\u6839\u5C5E\u4E8E\u53E6\u4E00\u4E2A\u540C\u6B65\u7EC4\uFF08instanceId \u4E0D\u4E00\u81F4\uFF09\uFF0C\u5DF2\u8DF3\u8FC7\u8BE5\u540E\u7AEF"
4570
- );
4789
+ reason: describeConflict(result),
4790
+ ...result.conflict ? { conflict: result.conflict } : {},
4791
+ remote: result.remote,
4792
+ local: { kind: "data", id: this.groupId, instanceId: this.instanceId },
4793
+ // 只对齐 instanceId:要求 kind 与 id 都相同(同一个逻辑组,只有身份不同)。
4794
+ canAdoptRemoteInstance: !!result.remote?.instanceId && result.remote.kind === "data" && result.remote.id === this.groupId,
4795
+ // 改写远端:要求 kind 相同(组 id 不同才需要它,代价是动了共享的远端根)。
4796
+ canRewriteRemoteIdentity: result.remote ? result.remote.kind === "data" : false,
4797
+ ...result.unreadable ? { unreadable: true } : {},
4798
+ ...result.error ? { error: result.error } : {}
4799
+ });
4571
4800
  log5.warn(
4572
4801
  `[AppDataGroup:${this.groupId}] backend "${backendId}" belongs to another sync group \u2014 sync pair skipped`
4573
4802
  );
4803
+ } else {
4804
+ this.skippedBackends.delete(backendId);
4805
+ this.backendConflicts.delete(backendId);
4574
4806
  }
4575
- return state;
4807
+ return result.state;
4576
4808
  } catch (err) {
4577
4809
  log5.warn(`[AppDataGroup:${this.groupId}] ownership check failed for "${backendId}":`, err);
4578
- this.skippedBackends.set(backendId, `\u5F52\u5C5E\u6821\u9A8C\u5931\u8D25\uFF1A${err?.message ?? String(err)}`);
4810
+ const message = err?.message ?? String(err);
4811
+ this.skippedBackends.set(backendId, `\u5F52\u5C5E\u6821\u9A8C\u5931\u8D25\uFF1A${message}`);
4812
+ this.backendConflicts.set(backendId, {
4813
+ backendId,
4814
+ reason: `\u5F52\u5C5E\u6821\u9A8C\u5931\u8D25\uFF1A${message}`,
4815
+ remote: null,
4816
+ local: { kind: "data", id: this.groupId, instanceId: this.instanceId },
4817
+ canAdoptRemoteInstance: false,
4818
+ canRewriteRemoteIdentity: false
4819
+ });
4579
4820
  return "conflict";
4580
4821
  }
4581
4822
  }
4823
+ /** 归属冲突的完整信息(UI 直接展示两侧身份,不用猜)。 */
4824
+ listBackendConflicts() {
4825
+ return Array.from(this.backendConflicts.values());
4826
+ }
4827
+ /**
4828
+ * 用户确认后解决归属冲突。
4829
+ *
4830
+ * - `adopt-remote-instance`:只把本地 instanceId 对齐成远端值(本地库名、
4831
+ * 引导副本路径都不变),随后重写 `.meta/group.json` 与引导副本。
4832
+ * - `rewrite-remote-identity`:把远端 `group.json` 改写成本组的 kind/id/
4833
+ * instanceId。会影响到共享该远端根的其它副本,调用方必须先警告用户。
4834
+ *
4835
+ * 成功后冲突记录被移除;调用方应重新连接(本组需要重新 init 才能建对)。
4836
+ */
4837
+ async resolveBackendConflict(backendId, mode) {
4838
+ if (!this.instanceId) {
4839
+ return { mode, ok: false, reason: "\u672C\u7EC4\u5C1A\u672A\u5206\u914D instanceId\uFF0C\u65E0\u6CD5\u5BF9\u9F50" };
4840
+ }
4841
+ const desc = this._backends?.find((b) => b.id === backendId);
4842
+ if (!desc) {
4843
+ return { mode, ok: false, reason: `\u627E\u4E0D\u5230\u540E\u7AEF ${backendId}\uFF08\u53EF\u80FD\u5DF2\u88AB\u5220\u9664\uFF09` };
4844
+ }
4845
+ let instance;
4846
+ try {
4847
+ instance = await createBackend({ type: desc.type, options: desc.options });
4848
+ } catch (err) {
4849
+ return { mode, ok: false, reason: `\u521B\u5EFA\u540E\u7AEF\u5931\u8D25\uFF1A${err?.message ?? String(err)}` };
4850
+ }
4851
+ try {
4852
+ const identity = {
4853
+ kind: "data",
4854
+ id: this.groupId,
4855
+ instanceId: this.instanceId,
4856
+ ...this.name ? { name: this.name } : {},
4857
+ features: this.features
4858
+ };
4859
+ const result = await resolveRemoteIdentity(instance, identity, mode);
4860
+ if (!result.ok) return { mode, ok: false, ...result.reason ? { reason: result.reason } : {} };
4861
+ if (mode === "adopt-remote-instance" && result.instanceId) {
4862
+ this.instanceId = result.instanceId;
4863
+ await this.writeOwnGroupDescriptor();
4864
+ try {
4865
+ await this.parent.updateAppDataGroupDescriptor(this.groupId, this._backends ?? [], {
4866
+ name: this.name,
4867
+ features: this._declaredFeatures,
4868
+ instanceId: this.instanceId
4869
+ });
4870
+ } catch (err) {
4871
+ log5.warn(`[AppDataGroup:${this.groupId}] failed to update bootstrap descriptor instanceId:`, err);
4872
+ }
4873
+ }
4874
+ this.backendConflicts.delete(backendId);
4875
+ this.skippedBackends.delete(backendId);
4876
+ return { mode, ok: true, ...result.instanceId ? { instanceId: result.instanceId } : {} };
4877
+ } catch (err) {
4878
+ return { mode, ok: false, reason: `\u5BF9\u9F50\u5931\u8D25\uFF1A${err?.message ?? String(err)}` };
4879
+ } finally {
4880
+ try {
4881
+ await instance.dispose?.();
4882
+ } catch {
4883
+ }
4884
+ }
4885
+ }
4582
4886
  async init() {
4583
4887
  const storeName = dataGroupLocalStoreName(this.appId, this.groupId);
4584
4888
  try {
@@ -5255,13 +5559,141 @@ function sidecarOwnerPath(path) {
5255
5559
  return owner === "" ? null : owner;
5256
5560
  }
5257
5561
 
5562
+ // src/local-purge.ts
5563
+ var CONFIG_STORE_PREFIX = "zen-fs-config-config-";
5564
+ var DATA_STORE_PREFIX = "zen-fs-config-data-";
5565
+ function getIdb() {
5566
+ const idb = globalThis.indexedDB;
5567
+ if (!idb || typeof idb.deleteDatabase !== "function") return null;
5568
+ return idb;
5569
+ }
5570
+ function deleteIndexedDbStore(name, timeoutMs = 4e3) {
5571
+ const idb = getIdb();
5572
+ if (!idb) {
5573
+ return Promise.resolve({
5574
+ storeName: name,
5575
+ deleted: false,
5576
+ blocked: false,
5577
+ unsupported: true,
5578
+ error: "\u5F53\u524D\u73AF\u5883\u6CA1\u6709 IndexedDB\uFF1A\u65E0\u6CD5\u5220\u9664\u672C\u5730\u5E93"
5579
+ });
5580
+ }
5581
+ return new Promise((resolve) => {
5582
+ let settled = false;
5583
+ let blocked = false;
5584
+ let timer;
5585
+ const finish = (result) => {
5586
+ if (settled) return;
5587
+ settled = true;
5588
+ if (timer) clearTimeout(timer);
5589
+ resolve(result);
5590
+ };
5591
+ let request;
5592
+ try {
5593
+ request = idb.deleteDatabase(name);
5594
+ } catch (err) {
5595
+ finish({ storeName: name, deleted: false, blocked: false, error: summarizeError(err).message });
5596
+ return;
5597
+ }
5598
+ request.onsuccess = () => finish({ storeName: name, deleted: true, blocked: false });
5599
+ request.onerror = () => finish({
5600
+ storeName: name,
5601
+ deleted: false,
5602
+ blocked: false,
5603
+ error: summarizeError(request.error).message
5604
+ });
5605
+ request.onblocked = () => {
5606
+ blocked = true;
5607
+ };
5608
+ timer = setTimeout(() => {
5609
+ finish({
5610
+ storeName: name,
5611
+ deleted: false,
5612
+ blocked,
5613
+ error: blocked ? "\u5220\u9664\u88AB\u5176\u5B83\u9875\u9762/\u5B9E\u4F8B\u5360\u7528\uFF08blocked\uFF09\uFF1A\u8BF7\u5173\u95ED\u5176\u5B83\u6253\u5F00\u8BE5\u9875\u9762\u7684\u6807\u7B7E\u9875\u540E\u91CD\u8BD5" : "\u5220\u9664\u8D85\u65F6\uFF1AIndexedDB \u672A\u5728\u9884\u671F\u65F6\u95F4\u5185\u54CD\u5E94"
5614
+ });
5615
+ }, timeoutMs);
5616
+ });
5617
+ }
5618
+ function localSyncStoreNames(appId, groupIds = []) {
5619
+ const names = /* @__PURE__ */ new Set([
5620
+ `${CONFIG_STORE_PREFIX}${appId}`,
5621
+ `${DATA_STORE_PREFIX}${appId}`
5622
+ ]);
5623
+ for (const groupId of groupIds) {
5624
+ if (!groupId) continue;
5625
+ names.add(`${DATA_STORE_PREFIX}${appId}-${groupId}`);
5626
+ }
5627
+ return Array.from(names);
5628
+ }
5629
+ async function purgeLocalSyncConfig(appId, options = {}) {
5630
+ const idb = getIdb();
5631
+ const names = new Set(localSyncStoreNames(appId, options.groupIds));
5632
+ const removedStorageKeys = [];
5633
+ const removeStorageKeys = () => {
5634
+ try {
5635
+ const ls = globalThis.localStorage;
5636
+ if (!ls) return;
5637
+ for (const key of options.extraStorageKeys ?? []) {
5638
+ try {
5639
+ if (ls.getItem(key) !== null) {
5640
+ ls.removeItem(key);
5641
+ removedStorageKeys.push(key);
5642
+ }
5643
+ } catch {
5644
+ }
5645
+ }
5646
+ } catch {
5647
+ }
5648
+ };
5649
+ if (!idb) {
5650
+ removeStorageKeys();
5651
+ return { appId, databases: [], removedStorageKeys, unsupported: true };
5652
+ }
5653
+ try {
5654
+ const list = await idb.databases?.();
5655
+ for (const entry of list ?? []) {
5656
+ const name = entry?.name;
5657
+ if (!name) continue;
5658
+ if (name === `${CONFIG_STORE_PREFIX}${appId}`) names.add(name);
5659
+ if (name === `${DATA_STORE_PREFIX}${appId}` || name.startsWith(`${DATA_STORE_PREFIX}${appId}-`)) {
5660
+ names.add(name);
5661
+ }
5662
+ }
5663
+ } catch {
5664
+ }
5665
+ const databases = [];
5666
+ for (const name of names) {
5667
+ databases.push(await deleteIndexedDbStore(name, options.timeoutMs));
5668
+ }
5669
+ removeStorageKeys();
5670
+ return { appId, databases, removedStorageKeys };
5671
+ }
5672
+
5258
5673
  // src/connect.ts
5674
+ var isInstanceIdLike = (value) => typeof value === "string" && isValidGroupInstanceId(value);
5259
5675
  var log6 = createLogger2("connect");
5260
5676
  var GROUP_TYPE_FILE2 = "/.config/group-type";
5261
5677
  var LEGACY_GROUP_TYPE_FILE2 = "/.meta/group-type";
5262
- async function detectGroupType(type, options) {
5678
+ async function detectGroupTypeDetailed(type, options) {
5263
5679
  log6(`detectGroupType: connecting to ${type}...`);
5264
5680
  const tempBackend = await createBackend({ type, options });
5681
+ let remote = null;
5682
+ try {
5683
+ try {
5684
+ const descriptor = await readGroupDescriptor(tempBackend);
5685
+ if (descriptor) {
5686
+ remote = {
5687
+ kind: descriptor.kind,
5688
+ id: descriptor.id,
5689
+ instanceId: isInstanceIdLike(descriptor.instanceId) ? descriptor.instanceId : void 0,
5690
+ ...descriptor.name ? { name: descriptor.name } : {}
5691
+ };
5692
+ }
5693
+ } catch {
5694
+ }
5695
+ } finally {
5696
+ }
5265
5697
  try {
5266
5698
  for (const path of [GROUP_TYPE_FILE2, LEGACY_GROUP_TYPE_FILE2]) {
5267
5699
  try {
@@ -5269,15 +5701,15 @@ async function detectGroupType(type, options) {
5269
5701
  const groupType = raw.trim();
5270
5702
  if (groupType === "config-sync" || groupType === "data-sync") {
5271
5703
  log6(`detectGroupType: detected "${groupType}" at ${path}`);
5272
- return groupType;
5704
+ return { groupType, remote };
5273
5705
  }
5274
5706
  log6(`detectGroupType: unknown group-type value "${groupType}" at ${path}, treating as null`);
5275
- return null;
5707
+ return { groupType: null, remote };
5276
5708
  } catch {
5277
5709
  }
5278
5710
  }
5279
5711
  log6(`detectGroupType: no group-type file found (new backend)`);
5280
- return null;
5712
+ return { groupType: null, remote };
5281
5713
  } finally {
5282
5714
  if (tempBackend?.dispose) {
5283
5715
  await tempBackend.dispose();
@@ -5322,12 +5754,15 @@ async function connect(appId, options = {}) {
5322
5754
  };
5323
5755
  }
5324
5756
  const { type, options: backendOptions } = options.backendInfo;
5325
- const detectedType = await detectGroupType(type, backendOptions);
5757
+ const detected = await detectGroupTypeDetailed(type, backendOptions);
5758
+ const detectedType = detected.groupType;
5326
5759
  let groupType;
5327
5760
  if (detectedType) {
5328
5761
  if (options.groupType && options.groupType !== detectedType) {
5762
+ const remoteText = summarizeIdentity(detected.remote);
5763
+ const advice = detectedType === "config-sync" ? "\u8BE5\u8FDC\u7AEF\u6839\u5DF2\u88AB\u4E00\u4E2A\u914D\u7F6E\u7EC4\u5360\u7528\uFF1A\u8BF7\u7ED9\u6570\u636E\u7EC4\u6362\u4E00\u4E2A\u4E13\u5C5E\u7684\u8FDC\u7AEF\u6839\uFF0C\u6216\u5728\u914D\u7F6E\u7EC4\u4FA7\u89E3\u9664\u5BF9\u8BE5\u6839\u7684\u7ED1\u5B9A" : "\u8BE5\u8FDC\u7AEF\u6839\u5DF2\u88AB\u4E00\u4E2A\u6570\u636E\u7EC4\u5360\u7528\uFF1A\u8BF7\u7ED9\u914D\u7F6E\u7EC4\u6362\u4E00\u4E2A\u8FDC\u7AEF\u6839\uFF0C\u6216\u5220\u9664\u90A3\u4E2A\u6570\u636E\u7EC4\u540E\u7AEF";
5329
5764
  throw new Error(
5330
- `Group type mismatch: remote backend is "${detectedType}" but options.groupType is "${options.groupType}"`
5765
+ `Group type mismatch: \u8FDC\u7AEF\u6807\u8BB0\u4E3A "${detectedType}"\uFF08${remoteText}\uFF09\uFF0C\u672C\u7AEF\u8981\u6C42 "${options.groupType}"\u3002${advice}`
5331
5766
  );
5332
5767
  }
5333
5768
  groupType = detectedType;
@@ -5409,6 +5844,8 @@ export {
5409
5844
  TombstoneStore,
5410
5845
  VERSIONS_DIR,
5411
5846
  VersionStore,
5847
+ bindRemoteGroupIdentity,
5848
+ bindRemoteGroupIdentityDetailed,
5412
5849
  configKeyToFilePath,
5413
5850
  connect,
5414
5851
  createBackend,
@@ -5416,6 +5853,7 @@ export {
5416
5853
  createSerializerChain,
5417
5854
  dataGroupLocalStoreName,
5418
5855
  deleteDataGroupLocalStore,
5856
+ deleteIndexedDbStore,
5419
5857
  encodeMetaPath,
5420
5858
  getAccountFields,
5421
5859
  getBackendMetadata,
@@ -5426,20 +5864,27 @@ export {
5426
5864
  isKeepFile,
5427
5865
  isLocalStorageUnavailableError,
5428
5866
  isMtimeSidecar,
5867
+ isValidGroupInstanceId,
5429
5868
  legacyVersionPathFor,
5430
5869
  listBackendMetadata,
5431
5870
  listBackends,
5432
5871
  localPrimaryType,
5872
+ localSyncStoreNames,
5433
5873
  mergeAccountFields,
5434
5874
  migrateVersionSidecars,
5875
+ newGroupInstanceId,
5435
5876
  purgeKeepFiles,
5877
+ purgeLocalSyncConfig,
5436
5878
  purgeMtimeSidecars,
5437
5879
  readGroupDescriptor,
5438
5880
  readVersion,
5439
5881
  registerBackend,
5440
5882
  registerFolderBackend,
5441
5883
  resolveLocalPrimary,
5884
+ resolveRemoteIdentity,
5442
5885
  sha256,
5886
+ shortInstanceId,
5887
+ summarizeIdentity,
5443
5888
  unregisterBackend,
5444
5889
  verifyOrRepairVersion,
5445
5890
  versionPathFor,