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/dist/index.mjs CHANGED
@@ -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
 
14
14
  // src/config-repo.ts
15
15
  import {
@@ -214,6 +214,92 @@ function createChrootFS(inner, root, options = {}) {
214
214
  async function ensureParentDir(absolutePath) {
215
215
  }
216
216
 
217
+ // src/group-type-guard.ts
218
+ import { createLogger } from "@richard432/localstorage-logger";
219
+ var log = createLogger("zen-fs-config:group-type-guard");
220
+ var GROUP_TYPE_FILES = /* @__PURE__ */ new Set(["/.config/group-type", "/.meta/group-type"]);
221
+ var GROUP_DESCRIPTOR_FILE = "/.meta/group.json";
222
+ var APP_DATA_GROUP_DESCRIPTOR_RE = /^\/\.config\/app-data-groups\/[^/]+\/[^/]+\.json$/;
223
+ function decode(data) {
224
+ if (typeof data === "string") return data;
225
+ if (data instanceof ArrayBuffer) return new TextDecoder().decode(new Uint8Array(data));
226
+ return new TextDecoder().decode(data);
227
+ }
228
+ function safeParse(text) {
229
+ try {
230
+ return JSON.parse(text);
231
+ } catch {
232
+ return null;
233
+ }
234
+ }
235
+ function readGroupIdentity(path, data) {
236
+ const normalized = path.length > 1 && path.endsWith("/") ? path.slice(0, -1) : path;
237
+ const isGroupType = GROUP_TYPE_FILES.has(normalized);
238
+ const isGroupDescriptor = normalized === GROUP_DESCRIPTOR_FILE;
239
+ const isAppDataGroup = APP_DATA_GROUP_DESCRIPTOR_RE.test(normalized);
240
+ if (!isGroupType && !isGroupDescriptor && !isAppDataGroup) return null;
241
+ const text = decode(data);
242
+ if (isGroupType) {
243
+ const value = text.trim();
244
+ return value || null;
245
+ }
246
+ const parsed = safeParse(text);
247
+ if (isGroupDescriptor) {
248
+ return typeof parsed?.kind === "string" ? `kind:${parsed.kind}` : null;
249
+ }
250
+ return typeof parsed?.groupType === "string" ? `groupType:${parsed.groupType}` : null;
251
+ }
252
+ async function readExistingIdentity(fs, path) {
253
+ try {
254
+ const raw = await fs.readFile(path, "utf-8");
255
+ return readGroupIdentity(path, raw);
256
+ } catch {
257
+ return null;
258
+ }
259
+ }
260
+ function wrapGroupTypeGuard(fs, side, onBlock) {
261
+ const reported = /* @__PURE__ */ new Set();
262
+ const guarded = Object.create(fs);
263
+ const lastBlock = { current: null };
264
+ guarded.getLastBlockedGroupType = () => lastBlock.current;
265
+ const allow = async (path, data) => {
266
+ const incoming = readGroupIdentity(path, data);
267
+ if (incoming === null) return true;
268
+ const existing = await readExistingIdentity(fs, path);
269
+ if (existing === null || existing === incoming) return true;
270
+ const signature = `${side}|${path}|${existing}->${incoming}`;
271
+ const block = { side, path, existing, incoming };
272
+ lastBlock.current = block;
273
+ if (!reported.has(signature)) {
274
+ reported.add(signature);
275
+ log.warn(
276
+ `[GroupType] blocked group-type change on ${side}: ${path} would change "${existing}" \u2192 "${incoming}" \u2014 identity is write-once, the incoming value is dropped (fix the group wiring instead of syncing it)`
277
+ );
278
+ }
279
+ try {
280
+ onBlock?.(block);
281
+ } catch {
282
+ }
283
+ return false;
284
+ };
285
+ guarded.writeFile = async (path, data) => {
286
+ if (!await allow(path, data)) return;
287
+ return fs.writeFile(path, data);
288
+ };
289
+ if (typeof fs.writeFileWithMtime === "function") {
290
+ guarded.writeFileWithMtime = async (path, data, mtime) => {
291
+ if (!await allow(path, data)) return;
292
+ return fs.writeFileWithMtime(path, data, mtime);
293
+ };
294
+ }
295
+ guarded.backendName = sideLabel(fs.backendName, side);
296
+ return guarded;
297
+ }
298
+ function sideLabel(name, side) {
299
+ if (!name) return side;
300
+ return name.includes(side) ? name : `${name}\xB7${side}`;
301
+ }
302
+
217
303
  // src/adapters.ts
218
304
  function toUint8Array(data) {
219
305
  if (data instanceof Uint8Array) return data;
@@ -287,7 +373,7 @@ function backendToSyncableFS(backend, name) {
287
373
  } else {
288
374
  syncable.backendName = backend.constructor.name || "Backend";
289
375
  }
290
- return syncable;
376
+ return wrapGroupTypeGuard(syncable, syncable.backendName || "backend");
291
377
  }
292
378
 
293
379
  // src/folder-backend.ts
@@ -296,13 +382,13 @@ import { SyncMapTransaction, StoreFS } from "@zenfs/core";
296
382
  // src/logger.ts
297
383
  import { createLogger as createLoggerBase } from "@richard432/localstorage-logger";
298
384
  var MODULE_PREFIX = "zen-fs-config";
299
- function createLogger(prefix) {
385
+ function createLogger2(prefix) {
300
386
  const logger = createLoggerBase(`${MODULE_PREFIX}:${prefix}`);
301
387
  return (...args) => logger.log(...args);
302
388
  }
303
389
 
304
390
  // src/folder-backend.ts
305
- var log = createLogger("folder-backend");
391
+ var log2 = createLogger2("folder-backend");
306
392
  var FolderStore = class {
307
393
  name = "folder";
308
394
  label;
@@ -379,7 +465,7 @@ function registerFolderBackend() {
379
465
  const pathMod = await import("path");
380
466
  const dir = options.path;
381
467
  const store = new FolderStore({ path: dir, label: options.label, fs, pathMod });
382
- return (await import("./backend-registry-RBKWNJZI.mjs")).wrapZenFSFileSystem({ backend: FolderBackend, path: dir, label: options.label });
468
+ return (await import("./backend-registry-UCAMGG6O.mjs")).wrapZenFSFileSystem({ backend: FolderBackend, path: dir, label: options.label });
383
469
  },
384
470
  {
385
471
  type: "Folder",
@@ -389,7 +475,7 @@ function registerFolderBackend() {
389
475
  defaultOptions: { path: "" }
390
476
  }
391
477
  );
392
- log("Folder backend registered");
478
+ log2("Folder backend registered");
393
479
  }
394
480
  registerFolderBackend();
395
481
  function isBrowserEnv() {
@@ -542,7 +628,7 @@ function deleteDataGroupLocalStore(appId, groupId, options = {}) {
542
628
  }
543
629
 
544
630
  // src/config-repo.ts
545
- import { createLogger as createLogger3 } from "@richard432/localstorage-logger";
631
+ import { createLogger as createLogger5 } from "@richard432/localstorage-logger";
546
632
 
547
633
  // src/version.ts
548
634
  function versionPathFor(configFilePath) {
@@ -785,330 +871,165 @@ async function verifyOrRepairVersion(fs, configFilePath, author) {
785
871
  }
786
872
  }
787
873
 
788
- // src/mtime-cleanup.ts
789
- function isMtimeSidecar(fileName) {
790
- return fileName.endsWith(".mtime");
874
+ // src/group-meta.ts
875
+ import { createLogger as createLogger3 } from "@richard432/localstorage-logger";
876
+
877
+ // src/canonical-json.ts
878
+ var FEATURE_ORDER = ["tombstones", "versions", "conflicts", "configHost", "appData"];
879
+ var GROUP_DESCRIPTOR_ORDER = ["schemaVersion", "kind", "id", "instanceId", "name", "features"];
880
+ var APP_DATA_GROUP_ORDER = ["id", "groupType", "instanceId", "name", "features", "backends"];
881
+ var BACKEND_ORDER = ["id", "type", "options", "accountBackendId", "description", "createdAt"];
882
+ function compareKeys(a, b) {
883
+ return a < b ? -1 : a > b ? 1 : 0;
791
884
  }
792
- var S_IFDIR = 16384;
793
- function isDirectory(stat) {
794
- return typeof stat.mode === "number" && (stat.mode & S_IFDIR) === S_IFDIR;
885
+ function isPlainObject(value) {
886
+ return typeof value === "object" && value !== null && !Array.isArray(value);
795
887
  }
796
- function joinPath(dir, entry) {
797
- if (dir === "/" || dir === "") return `/${entry}`;
798
- return `${dir.replace(/\/+$/, "")}/${entry}`;
888
+ function canonicalObject(value, order = []) {
889
+ const out = {};
890
+ for (const key of order) {
891
+ if (value[key] !== void 0) out[key] = canonicalField(key, value[key]);
892
+ }
893
+ for (const key of Object.keys(value).sort(compareKeys)) {
894
+ if (order.includes(key) || value[key] === void 0) continue;
895
+ out[key] = canonicalField(key, value[key]);
896
+ }
897
+ return out;
799
898
  }
800
- async function purgeMtimeSidecars(fs, options = {}) {
801
- const root = options.root && options.root !== "" ? options.root : "/";
802
- const dryRun = options.dryRun ?? false;
803
- const result = { scanned: 0, removed: [], failed: [] };
804
- const stack = [root];
805
- while (stack.length > 0) {
806
- const dir = stack.pop();
807
- let entries;
808
- try {
809
- entries = await fs.readdir(dir);
810
- } catch {
811
- continue;
812
- }
813
- for (const entry of entries) {
814
- const fullPath = joinPath(dir, entry);
815
- let stat;
816
- try {
817
- stat = await fs.stat(fullPath);
818
- } catch {
819
- continue;
820
- }
821
- if (isDirectory(stat)) {
822
- stack.push(fullPath);
823
- continue;
824
- }
825
- result.scanned++;
826
- if (!isMtimeSidecar(entry)) continue;
827
- if (dryRun) {
828
- result.removed.push(fullPath);
829
- continue;
830
- }
831
- try {
832
- await fs.unlink(fullPath);
833
- result.removed.push(fullPath);
834
- } catch {
835
- result.failed.push(fullPath);
836
- }
899
+ function canonicalField(key, value) {
900
+ if (Array.isArray(value)) {
901
+ if (key === "backends") {
902
+ return value.map((item) => isPlainObject(item) ? canonicalObject(item, BACKEND_ORDER) : item).sort(
903
+ (a, b) => compareKeys(String(a?.id ?? ""), String(b?.id ?? ""))
904
+ );
837
905
  }
906
+ return value.map((item) => canonicalField("", item));
838
907
  }
839
- return result;
908
+ if (isPlainObject(value)) {
909
+ if (key === "features") return canonicalObject(value, FEATURE_ORDER);
910
+ return canonicalObject(value);
911
+ }
912
+ return value;
840
913
  }
841
-
842
- // src/keep-cleanup.ts
843
- function isKeepFile(fileName) {
844
- return fileName === ".keep";
914
+ function stringify(value) {
915
+ return JSON.stringify(value, null, 2);
845
916
  }
846
- var S_IFDIR2 = 16384;
847
- var DEFAULT_PROTECTED_DIRS = ["/.meta/backends/.keep"];
848
- function isDirectory2(stat) {
849
- return typeof stat.mode === "number" && (stat.mode & S_IFDIR2) === S_IFDIR2;
917
+ function serializeGroupDescriptor(descriptor) {
918
+ const { updatedAt: _ignored, ...rest } = descriptor;
919
+ return stringify(canonicalObject(rest, GROUP_DESCRIPTOR_ORDER));
850
920
  }
851
- function joinPath2(dir, entry) {
852
- if (dir === "/" || dir === "") return `/${entry}`;
853
- return `${dir.replace(/\/+$/, "")}/${entry}`;
921
+ function serializeBackendDescriptor(descriptor) {
922
+ return stringify(canonicalObject(descriptor, BACKEND_ORDER));
854
923
  }
855
- function isProtected(fullPath, protectedDirs) {
856
- return protectedDirs.some((d) => {
857
- const dir = d.endsWith("/") ? d.slice(0, -1) : d;
858
- return fullPath === dir || fullPath.startsWith(dir + "/");
859
- });
924
+ function serializeAppDataGroupDescriptor(descriptor) {
925
+ return stringify(canonicalObject(descriptor, APP_DATA_GROUP_ORDER));
860
926
  }
861
- async function purgeKeepFiles(fs, options = {}) {
862
- const root = options.root && options.root !== "" ? options.root : "/";
863
- const dryRun = options.dryRun ?? false;
864
- const protectedDirs = options.protectedDirs ?? DEFAULT_PROTECTED_DIRS;
865
- const result = { scanned: 0, removed: [], failed: [] };
866
- const stack = [root];
867
- while (stack.length > 0) {
868
- const dir = stack.pop();
869
- if (isProtected(dir, protectedDirs)) continue;
870
- let entries;
871
- try {
872
- entries = await fs.readdir(dir);
873
- } catch {
874
- continue;
875
- }
876
- for (const entry of entries) {
877
- const fullPath = joinPath2(dir, entry);
878
- if (isProtected(fullPath, protectedDirs)) continue;
879
- let stat;
880
- try {
881
- stat = await fs.stat(fullPath);
882
- } catch {
883
- continue;
884
- }
885
- if (isDirectory2(stat)) {
886
- stack.push(fullPath);
887
- continue;
888
- }
889
- result.scanned++;
890
- if (!isKeepFile(entry)) continue;
891
- if (dryRun) {
892
- result.removed.push(fullPath);
893
- continue;
894
- }
895
- try {
896
- await fs.unlink(fullPath);
897
- result.removed.push(fullPath);
898
- } catch {
899
- result.failed.push(fullPath);
900
- }
901
- }
902
- }
903
- return result;
927
+ function stripBackendCreatedAt(descriptor) {
928
+ const { createdAt: _ignored, ...rest } = descriptor;
929
+ return rest;
930
+ }
931
+ function mergeBackendDescriptor(existing, incoming) {
932
+ const existingCreatedAt = typeof existing?.createdAt === "number" ? existing.createdAt : void 0;
933
+ const incomingCreatedAt = typeof incoming.createdAt === "number" ? incoming.createdAt : void 0;
934
+ const createdAt = existingCreatedAt === void 0 ? incomingCreatedAt : incomingCreatedAt === void 0 ? existingCreatedAt : Math.min(existingCreatedAt, incomingCreatedAt);
935
+ return createdAt === void 0 ? stripBackendCreatedAt(incoming) : { ...incoming, createdAt };
936
+ }
937
+ function mergeBackendCreatedAt(incoming, existing) {
938
+ if (!existing || existing.length === 0) return incoming;
939
+ const byId = new Map(existing.map((d) => [d.id, d]));
940
+ return incoming.map((desc) => mergeBackendDescriptor(byId.get(desc.id), desc));
941
+ }
942
+ function mergeDescriptorCreatedAt(descriptor, existing) {
943
+ return {
944
+ ...descriptor,
945
+ backends: mergeBackendCreatedAt(descriptor.backends, existing?.backends)
946
+ };
904
947
  }
905
948
 
906
- // src/version-migration.ts
907
- var S_IFDIR3 = 16384;
908
- function isDir(stat) {
909
- return typeof stat.mode === "number" && (stat.mode & S_IFDIR3) === S_IFDIR3;
949
+ // src/group-meta.ts
950
+ var log3 = createLogger3("zen-fs-config:tombstones");
951
+ var META_DIR = "/.meta";
952
+ var GROUP_DESCRIPTOR_FILE2 = `${META_DIR}/group.json`;
953
+ var META_BACKENDS_DIR = `${META_DIR}/backends`;
954
+ var TOMBSTONES_DIR = `${META_DIR}/tombstones`;
955
+ var RECREATE_AFTER_DELETE_SKEW_MS = 3e3;
956
+ var TOMBSTONE_RETENTION_MS = 24 * 60 * 60 * 1e3;
957
+ var TOMBSTONE_PLACEHOLDER_RETENTION_MS = 10 * 60 * 1e3;
958
+ function tombstoneRetentionMs(tombstonePath) {
959
+ if (tombstonePath.endsWith(".mtime") || tombstonePath === "/.keep" || tombstonePath.endsWith("/.keep")) {
960
+ return TOMBSTONE_PLACEHOLDER_RETENTION_MS;
961
+ }
962
+ return TOMBSTONE_RETENTION_MS;
910
963
  }
911
- function joinPath3(dir, entry) {
912
- if (dir === "/" || dir === "") return `/${entry}`;
913
- return `${dir.replace(/\/+$/, "")}/${entry}`;
964
+ function isTombstoneRetentionElapsed(tombstone, now = Date.now()) {
965
+ const deletedAt = Number(tombstone.deletedAt);
966
+ if (!Number.isFinite(deletedAt)) return true;
967
+ return now - deletedAt >= tombstoneRetentionMs(tombstone.path);
914
968
  }
915
- async function existsPath(fs, p) {
969
+ function isDirectoryTombstone(tombstone) {
970
+ return tombstone.type === "directory";
971
+ }
972
+ function serializeTombstone(tombstone) {
973
+ const ordered = {
974
+ path: tombstone.path,
975
+ deletedAt: tombstone.deletedAt,
976
+ deletedBy: tombstone.deletedBy,
977
+ confirmedBy: tombstone.confirmedBy
978
+ };
979
+ if (tombstone.type) ordered.type = tombstone.type;
980
+ return JSON.stringify(ordered, null, 2);
981
+ }
982
+ async function purgeTombstonedTree(fs, targetPath) {
983
+ let isDir2 = false;
916
984
  try {
917
- await fs.stat(p);
918
- return true;
985
+ const stat = await fs.stat?.(targetPath);
986
+ if (stat) {
987
+ if (typeof stat.isDirectory === "function") isDir2 = stat.isDirectory();
988
+ else {
989
+ const mode = Number(stat.mode ?? 0);
990
+ isDir2 = mode > 0 && (mode & 61440) === 16384;
991
+ }
992
+ }
919
993
  } catch {
920
- return false;
994
+ isDir2 = false;
921
995
  }
922
- }
923
- function configNameFromLegacy(entry) {
924
- const noMtime = entry.endsWith(".version.mtime") ? entry.slice(0, -".version.mtime".length) : entry.slice(0, -".version".length);
925
- return noMtime.slice(1);
926
- }
927
- async function resolveTarget(fs, dir, entry) {
928
- const configName = configNameFromLegacy(entry);
929
- const configPath = joinPath3(dir, configName);
930
- const dotConfigPath = joinPath3(dir, `.${configName}`);
931
- if (await existsPath(fs, dotConfigPath)) {
932
- return { action: "skip" };
996
+ if (!isDir2) {
997
+ try {
998
+ await fs.readdir(targetPath);
999
+ isDir2 = true;
1000
+ } catch {
1001
+ isDir2 = false;
1002
+ }
933
1003
  }
934
- if (await existsPath(fs, configPath)) {
935
- return { action: "rename", newPath: versionPathFor(configPath) ?? `${configName}.version` };
1004
+ if (!isDir2) {
1005
+ try {
1006
+ await fs.unlink(targetPath);
1007
+ } catch {
1008
+ }
1009
+ return;
936
1010
  }
937
- return { action: "delete" };
938
- }
939
- async function migrateVersionSidecars(fs, options = {}) {
940
- const root = options.root && options.root !== "" ? options.root : "/";
941
- const dryRun = options.dryRun ?? false;
942
- const replicas = options.replicas ?? [];
943
- const result = {
944
- renamed: [],
945
- deleted: [],
946
- remoteDeleted: [],
947
- failed: []
948
- };
949
- const stack = [root];
950
- while (stack.length > 0) {
951
- const dir = stack.pop();
952
- let entries;
1011
+ for (const placeholder of [`${targetPath}/.keep`, `${targetPath}/.keep.mtime`]) {
953
1012
  try {
954
- entries = await fs.readdir(dir);
1013
+ await fs.unlink(placeholder);
955
1014
  } catch {
956
- continue;
957
- }
958
- for (const entry of entries) {
959
- const full = joinPath3(dir, entry);
960
- let stat;
961
- try {
962
- stat = await fs.stat(full);
963
- } catch {
964
- continue;
965
- }
966
- if (isDir(stat)) {
967
- stack.push(full);
968
- continue;
969
- }
970
- const isLegacyVersion = entry.startsWith(".") && (entry.endsWith(".version") || entry.endsWith(".version.mtime"));
971
- if (!isLegacyVersion) continue;
972
- const legacyVerPath = entry.endsWith(".version.mtime") ? full.slice(0, -".mtime".length) : full;
973
- const target = await resolveTarget(fs, dir, entry);
974
- if (target.action === "skip") continue;
975
- const legacyMtimePath = `${legacyVerPath}.mtime`;
976
- const newMtimePath = target.newPath ? `${target.newPath}.mtime` : null;
977
- if (dryRun) {
978
- if (target.action === "rename") result.renamed.push(full);
979
- else result.deleted.push(full);
980
- continue;
981
- }
982
- try {
983
- if (target.action === "rename") {
984
- if (await existsPath(fs, target.newPath)) {
985
- await fs.unlink(legacyVerPath);
986
- result.deleted.push(full);
987
- } else {
988
- const content = await fs.readFile(legacyVerPath);
989
- const bytes = typeof content === "string" ? new TextEncoder().encode(content) : content;
990
- await fs.writeFile(target.newPath, bytes);
991
- await fs.unlink(legacyVerPath);
992
- result.renamed.push(full);
993
- }
994
- if (newMtimePath && await existsPath(fs, legacyMtimePath)) {
995
- try {
996
- const mc = await fs.readFile(legacyMtimePath);
997
- const mb = typeof mc === "string" ? new TextEncoder().encode(mc) : mc;
998
- await fs.writeFile(newMtimePath, mb);
999
- await fs.unlink(legacyMtimePath);
1000
- } catch {
1001
- }
1002
- }
1003
- } else {
1004
- await fs.unlink(legacyVerPath);
1005
- result.deleted.push(full);
1006
- if (await existsPath(fs, legacyMtimePath)) {
1007
- try {
1008
- await fs.unlink(legacyMtimePath);
1009
- } catch {
1010
- }
1011
- }
1012
- }
1013
- } catch (e) {
1014
- result.failed.push(full);
1015
- continue;
1016
- }
1017
- for (const rep of replicas) {
1018
- for (const rp of [legacyVerPath, legacyMtimePath]) {
1019
- try {
1020
- await rep.unlink(rp);
1021
- result.remoteDeleted.push(rp);
1022
- } catch {
1023
- }
1024
- }
1025
- }
1026
1015
  }
1027
1016
  }
1028
- return result;
1029
- }
1030
-
1031
- // src/group-meta.ts
1032
- import { createLogger as createLogger2 } from "@richard432/localstorage-logger";
1033
-
1034
- // src/canonical-json.ts
1035
- var FEATURE_ORDER = ["tombstones", "versions", "conflicts", "configHost", "appData"];
1036
- var GROUP_DESCRIPTOR_ORDER = ["schemaVersion", "kind", "id", "name", "features"];
1037
- var APP_DATA_GROUP_ORDER = ["id", "groupType", "name", "features", "backends"];
1038
- var BACKEND_ORDER = ["id", "type", "options", "accountBackendId", "description", "createdAt"];
1039
- function compareKeys(a, b) {
1040
- return a < b ? -1 : a > b ? 1 : 0;
1041
- }
1042
- function isPlainObject(value) {
1043
- return typeof value === "object" && value !== null && !Array.isArray(value);
1044
- }
1045
- function canonicalObject(value, order = []) {
1046
- const out = {};
1047
- for (const key of order) {
1048
- if (value[key] !== void 0) out[key] = canonicalField(key, value[key]);
1049
- }
1050
- for (const key of Object.keys(value).sort(compareKeys)) {
1051
- if (order.includes(key) || value[key] === void 0) continue;
1052
- out[key] = canonicalField(key, value[key]);
1017
+ let children = [];
1018
+ try {
1019
+ children = await fs.readdir(targetPath);
1020
+ } catch {
1053
1021
  }
1054
- return out;
1055
- }
1056
- function canonicalField(key, value) {
1057
- if (Array.isArray(value)) {
1058
- if (key === "backends") {
1059
- return value.map((item) => isPlainObject(item) ? canonicalObject(item, BACKEND_ORDER) : item).sort(
1060
- (a, b) => compareKeys(String(a?.id ?? ""), String(b?.id ?? ""))
1061
- );
1022
+ for (const child of children) await purgeTombstonedTree(fs, `${targetPath}/${child}`);
1023
+ try {
1024
+ if (typeof fs.rmdir === "function") await fs.rmdir(targetPath);
1025
+ else await fs.unlink(targetPath);
1026
+ } catch {
1027
+ try {
1028
+ await fs.unlink(targetPath);
1029
+ } catch {
1062
1030
  }
1063
- return value.map((item) => canonicalField("", item));
1064
1031
  }
1065
- if (isPlainObject(value)) {
1066
- if (key === "features") return canonicalObject(value, FEATURE_ORDER);
1067
- return canonicalObject(value);
1068
- }
1069
- return value;
1070
- }
1071
- function stringify(value) {
1072
- return JSON.stringify(value, null, 2);
1073
- }
1074
- function serializeGroupDescriptor(descriptor) {
1075
- const { updatedAt: _ignored, ...rest } = descriptor;
1076
- return stringify(canonicalObject(rest, GROUP_DESCRIPTOR_ORDER));
1077
- }
1078
- function serializeBackendDescriptor(descriptor) {
1079
- return stringify(canonicalObject(descriptor, BACKEND_ORDER));
1080
- }
1081
- function serializeAppDataGroupDescriptor(descriptor) {
1082
- return stringify(canonicalObject(descriptor, APP_DATA_GROUP_ORDER));
1083
- }
1084
- function stripBackendCreatedAt(descriptor) {
1085
- const { createdAt: _ignored, ...rest } = descriptor;
1086
- return rest;
1087
- }
1088
- function mergeBackendDescriptor(existing, incoming) {
1089
- const existingCreatedAt = typeof existing?.createdAt === "number" ? existing.createdAt : void 0;
1090
- const incomingCreatedAt = typeof incoming.createdAt === "number" ? incoming.createdAt : void 0;
1091
- const createdAt = existingCreatedAt === void 0 ? incomingCreatedAt : incomingCreatedAt === void 0 ? existingCreatedAt : Math.min(existingCreatedAt, incomingCreatedAt);
1092
- return createdAt === void 0 ? stripBackendCreatedAt(incoming) : { ...incoming, createdAt };
1093
1032
  }
1094
- function mergeBackendCreatedAt(incoming, existing) {
1095
- if (!existing || existing.length === 0) return incoming;
1096
- const byId = new Map(existing.map((d) => [d.id, d]));
1097
- return incoming.map((desc) => mergeBackendDescriptor(byId.get(desc.id), desc));
1098
- }
1099
- function mergeDescriptorCreatedAt(descriptor, existing) {
1100
- return {
1101
- ...descriptor,
1102
- backends: mergeBackendCreatedAt(descriptor.backends, existing?.backends)
1103
- };
1104
- }
1105
-
1106
- // src/group-meta.ts
1107
- var log2 = createLogger2("zen-fs-config:tombstones");
1108
- var META_DIR = "/.meta";
1109
- var GROUP_DESCRIPTOR_FILE = `${META_DIR}/group.json`;
1110
- var META_BACKENDS_DIR = `${META_DIR}/backends`;
1111
- var TOMBSTONES_DIR = `${META_DIR}/tombstones`;
1112
1033
  var LEGACY_TOMBSTONES_DIR = `${META_DIR}/.deleted`;
1113
1034
  var VERSIONS_DIR = `${META_DIR}/versions`;
1114
1035
  var CONFLICTS_DIR = `${META_DIR}/conflicts`;
@@ -1171,6 +1092,9 @@ async function existsSafe(fs, path) {
1171
1092
  function isMtimeSidecarPath(path) {
1172
1093
  return path.endsWith(".mtime");
1173
1094
  }
1095
+ function isHiddenPlaceholderPath(path) {
1096
+ return isMtimeSidecarPath(path) || path === "/.keep" || path.endsWith("/.keep");
1097
+ }
1174
1098
  function encodeMetaPath(filePath) {
1175
1099
  const normalized = filePath.startsWith("/") ? filePath : `/${filePath}`;
1176
1100
  return normalized.replace(/^\//, "").replace(/\//g, "__").replace(/\./g, "++");
@@ -1189,15 +1113,21 @@ function normalizeTombstoneRecord(value, fallbackPath) {
1189
1113
  const record = value;
1190
1114
  const rawPath = typeof record.path === "string" ? record.path : fallbackPath;
1191
1115
  if (!rawPath) return null;
1192
- const path = rawPath.startsWith("/") ? rawPath : `/${rawPath}`;
1116
+ const path = normalizeTombstonePath(rawPath);
1193
1117
  const confirmedBy = Array.isArray(record.confirmedBy) ? record.confirmedBy.filter((id) => typeof id === "string") : [];
1118
+ const type = record.type === "directory" ? "directory" : record.type === "file" ? "file" : void 0;
1194
1119
  return {
1195
1120
  path,
1196
1121
  deletedAt: typeof record.deletedAt === "number" ? record.deletedAt : 0,
1197
1122
  deletedBy: typeof record.deletedBy === "string" ? record.deletedBy : "unknown",
1198
- confirmedBy
1123
+ confirmedBy,
1124
+ ...type ? { type } : {}
1199
1125
  };
1200
1126
  }
1127
+ function normalizeTombstonePath(rawPath) {
1128
+ const withLeading = rawPath.startsWith("/") ? rawPath : `/${rawPath}`;
1129
+ return withLeading.length > 1 ? withLeading.replace(/\/+$/, "") || "/" : withLeading;
1130
+ }
1201
1131
  function extractJsonObjects(raw) {
1202
1132
  const objects = [];
1203
1133
  let depth = 0;
@@ -1278,6 +1208,7 @@ function mergeTombstone(byPath, tombstone) {
1278
1208
  for (const id of tombstone.confirmedBy) {
1279
1209
  if (!prev.confirmedBy.includes(id)) prev.confirmedBy.push(id);
1280
1210
  }
1211
+ if (isDirectoryTombstone(tombstone) && !isDirectoryTombstone(prev)) prev.type = "directory";
1281
1212
  }
1282
1213
  async function readTombstonesFromFs(fs, warn) {
1283
1214
  const byPath = /* @__PURE__ */ new Map();
@@ -1312,16 +1243,16 @@ async function readTombstonesFromFs(fs, warn) {
1312
1243
  return Array.from(byPath.values());
1313
1244
  }
1314
1245
  async function readGroupDescriptor(fs) {
1315
- const parsed = await readJson(fs, GROUP_DESCRIPTOR_FILE);
1246
+ const parsed = await readJson(fs, GROUP_DESCRIPTOR_FILE2);
1316
1247
  if (!parsed) return null;
1317
1248
  const { updatedAt: _ignored, ...rest } = parsed;
1318
1249
  return rest;
1319
1250
  }
1320
1251
  async function writeGroupDescriptor(fs, descriptor) {
1321
1252
  const bytes = serializeGroupDescriptor(descriptor);
1322
- if (await readText(fs, GROUP_DESCRIPTOR_FILE) === bytes) return;
1323
- await ensureParentDir2(fs, GROUP_DESCRIPTOR_FILE);
1324
- await fs.writeFile(GROUP_DESCRIPTOR_FILE, new TextEncoder().encode(bytes));
1253
+ if (await readText(fs, GROUP_DESCRIPTOR_FILE2) === bytes) return;
1254
+ await ensureParentDir2(fs, GROUP_DESCRIPTOR_FILE2);
1255
+ await fs.writeFile(GROUP_DESCRIPTOR_FILE2, new TextEncoder().encode(bytes));
1325
1256
  }
1326
1257
  function assertValidBackendId(id) {
1327
1258
  if (typeof id !== "string" || id.trim() === "") {
@@ -1383,23 +1314,31 @@ var TombstoneStore = class {
1383
1314
  }
1384
1315
  fs;
1385
1316
  author;
1317
+ /**
1318
+ * 本轮 `process()` 真正核对过"确实不存在"的(路径 → 目标 id)。
1319
+ *
1320
+ * 只有出现在这里的副本才会被写进 `confirmedBy`(见 {@link confirm}),与
1321
+ * 配置组 `ConfigRepo.updateTombstoneConfirmations` 的保守语义一致:副本删除
1322
+ * 失败(网络、后端限制、只剩占位目录)时绝不算已确认。
1323
+ */
1324
+ verifiedAbsent = /* @__PURE__ */ new Map();
1386
1325
  pathFor(filePath) {
1387
1326
  return `${TOMBSTONES_DIR}/${encodeMetaPath(filePath)}.json`;
1388
1327
  }
1389
1328
  /** All tombstones. */
1390
1329
  async list() {
1391
- return readTombstonesFromFs(this.fs, (message) => log2.warn(message));
1330
+ return readTombstonesFromFs(this.fs, (message) => log3.warn(message));
1392
1331
  }
1393
1332
  /** Write a tombstone. */
1394
1333
  async write(tombstone) {
1395
- const bytes = new TextEncoder().encode(JSON.stringify(tombstone, null, 2));
1334
+ const bytes = new TextEncoder().encode(serializeTombstone(tombstone));
1396
1335
  const p = this.pathFor(tombstone.path);
1397
1336
  await ensureParentDir2(this.fs, p);
1398
1337
  await this.fs.writeFile(p, bytes);
1399
1338
  }
1400
1339
  /** Persist an updated tombstone (confirmations) when it still exists. */
1401
1340
  async save(tombstone) {
1402
- const bytes = new TextEncoder().encode(JSON.stringify(tombstone, null, 2));
1341
+ const bytes = new TextEncoder().encode(serializeTombstone(tombstone));
1403
1342
  const p = this.pathFor(tombstone.path);
1404
1343
  if (!await existsSafe(this.fs, p)) return;
1405
1344
  await this.fs.writeFile(p, bytes);
@@ -1416,34 +1355,121 @@ var TombstoneStore = class {
1416
1355
  /**
1417
1356
  * Delete every tombstoned file (and its version record) on the local store
1418
1357
  * and on each target backend, so bi-directional sync cannot resurrect it.
1358
+ *
1359
+ * 墓碑只对「删除之后没有再写入」的路径有效。同步类工具会不断重建某些文件
1360
+ * (最典型的是 `.sync.lock`:每轮删除 → 重建),若墓碑永久生效,路径会被每一
1361
+ * 轮 preSync 删掉,表现为「刚写完 1 秒就消失、锁永远拿不到」。因此这里先判定
1362
+ * 目标路径是否在 `deletedAt` 之后被重新写入:是则墓碑已被用户写操作撤销,保留
1363
+ * 文件并删除墓碑;否则按删除传播处理。
1419
1364
  */
1420
1365
  async process(targets = []) {
1421
1366
  const tombstones = await this.list();
1367
+ const expired = [];
1368
+ this.verifiedAbsent.clear();
1422
1369
  for (const tombstone of tombstones) {
1423
- await this.deleteEverywhere(this.fs, tombstone.path);
1370
+ if (await this.wasRecreatedAfterDeletion(tombstone)) {
1371
+ expired.push(tombstone);
1372
+ continue;
1373
+ }
1374
+ await this.deleteEverywhere(this.fs, tombstone);
1424
1375
  for (const target of targets) {
1425
- await this.deleteEverywhere(target.fs, tombstone.path);
1376
+ await this.deleteEverywhere(target.fs, tombstone);
1426
1377
  }
1378
+ for (const target of targets) {
1379
+ if (await this.absentOnTarget(target.fs, tombstone)) {
1380
+ this.markVerified(tombstone.path, target.id);
1381
+ }
1382
+ }
1383
+ }
1384
+ for (const tombstone of expired) {
1385
+ await this.remove(tombstone);
1386
+ log3.log(
1387
+ `[TombstoneStore] expired tombstone for ${tombstone.path} \u2014 recreated after deletion`
1388
+ );
1389
+ }
1390
+ }
1391
+ markVerified(path, targetId) {
1392
+ let ids = this.verifiedAbsent.get(path);
1393
+ if (!ids) {
1394
+ ids = /* @__PURE__ */ new Set();
1395
+ this.verifiedAbsent.set(path, ids);
1396
+ }
1397
+ ids.add(targetId);
1398
+ }
1399
+ /**
1400
+ * 目标上该路径当前是否确实不存在。
1401
+ *
1402
+ * `.mtime` 侧车与 `.keep` 占位对部分后端不可见(`exists()` 恒为 false),这类
1403
+ * 路径只能相信本轮 unlink 没有报错,因此按"不可见即可信"处理(与配置组的
1404
+ * `allReplicasConfirmAbsent` 一致)。
1405
+ */
1406
+ async absentOnTarget(fs, tombstone) {
1407
+ if (!isDirectoryTombstone(tombstone) && isHiddenPlaceholderPath(tombstone.path)) {
1408
+ return true;
1409
+ }
1410
+ try {
1411
+ const stat = await fs.stat?.(tombstone.path);
1412
+ if (stat) return false;
1413
+ } catch {
1414
+ }
1415
+ try {
1416
+ if (typeof fs.exists === "function") return !await fs.exists(tombstone.path);
1417
+ } catch {
1418
+ }
1419
+ return true;
1420
+ }
1421
+ /**
1422
+ * 本地存储上该路径的 mtime 是否晚于墓碑的删除时刻。
1423
+ *
1424
+ * 只看本地主存储:副本上的同路径文件可能只是「删除之前的旧副本」,它的 mtime
1425
+ * 本来就旧,用副本判定既不可靠又会掩盖真正的删除传播。
1426
+ */
1427
+ async wasRecreatedAfterDeletion(tombstone) {
1428
+ const mtimeMs = await this.mtimeOf(this.fs, tombstone.path);
1429
+ if (mtimeMs === null) return false;
1430
+ return mtimeMs > tombstone.deletedAt + RECREATE_AFTER_DELETE_SKEW_MS;
1431
+ }
1432
+ async mtimeOf(fs, filePath) {
1433
+ try {
1434
+ const stat = await fs.stat?.(filePath);
1435
+ const mtimeMs = Number(stat?.mtimeMs);
1436
+ return Number.isFinite(mtimeMs) ? mtimeMs : null;
1437
+ } catch {
1438
+ return null;
1427
1439
  }
1428
1440
  }
1429
- async deleteEverywhere(fs, filePath) {
1430
- if (!isMtimeSidecarPath(filePath) && !await existsSafe(fs, filePath)) return;
1441
+ async deleteEverywhere(fs, tombstone) {
1442
+ if (isDirectoryTombstone(tombstone)) {
1443
+ await purgeTombstonedTree(fs, tombstone.path);
1444
+ return;
1445
+ }
1446
+ if (!isMtimeSidecarPath(tombstone.path) && !await existsSafe(fs, tombstone.path)) return;
1431
1447
  try {
1432
- await fs.unlink(filePath);
1448
+ await fs.unlink(tombstone.path);
1433
1449
  } catch {
1434
1450
  }
1435
1451
  }
1436
- /** Add the given backend ids to every tombstone's confirmation set. */
1437
- async confirm(backendIds) {
1452
+ /**
1453
+ * 把本轮真正核对过"确实不存在"的目标写进墓碑的 `confirmedBy`。
1454
+ *
1455
+ * 旧实现把传入的后端 id 无条件写入,等于"跑过一轮就算所有副本都清干净了";
1456
+ * 副本删除失败时墓碑仍会被 GC,下一轮同步再把残留拉回本地。现在只确认
1457
+ * {@link process} 中现场核对通过的目标(与配置组语义一致),并支持只传 id
1458
+ * 的旧调用方式(此时沿用同一份核对结果)。
1459
+ */
1460
+ async confirm(targets) {
1461
+ const isTargetList = (value) => value.length > 0 && typeof value[0] === "object";
1462
+ const ids = isTargetList(targets) ? targets.map((t) => t.id) : targets;
1438
1463
  const tombstones = await this.list();
1439
1464
  let modified = 0;
1440
1465
  for (const tombstone of tombstones) {
1466
+ const verified = this.verifiedAbsent.get(tombstone.path);
1441
1467
  let changed = false;
1442
- for (const id of backendIds) {
1443
- if (!tombstone.confirmedBy.includes(id)) {
1444
- tombstone.confirmedBy.push(id);
1445
- changed = true;
1446
- }
1468
+ for (const id of ids) {
1469
+ if (tombstone.confirmedBy.includes(id)) continue;
1470
+ if (!verified?.has(id)) continue;
1471
+ tombstone.confirmedBy.push(id);
1472
+ changed = true;
1447
1473
  }
1448
1474
  if (!changed) continue;
1449
1475
  try {
@@ -1458,8 +1484,17 @@ var TombstoneStore = class {
1458
1484
  async gc(allBackendIds, targets = []) {
1459
1485
  const tombstones = await this.list();
1460
1486
  for (const tombstone of tombstones) {
1487
+ if (!isTombstoneRetentionElapsed(tombstone)) continue;
1461
1488
  const allConfirmed = allBackendIds.every((id) => tombstone.confirmedBy.includes(id));
1462
1489
  if (!allConfirmed) continue;
1490
+ let stillAbsent = true;
1491
+ for (const target of targets) {
1492
+ if (!await this.absentOnTarget(target.fs, tombstone)) {
1493
+ stillAbsent = false;
1494
+ break;
1495
+ }
1496
+ }
1497
+ if (!stillAbsent) continue;
1463
1498
  const p = this.pathFor(tombstone.path);
1464
1499
  if (await existsSafe(this.fs, p)) {
1465
1500
  try {
@@ -1565,52 +1600,362 @@ var ConflictStore = class {
1565
1600
  } catch {
1566
1601
  continue;
1567
1602
  }
1568
- for (const entry of entries) {
1569
- if (seen.has(entry)) continue;
1570
- const archive = await readJson(this.fs, `${dir}/${entry}/meta.json`);
1571
- if (!archive) continue;
1572
- seen.add(entry);
1573
- archives.push(archive);
1574
- }
1575
- }
1576
- return archives.sort((a, b) => a.timestamp - b.timestamp);
1577
- }
1578
- candidatesFor(conflictId) {
1579
- const id = conflictId.replace(/\/meta\.json$/, "");
1580
- return [`${CONFLICTS_DIR}/${id}`, `${LEGACY_CONFLICTS_DIR}/${id}`];
1581
- }
1582
- async readBackup(conflictId, fileType) {
1583
- for (const dir of this.candidatesFor(conflictId)) {
1584
- const p = `${dir}/${fileType}`;
1603
+ for (const entry of entries) {
1604
+ if (seen.has(entry)) continue;
1605
+ const archive = await readJson(this.fs, `${dir}/${entry}/meta.json`);
1606
+ if (!archive) continue;
1607
+ seen.add(entry);
1608
+ archives.push(archive);
1609
+ }
1610
+ }
1611
+ return archives.sort((a, b) => a.timestamp - b.timestamp);
1612
+ }
1613
+ candidatesFor(conflictId) {
1614
+ const id = conflictId.replace(/\/meta\.json$/, "");
1615
+ return [`${CONFLICTS_DIR}/${id}`, `${LEGACY_CONFLICTS_DIR}/${id}`];
1616
+ }
1617
+ async readBackup(conflictId, fileType) {
1618
+ for (const dir of this.candidatesFor(conflictId)) {
1619
+ const p = `${dir}/${fileType}`;
1620
+ try {
1621
+ return new TextDecoder().decode(toBytes(await this.fs.readFile(p)));
1622
+ } catch {
1623
+ }
1624
+ }
1625
+ throw new Error(`Conflict backup not found: ${conflictId}/${fileType}`);
1626
+ }
1627
+ /** Resolve a conflict with raw (already serialized) content. */
1628
+ async resolve(conflictId, mergedContent) {
1629
+ for (const dir of this.candidatesFor(conflictId)) {
1630
+ const metaPath = `${dir}/meta.json`;
1631
+ const archive = await readJson(this.fs, metaPath);
1632
+ if (!archive) continue;
1633
+ const bytes = typeof mergedContent === "string" ? new TextEncoder().encode(mergedContent) : mergedContent;
1634
+ await ensureParentDir2(this.fs, archive.conflictPath);
1635
+ await this.fs.writeFile(archive.conflictPath, bytes);
1636
+ await this.versions.record(archive.conflictPath, bytes);
1637
+ await this.fs.writeFile(`${dir}/resolved`, bytes);
1638
+ archive.resolvedBackupPath = "./resolved";
1639
+ await writeJson(this.fs, metaPath, archive);
1640
+ return;
1641
+ }
1642
+ throw new Error(`Failed to resolve conflict ${conflictId}: archive not found`);
1643
+ }
1644
+ };
1645
+
1646
+ // src/group-identity.ts
1647
+ import { createLogger as createLogger4 } from "@richard432/localstorage-logger";
1648
+ var log4 = createLogger4("zen-fs-config:group-identity");
1649
+ 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;
1650
+ function newGroupInstanceId() {
1651
+ const cryptoObj = globalThis?.crypto;
1652
+ if (cryptoObj?.randomUUID) return cryptoObj.randomUUID();
1653
+ const bytes = new Uint8Array(16);
1654
+ if (cryptoObj?.getRandomValues) {
1655
+ cryptoObj.getRandomValues(bytes);
1656
+ } else {
1657
+ for (let i = 0; i < bytes.length; i += 1) bytes[i] = Math.floor(Math.random() * 256);
1658
+ }
1659
+ bytes[6] = bytes[6] & 15 | 64;
1660
+ bytes[8] = bytes[8] & 63 | 128;
1661
+ const hex = Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join("");
1662
+ return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
1663
+ }
1664
+ function isValidGroupInstanceId(value) {
1665
+ return typeof value === "string" && INSTANCE_ID_RE.test(value.trim());
1666
+ }
1667
+ async function bindRemoteGroupIdentity(remoteFS, identity) {
1668
+ let remote = null;
1669
+ try {
1670
+ remote = await readGroupDescriptor(remoteFS);
1671
+ } catch (err) {
1672
+ log4.warn(`[GroupIdentity] failed to read remote ${identity.kind}/"${identity.id}" group.json:`, err);
1673
+ throw err;
1674
+ }
1675
+ const current = remote?.instanceId;
1676
+ if (isValidGroupInstanceId(current)) {
1677
+ if (current === identity.instanceId) return "match";
1678
+ log4.warn(
1679
+ `[GroupIdentity] backend belongs to another sync group (remote instanceId=${current}, this group=${identity.instanceId}, kind ${remote?.kind ?? "?"}/"${remote?.id ?? "?"}") \u2014 sync pair NOT created`
1680
+ );
1681
+ return "conflict";
1682
+ }
1683
+ const next = {
1684
+ schemaVersion: 2,
1685
+ kind: remote?.kind ?? identity.kind,
1686
+ id: remote?.id ?? identity.id,
1687
+ instanceId: identity.instanceId,
1688
+ ...remote?.name ?? identity.name ? { name: remote?.name ?? identity.name } : {},
1689
+ ...remote?.features ?? identity.features ? { features: remote?.features ?? identity.features } : {}
1690
+ };
1691
+ if (next.kind !== identity.kind) {
1692
+ log4.warn(
1693
+ `[GroupIdentity] remote kind "${next.kind}" \u2260 this group kind "${identity.kind}" \u2014 sync pair NOT created`
1694
+ );
1695
+ return "conflict";
1696
+ }
1697
+ try {
1698
+ await writeGroupDescriptor(remoteFS, next);
1699
+ } catch (err) {
1700
+ log4.warn(`[GroupIdentity] failed to claim remote root for "${identity.id}":`, err);
1701
+ return "conflict";
1702
+ }
1703
+ log4.log(
1704
+ `[GroupIdentity] claimed remote root for ${identity.kind}/"${identity.id}" (instanceId=${identity.instanceId})`
1705
+ );
1706
+ return "claimed";
1707
+ }
1708
+ function pickInstanceId(descriptor) {
1709
+ const value = descriptor?.instanceId;
1710
+ return isValidGroupInstanceId(value) ? value : void 0;
1711
+ }
1712
+
1713
+ // src/mtime-cleanup.ts
1714
+ function isMtimeSidecar(fileName) {
1715
+ return fileName.endsWith(".mtime");
1716
+ }
1717
+ var S_IFDIR = 16384;
1718
+ function isDirectory(stat) {
1719
+ return typeof stat.mode === "number" && (stat.mode & S_IFDIR) === S_IFDIR;
1720
+ }
1721
+ function joinPath(dir, entry) {
1722
+ if (dir === "/" || dir === "") return `/${entry}`;
1723
+ return `${dir.replace(/\/+$/, "")}/${entry}`;
1724
+ }
1725
+ async function purgeMtimeSidecars(fs, options = {}) {
1726
+ const root = options.root && options.root !== "" ? options.root : "/";
1727
+ const dryRun = options.dryRun ?? false;
1728
+ const result = { scanned: 0, removed: [], failed: [] };
1729
+ const stack = [root];
1730
+ while (stack.length > 0) {
1731
+ const dir = stack.pop();
1732
+ let entries;
1733
+ try {
1734
+ entries = await fs.readdir(dir);
1735
+ } catch {
1736
+ continue;
1737
+ }
1738
+ for (const entry of entries) {
1739
+ const fullPath = joinPath(dir, entry);
1740
+ let stat;
1741
+ try {
1742
+ stat = await fs.stat(fullPath);
1743
+ } catch {
1744
+ continue;
1745
+ }
1746
+ if (isDirectory(stat)) {
1747
+ stack.push(fullPath);
1748
+ continue;
1749
+ }
1750
+ result.scanned++;
1751
+ if (!isMtimeSidecar(entry)) continue;
1752
+ if (dryRun) {
1753
+ result.removed.push(fullPath);
1754
+ continue;
1755
+ }
1756
+ try {
1757
+ await fs.unlink(fullPath);
1758
+ result.removed.push(fullPath);
1759
+ } catch {
1760
+ result.failed.push(fullPath);
1761
+ }
1762
+ }
1763
+ }
1764
+ return result;
1765
+ }
1766
+
1767
+ // src/keep-cleanup.ts
1768
+ function isKeepFile(fileName) {
1769
+ return fileName === ".keep";
1770
+ }
1771
+ var S_IFDIR2 = 16384;
1772
+ var DEFAULT_PROTECTED_DIRS = ["/.meta/backends/.keep"];
1773
+ function isDirectory2(stat) {
1774
+ return typeof stat.mode === "number" && (stat.mode & S_IFDIR2) === S_IFDIR2;
1775
+ }
1776
+ function joinPath2(dir, entry) {
1777
+ if (dir === "/" || dir === "") return `/${entry}`;
1778
+ return `${dir.replace(/\/+$/, "")}/${entry}`;
1779
+ }
1780
+ function isProtected(fullPath, protectedDirs) {
1781
+ return protectedDirs.some((d) => {
1782
+ const dir = d.endsWith("/") ? d.slice(0, -1) : d;
1783
+ return fullPath === dir || fullPath.startsWith(dir + "/");
1784
+ });
1785
+ }
1786
+ async function purgeKeepFiles(fs, options = {}) {
1787
+ const root = options.root && options.root !== "" ? options.root : "/";
1788
+ const dryRun = options.dryRun ?? false;
1789
+ const protectedDirs = options.protectedDirs ?? DEFAULT_PROTECTED_DIRS;
1790
+ const result = { scanned: 0, removed: [], failed: [] };
1791
+ const stack = [root];
1792
+ while (stack.length > 0) {
1793
+ const dir = stack.pop();
1794
+ if (isProtected(dir, protectedDirs)) continue;
1795
+ let entries;
1796
+ try {
1797
+ entries = await fs.readdir(dir);
1798
+ } catch {
1799
+ continue;
1800
+ }
1801
+ for (const entry of entries) {
1802
+ const fullPath = joinPath2(dir, entry);
1803
+ if (isProtected(fullPath, protectedDirs)) continue;
1804
+ let stat;
1805
+ try {
1806
+ stat = await fs.stat(fullPath);
1807
+ } catch {
1808
+ continue;
1809
+ }
1810
+ if (isDirectory2(stat)) {
1811
+ stack.push(fullPath);
1812
+ continue;
1813
+ }
1814
+ result.scanned++;
1815
+ if (!isKeepFile(entry)) continue;
1816
+ if (dryRun) {
1817
+ result.removed.push(fullPath);
1818
+ continue;
1819
+ }
1820
+ try {
1821
+ await fs.unlink(fullPath);
1822
+ result.removed.push(fullPath);
1823
+ } catch {
1824
+ result.failed.push(fullPath);
1825
+ }
1826
+ }
1827
+ }
1828
+ return result;
1829
+ }
1830
+
1831
+ // src/version-migration.ts
1832
+ var S_IFDIR3 = 16384;
1833
+ function isDir(stat) {
1834
+ return typeof stat.mode === "number" && (stat.mode & S_IFDIR3) === S_IFDIR3;
1835
+ }
1836
+ function joinPath3(dir, entry) {
1837
+ if (dir === "/" || dir === "") return `/${entry}`;
1838
+ return `${dir.replace(/\/+$/, "")}/${entry}`;
1839
+ }
1840
+ async function existsPath(fs, p) {
1841
+ try {
1842
+ await fs.stat(p);
1843
+ return true;
1844
+ } catch {
1845
+ return false;
1846
+ }
1847
+ }
1848
+ function configNameFromLegacy(entry) {
1849
+ const noMtime = entry.endsWith(".version.mtime") ? entry.slice(0, -".version.mtime".length) : entry.slice(0, -".version".length);
1850
+ return noMtime.slice(1);
1851
+ }
1852
+ async function resolveTarget(fs, dir, entry) {
1853
+ const configName = configNameFromLegacy(entry);
1854
+ const configPath = joinPath3(dir, configName);
1855
+ const dotConfigPath = joinPath3(dir, `.${configName}`);
1856
+ if (await existsPath(fs, dotConfigPath)) {
1857
+ return { action: "skip" };
1858
+ }
1859
+ if (await existsPath(fs, configPath)) {
1860
+ return { action: "rename", newPath: versionPathFor(configPath) ?? `${configName}.version` };
1861
+ }
1862
+ return { action: "delete" };
1863
+ }
1864
+ async function migrateVersionSidecars(fs, options = {}) {
1865
+ const root = options.root && options.root !== "" ? options.root : "/";
1866
+ const dryRun = options.dryRun ?? false;
1867
+ const replicas = options.replicas ?? [];
1868
+ const result = {
1869
+ renamed: [],
1870
+ deleted: [],
1871
+ remoteDeleted: [],
1872
+ failed: []
1873
+ };
1874
+ const stack = [root];
1875
+ while (stack.length > 0) {
1876
+ const dir = stack.pop();
1877
+ let entries;
1878
+ try {
1879
+ entries = await fs.readdir(dir);
1880
+ } catch {
1881
+ continue;
1882
+ }
1883
+ for (const entry of entries) {
1884
+ const full = joinPath3(dir, entry);
1885
+ let stat;
1886
+ try {
1887
+ stat = await fs.stat(full);
1888
+ } catch {
1889
+ continue;
1890
+ }
1891
+ if (isDir(stat)) {
1892
+ stack.push(full);
1893
+ continue;
1894
+ }
1895
+ const isLegacyVersion = entry.startsWith(".") && (entry.endsWith(".version") || entry.endsWith(".version.mtime"));
1896
+ if (!isLegacyVersion) continue;
1897
+ const legacyVerPath = entry.endsWith(".version.mtime") ? full.slice(0, -".mtime".length) : full;
1898
+ const target = await resolveTarget(fs, dir, entry);
1899
+ if (target.action === "skip") continue;
1900
+ const legacyMtimePath = `${legacyVerPath}.mtime`;
1901
+ const newMtimePath = target.newPath ? `${target.newPath}.mtime` : null;
1902
+ if (dryRun) {
1903
+ if (target.action === "rename") result.renamed.push(full);
1904
+ else result.deleted.push(full);
1905
+ continue;
1906
+ }
1585
1907
  try {
1586
- return new TextDecoder().decode(toBytes(await this.fs.readFile(p)));
1587
- } catch {
1908
+ if (target.action === "rename") {
1909
+ if (await existsPath(fs, target.newPath)) {
1910
+ await fs.unlink(legacyVerPath);
1911
+ result.deleted.push(full);
1912
+ } else {
1913
+ const content = await fs.readFile(legacyVerPath);
1914
+ const bytes = typeof content === "string" ? new TextEncoder().encode(content) : content;
1915
+ await fs.writeFile(target.newPath, bytes);
1916
+ await fs.unlink(legacyVerPath);
1917
+ result.renamed.push(full);
1918
+ }
1919
+ if (newMtimePath && await existsPath(fs, legacyMtimePath)) {
1920
+ try {
1921
+ const mc = await fs.readFile(legacyMtimePath);
1922
+ const mb = typeof mc === "string" ? new TextEncoder().encode(mc) : mc;
1923
+ await fs.writeFile(newMtimePath, mb);
1924
+ await fs.unlink(legacyMtimePath);
1925
+ } catch {
1926
+ }
1927
+ }
1928
+ } else {
1929
+ await fs.unlink(legacyVerPath);
1930
+ result.deleted.push(full);
1931
+ if (await existsPath(fs, legacyMtimePath)) {
1932
+ try {
1933
+ await fs.unlink(legacyMtimePath);
1934
+ } catch {
1935
+ }
1936
+ }
1937
+ }
1938
+ } catch (e) {
1939
+ result.failed.push(full);
1940
+ continue;
1941
+ }
1942
+ for (const rep of replicas) {
1943
+ for (const rp of [legacyVerPath, legacyMtimePath]) {
1944
+ try {
1945
+ await rep.unlink(rp);
1946
+ result.remoteDeleted.push(rp);
1947
+ } catch {
1948
+ }
1949
+ }
1588
1950
  }
1589
1951
  }
1590
- throw new Error(`Conflict backup not found: ${conflictId}/${fileType}`);
1591
- }
1592
- /** Resolve a conflict with raw (already serialized) content. */
1593
- async resolve(conflictId, mergedContent) {
1594
- for (const dir of this.candidatesFor(conflictId)) {
1595
- const metaPath = `${dir}/meta.json`;
1596
- const archive = await readJson(this.fs, metaPath);
1597
- if (!archive) continue;
1598
- const bytes = typeof mergedContent === "string" ? new TextEncoder().encode(mergedContent) : mergedContent;
1599
- await ensureParentDir2(this.fs, archive.conflictPath);
1600
- await this.fs.writeFile(archive.conflictPath, bytes);
1601
- await this.versions.record(archive.conflictPath, bytes);
1602
- await this.fs.writeFile(`${dir}/resolved`, bytes);
1603
- archive.resolvedBackupPath = "./resolved";
1604
- await writeJson(this.fs, metaPath, archive);
1605
- return;
1606
- }
1607
- throw new Error(`Failed to resolve conflict ${conflictId}: archive not found`);
1608
1952
  }
1609
- };
1953
+ return result;
1954
+ }
1610
1955
 
1611
1956
  // src/config-repo.ts
1612
- var log3 = createLogger3("zen-fs-config:config-repo");
1613
- var GROUP_DESCRIPTOR_FILE2 = `${META_DIR}/group.json`;
1957
+ var log5 = createLogger5("zen-fs-config:config-repo");
1958
+ var GROUP_DESCRIPTOR_FILE3 = `${META_DIR}/group.json`;
1614
1959
  var GROUP_TYPE_FILE = `${CONFIG_DIR}/group-type`;
1615
1960
  var LEGACY_GROUP_TYPE_FILE = `${META_DIR}/group-type`;
1616
1961
  var BACKENDS_FILE = `${META_DIR}/backends.json`;
@@ -1642,81 +1987,6 @@ async function isDirectoryPath(fs, absolutePath) {
1642
1987
  return false;
1643
1988
  }
1644
1989
  }
1645
- async function collectFilesUnder(fs, dir, out = []) {
1646
- const entries = await fs.readdir(dir);
1647
- for (const entry of entries) {
1648
- const child = dir === "/" ? `/${entry}` : `${dir}/${entry}`;
1649
- if (await isDirectoryPath(fs, child)) {
1650
- await collectFilesUnder(fs, child, out);
1651
- } else {
1652
- out.push(child);
1653
- }
1654
- }
1655
- return out;
1656
- }
1657
- async function collectDirectoriesUnder(fs, dir, out = []) {
1658
- out.push(dir);
1659
- let entries;
1660
- try {
1661
- entries = await fs.readdir(dir);
1662
- } catch {
1663
- return out;
1664
- }
1665
- for (const entry of entries) {
1666
- const child = dir === "/" ? `/${entry}` : `${dir}/${entry}`;
1667
- if (await isDirectoryPath(fs, child)) await collectDirectoriesUnder(fs, child, out);
1668
- }
1669
- return out;
1670
- }
1671
- async function removeDirectoryTree(fs, dir) {
1672
- let entries;
1673
- try {
1674
- entries = await fs.readdir(dir);
1675
- } catch {
1676
- return;
1677
- }
1678
- for (const entry of entries) {
1679
- const child = dir === "/" ? `/${entry}` : `${dir}/${entry}`;
1680
- if (await isDirectoryPath(fs, child)) await removeDirectoryTree(fs, child);
1681
- }
1682
- try {
1683
- await fs.rmdir?.(dir);
1684
- } catch {
1685
- }
1686
- }
1687
- async function collectFilesUnderAny(surfaces, dir, onError) {
1688
- const merged = /* @__PURE__ */ new Set();
1689
- for (const surface of surfaces) {
1690
- try {
1691
- for (const file of await collectFilesUnder(surface.fs, dir)) merged.add(file);
1692
- } catch (error) {
1693
- onError(surface.label, error);
1694
- }
1695
- }
1696
- return [...merged];
1697
- }
1698
- async function collectDirectoriesUnderStrict(fs, dir, out = []) {
1699
- out.push(dir);
1700
- const entries = await fs.readdir(dir);
1701
- for (const entry of entries) {
1702
- const child = dir === "/" ? `/${entry}` : `${dir}/${entry}`;
1703
- if (await isDirectoryPath(fs, child)) await collectDirectoriesUnderStrict(fs, child, out);
1704
- }
1705
- return out;
1706
- }
1707
- async function collectDirectoriesUnderAny(surfaces, dir, onError) {
1708
- const merged = /* @__PURE__ */ new Set();
1709
- for (const surface of surfaces) {
1710
- const found = [];
1711
- try {
1712
- await collectDirectoriesUnderStrict(surface.fs, dir, found);
1713
- } catch (error) {
1714
- onError(surface.label, error);
1715
- }
1716
- for (const child of found) merged.add(child);
1717
- }
1718
- return [...merged];
1719
- }
1720
1990
  async function isDirectoryAny(surfaces, path) {
1721
1991
  for (const surface of surfaces) {
1722
1992
  if (await isDirectoryPath(surface.fs, path)) return true;
@@ -1744,6 +2014,7 @@ function normalizeGroupName(value) {
1744
2014
  }
1745
2015
  var CONFIG_ONLY_PREFIXES = [CONFIG_DIR, NODES_DIR, SHARED_DIR];
1746
2016
  var LOCAL_IDB_BACKEND_ID = "local-idb";
2017
+ var TOMBSTONE_RECREATE_SKEW_MS = 3e3;
1747
2018
  function tombstoneFileName(filePath) {
1748
2019
  return `${encodeMetaPath(filePath)}.json`;
1749
2020
  }
@@ -1852,6 +2123,15 @@ var ConfigRepo = class {
1852
2123
  tombstoneConfirmations = /* @__PURE__ */ new Map();
1853
2124
  /** Per-backend sync state (successful pairs + connect failures). */
1854
2125
  backendStates = /* @__PURE__ */ new Map();
2126
+ /**
2127
+ * 本组的实例身份(UUID,见 `group-identity.ts`)。
2128
+ *
2129
+ * 它同时是同步边界:连接任何远端副本前先比对对方 `.meta/group.json` 里的
2130
+ * `instanceId`,不一致就不建同步对 —— 两个不同的同步组永不互相同步。
2131
+ */
2132
+ instanceId;
2133
+ /** 因归属他人而被跳过的后端 id → 原因,供 UI 展示。 */
2134
+ skippedBackends = /* @__PURE__ */ new Map();
1855
2135
  /** Last known backend descriptors, for the synchronous unified handle API. */
1856
2136
  backendDescriptorCache = [];
1857
2137
  /**
@@ -1923,7 +2203,7 @@ var ConfigRepo = class {
1923
2203
  const bytes = this.serializer.serialize(data, fullPath);
1924
2204
  this.configCache.set(fullPath, data);
1925
2205
  this.persistConfig(fullPath, bytes).catch((err) => {
1926
- log3.error(`[zen-fs-config] Failed to persist ${fullPath}:`, err);
2206
+ log5.error(`[zen-fs-config] Failed to persist ${fullPath}:`, err);
1927
2207
  });
1928
2208
  }
1929
2209
  // -----------------------------------------------------------------------
@@ -2040,19 +2320,22 @@ var ConfigRepo = class {
2040
2320
  // Tombstone (Deletion Tracking)
2041
2321
  // -----------------------------------------------------------------------
2042
2322
  /**
2043
- * Write the tombstone record for `filePath` under `.meta/tombstones/`.
2044
- * Records only metadata — it never creates the deleted file locally, and the
2323
+ * Write the tombstone record for `path` under `.meta/tombstones/`.
2324
+ * Records only metadata — it never creates the deleted path locally, and the
2045
2325
  * legacy `/.meta/.deleted/` archive is neither read nor written.
2326
+ *
2327
+ * `type: 'directory'` 表示这是一条目录墓碑:应用时按整棵树清理。
2046
2328
  */
2047
- async writeTombstoneFor(filePath) {
2048
- const normalizedPath = filePath.startsWith("/") ? filePath : "/" + filePath;
2329
+ async writeTombstoneFor(path, type) {
2330
+ const normalizedPath = normalizeTombstonePath(path);
2049
2331
  const tombstone = {
2050
2332
  path: normalizedPath,
2051
2333
  deletedAt: Date.now(),
2052
2334
  deletedBy: this.primaryBackendId,
2053
- confirmedBy: [this.primaryBackendId]
2335
+ confirmedBy: [this.primaryBackendId],
2336
+ ...type ? { type } : {}
2054
2337
  };
2055
- const tombstoneBytes = new TextEncoder().encode(JSON.stringify(tombstone, null, 2));
2338
+ const tombstoneBytes = new TextEncoder().encode(serializeTombstone(tombstone));
2056
2339
  const tombstonePath = tombstonePathFor(normalizedPath, TOMBSTONES_DIR);
2057
2340
  await this.ensureDir(tombstonePath);
2058
2341
  await this.cachedFS.writeFile(tombstonePath, tombstoneBytes);
@@ -2063,29 +2346,17 @@ var ConfigRepo = class {
2063
2346
  */
2064
2347
  async deleteFile(path) {
2065
2348
  this.assertNotDisposed();
2066
- const normalizedPath = path.startsWith("/") ? path : "/" + path;
2349
+ const normalizedPath = normalizeTombstonePath(path);
2067
2350
  const surfaces = [{ label: "local-cache", fs: this.cachedFS }];
2068
2351
  for (const [id, replica] of this.replicaBackends) {
2069
2352
  surfaces.push({ label: id, fs: replica.instance });
2070
2353
  }
2071
- const onEnumerateError = (label, error) => {
2072
- const reason = error?.message ?? String(error);
2073
- log3.warn(
2074
- `[ConfigRepo] deleteFile(directory): cannot enumerate "${label}" under ${normalizedPath}: ${reason}`
2075
- );
2076
- };
2077
2354
  if (await isDirectoryAny(surfaces, normalizedPath)) {
2078
- const files = await collectFilesUnderAny(surfaces, normalizedPath, onEnumerateError);
2079
- for (const file of files) await this.deleteFile(file);
2080
- for (const dir of await collectDirectoriesUnderAny(surfaces, normalizedPath, onEnumerateError)) {
2081
- const keepPath = dir === "/" ? "/.keep" : `${dir}/.keep`;
2082
- await this.writeTombstoneFor(keepPath);
2083
- await this.writeTombstoneFor(`${keepPath}.mtime`);
2084
- }
2085
- await removeDirectoryTree(this.cachedFS, normalizedPath);
2355
+ await this.writeTombstoneFor(normalizedPath, "directory");
2356
+ await this.purgePathOnBackend(this.cachedFS, normalizedPath);
2086
2357
  this.invalidateTombstoneCache();
2087
2358
  this.schedulePostDeleteSync();
2088
- log3.log(`[ConfigRepo] deleteFile(directory): ${normalizedPath} (${files.length} file(s))`);
2359
+ log5.log(`[ConfigRepo] deleteFile(directory): ${normalizedPath} (single directory tombstone)`);
2089
2360
  return;
2090
2361
  }
2091
2362
  await this.writeTombstoneFor(normalizedPath);
@@ -2106,7 +2377,7 @@ var ConfigRepo = class {
2106
2377
  } catch {
2107
2378
  }
2108
2379
  }
2109
- log3.log(`[ConfigRepo] deleteFile: ${normalizedPath} (tombstone at ${tombstonePathFor(normalizedPath)})`);
2380
+ log5.log(`[ConfigRepo] deleteFile: ${normalizedPath} (tombstone at ${tombstonePathFor(normalizedPath)})`);
2110
2381
  this.invalidateTombstoneCache();
2111
2382
  this.schedulePostDeleteSync();
2112
2383
  }
@@ -2124,7 +2395,7 @@ var ConfigRepo = class {
2124
2395
  this.postDeleteSyncTimer = void 0;
2125
2396
  if (this.disposed) return;
2126
2397
  this.syncEngine.syncAll().catch((err) => {
2127
- log3.warn("[ConfigRepo] post-delete sync failed:", err);
2398
+ log5.warn("[ConfigRepo] post-delete sync failed:", err);
2128
2399
  });
2129
2400
  }, 500);
2130
2401
  }
@@ -2136,7 +2407,7 @@ var ConfigRepo = class {
2136
2407
  if (this.tombstoneCache !== null) {
2137
2408
  return this.tombstoneCache;
2138
2409
  }
2139
- this.tombstoneCache = await readTombstonesFromFs(this.cachedFS, (message) => log3.warn(message));
2410
+ this.tombstoneCache = await readTombstonesFromFs(this.cachedFS, (message) => log5.warn(message));
2140
2411
  this.refreshSyncExclusions(this.tombstoneCache);
2141
2412
  return this.tombstoneCache;
2142
2413
  }
@@ -2154,16 +2425,40 @@ var ConfigRepo = class {
2154
2425
  for (const tombstone of tombstones) {
2155
2426
  if (!tombstone.path) continue;
2156
2427
  add(tombstone.path);
2157
- if (tombstone.path === "/.keep" || tombstone.path.endsWith("/.keep") || tombstone.path.endsWith("/.keep.mtime")) {
2158
- const dir = tombstone.path.slice(0, tombstone.path.lastIndexOf("/")) || "/";
2159
- if (dir !== "/") add(dir);
2160
- }
2161
2428
  }
2162
2429
  }
2163
2430
  /** Invalidate the tombstone cache — call after tombstones are modified. */
2164
2431
  invalidateTombstoneCache() {
2165
2432
  this.tombstoneCache = null;
2166
2433
  }
2434
+ /**
2435
+ * 判定墓碑目标路径是否在删除之后被重新创建。
2436
+ *
2437
+ * 墓碑表达的是「删除意图」,但删除之后同一路径完全可能被再次写入。同步类工具
2438
+ * 的锁文件(`.sync.lock`)就是每轮「删除 → 重建」;若把墓碑当作永久否决权,
2439
+ * 这个路径会被每一轮 sync 反复删除,表现为「刚写进去 1 秒后就消失」、锁永远拿
2440
+ * 不到、深层目录刚建就没了。
2441
+ *
2442
+ * 判定依据是文件 mtime 晚于 `deletedAt`:写入必然刷新 mtime,因此 mtime 比删除
2443
+ * 时刻新就意味着这条墓碑已经被写操作撤销。
2444
+ */
2445
+ async isPathRecreatedAfterTombstone(tombstone) {
2446
+ const surfaces = [{ label: "local-cache", fs: this.cachedFS }];
2447
+ for (const [id, replica] of this.replicaBackends) {
2448
+ surfaces.push({ label: id, fs: replica.instance });
2449
+ }
2450
+ for (const surface of surfaces) {
2451
+ let mtimeMs;
2452
+ try {
2453
+ const inode = await surface.fs.stat(tombstone.path);
2454
+ mtimeMs = Number(inode?.mtimeMs ?? 0);
2455
+ } catch {
2456
+ continue;
2457
+ }
2458
+ if (mtimeMs > tombstone.deletedAt + TOMBSTONE_RECREATE_SKEW_MS) return true;
2459
+ }
2460
+ return false;
2461
+ }
2167
2462
  /**
2168
2463
  * Before sync: for each tombstone, delete the actual file on all replicas.
2169
2464
  * This prevents bi-directional sync from copying the file back.
@@ -2181,10 +2476,16 @@ var ConfigRepo = class {
2181
2476
  let processed = 0;
2182
2477
  let alreadyDeleted = 0;
2183
2478
  let unresolved = 0;
2479
+ const expired = [];
2184
2480
  for (const tombstone of tombstones) {
2185
2481
  const isKeepPlaceholder = tombstone.path === "/.keep" || tombstone.path.endsWith("/.keep");
2186
2482
  const forceDelete = isMtimeSidecar(tombstone.path) || isKeepPlaceholder;
2187
- const tVersionPath = forceDelete ? null : versionPathFor(tombstone.path);
2483
+ const isDirTombstone = isDirectoryTombstone(tombstone);
2484
+ const tVersionPath = forceDelete || isDirTombstone ? null : versionPathFor(tombstone.path);
2485
+ if (!forceDelete && await this.isPathRecreatedAfterTombstone(tombstone)) {
2486
+ expired.push(tombstone);
2487
+ continue;
2488
+ }
2188
2489
  const sidecarOwner = sidecarOwnerPath(tombstone.path);
2189
2490
  const isKeepSidecar = sidecarOwner === "/.keep" || (sidecarOwner?.endsWith("/.keep") ?? false);
2190
2491
  const liveSidecarCandidate = sidecarOwner !== null && !isKeepSidecar;
@@ -2238,14 +2539,27 @@ var ConfigRepo = class {
2238
2539
  confirmed.add(replicaId);
2239
2540
  } else {
2240
2541
  unresolved++;
2241
- log3.warn(
2542
+ log5.warn(
2242
2543
  `[ConfigRepo] tombstone kept: ${tombstone.path} still present on replica ${replicaId}`
2243
2544
  );
2244
2545
  }
2245
2546
  }
2246
2547
  }
2548
+ if (expired.length > 0) {
2549
+ for (const tombstone of expired) {
2550
+ try {
2551
+ await this.cachedFS.unlink(tombstonePathFor(tombstone.path, TOMBSTONES_DIR));
2552
+ } catch {
2553
+ }
2554
+ }
2555
+ this.invalidateTombstoneCache();
2556
+ await this.readTombstones();
2557
+ log5.log(
2558
+ `[ConfigRepo] processTombstones: expired ${expired.length} tombstone(s) \u2014 path recreated after deletion`
2559
+ );
2560
+ }
2247
2561
  if (processed > 0 || alreadyDeleted > 0 || unresolved > 0) {
2248
- log3.log(
2562
+ log5.log(
2249
2563
  `[ConfigRepo] processTombstones: ${tombstones.length} tombstone(s), ${processed} deleted, ${alreadyDeleted} already gone, ${unresolved} unresolved`
2250
2564
  );
2251
2565
  }
@@ -2346,21 +2660,21 @@ var ConfigRepo = class {
2346
2660
  const innerBackendName = fs?.inner?.backendName;
2347
2661
  const directBackendName = fs?.backendName;
2348
2662
  const backendLabel = innerBackendName ?? directBackendName ?? innerBackend ?? ctorName;
2349
- log3.log(`[TOMB-TRACE] safeExists(${path}): fs type=${ctorName} backend=${backendLabel} hasExists=${hasExists} hasStat=${hasStat} inner=${innerBackend ?? "N/A"}`);
2663
+ log5.log(`[TOMB-TRACE] safeExists(${path}): fs type=${ctorName} backend=${backendLabel} hasExists=${hasExists} hasStat=${hasStat} inner=${innerBackend ?? "N/A"}`);
2350
2664
  if (hasExists) {
2351
- log3.log(`[TOMB-TRACE] safeExists(${path}): \u2192 calling fs.exists() [backend=${backendLabel}]`);
2665
+ log5.log(`[TOMB-TRACE] safeExists(${path}): \u2192 calling fs.exists() [backend=${backendLabel}]`);
2352
2666
  const result = await fs.exists(path);
2353
- log3.log(`[TOMB-TRACE] safeExists(${path}): \u2190 fs.exists() [backend=${backendLabel}] \u2192 ${result}`);
2667
+ log5.log(`[TOMB-TRACE] safeExists(${path}): \u2190 fs.exists() [backend=${backendLabel}] \u2192 ${result}`);
2354
2668
  return result;
2355
2669
  }
2356
- log3.log(`[TOMB-TRACE] safeExists(${path}): no exists(), calling fs.stat() [backend=${backendLabel}]`);
2670
+ log5.log(`[TOMB-TRACE] safeExists(${path}): no exists(), calling fs.stat() [backend=${backendLabel}]`);
2357
2671
  await fs.stat(path);
2358
- log3.log(`[TOMB-TRACE] safeExists(${path}): \u2190 fs.stat() [backend=${backendLabel}] \u2192 OK (exists)`);
2672
+ log5.log(`[TOMB-TRACE] safeExists(${path}): \u2190 fs.stat() [backend=${backendLabel}] \u2192 OK (exists)`);
2359
2673
  return true;
2360
2674
  } catch (err) {
2361
2675
  const errCode = err?.code ?? err?.status ?? "";
2362
2676
  const errName = err?.constructor?.name ?? "";
2363
- log3.log(`[TOMB-TRACE] safeExists(${path}): \u2190 ERROR ${errName} ${errCode} ${err?.message ?? err}`);
2677
+ log5.log(`[TOMB-TRACE] safeExists(${path}): \u2190 ERROR ${errName} ${errCode} ${err?.message ?? err}`);
2364
2678
  return false;
2365
2679
  }
2366
2680
  }
@@ -2387,13 +2701,13 @@ var ConfigRepo = class {
2387
2701
  this.assertNotDisposed();
2388
2702
  const result = await purgeMtimeSidecars(this.cachedFS, options);
2389
2703
  if (result.removed.length > 0) {
2390
- log3.log(
2704
+ log5.log(
2391
2705
  `[ConfigRepo] purged ${result.removed.length} .mtime sidecar(s) from local primary` + (options?.dryRun ? " (dry run)" : ""),
2392
2706
  result.removed
2393
2707
  );
2394
2708
  }
2395
2709
  if (result.failed.length > 0) {
2396
- log3.warn(`[ConfigRepo] failed to purge ${result.failed.length} .mtime sidecar(s):`, result.failed);
2710
+ log5.warn(`[ConfigRepo] failed to purge ${result.failed.length} .mtime sidecar(s):`, result.failed);
2397
2711
  }
2398
2712
  return result;
2399
2713
  }
@@ -2413,13 +2727,13 @@ var ConfigRepo = class {
2413
2727
  this.assertNotDisposed();
2414
2728
  const result = await purgeKeepFiles(this.cachedFS, options);
2415
2729
  if (result.removed.length > 0) {
2416
- log3.log(
2730
+ log5.log(
2417
2731
  `[ConfigRepo] purged ${result.removed.length} .keep placeholder(s) from local primary` + (options?.dryRun ? " (dry run)" : ""),
2418
2732
  result.removed
2419
2733
  );
2420
2734
  }
2421
2735
  if (result.failed.length > 0) {
2422
- log3.warn(`[ConfigRepo] failed to purge ${result.failed.length} .keep placeholder(s):`, result.failed);
2736
+ log5.warn(`[ConfigRepo] failed to purge ${result.failed.length} .keep placeholder(s):`, result.failed);
2423
2737
  }
2424
2738
  return result;
2425
2739
  }
@@ -2438,24 +2752,24 @@ var ConfigRepo = class {
2438
2752
  }));
2439
2753
  const result = await migrateVersionSidecars(this.cachedFS, { replicas });
2440
2754
  if (result.renamed.length > 0) {
2441
- log3.log(
2755
+ log5.log(
2442
2756
  `[ConfigRepo] migrated ${result.renamed.length} legacy version sidecar(s) to new naming`,
2443
2757
  result.renamed
2444
2758
  );
2445
2759
  }
2446
2760
  if (result.deleted.length > 0) {
2447
- log3.log(
2761
+ log5.log(
2448
2762
  `[ConfigRepo] removed ${result.deleted.length} orphaned legacy version sidecar(s)`,
2449
2763
  result.deleted
2450
2764
  );
2451
2765
  }
2452
2766
  if (result.remoteDeleted.length > 0) {
2453
- log3.log(
2767
+ log5.log(
2454
2768
  `[ConfigRepo] removed ${result.remoteDeleted.length} remote residual legacy version sidecar(s)`
2455
2769
  );
2456
2770
  }
2457
2771
  if (result.failed.length > 0) {
2458
- log3.warn(`[ConfigRepo] failed to migrate ${result.failed.length} legacy version sidecar(s):`, result.failed);
2772
+ log5.warn(`[ConfigRepo] failed to migrate ${result.failed.length} legacy version sidecar(s):`, result.failed);
2459
2773
  }
2460
2774
  return result;
2461
2775
  }
@@ -2478,9 +2792,9 @@ var ConfigRepo = class {
2478
2792
  */
2479
2793
  startBackgroundSync() {
2480
2794
  this.initialSyncPromise = this.initialSyncAndDedup().then(() => {
2481
- log3.log("[ConfigRepo] Background initial sync complete");
2795
+ log5.log("[ConfigRepo] Background initial sync complete");
2482
2796
  }).catch((err) => {
2483
- log3.error("[ConfigRepo] Background initial sync failed:", err);
2797
+ log5.error("[ConfigRepo] Background initial sync failed:", err);
2484
2798
  }).finally(() => {
2485
2799
  this.initialSyncPromise = null;
2486
2800
  });
@@ -2509,7 +2823,7 @@ var ConfigRepo = class {
2509
2823
  }
2510
2824
  if (changed) {
2511
2825
  try {
2512
- const bytes = new TextEncoder().encode(JSON.stringify(tombstone, null, 2));
2826
+ const bytes = new TextEncoder().encode(serializeTombstone(tombstone));
2513
2827
  const tombstonePath = tombstonePathFor(tombstone.path, TOMBSTONES_DIR);
2514
2828
  if (await this.safeExists(this.cachedFS, tombstonePath)) {
2515
2829
  await this.cachedFS.writeFile(tombstonePath, bytes);
@@ -2519,7 +2833,7 @@ var ConfigRepo = class {
2519
2833
  }
2520
2834
  }
2521
2835
  }
2522
- log3.log(`[ConfigRepo] updateTombstoneConfirmations: ${modified} tombstone(s) updated`);
2836
+ log5.log(`[ConfigRepo] updateTombstoneConfirmations: ${modified} tombstone(s) updated`);
2523
2837
  if (modified > 0) this.invalidateTombstoneCache();
2524
2838
  }
2525
2839
  /**
@@ -2557,7 +2871,12 @@ var ConfigRepo = class {
2557
2871
  const tombstones = await this.readTombstones();
2558
2872
  if (tombstones.length === 0) return;
2559
2873
  const allBackendIds = [...this.replicaBackends.keys()];
2874
+ let keptByRetention = 0;
2560
2875
  for (const tombstone of tombstones) {
2876
+ if (!isTombstoneRetentionElapsed(tombstone)) {
2877
+ keptByRetention++;
2878
+ continue;
2879
+ }
2561
2880
  const allConfirmed = await this.allReplicasConfirmAbsent(tombstone.path);
2562
2881
  if (allConfirmed) {
2563
2882
  const tombstonePath = tombstonePathFor(tombstone.path, TOMBSTONES_DIR);
@@ -2573,9 +2892,12 @@ var ConfigRepo = class {
2573
2892
  }
2574
2893
  }
2575
2894
  }
2576
- log3.log(`[ConfigRepo] gcTombstones: removed ${tombstonePath} (all ${allBackendIds.length} backends confirmed)`);
2895
+ log5.log(`[ConfigRepo] gcTombstones: removed ${tombstonePath} (all ${allBackendIds.length} backends confirmed)`);
2577
2896
  }
2578
2897
  }
2898
+ if (keptByRetention > 0) {
2899
+ log5.log(`[ConfigRepo] gcTombstones: kept ${keptByRetention} tombstone(s) within retention window`);
2900
+ }
2579
2901
  }
2580
2902
  /**
2581
2903
  * Sync .meta/ files (backends.json) to all replica backends.
@@ -2589,7 +2911,7 @@ var ConfigRepo = class {
2589
2911
  this.assertNotDisposed();
2590
2912
  const results = await this.flush();
2591
2913
  for (const result of results) {
2592
- log3.log(
2914
+ log5.log(
2593
2915
  `[ConfigRepo] syncMetaToReplicas: ${result.pairId} +${result.filesCreated}/~${result.filesUpdated}/-${result.filesDeleted} skip:${result.filesSkipped} ${result.durationMs}ms`
2594
2916
  );
2595
2917
  }
@@ -2762,21 +3084,29 @@ var ConfigRepo = class {
2762
3084
  // Internal — Setup
2763
3085
  // -----------------------------------------------------------------------
2764
3086
  async setupSync(backends, primaryBackendId, pollIntervalMs) {
2765
- log3.log(`[ConfigRepo] setupSync: ${backends.length} backends, primary=${primaryBackendId} pollInterval=${pollIntervalMs ?? "default"}ms`);
3087
+ log5.log(`[ConfigRepo] setupSync: ${backends.length} backends, primary=${primaryBackendId} pollInterval=${pollIntervalMs ?? "default"}ms`);
2766
3088
  for (const desc of backends) {
2767
3089
  if (desc.id === primaryBackendId) continue;
2768
3090
  if (desc.enabled === false) {
2769
- log3.log(`[ConfigRepo] Skipping disabled replica: ${desc.id}`);
3091
+ log5.log(`[ConfigRepo] Skipping disabled replica: ${desc.id}`);
2770
3092
  continue;
2771
3093
  }
2772
- log3.log(`[ConfigRepo] Creating replica backend: id=${desc.id}, type=${desc.type}`);
3094
+ log5.log(`[ConfigRepo] Creating replica backend: id=${desc.id}, type=${desc.type}`);
2773
3095
  try {
2774
3096
  const instance = await createBackend(desc);
3097
+ const owner = await this.bindBackendIdentity(instance, desc.id);
3098
+ if (owner === "conflict") {
3099
+ try {
3100
+ await instance.dispose?.();
3101
+ } catch {
3102
+ }
3103
+ continue;
3104
+ }
2775
3105
  let fsInstance = instance;
2776
3106
  if (this.cacheOptions) {
2777
3107
  const { wrapWithCache } = await import("./cache-wrapper-S5HRLRQX.mjs");
2778
3108
  fsInstance = wrapWithCache(instance, desc.id, this.cacheOptions);
2779
- log3.log(`[ConfigRepo] Replica ${desc.id} wrapped with CachedFileSystem (store=${this.cacheOptions.storeType ?? "IdbCacheStore"})`);
3109
+ log5.log(`[ConfigRepo] Replica ${desc.id} wrapped with CachedFileSystem (store=${this.cacheOptions.storeType ?? "IdbCacheStore"})`);
2780
3110
  }
2781
3111
  const syncable = backendToSyncableFS(fsInstance, `${desc.type}(${desc.id})`);
2782
3112
  const pair = this.syncEngine.addPair(
@@ -2794,7 +3124,7 @@ var ConfigRepo = class {
2794
3124
  this.invalidateTombstoneCache();
2795
3125
  await this.processTombstones();
2796
3126
  } catch (err) {
2797
- log3.warn("[ConfigRepo] preSyncHook processTombstones failed:", err);
3127
+ log5.warn("[ConfigRepo] preSyncHook processTombstones failed:", err);
2798
3128
  }
2799
3129
  },
2800
3130
  postSyncHook: async () => {
@@ -2803,7 +3133,7 @@ var ConfigRepo = class {
2803
3133
  await this.processTombstones();
2804
3134
  await this.updateTombstoneConfirmations();
2805
3135
  } catch (err) {
2806
- log3.warn("[ConfigRepo] postSyncHook tombstone processing failed:", err);
3136
+ log5.warn("[ConfigRepo] postSyncHook tombstone processing failed:", err);
2807
3137
  }
2808
3138
  }
2809
3139
  },
@@ -2816,9 +3146,9 @@ var ConfigRepo = class {
2816
3146
  };
2817
3147
  this.syncEngine.on(pair.pairId, "conflict", conflictHandler);
2818
3148
  this.trackSyncErrors(desc.id, pair.pairId);
2819
- log3.log(`[ConfigRepo] Replica ${desc.id} created, sync pair=${pair.pairId}`);
3149
+ log5.log(`[ConfigRepo] Replica ${desc.id} created, sync pair=${pair.pairId}`);
2820
3150
  } catch (err) {
2821
- log3.error(`[ConfigRepo] Failed to create replica ${desc.id} (${desc.type}):`, err);
3151
+ log5.error(`[ConfigRepo] Failed to create replica ${desc.id} (${desc.type}):`, err);
2822
3152
  this.backendStates.set(desc.id, {
2823
3153
  backendId: desc.id,
2824
3154
  error: {
@@ -2828,8 +3158,8 @@ var ConfigRepo = class {
2828
3158
  });
2829
3159
  }
2830
3160
  }
2831
- log3.log(`[ConfigRepo] setupSync complete. Replicas:`, Array.from(this.replicaBackends.keys()));
2832
- log3.log(`[ConfigRepo] Sync statuses:`, this.getSyncStatuses());
3161
+ log5.log(`[ConfigRepo] setupSync complete. Replicas:`, Array.from(this.replicaBackends.keys()));
3162
+ log5.log(`[ConfigRepo] Sync statuses:`, this.getSyncStatuses());
2833
3163
  }
2834
3164
  // -----------------------------------------------------------------------
2835
3165
  // Internal — Persistence
@@ -2841,12 +3171,12 @@ var ConfigRepo = class {
2841
3171
  try {
2842
3172
  const existing = await readVersion(this.fullFS, vPath);
2843
3173
  if (existing && existing.hash === version.hash) {
2844
- log3.log("[ConfigRepo] skip version sidecar (hash unchanged):", vPath);
3174
+ log5.log("[ConfigRepo] skip version sidecar (hash unchanged):", vPath);
2845
3175
  return;
2846
3176
  }
2847
3177
  } catch {
2848
3178
  }
2849
- log3.log("[ConfigRepo] write version sidecar:", vPath, "v" + version.version);
3179
+ log5.log("[ConfigRepo] write version sidecar:", vPath, "v" + version.version);
2850
3180
  await this.ensureDir(vPath);
2851
3181
  await writeVersion(this.fullFS, vPath, version);
2852
3182
  }
@@ -2950,7 +3280,7 @@ var ConfigRepo = class {
2950
3280
  await this.resolveConflict(`${conflictId}/meta.json`, customMerge);
2951
3281
  }
2952
3282
  } catch (err) {
2953
- log3.error("[zen-fs-config] Conflict handler error:", err);
3283
+ log5.error("[zen-fs-config] Conflict handler error:", err);
2954
3284
  }
2955
3285
  }
2956
3286
  }
@@ -3066,11 +3396,11 @@ var ConfigRepo = class {
3066
3396
  }
3067
3397
  return { kind: "ok", desc, mtime };
3068
3398
  } else {
3069
- log3.warn(`[ConfigRepo] Backend descriptor ${entry} is missing id/type fields, marking for cleanup`);
3399
+ log5.warn(`[ConfigRepo] Backend descriptor ${entry} is missing id/type fields, marking for cleanup`);
3070
3400
  return { kind: "corrupt", filePath };
3071
3401
  }
3072
3402
  } catch (parseErr) {
3073
- log3.warn(`[ConfigRepo] Backend descriptor ${entry} has corrupted JSON: ${parseErr}. Marking for cleanup.`);
3403
+ log5.warn(`[ConfigRepo] Backend descriptor ${entry} has corrupted JSON: ${parseErr}. Marking for cleanup.`);
3074
3404
  return { kind: "corrupt", filePath };
3075
3405
  }
3076
3406
  })
@@ -3136,7 +3466,7 @@ var ConfigRepo = class {
3136
3466
  }
3137
3467
  }
3138
3468
  if (duplicates.length > 0) {
3139
- log3.log(
3469
+ log5.log(
3140
3470
  `[ConfigRepo] readAllBackendDescriptors: removing ${duplicates.length} duplicate(s): ${duplicates.join(", ")}`
3141
3471
  );
3142
3472
  for (const dupId of duplicates) {
@@ -3268,7 +3598,7 @@ var ConfigRepo = class {
3268
3598
  * Shared by addBackend() and replaceBackend().
3269
3599
  */
3270
3600
  async setupReplica(id, type, options, description) {
3271
- log3.log(`[ConfigRepo] addBackend: creating ${id} (${type})...`);
3601
+ log5.log(`[ConfigRepo] addBackend: creating ${id} (${type})...`);
3272
3602
  const instance = await createBackend({ type, options });
3273
3603
  const syncable = backendToSyncableFS(instance, `${type}(${id})`);
3274
3604
  const desc = { id, type, options, description };
@@ -3286,7 +3616,7 @@ var ConfigRepo = class {
3286
3616
  this.invalidateTombstoneCache();
3287
3617
  await this.processTombstones();
3288
3618
  } catch (err) {
3289
- log3.warn("[ConfigRepo] preSyncHook processTombstones failed:", err);
3619
+ log5.warn("[ConfigRepo] preSyncHook processTombstones failed:", err);
3290
3620
  }
3291
3621
  },
3292
3622
  postSyncHook: async () => {
@@ -3295,7 +3625,7 @@ var ConfigRepo = class {
3295
3625
  await this.processTombstones();
3296
3626
  await this.updateTombstoneConfirmations();
3297
3627
  } catch (err) {
3298
- log3.warn("[ConfigRepo] postSyncHook tombstone processing failed:", err);
3628
+ log5.warn("[ConfigRepo] postSyncHook tombstone processing failed:", err);
3299
3629
  }
3300
3630
  }
3301
3631
  },
@@ -3308,7 +3638,7 @@ var ConfigRepo = class {
3308
3638
  };
3309
3639
  this.syncEngine.on(pair.pairId, "conflict", conflictHandler);
3310
3640
  this.trackSyncErrors(id, pair.pairId);
3311
- log3.log(`[ConfigRepo] addBackend: ${id} (${type}) added, sync pair=${pair.pairId}`);
3641
+ log5.log(`[ConfigRepo] addBackend: ${id} (${type}) added, sync pair=${pair.pairId}`);
3312
3642
  await this.syncMetaToReplicas();
3313
3643
  this.syncEngine.watch(pair.pairId);
3314
3644
  return pair.pairId;
@@ -3334,13 +3664,13 @@ var ConfigRepo = class {
3334
3664
  }
3335
3665
  }
3336
3666
  this.syncEngine.removePair(replica.pairId);
3337
- log3.log(`[ConfigRepo] removeBackend: sync pair ${replica.pairId} removed`);
3667
+ log5.log(`[ConfigRepo] removeBackend: sync pair ${replica.pairId} removed`);
3338
3668
  this.replicaBackends.delete(id);
3339
3669
  if (replica.instance?.dispose) {
3340
3670
  await replica.instance.dispose();
3341
3671
  }
3342
3672
  } else {
3343
- log3.log(`[ConfigRepo] removeBackend: "${id}" not in replicaBackends, cleaning up descriptor only`);
3673
+ log5.log(`[ConfigRepo] removeBackend: "${id}" not in replicaBackends, cleaning up descriptor only`);
3344
3674
  for (const descPath of descPaths) {
3345
3675
  try {
3346
3676
  await this.deleteFile(descPath);
@@ -3351,7 +3681,7 @@ var ConfigRepo = class {
3351
3681
  }
3352
3682
  this.backendStates.delete(id);
3353
3683
  this.schedulePostDeleteSync();
3354
- log3.log(`[ConfigRepo] removeBackend: ${id} removed (tombstone written, remote cleaned)`);
3684
+ log5.log(`[ConfigRepo] removeBackend: ${id} removed (tombstone written, remote cleaned)`);
3355
3685
  }
3356
3686
  /**
3357
3687
  * Replace a config-sync backend's parameters in place (same id).
@@ -3398,11 +3728,11 @@ var ConfigRepo = class {
3398
3728
  await this.setupReplica(id, type, options, description ?? before.description);
3399
3729
  } catch (err) {
3400
3730
  const reason = err instanceof Error ? err.message : String(err);
3401
- log3.warn(`[ConfigRepo] replaceBackend: "${id}" failed, rolling back old options:`, err);
3731
+ log5.warn(`[ConfigRepo] replaceBackend: "${id}" failed, rolling back old options:`, err);
3402
3732
  try {
3403
3733
  await this.setupReplica(id, before.type, before.options, before.description);
3404
3734
  } catch (rollbackErr) {
3405
- log3.error(`[ConfigRepo] replaceBackend: rollback for "${id}" ALSO failed:`, rollbackErr);
3735
+ log5.error(`[ConfigRepo] replaceBackend: rollback for "${id}" ALSO failed:`, rollbackErr);
3406
3736
  }
3407
3737
  throw new Error(`\u66F4\u65B0\u540E\u7AEF\u53C2\u6570\u5931\u8D25\uFF1A${reason}\uFF08\u5DF2\u5C1D\u8BD5\u56DE\u6EDA\u65E7\u53C2\u6570\uFF09`);
3408
3738
  }
@@ -3410,6 +3740,80 @@ var ConfigRepo = class {
3410
3740
  // -----------------------------------------------------------------------
3411
3741
  // IConfigRepo — Group Type
3412
3742
  // -----------------------------------------------------------------------
3743
+ /**
3744
+ * 本组的同步身份(kind + id + 不可变 instanceId)。
3745
+ *
3746
+ * 首次调用时若 `.meta/group.json` 里还没有 `instanceId`(老部署),生成一个
3747
+ * 并就地写回 —— 只写一次,之后字节相同不再落盘。
3748
+ */
3749
+ async ensureGroupIdentity(kind = "config", id = CONFIG_GROUP_ID) {
3750
+ let existingFeatures;
3751
+ if (!this.instanceId) {
3752
+ let existing = null;
3753
+ try {
3754
+ existing = await readGroupDescriptor(this.cachedFS);
3755
+ } catch {
3756
+ }
3757
+ const known = pickInstanceId(existing);
3758
+ existingFeatures = existing?.features ?? CONFIG_GROUP_FEATURES;
3759
+ this.instanceId = known ?? newGroupInstanceId();
3760
+ if (!known) {
3761
+ try {
3762
+ await writeGroupDescriptor(this.cachedFS, {
3763
+ schemaVersion: 2,
3764
+ kind: existing?.kind ?? kind,
3765
+ id: existing?.id ?? id,
3766
+ instanceId: this.instanceId,
3767
+ ...existing?.name ?? this.name ? { name: existing?.name ?? this.name } : {},
3768
+ features: existing?.features ?? CONFIG_GROUP_FEATURES
3769
+ });
3770
+ log5.log(`[ConfigRepo] group instanceId assigned: ${this.instanceId} (kind=${existing?.kind ?? kind})`);
3771
+ } catch (err) {
3772
+ log5.warn("[ConfigRepo] failed to persist group instanceId:", err);
3773
+ }
3774
+ }
3775
+ }
3776
+ return {
3777
+ kind,
3778
+ id,
3779
+ instanceId: this.instanceId,
3780
+ ...this.name ? { name: this.name } : {},
3781
+ ...existingFeatures ? { features: existingFeatures } : {}
3782
+ };
3783
+ }
3784
+ /** 组实例身份(未初始化时先兜底生成并落盘)。 */
3785
+ async ensureGroupInstanceId() {
3786
+ return (await this.ensureGroupIdentity()).instanceId;
3787
+ }
3788
+ /** 组实例身份(同步读取;init 之前可能为 `undefined`)。 */
3789
+ getGroupInstanceId() {
3790
+ return this.instanceId;
3791
+ }
3792
+ /**
3793
+ * 连接远端前校验归属:属于别的组 → `conflict`(调用方必须跳过、不建同步对)。
3794
+ * 老仓库(无 instanceId)会被本组认领。
3795
+ */
3796
+ async bindBackendIdentity(instance, backendId) {
3797
+ try {
3798
+ const identity = await this.ensureGroupIdentity();
3799
+ const state = await bindRemoteGroupIdentity(instance, identity);
3800
+ if (state === "conflict") {
3801
+ this.skippedBackends.set(
3802
+ backendId,
3803
+ `\u8FDC\u7AEF\u6839\u5C5E\u4E8E\u53E6\u4E00\u4E2A\u540C\u6B65\u7EC4\uFF08instanceId \u4E0D\u4E00\u81F4\uFF09\uFF0C\u5DF2\u8DF3\u8FC7\u8BE5\u540E\u7AEF`
3804
+ );
3805
+ }
3806
+ return state;
3807
+ } catch (err) {
3808
+ log5.warn(`[ConfigRepo] identity check failed for backend "${backendId}", skipping it:`, err);
3809
+ this.skippedBackends.set(backendId, `\u5F52\u5C5E\u6821\u9A8C\u5931\u8D25\uFF1A${err?.message ?? String(err)}`);
3810
+ return "conflict";
3811
+ }
3812
+ }
3813
+ /** 因归属他人而被跳过的后端(id → 原因)。 */
3814
+ listSkippedBackends() {
3815
+ return Array.from(this.skippedBackends, ([backendId, reason]) => ({ backendId, reason }));
3816
+ }
3413
3817
  /** Write the group-type marker file if it doesn't exist. */
3414
3818
  async ensureGroupType(type) {
3415
3819
  this.assertNotDisposed();
@@ -3418,7 +3822,7 @@ var ConfigRepo = class {
3418
3822
  const existing = await this.cachedFS.readFile(path, "utf-8");
3419
3823
  const current = existing.trim();
3420
3824
  if (current && current !== type) {
3421
- log3.warn(`[ConfigRepo] group-type already set to "${current}" at ${path}, ignoring request to set "${type}"`);
3825
+ log5.warn(`[ConfigRepo] group-type already set to "${current}" at ${path}, ignoring request to set "${type}"`);
3422
3826
  return;
3423
3827
  }
3424
3828
  } catch {
@@ -3432,10 +3836,12 @@ var ConfigRepo = class {
3432
3836
  }
3433
3837
  const existingDescriptor = await readGroupDescriptor(this.cachedFS);
3434
3838
  if (!existingDescriptor) {
3839
+ this.instanceId = newGroupInstanceId();
3435
3840
  await writeGroupDescriptor(this.cachedFS, {
3436
3841
  schemaVersion: 2,
3437
3842
  kind: "config",
3438
3843
  id: CONFIG_GROUP_ID,
3844
+ instanceId: this.instanceId,
3439
3845
  ...this.name ? { name: this.name } : {},
3440
3846
  features: CONFIG_GROUP_FEATURES
3441
3847
  });
@@ -3449,7 +3855,22 @@ var ConfigRepo = class {
3449
3855
  features: existingDescriptor.features ?? CONFIG_GROUP_FEATURES
3450
3856
  });
3451
3857
  }
3452
- log3.log(`[ConfigRepo] group-type set to "${type}"`);
3858
+ const knownInstanceId = pickInstanceId(existingDescriptor);
3859
+ if (knownInstanceId) {
3860
+ this.instanceId = knownInstanceId;
3861
+ } else if (!this.instanceId) {
3862
+ this.instanceId = newGroupInstanceId();
3863
+ await writeGroupDescriptor(this.cachedFS, {
3864
+ schemaVersion: 2,
3865
+ kind: existingDescriptor?.kind ?? "config",
3866
+ id: existingDescriptor?.id ?? CONFIG_GROUP_ID,
3867
+ instanceId: this.instanceId,
3868
+ ...existingDescriptor?.name ?? this.name ? { name: existingDescriptor?.name ?? this.name } : {},
3869
+ ...existingDescriptor?.features ? { features: existingDescriptor.features } : {}
3870
+ });
3871
+ log5.log(`[ConfigRepo] assigned group instanceId ${this.instanceId} (kind=${existingDescriptor?.kind ?? "config"})`);
3872
+ }
3873
+ log5.log(`[ConfigRepo] group-type set to "${type}"`);
3453
3874
  }
3454
3875
  /** Read the group-type marker. Returns null if not set (new path, then legacy). */
3455
3876
  async getGroupType() {
@@ -3544,7 +3965,7 @@ var ConfigRepo = class {
3544
3965
  if (this.appDataGroups.has(id)) {
3545
3966
  throw new Error(`App data group "${id}" already exists. Use removeAppDataGroup() first.`);
3546
3967
  }
3547
- log3.log(`[ConfigRepo] createAppDataGroup: creating "${id}" with ${backends.length} backend(s)`);
3968
+ log5.log(`[ConfigRepo] createAppDataGroup: creating "${id}" with ${backends.length} backend(s)`);
3548
3969
  const resolvedBackends = [];
3549
3970
  for (const desc of backends) {
3550
3971
  assertValidBackendId(desc.id);
@@ -3552,6 +3973,7 @@ var ConfigRepo = class {
3552
3973
  resolvedBackends.push({ ...desc, options: mergedOptions });
3553
3974
  }
3554
3975
  await this.assertNoSharedRemote(resolvedBackends, id);
3976
+ const instanceId = newGroupInstanceId();
3555
3977
  const group = new AppDataGroupImpl(
3556
3978
  id,
3557
3979
  this.appId,
@@ -3559,19 +3981,25 @@ var ConfigRepo = class {
3559
3981
  this.pollIntervalMs,
3560
3982
  this,
3561
3983
  // 显式新拓扑:以参数为准并写入 `.meta/backends/`。
3562
- { name: options.name, features: options.features, backendsAreAuthoritative: true }
3984
+ {
3985
+ name: options.name,
3986
+ features: options.features,
3987
+ backendsAreAuthoritative: true,
3988
+ instanceId
3989
+ }
3563
3990
  );
3564
3991
  await group.init();
3565
3992
  const descriptor = {
3566
3993
  id,
3567
3994
  groupType: "data-sync",
3995
+ instanceId: group.getGroupInstanceId() ?? instanceId,
3568
3996
  ...options.name ? { name: options.name } : {},
3569
3997
  ...options.features ? { features: options.features } : {},
3570
3998
  backends: group.listDeclaredBackends()
3571
3999
  };
3572
4000
  await this.writeAppDataGroupDescriptorFile(id, descriptor);
3573
4001
  this.appDataGroups.set(id, group);
3574
- log3.log(`[ConfigRepo] createAppDataGroup: "${id}" created`);
4002
+ log5.log(`[ConfigRepo] createAppDataGroup: "${id}" created`);
3575
4003
  return group;
3576
4004
  }
3577
4005
  /**
@@ -3588,9 +4016,13 @@ var ConfigRepo = class {
3588
4016
  const existing = await this.readAppDataGroupDescriptor(id);
3589
4017
  const name = meta?.name ?? existing?.name;
3590
4018
  const features = meta?.features ?? existing?.features;
4019
+ const liveGroup = this.appDataGroups.get(id);
4020
+ const liveInstanceId = liveGroup?.getGroupInstanceId();
4021
+ const instanceId = pickInstanceId(existing) ?? (isValidGroupInstanceId(liveInstanceId) ? liveInstanceId : void 0);
3591
4022
  const descriptor = {
3592
4023
  id,
3593
4024
  groupType: "data-sync",
4025
+ ...instanceId ? { instanceId } : {},
3594
4026
  ...name ? { name } : {},
3595
4027
  ...features ? { features } : {},
3596
4028
  backends
@@ -3614,7 +4046,7 @@ var ConfigRepo = class {
3614
4046
  try {
3615
4047
  await live.writeOwnGroupDescriptor();
3616
4048
  } catch (err) {
3617
- log3.warn(`[ConfigRepo] updateAppDataGroupName: "${id}" group.json update failed:`, err);
4049
+ log5.warn(`[ConfigRepo] updateAppDataGroupName: "${id}" group.json update failed:`, err);
3618
4050
  }
3619
4051
  }
3620
4052
  const descriptor = {
@@ -3658,6 +4090,9 @@ var ConfigRepo = class {
3658
4090
  const nextBackends = declared.map(
3659
4091
  (b, i) => i === index ? { ...candidate, options: mergedOptions } : b
3660
4092
  );
4093
+ const descriptorNow = await this.readAppDataGroupDescriptor(groupId);
4094
+ const instanceIdFromLive = live?.getGroupInstanceId();
4095
+ const instanceId = pickInstanceId(descriptorNow) ?? (isValidGroupInstanceId(instanceIdFromLive) ? instanceIdFromLive : void 0);
3661
4096
  if (live) {
3662
4097
  await live.dispose();
3663
4098
  this.appDataGroups.delete(groupId);
@@ -3669,7 +4104,7 @@ var ConfigRepo = class {
3669
4104
  nextBackends,
3670
4105
  this.pollIntervalMs,
3671
4106
  this,
3672
- { backendsAreAuthoritative: true }
4107
+ { backendsAreAuthoritative: true, ...instanceId ? { instanceId } : {} }
3673
4108
  );
3674
4109
  await group.init();
3675
4110
  await this.updateAppDataGroupDescriptor(groupId, group.listDeclaredBackends());
@@ -3677,7 +4112,7 @@ var ConfigRepo = class {
3677
4112
  return group;
3678
4113
  } catch (err) {
3679
4114
  const reason = err instanceof Error ? err.message : String(err);
3680
- log3.warn(`[ConfigRepo] replaceAppDataGroupBackend: "${backendId}" failed, rolling back:`, err);
4115
+ log5.warn(`[ConfigRepo] replaceAppDataGroupBackend: "${backendId}" failed, rolling back:`, err);
3681
4116
  try {
3682
4117
  const restored = new AppDataGroupImpl(
3683
4118
  groupId,
@@ -3685,13 +4120,13 @@ var ConfigRepo = class {
3685
4120
  oldBackends,
3686
4121
  this.pollIntervalMs,
3687
4122
  this,
3688
- { backendsAreAuthoritative: true }
4123
+ { backendsAreAuthoritative: true, ...instanceId ? { instanceId } : {} }
3689
4124
  );
3690
4125
  await restored.init();
3691
4126
  await this.updateAppDataGroupDescriptor(groupId, restored.listDeclaredBackends());
3692
4127
  this.appDataGroups.set(groupId, restored);
3693
4128
  } catch (rollbackErr) {
3694
- log3.error("[ConfigRepo] replaceAppDataGroupBackend: rollback ALSO failed:", rollbackErr);
4129
+ log5.error("[ConfigRepo] replaceAppDataGroupBackend: rollback ALSO failed:", rollbackErr);
3695
4130
  }
3696
4131
  throw new Error(`\u66F4\u65B0\u540E\u7AEF\u53C2\u6570\u5931\u8D25\uFF1A${reason}\uFF08\u5DF2\u5C1D\u8BD5\u56DE\u6EDA\u65E7\u53C2\u6570\uFF09`);
3697
4132
  }
@@ -3729,10 +4164,12 @@ var ConfigRepo = class {
3729
4164
  const version = await incrementVersion(this.fullFS, path, bytes, author);
3730
4165
  await this.writeVersionSidecar(path, version);
3731
4166
  }
4167
+ const identity = await this.ensureGroupIdentity();
3732
4168
  await writeGroupDescriptor(this.cachedFS, {
3733
4169
  schemaVersion: 2,
3734
4170
  kind: "config",
3735
4171
  id: CONFIG_GROUP_ID,
4172
+ instanceId: identity.instanceId,
3736
4173
  name: normalized,
3737
4174
  features: CONFIG_GROUP_FEATURES
3738
4175
  });
@@ -3809,7 +4246,7 @@ var ConfigRepo = class {
3809
4246
  try {
3810
4247
  await this.deleteFile(descPath);
3811
4248
  } catch (err) {
3812
- log3.log(`[ConfigRepo] removeAppDataGroup: deleteFile failed for "${id}" at ${descPath}:`, err);
4249
+ log5.log(`[ConfigRepo] removeAppDataGroup: deleteFile failed for "${id}" at ${descPath}:`, err);
3813
4250
  try {
3814
4251
  await this.cachedFS.unlink(descPath);
3815
4252
  } catch {
@@ -3817,7 +4254,7 @@ var ConfigRepo = class {
3817
4254
  await this.unlinkVersionSidecar(this.cachedFS, descPath);
3818
4255
  }
3819
4256
  }
3820
- log3.log(`[ConfigRepo] removeAppDataGroup: "${id}" removed`);
4257
+ log5.log(`[ConfigRepo] removeAppDataGroup: "${id}" removed`);
3821
4258
  }
3822
4259
  async listAccountBackends() {
3823
4260
  this.assertNotDisposed();
@@ -3854,10 +4291,20 @@ var AppDataGroupImpl = class {
3854
4291
  versions;
3855
4292
  conflicts;
3856
4293
  postDeleteTimer;
4294
+ /**
4295
+ * 墓碑路径的同步排除表(与配置组同一套机制)。
4296
+ *
4297
+ * 保留期内的墓碑路径不参与同步:否则副本上的残留会被当作"远端内容"逐文件
4298
+ * 拉回本地,把已删除的目录复活。数组与各同步对共享同一实例(zen-fs-sync
4299
+ * 每次检测时实时读取 `filter.excludePrefixes`),原地更新即可生效。
4300
+ */
4301
+ tombstoneExcludePrefixes = [...CONFIG_ONLY_PREFIXES];
4302
+ syncFilter = { excludePrefixes: this.tombstoneExcludePrefixes };
3857
4303
  constructor(groupId, appId, backends, pollIntervalMs, parent, descriptor = {}) {
3858
4304
  this.groupId = groupId;
3859
4305
  this.appId = appId;
3860
4306
  this.name = descriptor.name;
4307
+ this.instanceId = isValidGroupInstanceId(descriptor.instanceId) ? descriptor.instanceId : void 0;
3861
4308
  this.features = {
3862
4309
  ...DATA_GROUP_DEFAULT_FEATURES,
3863
4310
  ...descriptor.features,
@@ -3875,6 +4322,13 @@ var AppDataGroupImpl = class {
3875
4322
  }
3876
4323
  parent;
3877
4324
  _backends;
4325
+ /**
4326
+ * 组实例身份(UUID)。同步边界:远端 `.meta/group.json` 的 `instanceId`
4327
+ * 不一致就不建同步对,因此不同同步组之间永不互相搬运数据。
4328
+ */
4329
+ instanceId;
4330
+ /** 因归属他人而被跳过的后端 id → 原因。 */
4331
+ skippedBackends = /* @__PURE__ */ new Map();
3878
4332
  _pollIntervalMs;
3879
4333
  _backendsAreAuthoritative;
3880
4334
  /** 引导副本(`.config/` 里的描述符)原有的能力位,用于回刷时不丢信息。 */
@@ -3971,14 +4425,64 @@ var AppDataGroupImpl = class {
3971
4425
  }
3972
4426
  /** Write this group's own `.meta/group.json` (idempotent: identical bytes → no write). */
3973
4427
  async writeOwnGroupDescriptor() {
4428
+ if (!this.instanceId) {
4429
+ this.instanceId = newGroupInstanceId();
4430
+ log5.log(`[AppDataGroup:${this.groupId}] assigned instanceId ${this.instanceId}`);
4431
+ }
3974
4432
  await writeGroupDescriptor(this.localFS, {
3975
4433
  schemaVersion: 2,
3976
4434
  kind: "data",
3977
4435
  id: this.groupId,
4436
+ instanceId: this.instanceId,
3978
4437
  ...this.name ? { name: this.name } : {},
3979
4438
  features: this.features
3980
4439
  });
3981
4440
  }
4441
+ /** 本组实例身份(初始化后可用)。 */
4442
+ getGroupInstanceId() {
4443
+ return this.instanceId;
4444
+ }
4445
+ /** 因归属他人而被跳过的后端(id → 原因)。 */
4446
+ listSkippedBackends() {
4447
+ return Array.from(this.skippedBackends, ([backendId, reason]) => ({ backendId, reason }));
4448
+ }
4449
+ /**
4450
+ * 连接数据后端前的归属校验。
4451
+ *
4452
+ * - `match`:远端 `.meta/group.json` 的 `instanceId` 与本组一致 → 建同步对;
4453
+ * - `claimed`:远端是老仓库(无身份)→ 本组认领并写入,再建同步对;
4454
+ * - `conflict`:远端属于另一个同步组(或类型不符 / 读不到)→ 跳过,
4455
+ * **绝不建立同步对**,因此跨组数据不会被搬运。
4456
+ */
4457
+ async checkBackendOwnership(instance, backendId) {
4458
+ if (!this.instanceId) {
4459
+ this.skippedBackends.set(backendId, "\u672C\u7EC4\u5C1A\u672A\u5206\u914D instanceId\uFF0C\u5DF2\u8DF3\u8FC7\u8BE5\u540E\u7AEF");
4460
+ return "conflict";
4461
+ }
4462
+ try {
4463
+ const state = await bindRemoteGroupIdentity(instance, {
4464
+ kind: "data",
4465
+ id: this.groupId,
4466
+ instanceId: this.instanceId,
4467
+ ...this.name ? { name: this.name } : {},
4468
+ features: this.features
4469
+ });
4470
+ if (state === "conflict") {
4471
+ this.skippedBackends.set(
4472
+ backendId,
4473
+ "\u8FDC\u7AEF\u6839\u5C5E\u4E8E\u53E6\u4E00\u4E2A\u540C\u6B65\u7EC4\uFF08instanceId \u4E0D\u4E00\u81F4\uFF09\uFF0C\u5DF2\u8DF3\u8FC7\u8BE5\u540E\u7AEF"
4474
+ );
4475
+ log5.warn(
4476
+ `[AppDataGroup:${this.groupId}] backend "${backendId}" belongs to another sync group \u2014 sync pair skipped`
4477
+ );
4478
+ }
4479
+ return state;
4480
+ } catch (err) {
4481
+ log5.warn(`[AppDataGroup:${this.groupId}] ownership check failed for "${backendId}":`, err);
4482
+ this.skippedBackends.set(backendId, `\u5F52\u5C5E\u6821\u9A8C\u5931\u8D25\uFF1A${err?.message ?? String(err)}`);
4483
+ return "conflict";
4484
+ }
4485
+ }
3982
4486
  async init() {
3983
4487
  const storeName = dataGroupLocalStoreName(this.appId, this.groupId);
3984
4488
  try {
@@ -4006,40 +4510,56 @@ var AppDataGroupImpl = class {
4006
4510
  try {
4007
4511
  const purged = await purgeMtimeSidecars(this.localFS);
4008
4512
  if (purged.removed.length > 0) {
4009
- log3.warn(
4513
+ log5.warn(
4010
4514
  `[AppDataGroup:${this.groupId}] purged ${purged.removed.length} leaked .mtime sidecar(s):`,
4011
4515
  purged.removed
4012
4516
  );
4013
4517
  }
4014
4518
  } catch (err) {
4015
- log3.warn(`[AppDataGroup:${this.groupId}] .mtime purge failed:`, err?.message ?? err);
4519
+ log5.warn(`[AppDataGroup:${this.groupId}] .mtime purge failed:`, err?.message ?? err);
4016
4520
  }
4017
4521
  try {
4018
4522
  const purgedKeep = await purgeKeepFiles(this.localFS);
4019
4523
  if (purgedKeep.removed.length > 0) {
4020
- log3.warn(
4524
+ log5.warn(
4021
4525
  `[AppDataGroup:${this.groupId}] purged ${purgedKeep.removed.length} leaked .keep placeholder(s):`,
4022
4526
  purgedKeep.removed
4023
4527
  );
4024
4528
  }
4025
4529
  } catch (err) {
4026
- log3.warn(`[AppDataGroup:${this.groupId}] .keep purge failed:`, err?.message ?? err);
4530
+ log5.warn(`[AppDataGroup:${this.groupId}] .keep purge failed:`, err?.message ?? err);
4027
4531
  }
4028
4532
  const localSyncable = backendToSyncableFS(this.localFS, `local(${this.groupId})`);
4029
4533
  this.tombstones = new TombstoneStore(this.localFS, this.localBackendId);
4030
4534
  this.versions = new VersionStore(this.localFS, `${this.appId}/${this.groupId}`);
4031
4535
  this.conflicts = new ConflictStore(this.localFS, this.appId, `${this.groupId}`, this.versions);
4536
+ try {
4537
+ this.refreshSyncExclusions(await this.tombstones.list());
4538
+ } catch (err) {
4539
+ log5.warn(`[AppDataGroup:${this.groupId}] failed to load tombstones for exclusions:`, err);
4540
+ }
4032
4541
  let backendsChanged = false;
4033
4542
  try {
4034
4543
  backendsChanged = await this.loadBackendDescriptors();
4035
4544
  } catch (err) {
4036
- log3.warn(`[AppDataGroup:${this.groupId}] failed to load .meta/backends:`, err);
4545
+ log5.warn(`[AppDataGroup:${this.groupId}] failed to load .meta/backends:`, err);
4037
4546
  this._backends = this._backends ?? [];
4038
4547
  }
4548
+ if (!this.instanceId) {
4549
+ try {
4550
+ const existing = await readGroupDescriptor(this.localFS);
4551
+ this.instanceId = pickInstanceId(existing);
4552
+ if (this.instanceId) {
4553
+ log5.log(`[AppDataGroup:${this.groupId}] adopted instanceId ${this.instanceId} from local group.json`);
4554
+ }
4555
+ } catch (err) {
4556
+ log5.warn(`[AppDataGroup:${this.groupId}] failed to read local group.json:`, err);
4557
+ }
4558
+ }
4039
4559
  try {
4040
4560
  await this.writeOwnGroupDescriptor();
4041
4561
  } catch (err) {
4042
- log3.warn(`[AppDataGroup:${this.groupId}] failed to write .meta/group.json:`, err);
4562
+ log5.warn(`[AppDataGroup:${this.groupId}] failed to write .meta/group.json:`, err);
4043
4563
  }
4044
4564
  this.fs = createChrootFS(this.localFS, "/", {
4045
4565
  hiddenPrefixes: [META_DIR, CONFIG_DIR],
@@ -4049,7 +4569,7 @@ var AppDataGroupImpl = class {
4049
4569
  });
4050
4570
  const { kept, removed } = dedupeAppDataBackends(this._backends);
4051
4571
  if (removed.length > 0) {
4052
- log3.warn(
4572
+ log5.warn(
4053
4573
  `[AppDataGroup:${this.groupId}] dedupe: removing ${removed.length} duplicate backend(s) (${removed.map((b) => b.id).join(", ")}) \u2014 keeping ${kept.map((b) => b.id).join(", ")}`
4054
4574
  );
4055
4575
  this._backends = kept;
@@ -4063,12 +4583,20 @@ var AppDataGroupImpl = class {
4063
4583
  features: this._declaredFeatures
4064
4584
  });
4065
4585
  } catch (err) {
4066
- log3.warn(`[AppDataGroup:${this.groupId}] failed to persist backend topology:`, err);
4586
+ log5.warn(`[AppDataGroup:${this.groupId}] failed to persist backend topology:`, err);
4067
4587
  }
4068
4588
  }
4069
4589
  for (const desc of this._backends) {
4070
4590
  try {
4071
4591
  const instance = await createBackend({ type: desc.type, options: desc.options });
4592
+ const owned = await this.checkBackendOwnership(instance, desc.id);
4593
+ if (owned === "conflict") {
4594
+ try {
4595
+ await instance.dispose?.();
4596
+ } catch {
4597
+ }
4598
+ continue;
4599
+ }
4072
4600
  const syncable = backendToSyncableFS(instance, `${desc.type}(${desc.id})`);
4073
4601
  const pair = this.syncEngine.addPair(
4074
4602
  localSyncable,
@@ -4079,7 +4607,8 @@ var AppDataGroupImpl = class {
4079
4607
  pollIntervalMs: this._pollIntervalMs,
4080
4608
  // `.meta/` is intentionally NOT excluded: tombstones, versions and
4081
4609
  // conflicts must sync, otherwise deletions resurrect on other devices.
4082
- filter: { excludePrefixes: CONFIG_ONLY_PREFIXES },
4610
+ // 但要排除"当前墓碑指向的路径"(与配置组同一张表,实时生效)。
4611
+ filter: this.syncFilter,
4083
4612
  preSyncHook: async () => {
4084
4613
  await this.runTombstonePass("preSync");
4085
4614
  },
@@ -4095,26 +4624,26 @@ var AppDataGroupImpl = class {
4095
4624
  if (this.features.conflicts) {
4096
4625
  const conflictHandler = (event) => {
4097
4626
  this.archiveConflict(event).catch((err) => {
4098
- log3.warn(`[AppDataGroup:${this.groupId}] conflict archive failed:`, err);
4627
+ log5.warn(`[AppDataGroup:${this.groupId}] conflict archive failed:`, err);
4099
4628
  });
4100
4629
  };
4101
4630
  this.syncEngine.on(pair.pairId, "conflict", conflictHandler);
4102
4631
  }
4103
4632
  this.trackSyncErrors(desc.id, pair.pairId);
4104
- log3.log(`[AppDataGroup:${this.groupId}] backend ${desc.id} (${desc.type}) connected, pair=${pair.pairId}`);
4633
+ log5.log(`[AppDataGroup:${this.groupId}] backend ${desc.id} (${desc.type}) connected, pair=${pair.pairId}`);
4105
4634
  } catch (err) {
4106
4635
  const message = err instanceof Error ? err.message : String(err);
4107
4636
  this.backendStates.set(desc.id, {
4108
4637
  backendId: desc.id,
4109
4638
  error: { message, timestamp: Date.now() }
4110
4639
  });
4111
- log3.error(`[AppDataGroup:${this.groupId}] Failed to create backend ${desc.id} (${desc.type}):`, err);
4640
+ log5.error(`[AppDataGroup:${this.groupId}] Failed to create backend ${desc.id} (${desc.type}):`, err);
4112
4641
  }
4113
4642
  }
4114
4643
  try {
4115
4644
  await this.syncEngine.syncAll();
4116
4645
  } catch (err) {
4117
- log3.warn(`[AppDataGroup:${this.groupId}] Initial sync failed:`, err);
4646
+ log5.warn(`[AppDataGroup:${this.groupId}] Initial sync failed:`, err);
4118
4647
  }
4119
4648
  this.syncEngine.watchAll();
4120
4649
  }
@@ -4129,7 +4658,7 @@ var AppDataGroupImpl = class {
4129
4658
  try {
4130
4659
  await this.tombstones.gc(this.allBackendIds(), this.tombstoneTargets());
4131
4660
  } catch (err) {
4132
- log3.warn(`[AppDataGroup:${this.groupId}] tombstone GC failed:`, err);
4661
+ log5.warn(`[AppDataGroup:${this.groupId}] tombstone GC failed:`, err);
4133
4662
  }
4134
4663
  return Array.from(results.values());
4135
4664
  }
@@ -4164,31 +4693,47 @@ var AppDataGroupImpl = class {
4164
4693
  const bytes = typeof data === "string" ? new TextEncoder().encode(data) : toUint8Array2(data);
4165
4694
  await this.versions.record(path, bytes);
4166
4695
  } catch (err) {
4167
- log3.warn(`[AppDataGroup:${this.groupId}] version record failed for ${path}:`, err);
4696
+ log5.warn(`[AppDataGroup:${this.groupId}] version record failed for ${path}:`, err);
4168
4697
  }
4169
4698
  }
4170
4699
  /** Delete tombstoned files on local + every connected backend before/after sync. */
4171
4700
  async runTombstonePass(stage) {
4172
4701
  try {
4173
4702
  await this.tombstones.process(this.tombstoneTargets());
4703
+ this.refreshSyncExclusions(await this.tombstones.list());
4174
4704
  } catch (err) {
4175
- log3.warn(`[AppDataGroup:${this.groupId}] ${stage} tombstone pass failed:`, err);
4705
+ log5.warn(`[AppDataGroup:${this.groupId}] ${stage} tombstone pass failed:`, err);
4706
+ }
4707
+ }
4708
+ /**
4709
+ * 把当前墓碑路径写进同步排除表(原地更新共享数组)。
4710
+ *
4711
+ * 目录墓碑的 `${path}/` 前缀是故意的:整棵树已删除,保留期内任何子路径都不
4712
+ * 参与同步。注意**不能**为 `.keep` 占位排除父目录,否则真实数据会被一起挡掉。
4713
+ */
4714
+ refreshSyncExclusions(tombstones) {
4715
+ this.tombstoneExcludePrefixes.length = 0;
4716
+ this.tombstoneExcludePrefixes.push(...CONFIG_ONLY_PREFIXES);
4717
+ for (const tombstone of tombstones) {
4718
+ if (!tombstone.path) continue;
4719
+ this.tombstoneExcludePrefixes.push(tombstone.path, `${tombstone.path}/`);
4176
4720
  }
4177
4721
  }
4178
4722
  async confirmTombstones() {
4179
4723
  try {
4180
- await this.tombstones.confirm(this.allBackendIds());
4724
+ await this.tombstones.confirm(this.tombstoneTargets());
4181
4725
  } catch (err) {
4182
- log3.warn(`[AppDataGroup:${this.groupId}] tombstone confirmations failed:`, err);
4726
+ log5.warn(`[AppDataGroup:${this.groupId}] tombstone confirmations failed:`, err);
4183
4727
  }
4184
4728
  }
4185
- /** Write a tombstone for `filePath`. Records metadata only — it never creates the file. */
4186
- async writeTombstoneFor(filePath) {
4729
+ /** Write a tombstone for `path`. Records metadata only — it never creates the path. */
4730
+ async writeTombstoneFor(path, type) {
4187
4731
  await this.tombstones.write({
4188
- path: filePath.startsWith("/") ? filePath : `/${filePath}`,
4732
+ path: normalizeTombstonePath(path),
4189
4733
  deletedAt: Date.now(),
4190
4734
  deletedBy: this.localBackendId,
4191
- confirmedBy: [this.localBackendId]
4735
+ confirmedBy: [this.localBackendId],
4736
+ ...type ? { type } : {}
4192
4737
  });
4193
4738
  }
4194
4739
  /**
@@ -4203,16 +4748,10 @@ var AppDataGroupImpl = class {
4203
4748
  throw new Error(`Cannot delete metadata path "${normalized}"`);
4204
4749
  }
4205
4750
  if (await isDirectoryPath(this.localFS, normalized)) {
4206
- const files = await collectFilesUnder(this.localFS, normalized);
4207
- for (const file of files) await this.deleteFile(file);
4208
- for (const dir of await collectDirectoriesUnder(this.localFS, normalized)) {
4209
- const keepPath = dir === "/" ? "/.keep" : `${dir}/.keep`;
4210
- await this.writeTombstoneFor(keepPath);
4211
- await this.writeTombstoneFor(`${keepPath}.mtime`);
4212
- }
4213
- await removeDirectoryTree(this.localFS, normalized);
4751
+ await this.writeTombstoneFor(normalized, "directory");
4752
+ await purgeTombstonedTree(this.localFS, normalized);
4214
4753
  this.schedulePostDeleteSync();
4215
- log3.log(`[AppDataGroup:${this.groupId}] deleteFile(directory): ${normalized} (${files.length} file(s))`);
4754
+ log5.log(`[AppDataGroup:${this.groupId}] deleteFile(directory): ${normalized} (single directory tombstone)`);
4216
4755
  return;
4217
4756
  }
4218
4757
  await this.writeTombstoneFor(normalized);
@@ -4251,7 +4790,7 @@ var AppDataGroupImpl = class {
4251
4790
  try {
4252
4791
  await this.syncEngine.syncAll();
4253
4792
  } catch (err) {
4254
- log3.warn(`[AppDataGroup:${this.groupId}] sync after conflict resolve failed:`, err);
4793
+ log5.warn(`[AppDataGroup:${this.groupId}] sync after conflict resolve failed:`, err);
4255
4794
  }
4256
4795
  }
4257
4796
  readConflictBackup(conflictId, fileType) {
@@ -4286,7 +4825,7 @@ var AppDataGroupImpl = class {
4286
4825
  if (this.dataBackends.has(id)) {
4287
4826
  throw new Error(`Backend "${id}" already exists in data group "${this.groupId}"`);
4288
4827
  }
4289
- log3.log(`[AppDataGroup:${this.groupId}] addBackend: creating ${id} (${type})...`);
4828
+ log5.log(`[AppDataGroup:${this.groupId}] addBackend: creating ${id} (${type})...`);
4290
4829
  const instance = await createBackend({ type, options });
4291
4830
  const syncable = backendToSyncableFS(instance, `${type}(${id})`);
4292
4831
  const localSyncable = backendToSyncableFS(this.localFS, `local(${this.groupId})`);
@@ -4297,7 +4836,7 @@ var AppDataGroupImpl = class {
4297
4836
  direction: SyncDirection.BiDirectional,
4298
4837
  conflictStrategy: "source-wins",
4299
4838
  pollIntervalMs: this._pollIntervalMs,
4300
- filter: { excludePrefixes: CONFIG_ONLY_PREFIXES },
4839
+ filter: this.syncFilter,
4301
4840
  preSyncHook: async () => {
4302
4841
  await this.runTombstonePass("preSync");
4303
4842
  },
@@ -4314,13 +4853,13 @@ var AppDataGroupImpl = class {
4314
4853
  if (this.features.conflicts) {
4315
4854
  this.syncEngine.on(pair.pairId, "conflict", (event) => {
4316
4855
  this.archiveConflict(event).catch((err) => {
4317
- log3.warn(`[AppDataGroup:${this.groupId}] conflict archive failed:`, err);
4856
+ log5.warn(`[AppDataGroup:${this.groupId}] conflict archive failed:`, err);
4318
4857
  });
4319
4858
  });
4320
4859
  }
4321
4860
  this.trackSyncErrors(id, pair.pairId);
4322
4861
  this._backends = [...this._backends.filter((b) => b.id !== id), desc];
4323
- log3.log(`[AppDataGroup:${this.groupId}] addBackend: ${id} (${type}) connected, pair=${pair.pairId}`);
4862
+ log5.log(`[AppDataGroup:${this.groupId}] addBackend: ${id} (${type}) connected, pair=${pair.pairId}`);
4324
4863
  try {
4325
4864
  const stale = (await this.tombstones.list()).find(
4326
4865
  (t) => t.path === backendMetaFilePath(id)
@@ -4328,12 +4867,12 @@ var AppDataGroupImpl = class {
4328
4867
  if (stale) await this.tombstones.remove(stale);
4329
4868
  await writeBackendMetaDescriptor(this.localFS, desc);
4330
4869
  } catch (err) {
4331
- log3.warn(`[AppDataGroup:${this.groupId}] addBackend: failed to write .meta/backends/${id}.json:`, err);
4870
+ log5.warn(`[AppDataGroup:${this.groupId}] addBackend: failed to write .meta/backends/${id}.json:`, err);
4332
4871
  }
4333
4872
  try {
4334
4873
  await this.syncEngine.sync(pair.pairId);
4335
4874
  } catch (err) {
4336
- log3.warn(`[AppDataGroup:${this.groupId}] addBackend: initial sync failed for ${id}:`, err);
4875
+ log5.warn(`[AppDataGroup:${this.groupId}] addBackend: initial sync failed for ${id}:`, err);
4337
4876
  }
4338
4877
  this.syncEngine.watch(pair.pairId);
4339
4878
  await this.parent.updateAppDataGroupDescriptor(this.groupId, this._backends, {
@@ -4364,7 +4903,7 @@ var AppDataGroupImpl = class {
4364
4903
  if (backend?.instance?.dispose) {
4365
4904
  await backend.instance.dispose();
4366
4905
  }
4367
- log3.log(`[AppDataGroup:${this.groupId}] removeBackend: ${id} removed`);
4906
+ log5.log(`[AppDataGroup:${this.groupId}] removeBackend: ${id} removed`);
4368
4907
  }
4369
4908
  listBackends() {
4370
4909
  return Array.from(this.dataBackends.values()).map((b) => b.desc);
@@ -4406,44 +4945,44 @@ async function createConfigRepo(appId, options = {}) {
4406
4945
  idbStoreName: options.idbStoreName,
4407
4946
  folderPath: options.folderPath
4408
4947
  });
4409
- log3.log(`[createConfigRepo] Creating local primary (type: ${localPrimary.type})...`);
4948
+ log5.log(`[createConfigRepo] Creating local primary (type: ${localPrimary.type})...`);
4410
4949
  const primaryInstance = await createBackend(localPrimary);
4411
4950
  const cachedFS = primaryInstance;
4412
4951
  if (options.purgeMtimeSidecars !== false) {
4413
4952
  try {
4414
4953
  const purged = await purgeMtimeSidecars(cachedFS);
4415
4954
  if (purged.removed.length > 0) {
4416
- log3.warn(
4955
+ log5.warn(
4417
4956
  `[createConfigRepo] purged ${purged.removed.length} leaked .mtime sidecar(s) from local primary:`,
4418
4957
  purged.removed
4419
4958
  );
4420
4959
  }
4421
4960
  } catch (err) {
4422
- log3.warn(`[createConfigRepo] .mtime purge failed:`, err?.message ?? err);
4961
+ log5.warn(`[createConfigRepo] .mtime purge failed:`, err?.message ?? err);
4423
4962
  }
4424
4963
  }
4425
4964
  if (options.purgeKeepFiles !== false) {
4426
4965
  try {
4427
4966
  const purged = await purgeKeepFiles(cachedFS);
4428
4967
  if (purged.removed.length > 0) {
4429
- log3.warn(
4968
+ log5.warn(
4430
4969
  `[createConfigRepo] purged ${purged.removed.length} leaked .keep placeholder(s) from local primary:`,
4431
4970
  purged.removed
4432
4971
  );
4433
4972
  }
4434
4973
  } catch (err) {
4435
- log3.warn(`[createConfigRepo] .keep purge failed:`, err?.message ?? err);
4974
+ log5.warn(`[createConfigRepo] .keep purge failed:`, err?.message ?? err);
4436
4975
  }
4437
4976
  }
4438
4977
  const cacheOptions = options.cache === false ? void 0 : options.cache ?? {};
4439
4978
  try {
4440
4979
  await primaryInstance.mkdir(META_DIR);
4441
- log3.log(`[createConfigRepo] /.meta/ ready`);
4980
+ log5.log(`[createConfigRepo] /.meta/ ready`);
4442
4981
  } catch (err) {
4443
4982
  const msg = err.message || "";
4444
4983
  if (msg.includes("File exists") || msg.includes("EEXIST") || err.code === "EEXIST") {
4445
4984
  } else {
4446
- log3.error(`[createConfigRepo] Failed to ensure /.meta/:`, err.message);
4985
+ log5.error(`[createConfigRepo] Failed to ensure /.meta/:`, err.message);
4447
4986
  }
4448
4987
  }
4449
4988
  try {
@@ -4454,7 +4993,7 @@ async function createConfigRepo(appId, options = {}) {
4454
4993
  } catch {
4455
4994
  await ensureParentDir2(primaryInstance, path);
4456
4995
  await primaryInstance.writeFile(path, groupTypeBytes);
4457
- log3.log(`[createConfigRepo] group-type set to "config-sync" at ${path}`);
4996
+ log5.log(`[createConfigRepo] group-type set to "config-sync" at ${path}`);
4458
4997
  }
4459
4998
  }
4460
4999
  if (!await readGroupDescriptor(primaryInstance)) {
@@ -4462,11 +5001,12 @@ async function createConfigRepo(appId, options = {}) {
4462
5001
  schemaVersion: 2,
4463
5002
  kind: "config",
4464
5003
  id: CONFIG_GROUP_ID,
5004
+ instanceId: newGroupInstanceId(),
4465
5005
  features: CONFIG_GROUP_FEATURES
4466
5006
  });
4467
5007
  }
4468
5008
  } catch (err) {
4469
- log3.warn(`[createConfigRepo] Failed to write group metadata:`, err.message);
5009
+ log5.warn(`[createConfigRepo] Failed to write group metadata:`, err.message);
4470
5010
  }
4471
5011
  const tempRepo = new ConfigRepo(
4472
5012
  appId,
@@ -4480,11 +5020,11 @@ async function createConfigRepo(appId, options = {}) {
4480
5020
  );
4481
5021
  const oldBackendsMeta = await tempRepo.readMetaFile(BACKENDS_FILE);
4482
5022
  if (oldBackendsMeta && oldBackendsMeta.backends?.length > 0) {
4483
- log3.log(`[createConfigRepo] Migrating ${oldBackendsMeta.backends.length} backend(s) from backends.json to individual files...`);
5023
+ log5.log(`[createConfigRepo] Migrating ${oldBackendsMeta.backends.length} backend(s) from backends.json to individual files...`);
4484
5024
  await tempRepo.ensureDir(`${BACKENDS_DIR}/.keep`);
4485
5025
  for (const desc of oldBackendsMeta.backends) {
4486
5026
  if (desc.id === LOCAL_IDB_BACKEND_ID) {
4487
- log3.log(`[createConfigRepo] Skipping local backend ${desc.id} during migration`);
5027
+ log5.log(`[createConfigRepo] Skipping local backend ${desc.id} during migration`);
4488
5028
  continue;
4489
5029
  }
4490
5030
  await tempRepo.writeBackendDescriptor(desc);
@@ -4502,7 +5042,7 @@ async function createConfigRepo(appId, options = {}) {
4502
5042
  }
4503
5043
  }
4504
5044
  }
4505
- log3.log(`[createConfigRepo] Migration complete`);
5045
+ log5.log(`[createConfigRepo] Migration complete`);
4506
5046
  }
4507
5047
  let allBackends = await tempRepo.readAllBackendDescriptors();
4508
5048
  if (options.backendInfo) {
@@ -4520,19 +5060,19 @@ async function createConfigRepo(appId, options = {}) {
4520
5060
  type: options.backendInfo.type,
4521
5061
  options: options.backendInfo.options
4522
5062
  });
4523
- log3.log(`[createConfigRepo] Added replica backend: ${replicaId} (${options.backendInfo.type})`);
5063
+ log5.log(`[createConfigRepo] Added replica backend: ${replicaId} (${options.backendInfo.type})`);
4524
5064
  allBackends = [...allBackends, { id: replicaId, type: options.backendInfo.type, options: options.backendInfo.options }];
4525
5065
  } else if (dupConfig) {
4526
- log3.log(`[createConfigRepo] Replica with same config already registered as "${dupConfig.id}", skipping`);
5066
+ log5.log(`[createConfigRepo] Replica with same config already registered as "${dupConfig.id}", skipping`);
4527
5067
  } else {
4528
- log3.log(`[createConfigRepo] Replica ${replicaId} already registered`);
5068
+ log5.log(`[createConfigRepo] Replica ${replicaId} already registered`);
4529
5069
  }
4530
5070
  }
4531
- log3.log(`[createConfigRepo] Replica backends: ${allBackends.map((b) => b.id).join(", ") || "(none)"}`);
5071
+ log5.log(`[createConfigRepo] Replica backends: ${allBackends.map((b) => b.id).join(", ") || "(none)"}`);
4532
5072
  let nodeId = options.nodeId;
4533
5073
  if (!nodeId) {
4534
5074
  nodeId = `node-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`;
4535
- log3.log(`[createConfigRepo] Generated nodeId: ${nodeId}`);
5075
+ log5.log(`[createConfigRepo] Generated nodeId: ${nodeId}`);
4536
5076
  }
4537
5077
  const serializer = createSerializerChain(options.serializer);
4538
5078
  const repo = new ConfigRepo(
@@ -4555,19 +5095,19 @@ async function createConfigRepo(appId, options = {}) {
4555
5095
  try {
4556
5096
  const mig = await repo.migrateLegacyVersionSidecars();
4557
5097
  if (mig.renamed.length === 0 && mig.deleted.length === 0 && mig.remoteDeleted.length === 0) {
4558
- log3.log("[createConfigRepo] no legacy version sidecars to migrate");
5098
+ log5.log("[createConfigRepo] no legacy version sidecars to migrate");
4559
5099
  }
4560
5100
  } catch (err) {
4561
- log3.warn(`[createConfigRepo] version sidecar migration failed:`, err?.message ?? err);
5101
+ log5.warn(`[createConfigRepo] version sidecar migration failed:`, err?.message ?? err);
4562
5102
  }
4563
5103
  }
4564
5104
  await repo.load();
4565
5105
  if (repo.replicaCount > 0) {
4566
- log3.log("[createConfigRepo] Starting background initial sync + dedup...");
5106
+ log5.log("[createConfigRepo] Starting background initial sync + dedup...");
4567
5107
  repo.startBackgroundSync();
4568
5108
  }
4569
5109
  repo.syncMetaToReplicas().catch((err) => {
4570
- log3.error("[createConfigRepo] background syncMetaToReplicas failed:", err);
5110
+ log5.error("[createConfigRepo] background syncMetaToReplicas failed:", err);
4571
5111
  });
4572
5112
  return repo;
4573
5113
  }
@@ -4580,11 +5120,11 @@ function sidecarOwnerPath(path) {
4580
5120
  }
4581
5121
 
4582
5122
  // src/connect.ts
4583
- var log4 = createLogger("connect");
5123
+ var log6 = createLogger2("connect");
4584
5124
  var GROUP_TYPE_FILE2 = "/.config/group-type";
4585
5125
  var LEGACY_GROUP_TYPE_FILE2 = "/.meta/group-type";
4586
5126
  async function detectGroupType(type, options) {
4587
- log4(`detectGroupType: connecting to ${type}...`);
5127
+ log6(`detectGroupType: connecting to ${type}...`);
4588
5128
  const tempBackend = await createBackend({ type, options });
4589
5129
  try {
4590
5130
  for (const path of [GROUP_TYPE_FILE2, LEGACY_GROUP_TYPE_FILE2]) {
@@ -4592,15 +5132,15 @@ async function detectGroupType(type, options) {
4592
5132
  const raw = await tempBackend.readFile(path, "utf-8");
4593
5133
  const groupType = raw.trim();
4594
5134
  if (groupType === "config-sync" || groupType === "data-sync") {
4595
- log4(`detectGroupType: detected "${groupType}" at ${path}`);
5135
+ log6(`detectGroupType: detected "${groupType}" at ${path}`);
4596
5136
  return groupType;
4597
5137
  }
4598
- log4(`detectGroupType: unknown group-type value "${groupType}" at ${path}, treating as null`);
5138
+ log6(`detectGroupType: unknown group-type value "${groupType}" at ${path}, treating as null`);
4599
5139
  return null;
4600
5140
  } catch {
4601
5141
  }
4602
5142
  }
4603
- log4(`detectGroupType: no group-type file found (new backend)`);
5143
+ log6(`detectGroupType: no group-type file found (new backend)`);
4604
5144
  return null;
4605
5145
  } finally {
4606
5146
  if (tempBackend?.dispose) {
@@ -4609,7 +5149,7 @@ async function detectGroupType(type, options) {
4609
5149
  }
4610
5150
  }
4611
5151
  async function connect(appId, options = {}) {
4612
- log4(`connect: appId=${appId}`);
5152
+ log6(`connect: appId=${appId}`);
4613
5153
  if (!options.backendInfo) {
4614
5154
  const repo2 = await createConfigRepo(appId, {
4615
5155
  idbStoreName: options.idbStoreName,
@@ -4627,12 +5167,12 @@ async function connect(appId, options = {}) {
4627
5167
  try {
4628
5168
  appDataGroups2.push(await repo2.getAppDataGroup(d.id));
4629
5169
  } catch (err) {
4630
- log4(`connect: failed to load app data group "${d.id}":`, err);
5170
+ log6(`connect: failed to load app data group "${d.id}":`, err);
4631
5171
  }
4632
5172
  }
4633
5173
  const dataGroup2 = appDataGroups2[0];
4634
5174
  if (!dataGroup2 && descriptors2.length > 0) {
4635
- log4(
5175
+ log6(
4636
5176
  `connect: ${descriptors2.length} data group descriptor(s) found but none could be loaded; leaving them untouched (no empty group is created)`
4637
5177
  );
4638
5178
  }
@@ -4657,7 +5197,7 @@ async function connect(appId, options = {}) {
4657
5197
  groupType = detectedType;
4658
5198
  } else {
4659
5199
  groupType = options.groupType ?? "config-sync";
4660
- log4(`connect: new backend, using groupType="${groupType}"`);
5200
+ log6(`connect: new backend, using groupType="${groupType}"`);
4661
5201
  }
4662
5202
  const repo = await createConfigRepo(
4663
5203
  appId,
@@ -4686,14 +5226,14 @@ async function connect(appId, options = {}) {
4686
5226
  try {
4687
5227
  appDataGroups.push(await repo.getAppDataGroup(d.id));
4688
5228
  } catch (err) {
4689
- log4(`connect: failed to load app data group "${d.id}":`, err);
5229
+ log6(`connect: failed to load app data group "${d.id}":`, err);
4690
5230
  }
4691
5231
  }
4692
5232
  let dataGroup = appDataGroups[0];
4693
5233
  if (groupType === "data-sync") {
4694
5234
  if (!dataGroup) {
4695
5235
  if (descriptors.length > 0) {
4696
- log4(
5236
+ log6(
4697
5237
  `connect: ${descriptors.length} data group descriptor(s) exist but could not be loaded; refusing to create/overwrite "default"`
4698
5238
  );
4699
5239
  } else {
@@ -4722,7 +5262,7 @@ export {
4722
5262
  ConflictStore,
4723
5263
  DATA_GROUP_DEFAULT_FEATURES,
4724
5264
  FolderStore,
4725
- GROUP_DESCRIPTOR_FILE,
5265
+ GROUP_DESCRIPTOR_FILE2 as GROUP_DESCRIPTOR_FILE,
4726
5266
  LEGACY_CONFLICTS_DIR,
4727
5267
  LEGACY_TOMBSTONES_DIR,
4728
5268
  LOCAL_IDB_BACKEND_ID,