zen-fs-config 0.7.4 → 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/DESIGN.md CHANGED
@@ -98,6 +98,26 @@ A **sync group** is a set of backends that synchronize with each other. There ar
98
98
  | `data-sync` | Lightweight: data backends only, direct read/write, no config meta layer |
99
99
  | absent | New empty backend; caller decides group type at creation time |
100
100
 
101
+ **Group type is write-once, and sync may not change it**: besides the connect-time
102
+ check (`connect()` throws when `options.groupType` disagrees with the detected
103
+ type), every `SyncableFS` handed to the sync engine is wrapped by
104
+ `wrapGroupTypeGuard()` (`src/group-type-guard.ts`). The guard compares the
105
+ identity the sync write would produce with what the target side already holds and
106
+ drops the write when they differ, so a wrongly-wired replica can never flip a
107
+ config-sync group into a data-sync group (or the other way round). Guarded
108
+ identity fields:
109
+
110
+ | Path | Identity field | Allowed change |
111
+ |---|---|---|
112
+ | `.config/group-type`, `.meta/group-type` | trimmed text (`config-sync` / `data-sync`) | first write, or same value |
113
+ | `.meta/group.json` | `kind` (`config` / `data`) | first write, or same `kind` (name/features still update freely) |
114
+ | `.config/app-data-groups/{appId}/{id}.json` | `groupType` (`data-sync`) | first write, or same value |
115
+
116
+ Blocking is deliberately non-fatal: the write is skipped, a
117
+ `[GroupType] blocked group-type change on <side>` warning is logged once per
118
+ distinct (side, path, from→to) signature, and the repo stays usable. Fix the
119
+ group wiring instead of syncing the marker.
120
+
101
121
  ## 3. File System Structure
102
122
 
103
123
  ### 3.1 Config-Sync Group
package/README.md CHANGED
@@ -201,6 +201,22 @@ Detection & dispatch rules:
201
201
 
202
202
  `connect()` accepts the same options as `createConfigRepo` (`backendInfo`, `primaryBackendId`, `idbStoreName`, `nodeId`, `folderPath`, `cache`, `serializer`, `onConflict`, `syncPollIntervalMs`) plus `groupType`. On Node.js, pass `folderPath` (or set `ZEN_FS_CONFIG_HOME`) to enable local disk persistence.
203
203
 
204
+ ## App data group path semantics
205
+
206
+ `dataGroup.fs` exposes the **logical root of the data group** (the application's data directory). It is not a view of one backend's physical root.
207
+
208
+ - A write to a group-root-relative path such as `/struct/a.json` is replicated to every backend in the group.
209
+ - Each backend maps that same logical path into its own physical root: the Gitee/GitHub repo root, the RemoteStorage `basePath`, the WebDAV directory, etc.
210
+ - Backend `basePath` / repo root values are **physical roots**, not a shared logical prefix. Multiple backends with different physical roots are valid; do not reject a group just because their `basePath` values differ.
211
+ - Always use the same group-root-relative path for all backends. If the application defines a namespace inside the group (for example `app_data/folders`), that is an explicit application-level convention; do not derive it from backend `basePath`.
212
+
213
+ ```typescript
214
+ // dataGroup.fs is the logical group root; all attached backends receive this path.
215
+ await dataGroup.fs.promises.writeFile('/struct/host.json', json);
216
+ ```
217
+
218
+ A common mistake is to compare every backend's `basePath` and try to compute one "common write prefix". That conflates the logical group root with physical backend roots and incorrectly rejects otherwise valid multi-backend groups.
219
+
204
220
  ## Directory Structure
205
221
 
206
222
  ```
package/README.zh-CN.md CHANGED
@@ -194,6 +194,22 @@ if (result.groupType === 'data-sync') {
194
194
 
195
195
  `connect()` 接受与 `createConfigRepo` 相同的选项(`backendInfo`、`primaryBackendId`、`idbStoreName`、`nodeId`、`folderPath`、`cache`、`serializer`、`onConflict`、`syncPollIntervalMs`),另加 `groupType`。在 Node.js 上通过 `folderPath`(或设 `ZEN_FS_CONFIG_HOME`)开启本地磁盘持久化。
196
196
 
197
+ ## 数据组的路径语义
198
+
199
+ `dataGroup.fs` 暴露的是**数据组的逻辑根**(应用数据目录),不是某一个后端的物理根。
200
+
201
+ - 往组根相对路径(例如 `/struct/a.json`)写入,会同步到组内所有后端。
202
+ - 每个后端会把同一个逻辑路径映射到自己的物理根:Gitee/GitHub 仓库根、RemoteStorage 的 `basePath`、WebDAV 目录等。
203
+ - 后端的 `basePath` / 仓库根是**物理根**,不是所有后端共用的逻辑前缀。多个后端拥有不同的物理根是合法的;不要因为 `basePath` 不一致就判定数据组不可用。
204
+ - 所有后端都应使用同一个组根相对路径。如果应用要在组根下划一个命名空间(例如 `app_data/folders`),那是应用层显式约定,不能从后端 `basePath` 反推。
205
+
206
+ ```typescript
207
+ // dataGroup.fs 是数据组逻辑根;组内所有后端都会收到这个路径。
208
+ await dataGroup.fs.promises.writeFile('/struct/host.json', json);
209
+ ```
210
+
211
+ 一个常见错误是逐个比较后端的 `basePath`,再试图算出一个“公共写入前缀”。这把逻辑组根和物理后端根混为一谈,会误拒绝本来可用的多后端数据组。
212
+
197
213
  ## 目录结构
198
214
 
199
215
  ```
@@ -9,7 +9,7 @@ import {
9
9
  registerBackend,
10
10
  unregisterBackend,
11
11
  wrapZenFSFileSystem
12
- } from "./chunk-S2S3XBK2.mjs";
12
+ } from "./chunk-WURWDHNT.mjs";
13
13
  export {
14
14
  createBackend,
15
15
  getAccountFields,
@@ -54,6 +54,17 @@ async function wrapZenFSFileSystem(config) {
54
54
  const notifyChange = () => {
55
55
  if (changeCallback) changeCallback();
56
56
  };
57
+ const writeQueues = /* @__PURE__ */ new Map();
58
+ const runExclusive = async (path, task) => {
59
+ const prev = writeQueues.get(path);
60
+ const run = (prev ?? Promise.resolve()).catch(() => void 0).then(task);
61
+ writeQueues.set(path, run);
62
+ try {
63
+ await run;
64
+ } finally {
65
+ if (writeQueues.get(path) === run) writeQueues.delete(path);
66
+ }
67
+ };
57
68
  const backend = {
58
69
  async readFile(path, ...args) {
59
70
  const st = await isolatedFS.stat(path);
@@ -64,24 +75,28 @@ async function wrapZenFSFileSystem(config) {
64
75
  return buf;
65
76
  },
66
77
  async writeFile(path, data, _options) {
67
- const bytes = data instanceof ArrayBuffer ? new Uint8Array(data) : data instanceof Uint8Array ? data : new TextEncoder().encode(data);
68
- const parts = path.split("/").filter(Boolean);
69
- parts.pop();
70
- let dir = "";
71
- for (const p of parts) {
72
- dir += "/" + p;
73
- if (!await isolatedFS.exists(dir)) {
74
- await isolatedFS.mkdir(dir, { uid: 0, gid: 0, mode: 493 });
78
+ const source = data instanceof ArrayBuffer ? new Uint8Array(data) : data instanceof Uint8Array ? data : new TextEncoder().encode(data);
79
+ const bytes = new Uint8Array(source);
80
+ await runExclusive(path, async () => {
81
+ const parts = path.split("/").filter(Boolean);
82
+ parts.pop();
83
+ let dir = "";
84
+ for (const p of parts) {
85
+ dir += "/" + p;
86
+ if (!await isolatedFS.exists(dir)) {
87
+ await isolatedFS.mkdir(dir, { uid: 0, gid: 0, mode: 493 });
88
+ }
89
+ }
90
+ if (await isolatedFS.exists(path)) {
91
+ await isolatedFS.unlink(path);
75
92
  }
76
- }
77
- if (!await isolatedFS.exists(path)) {
78
93
  await isolatedFS.createFile(path, { uid: 0, gid: 0, mode: 420 });
79
- }
80
- await isolatedFS.write(path, bytes, 0);
81
- try {
82
- await isolatedFS.touch(path, { size: bytes.byteLength, mtimeMs: _options?.mtime ?? Date.now() });
83
- } catch {
84
- }
94
+ await isolatedFS.write(path, bytes, 0);
95
+ try {
96
+ await isolatedFS.touch(path, { size: bytes.byteLength, mtimeMs: _options?.mtime ?? Date.now() });
97
+ } catch {
98
+ }
99
+ });
85
100
  notifyChange();
86
101
  },
87
102
  async readdir(path) {
package/dist/index.d.mts CHANGED
@@ -160,9 +160,16 @@ interface VersionMeta {
160
160
  /** Timestamp when the version was created. */
161
161
  timestamp: number;
162
162
  }
163
- /** Content of a tombstone file in `.meta/.deleted/`. */
163
+ /**
164
+ * 墓碑目标类型。
165
+ * - `file`(缺省,兼容旧数据):只删除该路径这一个文件。
166
+ * - `directory`:删除整个目录树。目录墓碑只需一条记录,不必为树里每个文件
167
+ * 各写一条;应用时按树清理(含 `.keep` / `.keep.mtime` 占位)。
168
+ */
169
+ type TombstoneType = 'file' | 'directory';
170
+ /** Content of a tombstone file in `.meta/tombstones/`. */
164
171
  interface TombstoneMeta {
165
- /** The deleted file path. */
172
+ /** 被删除的路径(目录墓碑为目录本身,不带结尾 `/`)。 */
166
173
  path: string;
167
174
  /** Timestamp of deletion. */
168
175
  deletedAt: number;
@@ -170,6 +177,8 @@ interface TombstoneMeta {
170
177
  deletedBy: string;
171
178
  /** Backend IDs that have confirmed the deletion (synced). */
172
179
  confirmedBy: string[];
180
+ /** 目标类型;缺省视为 `file`(旧版本墓碑没有该字段)。 */
181
+ type?: TombstoneType;
173
182
  }
174
183
  /** Content of a conflict archive file in `.meta/.conflicts/`. */
175
184
  interface ConflictArchive {
@@ -347,6 +356,11 @@ interface AppDataGroupDescriptor {
347
356
  groupType: 'data-sync';
348
357
  /** User-editable display name. `id` is the stable identifier. */
349
358
  name?: string;
359
+ /**
360
+ * 组的实例身份(见 `GroupDescriptor.instanceId`)。引导副本随它一起下发,
361
+ * 让新设备在连远端之前就知道该组声明的身份,避免认领到别人的仓库。
362
+ */
363
+ instanceId?: string;
350
364
  /** Capability overrides (versions/conflicts are opt-in for data groups). */
351
365
  features?: Partial<SyncGroupFeatures>;
352
366
  backends: AppDataBackendDescriptor[];
@@ -393,6 +407,14 @@ interface GroupDescriptor {
393
407
  kind: SyncGroupKind;
394
408
  /** Group id (`config` for the config-sync group, the descriptor id otherwise). */
395
409
  id?: string;
410
+ /**
411
+ * 组的实例身份(UUID)。创建时生成一次,之后不可变。
412
+ *
413
+ * 同步边界就是它:连接任何远端之前先读对方的 `.meta/group.json`,实例身份
414
+ * 不一致就**不建立同步对**,因此两个不同的同步组永远不会互相同步。
415
+ * 缺失表示「尚未认领」的老仓库,由第一个连接的组认领并写入。
416
+ */
417
+ instanceId?: string;
396
418
  /** User-editable display name. */
397
419
  name?: string;
398
420
  features?: Partial<SyncGroupFeatures>;
@@ -420,6 +442,16 @@ interface SyncGroupHandle {
420
442
  /** Derived, never persisted separately from the descriptor. */
421
443
  readonly features: SyncGroupFeatures;
422
444
  readonly name?: string;
445
+ /**
446
+ * 本组的实例身份(UUID)。它是同步边界:连接远端前比对对方
447
+ * `.meta/group.json` 的 `instanceId`,不一致就不建同步对。
448
+ */
449
+ getGroupInstanceId(): string | undefined;
450
+ /** 因归属其他同步组而被跳过的后端(不建同步对)。 */
451
+ listSkippedBackends(): {
452
+ backendId: string;
453
+ reason: string;
454
+ }[];
423
455
  /** Direct fs view; metadata paths (`.meta`, `.config`) are hidden. */
424
456
  readonly fs: typeof node_fs;
425
457
  getSyncStatuses(): Map<string, SyncPairStatus>;
@@ -970,6 +1002,15 @@ declare class ConfigRepo implements IConfigRepo {
970
1002
  private readonly tombstoneConfirmations;
971
1003
  /** Per-backend sync state (successful pairs + connect failures). */
972
1004
  private backendStates;
1005
+ /**
1006
+ * 本组的实例身份(UUID,见 `group-identity.ts`)。
1007
+ *
1008
+ * 它同时是同步边界:连接任何远端副本前先比对对方 `.meta/group.json` 里的
1009
+ * `instanceId`,不一致就不建同步对 —— 两个不同的同步组永不互相同步。
1010
+ */
1011
+ private instanceId?;
1012
+ /** 因归属他人而被跳过的后端 id → 原因,供 UI 展示。 */
1013
+ private skippedBackends;
973
1014
  /** Last known backend descriptors, for the synchronous unified handle API. */
974
1015
  private backendDescriptorCache;
975
1016
  /**
@@ -994,9 +1035,11 @@ declare class ConfigRepo implements IConfigRepo {
994
1035
  peekNodeConfig<T = unknown>(nodeId: string, path: string): Promise<T>;
995
1036
  flush(): Promise<SyncResult[]>;
996
1037
  /**
997
- * Write the tombstone record for `filePath` under `.meta/tombstones/`.
998
- * Records only metadata — it never creates the deleted file locally, and the
1038
+ * Write the tombstone record for `path` under `.meta/tombstones/`.
1039
+ * Records only metadata — it never creates the deleted path locally, and the
999
1040
  * legacy `/.meta/.deleted/` archive is neither read nor written.
1041
+ *
1042
+ * `type: 'directory'` 表示这是一条目录墓碑:应用时按整棵树清理。
1000
1043
  */
1001
1044
  private writeTombstoneFor;
1002
1045
  /**
@@ -1025,6 +1068,18 @@ declare class ConfigRepo implements IConfigRepo {
1025
1068
  private refreshSyncExclusions;
1026
1069
  /** Invalidate the tombstone cache — call after tombstones are modified. */
1027
1070
  private invalidateTombstoneCache;
1071
+ /**
1072
+ * 判定墓碑目标路径是否在删除之后被重新创建。
1073
+ *
1074
+ * 墓碑表达的是「删除意图」,但删除之后同一路径完全可能被再次写入。同步类工具
1075
+ * 的锁文件(`.sync.lock`)就是每轮「删除 → 重建」;若把墓碑当作永久否决权,
1076
+ * 这个路径会被每一轮 sync 反复删除,表现为「刚写进去 1 秒后就消失」、锁永远拿
1077
+ * 不到、深层目录刚建就没了。
1078
+ *
1079
+ * 判定依据是文件 mtime 晚于 `deletedAt`:写入必然刷新 mtime,因此 mtime 比删除
1080
+ * 时刻新就意味着这条墓碑已经被写操作撤销。
1081
+ */
1082
+ private isPathRecreatedAfterTombstone;
1028
1083
  /**
1029
1084
  * Before sync: for each tombstone, delete the actual file on all replicas.
1030
1085
  * This prevents bi-directional sync from copying the file back.
@@ -1246,6 +1301,27 @@ declare class ConfigRepo implements IConfigRepo {
1246
1301
  * tombstoned, so this never delete-then-recreates it.
1247
1302
  */
1248
1303
  replaceBackend(id: string, type: string, options: Record<string, unknown>, description?: string): Promise<void>;
1304
+ /**
1305
+ * 本组的同步身份(kind + id + 不可变 instanceId)。
1306
+ *
1307
+ * 首次调用时若 `.meta/group.json` 里还没有 `instanceId`(老部署),生成一个
1308
+ * 并就地写回 —— 只写一次,之后字节相同不再落盘。
1309
+ */
1310
+ private ensureGroupIdentity;
1311
+ /** 组实例身份(未初始化时先兜底生成并落盘)。 */
1312
+ ensureGroupInstanceId(): Promise<string>;
1313
+ /** 组实例身份(同步读取;init 之前可能为 `undefined`)。 */
1314
+ getGroupInstanceId(): string | undefined;
1315
+ /**
1316
+ * 连接远端前校验归属:属于别的组 → `conflict`(调用方必须跳过、不建同步对)。
1317
+ * 老仓库(无 instanceId)会被本组认领。
1318
+ */
1319
+ private bindBackendIdentity;
1320
+ /** 因归属他人而被跳过的后端(id → 原因)。 */
1321
+ listSkippedBackends(): {
1322
+ backendId: string;
1323
+ reason: string;
1324
+ }[];
1249
1325
  /** Write the group-type marker file if it doesn't exist. */
1250
1326
  ensureGroupType(type: SyncGroupType): Promise<void>;
1251
1327
  /** Read the group-type marker. Returns null if not set (new path, then legacy). */
@@ -1613,6 +1689,14 @@ interface TombstoneTarget {
1613
1689
  declare class TombstoneStore {
1614
1690
  private fs;
1615
1691
  private author;
1692
+ /**
1693
+ * 本轮 `process()` 真正核对过"确实不存在"的(路径 → 目标 id)。
1694
+ *
1695
+ * 只有出现在这里的副本才会被写进 `confirmedBy`(见 {@link confirm}),与
1696
+ * 配置组 `ConfigRepo.updateTombstoneConfirmations` 的保守语义一致:副本删除
1697
+ * 失败(网络、后端限制、只剩占位目录)时绝不算已确认。
1698
+ */
1699
+ private readonly verifiedAbsent;
1616
1700
  constructor(fs: MetaFS, author: string);
1617
1701
  private pathFor;
1618
1702
  /** All tombstones. */
@@ -1626,11 +1710,41 @@ declare class TombstoneStore {
1626
1710
  /**
1627
1711
  * Delete every tombstoned file (and its version record) on the local store
1628
1712
  * and on each target backend, so bi-directional sync cannot resurrect it.
1713
+ *
1714
+ * 墓碑只对「删除之后没有再写入」的路径有效。同步类工具会不断重建某些文件
1715
+ * (最典型的是 `.sync.lock`:每轮删除 → 重建),若墓碑永久生效,路径会被每一
1716
+ * 轮 preSync 删掉,表现为「刚写完 1 秒就消失、锁永远拿不到」。因此这里先判定
1717
+ * 目标路径是否在 `deletedAt` 之后被重新写入:是则墓碑已被用户写操作撤销,保留
1718
+ * 文件并删除墓碑;否则按删除传播处理。
1629
1719
  */
1630
1720
  process(targets?: TombstoneTarget[]): Promise<void>;
1721
+ private markVerified;
1722
+ /**
1723
+ * 目标上该路径当前是否确实不存在。
1724
+ *
1725
+ * `.mtime` 侧车与 `.keep` 占位对部分后端不可见(`exists()` 恒为 false),这类
1726
+ * 路径只能相信本轮 unlink 没有报错,因此按"不可见即可信"处理(与配置组的
1727
+ * `allReplicasConfirmAbsent` 一致)。
1728
+ */
1729
+ private absentOnTarget;
1730
+ /**
1731
+ * 本地存储上该路径的 mtime 是否晚于墓碑的删除时刻。
1732
+ *
1733
+ * 只看本地主存储:副本上的同路径文件可能只是「删除之前的旧副本」,它的 mtime
1734
+ * 本来就旧,用副本判定既不可靠又会掩盖真正的删除传播。
1735
+ */
1736
+ private wasRecreatedAfterDeletion;
1737
+ private mtimeOf;
1631
1738
  private deleteEverywhere;
1632
- /** Add the given backend ids to every tombstone's confirmation set. */
1633
- confirm(backendIds: string[]): Promise<number>;
1739
+ /**
1740
+ * 把本轮真正核对过"确实不存在"的目标写进墓碑的 `confirmedBy`。
1741
+ *
1742
+ * 旧实现把传入的后端 id 无条件写入,等于"跑过一轮就算所有副本都清干净了";
1743
+ * 副本删除失败时墓碑仍会被 GC,下一轮同步再把残留拉回本地。现在只确认
1744
+ * {@link process} 中现场核对通过的目标(与配置组语义一致),并支持只传 id
1745
+ * 的旧调用方式(此时沿用同一份核对结果)。
1746
+ */
1747
+ confirm(targets: TombstoneTarget[] | string[]): Promise<number>;
1634
1748
  /** Remove tombstones confirmed by every connected backend. */
1635
1749
  gc(allBackendIds: string[], targets?: TombstoneTarget[]): Promise<void>;
1636
1750
  }
package/dist/index.d.ts CHANGED
@@ -160,9 +160,16 @@ interface VersionMeta {
160
160
  /** Timestamp when the version was created. */
161
161
  timestamp: number;
162
162
  }
163
- /** Content of a tombstone file in `.meta/.deleted/`. */
163
+ /**
164
+ * 墓碑目标类型。
165
+ * - `file`(缺省,兼容旧数据):只删除该路径这一个文件。
166
+ * - `directory`:删除整个目录树。目录墓碑只需一条记录,不必为树里每个文件
167
+ * 各写一条;应用时按树清理(含 `.keep` / `.keep.mtime` 占位)。
168
+ */
169
+ type TombstoneType = 'file' | 'directory';
170
+ /** Content of a tombstone file in `.meta/tombstones/`. */
164
171
  interface TombstoneMeta {
165
- /** The deleted file path. */
172
+ /** 被删除的路径(目录墓碑为目录本身,不带结尾 `/`)。 */
166
173
  path: string;
167
174
  /** Timestamp of deletion. */
168
175
  deletedAt: number;
@@ -170,6 +177,8 @@ interface TombstoneMeta {
170
177
  deletedBy: string;
171
178
  /** Backend IDs that have confirmed the deletion (synced). */
172
179
  confirmedBy: string[];
180
+ /** 目标类型;缺省视为 `file`(旧版本墓碑没有该字段)。 */
181
+ type?: TombstoneType;
173
182
  }
174
183
  /** Content of a conflict archive file in `.meta/.conflicts/`. */
175
184
  interface ConflictArchive {
@@ -347,6 +356,11 @@ interface AppDataGroupDescriptor {
347
356
  groupType: 'data-sync';
348
357
  /** User-editable display name. `id` is the stable identifier. */
349
358
  name?: string;
359
+ /**
360
+ * 组的实例身份(见 `GroupDescriptor.instanceId`)。引导副本随它一起下发,
361
+ * 让新设备在连远端之前就知道该组声明的身份,避免认领到别人的仓库。
362
+ */
363
+ instanceId?: string;
350
364
  /** Capability overrides (versions/conflicts are opt-in for data groups). */
351
365
  features?: Partial<SyncGroupFeatures>;
352
366
  backends: AppDataBackendDescriptor[];
@@ -393,6 +407,14 @@ interface GroupDescriptor {
393
407
  kind: SyncGroupKind;
394
408
  /** Group id (`config` for the config-sync group, the descriptor id otherwise). */
395
409
  id?: string;
410
+ /**
411
+ * 组的实例身份(UUID)。创建时生成一次,之后不可变。
412
+ *
413
+ * 同步边界就是它:连接任何远端之前先读对方的 `.meta/group.json`,实例身份
414
+ * 不一致就**不建立同步对**,因此两个不同的同步组永远不会互相同步。
415
+ * 缺失表示「尚未认领」的老仓库,由第一个连接的组认领并写入。
416
+ */
417
+ instanceId?: string;
396
418
  /** User-editable display name. */
397
419
  name?: string;
398
420
  features?: Partial<SyncGroupFeatures>;
@@ -420,6 +442,16 @@ interface SyncGroupHandle {
420
442
  /** Derived, never persisted separately from the descriptor. */
421
443
  readonly features: SyncGroupFeatures;
422
444
  readonly name?: string;
445
+ /**
446
+ * 本组的实例身份(UUID)。它是同步边界:连接远端前比对对方
447
+ * `.meta/group.json` 的 `instanceId`,不一致就不建同步对。
448
+ */
449
+ getGroupInstanceId(): string | undefined;
450
+ /** 因归属其他同步组而被跳过的后端(不建同步对)。 */
451
+ listSkippedBackends(): {
452
+ backendId: string;
453
+ reason: string;
454
+ }[];
423
455
  /** Direct fs view; metadata paths (`.meta`, `.config`) are hidden. */
424
456
  readonly fs: typeof node_fs;
425
457
  getSyncStatuses(): Map<string, SyncPairStatus>;
@@ -970,6 +1002,15 @@ declare class ConfigRepo implements IConfigRepo {
970
1002
  private readonly tombstoneConfirmations;
971
1003
  /** Per-backend sync state (successful pairs + connect failures). */
972
1004
  private backendStates;
1005
+ /**
1006
+ * 本组的实例身份(UUID,见 `group-identity.ts`)。
1007
+ *
1008
+ * 它同时是同步边界:连接任何远端副本前先比对对方 `.meta/group.json` 里的
1009
+ * `instanceId`,不一致就不建同步对 —— 两个不同的同步组永不互相同步。
1010
+ */
1011
+ private instanceId?;
1012
+ /** 因归属他人而被跳过的后端 id → 原因,供 UI 展示。 */
1013
+ private skippedBackends;
973
1014
  /** Last known backend descriptors, for the synchronous unified handle API. */
974
1015
  private backendDescriptorCache;
975
1016
  /**
@@ -994,9 +1035,11 @@ declare class ConfigRepo implements IConfigRepo {
994
1035
  peekNodeConfig<T = unknown>(nodeId: string, path: string): Promise<T>;
995
1036
  flush(): Promise<SyncResult[]>;
996
1037
  /**
997
- * Write the tombstone record for `filePath` under `.meta/tombstones/`.
998
- * Records only metadata — it never creates the deleted file locally, and the
1038
+ * Write the tombstone record for `path` under `.meta/tombstones/`.
1039
+ * Records only metadata — it never creates the deleted path locally, and the
999
1040
  * legacy `/.meta/.deleted/` archive is neither read nor written.
1041
+ *
1042
+ * `type: 'directory'` 表示这是一条目录墓碑:应用时按整棵树清理。
1000
1043
  */
1001
1044
  private writeTombstoneFor;
1002
1045
  /**
@@ -1025,6 +1068,18 @@ declare class ConfigRepo implements IConfigRepo {
1025
1068
  private refreshSyncExclusions;
1026
1069
  /** Invalidate the tombstone cache — call after tombstones are modified. */
1027
1070
  private invalidateTombstoneCache;
1071
+ /**
1072
+ * 判定墓碑目标路径是否在删除之后被重新创建。
1073
+ *
1074
+ * 墓碑表达的是「删除意图」,但删除之后同一路径完全可能被再次写入。同步类工具
1075
+ * 的锁文件(`.sync.lock`)就是每轮「删除 → 重建」;若把墓碑当作永久否决权,
1076
+ * 这个路径会被每一轮 sync 反复删除,表现为「刚写进去 1 秒后就消失」、锁永远拿
1077
+ * 不到、深层目录刚建就没了。
1078
+ *
1079
+ * 判定依据是文件 mtime 晚于 `deletedAt`:写入必然刷新 mtime,因此 mtime 比删除
1080
+ * 时刻新就意味着这条墓碑已经被写操作撤销。
1081
+ */
1082
+ private isPathRecreatedAfterTombstone;
1028
1083
  /**
1029
1084
  * Before sync: for each tombstone, delete the actual file on all replicas.
1030
1085
  * This prevents bi-directional sync from copying the file back.
@@ -1246,6 +1301,27 @@ declare class ConfigRepo implements IConfigRepo {
1246
1301
  * tombstoned, so this never delete-then-recreates it.
1247
1302
  */
1248
1303
  replaceBackend(id: string, type: string, options: Record<string, unknown>, description?: string): Promise<void>;
1304
+ /**
1305
+ * 本组的同步身份(kind + id + 不可变 instanceId)。
1306
+ *
1307
+ * 首次调用时若 `.meta/group.json` 里还没有 `instanceId`(老部署),生成一个
1308
+ * 并就地写回 —— 只写一次,之后字节相同不再落盘。
1309
+ */
1310
+ private ensureGroupIdentity;
1311
+ /** 组实例身份(未初始化时先兜底生成并落盘)。 */
1312
+ ensureGroupInstanceId(): Promise<string>;
1313
+ /** 组实例身份(同步读取;init 之前可能为 `undefined`)。 */
1314
+ getGroupInstanceId(): string | undefined;
1315
+ /**
1316
+ * 连接远端前校验归属:属于别的组 → `conflict`(调用方必须跳过、不建同步对)。
1317
+ * 老仓库(无 instanceId)会被本组认领。
1318
+ */
1319
+ private bindBackendIdentity;
1320
+ /** 因归属他人而被跳过的后端(id → 原因)。 */
1321
+ listSkippedBackends(): {
1322
+ backendId: string;
1323
+ reason: string;
1324
+ }[];
1249
1325
  /** Write the group-type marker file if it doesn't exist. */
1250
1326
  ensureGroupType(type: SyncGroupType): Promise<void>;
1251
1327
  /** Read the group-type marker. Returns null if not set (new path, then legacy). */
@@ -1613,6 +1689,14 @@ interface TombstoneTarget {
1613
1689
  declare class TombstoneStore {
1614
1690
  private fs;
1615
1691
  private author;
1692
+ /**
1693
+ * 本轮 `process()` 真正核对过"确实不存在"的(路径 → 目标 id)。
1694
+ *
1695
+ * 只有出现在这里的副本才会被写进 `confirmedBy`(见 {@link confirm}),与
1696
+ * 配置组 `ConfigRepo.updateTombstoneConfirmations` 的保守语义一致:副本删除
1697
+ * 失败(网络、后端限制、只剩占位目录)时绝不算已确认。
1698
+ */
1699
+ private readonly verifiedAbsent;
1616
1700
  constructor(fs: MetaFS, author: string);
1617
1701
  private pathFor;
1618
1702
  /** All tombstones. */
@@ -1626,11 +1710,41 @@ declare class TombstoneStore {
1626
1710
  /**
1627
1711
  * Delete every tombstoned file (and its version record) on the local store
1628
1712
  * and on each target backend, so bi-directional sync cannot resurrect it.
1713
+ *
1714
+ * 墓碑只对「删除之后没有再写入」的路径有效。同步类工具会不断重建某些文件
1715
+ * (最典型的是 `.sync.lock`:每轮删除 → 重建),若墓碑永久生效,路径会被每一
1716
+ * 轮 preSync 删掉,表现为「刚写完 1 秒就消失、锁永远拿不到」。因此这里先判定
1717
+ * 目标路径是否在 `deletedAt` 之后被重新写入:是则墓碑已被用户写操作撤销,保留
1718
+ * 文件并删除墓碑;否则按删除传播处理。
1629
1719
  */
1630
1720
  process(targets?: TombstoneTarget[]): Promise<void>;
1721
+ private markVerified;
1722
+ /**
1723
+ * 目标上该路径当前是否确实不存在。
1724
+ *
1725
+ * `.mtime` 侧车与 `.keep` 占位对部分后端不可见(`exists()` 恒为 false),这类
1726
+ * 路径只能相信本轮 unlink 没有报错,因此按"不可见即可信"处理(与配置组的
1727
+ * `allReplicasConfirmAbsent` 一致)。
1728
+ */
1729
+ private absentOnTarget;
1730
+ /**
1731
+ * 本地存储上该路径的 mtime 是否晚于墓碑的删除时刻。
1732
+ *
1733
+ * 只看本地主存储:副本上的同路径文件可能只是「删除之前的旧副本」,它的 mtime
1734
+ * 本来就旧,用副本判定既不可靠又会掩盖真正的删除传播。
1735
+ */
1736
+ private wasRecreatedAfterDeletion;
1737
+ private mtimeOf;
1631
1738
  private deleteEverywhere;
1632
- /** Add the given backend ids to every tombstone's confirmation set. */
1633
- confirm(backendIds: string[]): Promise<number>;
1739
+ /**
1740
+ * 把本轮真正核对过"确实不存在"的目标写进墓碑的 `confirmedBy`。
1741
+ *
1742
+ * 旧实现把传入的后端 id 无条件写入,等于"跑过一轮就算所有副本都清干净了";
1743
+ * 副本删除失败时墓碑仍会被 GC,下一轮同步再把残留拉回本地。现在只确认
1744
+ * {@link process} 中现场核对通过的目标(与配置组语义一致),并支持只传 id
1745
+ * 的旧调用方式(此时沿用同一份核对结果)。
1746
+ */
1747
+ confirm(targets: TombstoneTarget[] | string[]): Promise<number>;
1634
1748
  /** Remove tombstones confirmed by every connected backend. */
1635
1749
  gc(allBackendIds: string[], targets?: TombstoneTarget[]): Promise<void>;
1636
1750
  }