zen-fs-config 0.6.0 → 0.6.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -978,7 +978,7 @@ async function defaultNodeDir(appId, kind, groupId) {
978
978
  }
979
979
 
980
980
  // src/config-repo.ts
981
- var import_localstorage_logger2 = require("@richard432/localstorage-logger");
981
+ var import_localstorage_logger3 = require("@richard432/localstorage-logger");
982
982
 
983
983
  // src/version.ts
984
984
  function versionPathFor(configFilePath) {
@@ -1464,6 +1464,9 @@ async function migrateVersionSidecars(fs, options = {}) {
1464
1464
  return result;
1465
1465
  }
1466
1466
 
1467
+ // src/group-meta.ts
1468
+ var import_localstorage_logger2 = require("@richard432/localstorage-logger");
1469
+
1467
1470
  // src/canonical-json.ts
1468
1471
  var FEATURE_ORDER = ["tombstones", "versions", "conflicts", "configHost", "appData"];
1469
1472
  var GROUP_DESCRIPTOR_ORDER = ["schemaVersion", "kind", "id", "name", "features"];
@@ -1537,6 +1540,7 @@ function mergeDescriptorCreatedAt(descriptor, existing) {
1537
1540
  }
1538
1541
 
1539
1542
  // src/group-meta.ts
1543
+ var log2 = (0, import_localstorage_logger2.createLogger)("zen-fs-config:tombstones");
1540
1544
  var META_DIR = "/.meta";
1541
1545
  var GROUP_DESCRIPTOR_FILE = `${META_DIR}/group.json`;
1542
1546
  var META_BACKENDS_DIR = `${META_DIR}/backends`;
@@ -1607,6 +1611,141 @@ function encodeMetaPath(filePath) {
1607
1611
  const normalized = filePath.startsWith("/") ? filePath : `/${filePath}`;
1608
1612
  return normalized.replace(/^\//, "").replace(/\//g, "__").replace(/\./g, "++");
1609
1613
  }
1614
+ function decodeMetaPath(entry) {
1615
+ if (!entry.endsWith(".json")) return null;
1616
+ const encoded = entry.slice(0, -".json".length);
1617
+ if (!encoded) return null;
1618
+ return `/${encoded.replace(/__/g, "/").replace(/\+\+/g, ".")}`;
1619
+ }
1620
+ function fallbackTombstone(path) {
1621
+ return { path, deletedAt: 0, deletedBy: "unknown", confirmedBy: [] };
1622
+ }
1623
+ function normalizeTombstoneRecord(value, fallbackPath) {
1624
+ if (!value || typeof value !== "object" || Array.isArray(value)) return null;
1625
+ const record = value;
1626
+ const rawPath = typeof record.path === "string" ? record.path : fallbackPath;
1627
+ if (!rawPath) return null;
1628
+ const path = rawPath.startsWith("/") ? rawPath : `/${rawPath}`;
1629
+ const confirmedBy = Array.isArray(record.confirmedBy) ? record.confirmedBy.filter((id) => typeof id === "string") : [];
1630
+ return {
1631
+ path,
1632
+ deletedAt: typeof record.deletedAt === "number" ? record.deletedAt : 0,
1633
+ deletedBy: typeof record.deletedBy === "string" ? record.deletedBy : "unknown",
1634
+ confirmedBy
1635
+ };
1636
+ }
1637
+ function extractJsonObjects(raw) {
1638
+ const objects = [];
1639
+ let depth = 0;
1640
+ let start = -1;
1641
+ let inString = false;
1642
+ let escaped = false;
1643
+ for (let i = 0; i < raw.length; i++) {
1644
+ const ch = raw[i];
1645
+ if (inString) {
1646
+ if (escaped) escaped = false;
1647
+ else if (ch === "\\") escaped = true;
1648
+ else if (ch === '"') inString = false;
1649
+ continue;
1650
+ }
1651
+ if (ch === '"') {
1652
+ inString = true;
1653
+ continue;
1654
+ }
1655
+ if (ch === "{") {
1656
+ if (depth === 0) start = i;
1657
+ depth++;
1658
+ continue;
1659
+ }
1660
+ if (ch === "}") {
1661
+ if (depth === 0) continue;
1662
+ depth--;
1663
+ if (depth === 0 && start >= 0) {
1664
+ objects.push(raw.slice(start, i + 1));
1665
+ start = -1;
1666
+ }
1667
+ }
1668
+ }
1669
+ return objects;
1670
+ }
1671
+ function parseTombstoneFile(raw, fallbackPath) {
1672
+ const problems = [];
1673
+ const text = raw.trim();
1674
+ if (text === "") {
1675
+ problems.push("empty body");
1676
+ if (fallbackPath) {
1677
+ problems.push("path derived from filename");
1678
+ return { tombstones: [fallbackTombstone(fallbackPath)], problems };
1679
+ }
1680
+ problems.push("no path derivable from filename \u2014 skipped");
1681
+ return { tombstones: [], problems };
1682
+ }
1683
+ try {
1684
+ const parsed = normalizeTombstoneRecord(JSON.parse(text), fallbackPath);
1685
+ if (parsed) return { tombstones: [parsed], problems: [] };
1686
+ problems.push('JSON parsed but has no usable "path"');
1687
+ } catch (err) {
1688
+ problems.push(`JSON parse error: ${err instanceof Error ? err.message : String(err)}`);
1689
+ }
1690
+ const recovered = extractJsonObjects(text).map((chunk) => {
1691
+ try {
1692
+ return normalizeTombstoneRecord(JSON.parse(chunk));
1693
+ } catch {
1694
+ return null;
1695
+ }
1696
+ }).filter((t) => t !== null);
1697
+ if (recovered.length > 0) {
1698
+ if (recovered.length > 1) problems.push(`${recovered.length} concatenated documents recovered`);
1699
+ return { tombstones: recovered, problems };
1700
+ }
1701
+ if (fallbackPath) {
1702
+ problems.push("no recoverable document; path derived from filename");
1703
+ return { tombstones: [fallbackTombstone(fallbackPath)], problems };
1704
+ }
1705
+ problems.push("no recoverable document and no path derivable from filename \u2014 skipped");
1706
+ return { tombstones: [], problems };
1707
+ }
1708
+ function mergeTombstone(byPath, tombstone) {
1709
+ const prev = byPath.get(tombstone.path);
1710
+ if (!prev) {
1711
+ byPath.set(tombstone.path, tombstone);
1712
+ return;
1713
+ }
1714
+ for (const id of tombstone.confirmedBy) {
1715
+ if (!prev.confirmedBy.includes(id)) prev.confirmedBy.push(id);
1716
+ }
1717
+ }
1718
+ async function readTombstonesFromFs(fs, warn) {
1719
+ const byPath = /* @__PURE__ */ new Map();
1720
+ for (const dir of [TOMBSTONES_DIR, LEGACY_TOMBSTONES_DIR]) {
1721
+ let entries;
1722
+ try {
1723
+ entries = await fs.readdir(dir);
1724
+ } catch {
1725
+ continue;
1726
+ }
1727
+ for (const entry of entries) {
1728
+ if (!entry.endsWith(".json")) continue;
1729
+ const filePath = `${dir}/${entry}`;
1730
+ let raw;
1731
+ try {
1732
+ raw = new TextDecoder().decode(toBytes(await fs.readFile(filePath)));
1733
+ } catch (err) {
1734
+ warn(
1735
+ `[Tombstones] unreadable tombstone ${filePath}: ${err instanceof Error ? err.message : String(err)} \u2014 skipped`
1736
+ );
1737
+ continue;
1738
+ }
1739
+ const { tombstones, problems } = parseTombstoneFile(raw, decodeMetaPath(entry) ?? void 0);
1740
+ if (problems.length > 0) {
1741
+ const action = tombstones.length > 0 ? tombstones.map((t) => `"${t.path}" treated as deleted`).join(", ") : "skipped";
1742
+ warn(`[Tombstones] corrupt tombstone ${filePath}: ${problems.join("; ")} \u2192 ${action}`);
1743
+ }
1744
+ for (const tombstone of tombstones) mergeTombstone(byPath, tombstone);
1745
+ }
1746
+ }
1747
+ return Array.from(byPath.values());
1748
+ }
1610
1749
  async function readGroupDescriptor(fs) {
1611
1750
  const parsed = await readJson(fs, GROUP_DESCRIPTOR_FILE);
1612
1751
  if (!parsed) return null;
@@ -1684,29 +1823,7 @@ var TombstoneStore = class {
1684
1823
  }
1685
1824
  /** All tombstones, new path first, legacy only for paths not already seen. */
1686
1825
  async list() {
1687
- const byPath = /* @__PURE__ */ new Map();
1688
- for (const dir of [TOMBSTONES_DIR, LEGACY_TOMBSTONES_DIR]) {
1689
- let entries;
1690
- try {
1691
- entries = await this.fs.readdir(dir);
1692
- } catch {
1693
- continue;
1694
- }
1695
- for (const entry of entries) {
1696
- if (!entry.endsWith(".json")) continue;
1697
- const data = await readJson(this.fs, `${dir}/${entry}`);
1698
- if (!data || typeof data.path !== "string") continue;
1699
- const prev = byPath.get(data.path);
1700
- if (prev) {
1701
- for (const id of data.confirmedBy ?? []) {
1702
- if (!prev.confirmedBy.includes(id)) prev.confirmedBy.push(id);
1703
- }
1704
- } else {
1705
- byPath.set(data.path, data);
1706
- }
1707
- }
1708
- }
1709
- return Array.from(byPath.values());
1826
+ return readTombstonesFromFs(this.fs, (message) => log2.warn(message));
1710
1827
  }
1711
1828
  /** Write a tombstone (new + legacy mirror). */
1712
1829
  async write(tombstone) {
@@ -1938,7 +2055,7 @@ var ConflictStore = class {
1938
2055
  };
1939
2056
 
1940
2057
  // src/config-repo.ts
1941
- var log2 = (0, import_localstorage_logger2.createLogger)("zen-fs-config:config-repo");
2058
+ var log3 = (0, import_localstorage_logger3.createLogger)("zen-fs-config:config-repo");
1942
2059
  var GROUP_DESCRIPTOR_FILE2 = `${META_DIR}/group.json`;
1943
2060
  var GROUP_TYPE_FILE = `${CONFIG_DIR}/group-type`;
1944
2061
  var LEGACY_GROUP_TYPE_FILE = `${META_DIR}/group-type`;
@@ -2191,7 +2308,7 @@ var ConfigRepo = class {
2191
2308
  const bytes = this.serializer.serialize(data, fullPath);
2192
2309
  this.configCache.set(fullPath, data);
2193
2310
  this.persistConfig(fullPath, bytes).catch((err) => {
2194
- log2.error(`[zen-fs-config] Failed to persist ${fullPath}:`, err);
2311
+ log3.error(`[zen-fs-config] Failed to persist ${fullPath}:`, err);
2195
2312
  });
2196
2313
  }
2197
2314
  // -----------------------------------------------------------------------
@@ -2345,7 +2462,7 @@ var ConfigRepo = class {
2345
2462
  await removeDirectoryTree(this.cachedFS, normalizedPath);
2346
2463
  this.invalidateTombstoneCache();
2347
2464
  this.schedulePostDeleteSync();
2348
- log2.log(`[ConfigRepo] deleteFile(directory): ${normalizedPath} (${files.length} file(s))`);
2465
+ log3.log(`[ConfigRepo] deleteFile(directory): ${normalizedPath} (${files.length} file(s))`);
2349
2466
  return;
2350
2467
  }
2351
2468
  await this.writeTombstoneFor(normalizedPath);
@@ -2366,7 +2483,7 @@ var ConfigRepo = class {
2366
2483
  } catch {
2367
2484
  }
2368
2485
  }
2369
- log2.log(`[ConfigRepo] deleteFile: ${normalizedPath} (tombstone at ${tombstonePathFor(normalizedPath)})`);
2486
+ log3.log(`[ConfigRepo] deleteFile: ${normalizedPath} (tombstone at ${tombstonePathFor(normalizedPath)})`);
2370
2487
  this.invalidateTombstoneCache();
2371
2488
  this.schedulePostDeleteSync();
2372
2489
  }
@@ -2384,7 +2501,7 @@ var ConfigRepo = class {
2384
2501
  this.postDeleteSyncTimer = void 0;
2385
2502
  if (this.disposed) return;
2386
2503
  this.syncEngine.syncAll().catch((err) => {
2387
- log2.warn("[ConfigRepo] post-delete sync failed:", err);
2504
+ log3.warn("[ConfigRepo] post-delete sync failed:", err);
2388
2505
  });
2389
2506
  }, 500);
2390
2507
  }
@@ -2396,32 +2513,7 @@ var ConfigRepo = class {
2396
2513
  if (this.tombstoneCache !== null) {
2397
2514
  return this.tombstoneCache;
2398
2515
  }
2399
- const byPath = /* @__PURE__ */ new Map();
2400
- for (const dir of [TOMBSTONES_DIR, LEGACY_TOMBSTONES_DIR]) {
2401
- let entries;
2402
- try {
2403
- entries = await this.cachedFS.readdir(dir);
2404
- } catch {
2405
- continue;
2406
- }
2407
- for (const entry of entries) {
2408
- if (!entry.endsWith(".json")) continue;
2409
- try {
2410
- const raw = await this.cachedFS.readFile(`${dir}/${entry}`);
2411
- const data = JSON.parse(new TextDecoder().decode(toUint8Array2(raw)));
2412
- const prev = byPath.get(data.path);
2413
- if (prev) {
2414
- for (const id of data.confirmedBy ?? []) {
2415
- if (!prev.confirmedBy.includes(id)) prev.confirmedBy.push(id);
2416
- }
2417
- } else {
2418
- byPath.set(data.path, data);
2419
- }
2420
- } catch {
2421
- }
2422
- }
2423
- }
2424
- this.tombstoneCache = Array.from(byPath.values());
2516
+ this.tombstoneCache = await readTombstonesFromFs(this.cachedFS, (message) => log3.warn(message));
2425
2517
  return this.tombstoneCache;
2426
2518
  }
2427
2519
  /** Invalidate the tombstone cache — call after tombstones are modified. */
@@ -2446,11 +2538,11 @@ var ConfigRepo = class {
2446
2538
  for (const tombstone of tombstones) {
2447
2539
  const forceDelete = isMtimeSidecar(tombstone.path);
2448
2540
  const tVersionPath = forceDelete ? null : versionPathFor(tombstone.path);
2449
- log2.log(`[TOMB-TRACE] processing tombstone: path=${tombstone.path} versionPath=${tVersionPath ?? "null"} forceDelete=${forceDelete}`);
2541
+ log3.log(`[TOMB-TRACE] processing tombstone: path=${tombstone.path} versionPath=${tVersionPath ?? "null"} forceDelete=${forceDelete}`);
2450
2542
  const existedOnPrimary = forceDelete || await this.safeExists(this.cachedFS, tombstone.path);
2451
- log2.log(`[TOMB-TRACE] primary safeExists(${tombstone.path}) \u2192 ${existedOnPrimary}`);
2543
+ log3.log(`[TOMB-TRACE] primary safeExists(${tombstone.path}) \u2192 ${existedOnPrimary}`);
2452
2544
  if (existedOnPrimary) {
2453
- log2.log(`[TOMB-TRACE] tombstone check: ${tombstone.path} on primary \u2192 EXISTS`);
2545
+ log3.log(`[TOMB-TRACE] tombstone check: ${tombstone.path} on primary \u2192 EXISTS`);
2454
2546
  }
2455
2547
  if (existedOnPrimary) {
2456
2548
  try {
@@ -2461,7 +2553,7 @@ var ConfigRepo = class {
2461
2553
  }
2462
2554
  if (tVersionPath) {
2463
2555
  const vExistedOnPrimary = await this.safeExists(this.cachedFS, tVersionPath);
2464
- log2.log(`[TOMB-TRACE] primary safeExists(${tVersionPath}) \u2192 ${vExistedOnPrimary}`);
2556
+ log3.log(`[TOMB-TRACE] primary safeExists(${tVersionPath}) \u2192 ${vExistedOnPrimary}`);
2465
2557
  if (vExistedOnPrimary) {
2466
2558
  try {
2467
2559
  await this.cachedFS.unlink(tVersionPath);
@@ -2470,40 +2562,40 @@ var ConfigRepo = class {
2470
2562
  }
2471
2563
  }
2472
2564
  for (const [replicaId, replica] of this.replicaBackends) {
2473
- log2.log(`[TOMB-TRACE] checking replica: ${replicaId} for ${tombstone.path}`);
2565
+ log3.log(`[TOMB-TRACE] checking replica: ${replicaId} for ${tombstone.path}`);
2474
2566
  const existed = forceDelete || await this.safeExists(replica.instance, tombstone.path);
2475
- log2.log(`[TOMB-TRACE] replica ${replicaId} safeExists(${tombstone.path}) \u2192 ${existed}`);
2567
+ log3.log(`[TOMB-TRACE] replica ${replicaId} safeExists(${tombstone.path}) \u2192 ${existed}`);
2476
2568
  if (existed) {
2477
- log2.log(`[TOMB-TRACE] tombstone check: ${tombstone.path} on ${replicaId} \u2192 EXISTS`);
2569
+ log3.log(`[TOMB-TRACE] tombstone check: ${tombstone.path} on ${replicaId} \u2192 EXISTS`);
2478
2570
  try {
2479
- log2.log(`[TOMB-TRACE] calling unlink(${tombstone.path}) on ${replicaId}`);
2571
+ log3.log(`[TOMB-TRACE] calling unlink(${tombstone.path}) on ${replicaId}`);
2480
2572
  await replica.instance.unlink(tombstone.path);
2481
- log2.log(`[TOMB-TRACE] tombstone ${tombstone.path}: deleted on ${replicaId}`);
2573
+ log3.log(`[TOMB-TRACE] tombstone ${tombstone.path}: deleted on ${replicaId}`);
2482
2574
  processed++;
2483
2575
  } catch (err) {
2484
- log2.log(`[TOMB-TRACE] unlink(${tombstone.path}) on ${replicaId} FAILED: ${err}`);
2576
+ log3.log(`[TOMB-TRACE] unlink(${tombstone.path}) on ${replicaId} FAILED: ${err}`);
2485
2577
  alreadyDeleted++;
2486
2578
  }
2487
2579
  } else {
2488
- log2.log(`[TOMB-TRACE] replica ${replicaId}: already gone, skipping unlink`);
2580
+ log3.log(`[TOMB-TRACE] replica ${replicaId}: already gone, skipping unlink`);
2489
2581
  alreadyDeleted++;
2490
2582
  }
2491
2583
  if (tVersionPath) {
2492
2584
  const vExisted = await this.safeExists(replica.instance, tVersionPath);
2493
- log2.log(`[TOMB-TRACE] replica ${replicaId} safeExists(${tVersionPath}) \u2192 ${vExisted}`);
2585
+ log3.log(`[TOMB-TRACE] replica ${replicaId} safeExists(${tVersionPath}) \u2192 ${vExisted}`);
2494
2586
  if (vExisted) {
2495
2587
  try {
2496
- log2.log(`[TOMB-TRACE] calling unlink(${tVersionPath}) on ${replicaId}`);
2588
+ log3.log(`[TOMB-TRACE] calling unlink(${tVersionPath}) on ${replicaId}`);
2497
2589
  await replica.instance.unlink(tVersionPath);
2498
2590
  } catch (err) {
2499
- log2.log(`[TOMB-TRACE] unlink(${tVersionPath}) on ${replicaId} FAILED: ${err}`);
2591
+ log3.log(`[TOMB-TRACE] unlink(${tVersionPath}) on ${replicaId} FAILED: ${err}`);
2500
2592
  }
2501
2593
  }
2502
2594
  }
2503
2595
  }
2504
2596
  }
2505
2597
  if (processed > 0 || alreadyDeleted > 0) {
2506
- log2.log(`[TOMB-TRACE] processTombstones: ${tombstones.length} tombstone(s), ${processed} deleted, ${alreadyDeleted} already gone`);
2598
+ log3.log(`[TOMB-TRACE] processTombstones: ${tombstones.length} tombstone(s), ${processed} deleted, ${alreadyDeleted} already gone`);
2507
2599
  }
2508
2600
  }
2509
2601
  /**
@@ -2519,21 +2611,21 @@ var ConfigRepo = class {
2519
2611
  const innerBackendName = fs?.inner?.backendName;
2520
2612
  const directBackendName = fs?.backendName;
2521
2613
  const backendLabel = innerBackendName ?? directBackendName ?? innerBackend ?? ctorName;
2522
- log2.log(`[TOMB-TRACE] safeExists(${path}): fs type=${ctorName} backend=${backendLabel} hasExists=${hasExists} hasStat=${hasStat} inner=${innerBackend ?? "N/A"}`);
2614
+ log3.log(`[TOMB-TRACE] safeExists(${path}): fs type=${ctorName} backend=${backendLabel} hasExists=${hasExists} hasStat=${hasStat} inner=${innerBackend ?? "N/A"}`);
2523
2615
  if (hasExists) {
2524
- log2.log(`[TOMB-TRACE] safeExists(${path}): \u2192 calling fs.exists() [backend=${backendLabel}]`);
2616
+ log3.log(`[TOMB-TRACE] safeExists(${path}): \u2192 calling fs.exists() [backend=${backendLabel}]`);
2525
2617
  const result = await fs.exists(path);
2526
- log2.log(`[TOMB-TRACE] safeExists(${path}): \u2190 fs.exists() [backend=${backendLabel}] \u2192 ${result}`);
2618
+ log3.log(`[TOMB-TRACE] safeExists(${path}): \u2190 fs.exists() [backend=${backendLabel}] \u2192 ${result}`);
2527
2619
  return result;
2528
2620
  }
2529
- log2.log(`[TOMB-TRACE] safeExists(${path}): no exists(), calling fs.stat() [backend=${backendLabel}]`);
2621
+ log3.log(`[TOMB-TRACE] safeExists(${path}): no exists(), calling fs.stat() [backend=${backendLabel}]`);
2530
2622
  await fs.stat(path);
2531
- log2.log(`[TOMB-TRACE] safeExists(${path}): \u2190 fs.stat() [backend=${backendLabel}] \u2192 OK (exists)`);
2623
+ log3.log(`[TOMB-TRACE] safeExists(${path}): \u2190 fs.stat() [backend=${backendLabel}] \u2192 OK (exists)`);
2532
2624
  return true;
2533
2625
  } catch (err) {
2534
2626
  const errCode = err?.code ?? err?.status ?? "";
2535
2627
  const errName = err?.constructor?.name ?? "";
2536
- log2.log(`[TOMB-TRACE] safeExists(${path}): \u2190 ERROR ${errName} ${errCode} ${err?.message ?? err}`);
2628
+ log3.log(`[TOMB-TRACE] safeExists(${path}): \u2190 ERROR ${errName} ${errCode} ${err?.message ?? err}`);
2537
2629
  return false;
2538
2630
  }
2539
2631
  }
@@ -2560,13 +2652,13 @@ var ConfigRepo = class {
2560
2652
  this.assertNotDisposed();
2561
2653
  const result = await purgeMtimeSidecars(this.cachedFS, options);
2562
2654
  if (result.removed.length > 0) {
2563
- log2.log(
2655
+ log3.log(
2564
2656
  `[ConfigRepo] purged ${result.removed.length} .mtime sidecar(s) from local primary` + (options?.dryRun ? " (dry run)" : ""),
2565
2657
  result.removed
2566
2658
  );
2567
2659
  }
2568
2660
  if (result.failed.length > 0) {
2569
- log2.warn(`[ConfigRepo] failed to purge ${result.failed.length} .mtime sidecar(s):`, result.failed);
2661
+ log3.warn(`[ConfigRepo] failed to purge ${result.failed.length} .mtime sidecar(s):`, result.failed);
2570
2662
  }
2571
2663
  return result;
2572
2664
  }
@@ -2586,13 +2678,13 @@ var ConfigRepo = class {
2586
2678
  this.assertNotDisposed();
2587
2679
  const result = await purgeKeepFiles(this.cachedFS, options);
2588
2680
  if (result.removed.length > 0) {
2589
- log2.log(
2681
+ log3.log(
2590
2682
  `[ConfigRepo] purged ${result.removed.length} .keep placeholder(s) from local primary` + (options?.dryRun ? " (dry run)" : ""),
2591
2683
  result.removed
2592
2684
  );
2593
2685
  }
2594
2686
  if (result.failed.length > 0) {
2595
- log2.warn(`[ConfigRepo] failed to purge ${result.failed.length} .keep placeholder(s):`, result.failed);
2687
+ log3.warn(`[ConfigRepo] failed to purge ${result.failed.length} .keep placeholder(s):`, result.failed);
2596
2688
  }
2597
2689
  return result;
2598
2690
  }
@@ -2611,24 +2703,24 @@ var ConfigRepo = class {
2611
2703
  }));
2612
2704
  const result = await migrateVersionSidecars(this.cachedFS, { replicas });
2613
2705
  if (result.renamed.length > 0) {
2614
- log2.log(
2706
+ log3.log(
2615
2707
  `[ConfigRepo] migrated ${result.renamed.length} legacy version sidecar(s) to new naming`,
2616
2708
  result.renamed
2617
2709
  );
2618
2710
  }
2619
2711
  if (result.deleted.length > 0) {
2620
- log2.log(
2712
+ log3.log(
2621
2713
  `[ConfigRepo] removed ${result.deleted.length} orphaned legacy version sidecar(s)`,
2622
2714
  result.deleted
2623
2715
  );
2624
2716
  }
2625
2717
  if (result.remoteDeleted.length > 0) {
2626
- log2.log(
2718
+ log3.log(
2627
2719
  `[ConfigRepo] removed ${result.remoteDeleted.length} remote residual legacy version sidecar(s)`
2628
2720
  );
2629
2721
  }
2630
2722
  if (result.failed.length > 0) {
2631
- log2.warn(`[ConfigRepo] failed to migrate ${result.failed.length} legacy version sidecar(s):`, result.failed);
2723
+ log3.warn(`[ConfigRepo] failed to migrate ${result.failed.length} legacy version sidecar(s):`, result.failed);
2632
2724
  }
2633
2725
  return result;
2634
2726
  }
@@ -2651,9 +2743,9 @@ var ConfigRepo = class {
2651
2743
  */
2652
2744
  startBackgroundSync() {
2653
2745
  this.initialSyncPromise = this.initialSyncAndDedup().then(() => {
2654
- log2.log("[ConfigRepo] Background initial sync complete");
2746
+ log3.log("[ConfigRepo] Background initial sync complete");
2655
2747
  }).catch((err) => {
2656
- log2.error("[ConfigRepo] Background initial sync failed:", err);
2748
+ log3.error("[ConfigRepo] Background initial sync failed:", err);
2657
2749
  }).finally(() => {
2658
2750
  this.initialSyncPromise = null;
2659
2751
  });
@@ -2687,7 +2779,7 @@ var ConfigRepo = class {
2687
2779
  }
2688
2780
  }
2689
2781
  }
2690
- log2.log(`[ConfigRepo] updateTombstoneConfirmations: ${modified} tombstone(s) updated`);
2782
+ log3.log(`[ConfigRepo] updateTombstoneConfirmations: ${modified} tombstone(s) updated`);
2691
2783
  if (modified > 0) this.invalidateTombstoneCache();
2692
2784
  }
2693
2785
  /**
@@ -2719,7 +2811,7 @@ var ConfigRepo = class {
2719
2811
  }
2720
2812
  }
2721
2813
  }
2722
- log2.log(`[ConfigRepo] gcTombstones: removed ${tombstonePath} (all ${allBackendIds.length} backends confirmed)`);
2814
+ log3.log(`[ConfigRepo] gcTombstones: removed ${tombstonePath} (all ${allBackendIds.length} backends confirmed)`);
2723
2815
  }
2724
2816
  }
2725
2817
  }
@@ -2736,7 +2828,7 @@ var ConfigRepo = class {
2736
2828
  this.assertNotDisposed();
2737
2829
  const results = await this.flush();
2738
2830
  for (const result of results) {
2739
- log2.log(
2831
+ log3.log(
2740
2832
  `[ConfigRepo] syncMetaToReplicas: ${result.pairId} +${result.filesCreated}/~${result.filesUpdated}/-${result.filesDeleted} skip:${result.filesSkipped} ${result.durationMs}ms`
2741
2833
  );
2742
2834
  }
@@ -2753,6 +2845,32 @@ var ConfigRepo = class {
2753
2845
  this.assertNotDisposed();
2754
2846
  return new Map(this.backendStates);
2755
2847
  }
2848
+ /**
2849
+ * Mirror per-pair `sync:error` into `getBackendSyncStates()`.
2850
+ *
2851
+ * `SyncEngine.syncAll()` catches per-pair exceptions and substitutes an empty
2852
+ * result, so a failed replica otherwise only shows up as a missing
2853
+ * `lastResult`. Recording the real error lets callers report the actual
2854
+ * status (401/403/404/timeout) instead of guessing "remote unreachable or
2855
+ * invalid credentials".
2856
+ */
2857
+ trackSyncErrors(backendId, pairId) {
2858
+ this.syncEngine.on(pairId, "sync:error", (event) => {
2859
+ const error = event.error;
2860
+ this.backendStates.set(backendId, {
2861
+ backendId,
2862
+ pairId,
2863
+ error: {
2864
+ message: error instanceof Error ? error.message : String(error ?? "sync failed"),
2865
+ timestamp: Date.now()
2866
+ }
2867
+ });
2868
+ });
2869
+ this.syncEngine.on(pairId, "sync:end", () => {
2870
+ const current = this.backendStates.get(backendId);
2871
+ if (current?.error) this.backendStates.set(backendId, { backendId, pairId });
2872
+ });
2873
+ }
2756
2874
  /** Registered replica backend descriptors (excludes the implicit local primary). */
2757
2875
  listBackends() {
2758
2876
  this.assertNotDisposed();
@@ -2883,21 +3001,21 @@ var ConfigRepo = class {
2883
3001
  // Internal — Setup
2884
3002
  // -----------------------------------------------------------------------
2885
3003
  async setupSync(backends, primaryBackendId, pollIntervalMs) {
2886
- log2.log(`[ConfigRepo] setupSync: ${backends.length} backends, primary=${primaryBackendId} pollInterval=${pollIntervalMs ?? "default"}ms`);
3004
+ log3.log(`[ConfigRepo] setupSync: ${backends.length} backends, primary=${primaryBackendId} pollInterval=${pollIntervalMs ?? "default"}ms`);
2887
3005
  for (const desc of backends) {
2888
3006
  if (desc.id === primaryBackendId) continue;
2889
3007
  if (desc.enabled === false) {
2890
- log2.log(`[ConfigRepo] Skipping disabled replica: ${desc.id}`);
3008
+ log3.log(`[ConfigRepo] Skipping disabled replica: ${desc.id}`);
2891
3009
  continue;
2892
3010
  }
2893
- log2.log(`[ConfigRepo] Creating replica backend: id=${desc.id}, type=${desc.type}`);
3011
+ log3.log(`[ConfigRepo] Creating replica backend: id=${desc.id}, type=${desc.type}`);
2894
3012
  try {
2895
3013
  const instance = await createBackend(desc);
2896
3014
  let fsInstance = instance;
2897
3015
  if (this.cacheOptions) {
2898
3016
  const { wrapWithCache: wrapWithCache2 } = await Promise.resolve().then(() => (init_cache_wrapper(), cache_wrapper_exports));
2899
3017
  fsInstance = wrapWithCache2(instance, desc.id, this.cacheOptions);
2900
- log2.log(`[ConfigRepo] Replica ${desc.id} wrapped with CachedFileSystem (store=${this.cacheOptions.storeType ?? "IdbCacheStore"})`);
3018
+ log3.log(`[ConfigRepo] Replica ${desc.id} wrapped with CachedFileSystem (store=${this.cacheOptions.storeType ?? "IdbCacheStore"})`);
2901
3019
  }
2902
3020
  const syncable = backendToSyncableFS(fsInstance, `${desc.type}(${desc.id})`);
2903
3021
  const pair = this.syncEngine.addPair(
@@ -2912,7 +3030,7 @@ var ConfigRepo = class {
2912
3030
  this.invalidateTombstoneCache();
2913
3031
  await this.processTombstones();
2914
3032
  } catch (err) {
2915
- log2.warn("[ConfigRepo] preSyncHook processTombstones failed:", err);
3033
+ log3.warn("[ConfigRepo] preSyncHook processTombstones failed:", err);
2916
3034
  }
2917
3035
  },
2918
3036
  postSyncHook: async () => {
@@ -2921,7 +3039,7 @@ var ConfigRepo = class {
2921
3039
  await this.processTombstones();
2922
3040
  await this.updateTombstoneConfirmations();
2923
3041
  } catch (err) {
2924
- log2.warn("[ConfigRepo] postSyncHook tombstone processing failed:", err);
3042
+ log3.warn("[ConfigRepo] postSyncHook tombstone processing failed:", err);
2925
3043
  }
2926
3044
  }
2927
3045
  },
@@ -2933,9 +3051,10 @@ var ConfigRepo = class {
2933
3051
  this.handleConflict(event);
2934
3052
  };
2935
3053
  this.syncEngine.on(pair.pairId, "conflict", conflictHandler);
2936
- log2.log(`[ConfigRepo] Replica ${desc.id} created, sync pair=${pair.pairId}`);
3054
+ this.trackSyncErrors(desc.id, pair.pairId);
3055
+ log3.log(`[ConfigRepo] Replica ${desc.id} created, sync pair=${pair.pairId}`);
2937
3056
  } catch (err) {
2938
- log2.error(`[ConfigRepo] Failed to create replica ${desc.id} (${desc.type}):`, err);
3057
+ log3.error(`[ConfigRepo] Failed to create replica ${desc.id} (${desc.type}):`, err);
2939
3058
  this.backendStates.set(desc.id, {
2940
3059
  backendId: desc.id,
2941
3060
  error: {
@@ -2945,8 +3064,8 @@ var ConfigRepo = class {
2945
3064
  });
2946
3065
  }
2947
3066
  }
2948
- log2.log(`[ConfigRepo] setupSync complete. Replicas:`, Array.from(this.replicaBackends.keys()));
2949
- log2.log(`[ConfigRepo] Sync statuses:`, this.getSyncStatuses());
3067
+ log3.log(`[ConfigRepo] setupSync complete. Replicas:`, Array.from(this.replicaBackends.keys()));
3068
+ log3.log(`[ConfigRepo] Sync statuses:`, this.getSyncStatuses());
2950
3069
  }
2951
3070
  // -----------------------------------------------------------------------
2952
3071
  // Internal — Persistence
@@ -2958,12 +3077,12 @@ var ConfigRepo = class {
2958
3077
  try {
2959
3078
  const existing = await readVersion(this.fullFS, vPath);
2960
3079
  if (existing && existing.hash === version.hash) {
2961
- log2.log("[ConfigRepo] skip version sidecar (hash unchanged):", vPath);
3080
+ log3.log("[ConfigRepo] skip version sidecar (hash unchanged):", vPath);
2962
3081
  return;
2963
3082
  }
2964
3083
  } catch {
2965
3084
  }
2966
- log2.log("[ConfigRepo] write version sidecar:", vPath, "v" + version.version);
3085
+ log3.log("[ConfigRepo] write version sidecar:", vPath, "v" + version.version);
2967
3086
  await this.ensureDir(vPath);
2968
3087
  await writeVersion(this.fullFS, vPath, version);
2969
3088
  }
@@ -3067,7 +3186,7 @@ var ConfigRepo = class {
3067
3186
  await this.resolveConflict(`${conflictId}/meta.json`, customMerge);
3068
3187
  }
3069
3188
  } catch (err) {
3070
- log2.error("[zen-fs-config] Conflict handler error:", err);
3189
+ log3.error("[zen-fs-config] Conflict handler error:", err);
3071
3190
  }
3072
3191
  }
3073
3192
  }
@@ -3179,11 +3298,11 @@ var ConfigRepo = class {
3179
3298
  }
3180
3299
  return { kind: "ok", desc, mtime };
3181
3300
  } else {
3182
- log2.warn(`[ConfigRepo] Backend descriptor ${entry} is missing id/type fields, marking for cleanup`);
3301
+ log3.warn(`[ConfigRepo] Backend descriptor ${entry} is missing id/type fields, marking for cleanup`);
3183
3302
  return { kind: "corrupt", filePath };
3184
3303
  }
3185
3304
  } catch (parseErr) {
3186
- log2.warn(`[ConfigRepo] Backend descriptor ${entry} has corrupted JSON: ${parseErr}. Marking for cleanup.`);
3305
+ log3.warn(`[ConfigRepo] Backend descriptor ${entry} has corrupted JSON: ${parseErr}. Marking for cleanup.`);
3187
3306
  return { kind: "corrupt", filePath };
3188
3307
  }
3189
3308
  })
@@ -3254,7 +3373,7 @@ var ConfigRepo = class {
3254
3373
  }
3255
3374
  }
3256
3375
  if (duplicates.length > 0) {
3257
- log2.log(
3376
+ log3.log(
3258
3377
  `[ConfigRepo] readAllBackendDescriptors: removing ${duplicates.length} duplicate(s): ${duplicates.join(", ")}`
3259
3378
  );
3260
3379
  for (const dupId of duplicates) {
@@ -3385,7 +3504,7 @@ var ConfigRepo = class {
3385
3504
  * Shared by addBackend() and replaceBackend().
3386
3505
  */
3387
3506
  async setupReplica(id, type, options, description) {
3388
- log2.log(`[ConfigRepo] addBackend: creating ${id} (${type})...`);
3507
+ log3.log(`[ConfigRepo] addBackend: creating ${id} (${type})...`);
3389
3508
  const instance = await createBackend({ type, options });
3390
3509
  const syncable = backendToSyncableFS(instance, `${type}(${id})`);
3391
3510
  const desc = { id, type, options, description };
@@ -3401,7 +3520,7 @@ var ConfigRepo = class {
3401
3520
  this.invalidateTombstoneCache();
3402
3521
  await this.processTombstones();
3403
3522
  } catch (err) {
3404
- log2.warn("[ConfigRepo] preSyncHook processTombstones failed:", err);
3523
+ log3.warn("[ConfigRepo] preSyncHook processTombstones failed:", err);
3405
3524
  }
3406
3525
  },
3407
3526
  postSyncHook: async () => {
@@ -3410,7 +3529,7 @@ var ConfigRepo = class {
3410
3529
  await this.processTombstones();
3411
3530
  await this.updateTombstoneConfirmations();
3412
3531
  } catch (err) {
3413
- log2.warn("[ConfigRepo] postSyncHook tombstone processing failed:", err);
3532
+ log3.warn("[ConfigRepo] postSyncHook tombstone processing failed:", err);
3414
3533
  }
3415
3534
  }
3416
3535
  },
@@ -3422,7 +3541,8 @@ var ConfigRepo = class {
3422
3541
  this.handleConflict(event);
3423
3542
  };
3424
3543
  this.syncEngine.on(pair.pairId, "conflict", conflictHandler);
3425
- log2.log(`[ConfigRepo] addBackend: ${id} (${type}) added, sync pair=${pair.pairId}`);
3544
+ this.trackSyncErrors(id, pair.pairId);
3545
+ log3.log(`[ConfigRepo] addBackend: ${id} (${type}) added, sync pair=${pair.pairId}`);
3426
3546
  await this.syncMetaToReplicas();
3427
3547
  this.syncEngine.watch(pair.pairId);
3428
3548
  return pair.pairId;
@@ -3448,13 +3568,13 @@ var ConfigRepo = class {
3448
3568
  }
3449
3569
  }
3450
3570
  this.syncEngine.removePair(replica.pairId);
3451
- log2.log(`[ConfigRepo] removeBackend: sync pair ${replica.pairId} removed`);
3571
+ log3.log(`[ConfigRepo] removeBackend: sync pair ${replica.pairId} removed`);
3452
3572
  this.replicaBackends.delete(id);
3453
3573
  if (replica.instance?.dispose) {
3454
3574
  await replica.instance.dispose();
3455
3575
  }
3456
3576
  } else {
3457
- log2.log(`[ConfigRepo] removeBackend: "${id}" not in replicaBackends, cleaning up descriptor only`);
3577
+ log3.log(`[ConfigRepo] removeBackend: "${id}" not in replicaBackends, cleaning up descriptor only`);
3458
3578
  for (const descPath of descPaths) {
3459
3579
  try {
3460
3580
  await this.deleteFile(descPath);
@@ -3465,7 +3585,7 @@ var ConfigRepo = class {
3465
3585
  }
3466
3586
  this.backendStates.delete(id);
3467
3587
  this.schedulePostDeleteSync();
3468
- log2.log(`[ConfigRepo] removeBackend: ${id} removed (tombstone written, remote cleaned)`);
3588
+ log3.log(`[ConfigRepo] removeBackend: ${id} removed (tombstone written, remote cleaned)`);
3469
3589
  }
3470
3590
  /**
3471
3591
  * Replace a config-sync backend's parameters in place (same id).
@@ -3512,11 +3632,11 @@ var ConfigRepo = class {
3512
3632
  await this.setupReplica(id, type, options, description ?? before.description);
3513
3633
  } catch (err) {
3514
3634
  const reason = err instanceof Error ? err.message : String(err);
3515
- log2.warn(`[ConfigRepo] replaceBackend: "${id}" failed, rolling back old options:`, err);
3635
+ log3.warn(`[ConfigRepo] replaceBackend: "${id}" failed, rolling back old options:`, err);
3516
3636
  try {
3517
3637
  await this.setupReplica(id, before.type, before.options, before.description);
3518
3638
  } catch (rollbackErr) {
3519
- log2.error(`[ConfigRepo] replaceBackend: rollback for "${id}" ALSO failed:`, rollbackErr);
3639
+ log3.error(`[ConfigRepo] replaceBackend: rollback for "${id}" ALSO failed:`, rollbackErr);
3520
3640
  }
3521
3641
  throw new Error(`\u66F4\u65B0\u540E\u7AEF\u53C2\u6570\u5931\u8D25\uFF1A${reason}\uFF08\u5DF2\u5C1D\u8BD5\u56DE\u6EDA\u65E7\u53C2\u6570\uFF09`);
3522
3642
  }
@@ -3532,7 +3652,7 @@ var ConfigRepo = class {
3532
3652
  const existing = await this.cachedFS.readFile(path, "utf-8");
3533
3653
  const current = existing.trim();
3534
3654
  if (current && current !== type) {
3535
- log2.warn(`[ConfigRepo] group-type already set to "${current}" at ${path}, ignoring request to set "${type}"`);
3655
+ log3.warn(`[ConfigRepo] group-type already set to "${current}" at ${path}, ignoring request to set "${type}"`);
3536
3656
  return;
3537
3657
  }
3538
3658
  } catch {
@@ -3563,7 +3683,7 @@ var ConfigRepo = class {
3563
3683
  features: existingDescriptor.features ?? CONFIG_GROUP_FEATURES
3564
3684
  });
3565
3685
  }
3566
- log2.log(`[ConfigRepo] group-type set to "${type}"`);
3686
+ log3.log(`[ConfigRepo] group-type set to "${type}"`);
3567
3687
  }
3568
3688
  /** Read the group-type marker. Returns null if not set (new path, then legacy). */
3569
3689
  async getGroupType() {
@@ -3658,7 +3778,7 @@ var ConfigRepo = class {
3658
3778
  if (this.appDataGroups.has(id)) {
3659
3779
  throw new Error(`App data group "${id}" already exists. Use removeAppDataGroup() first.`);
3660
3780
  }
3661
- log2.log(`[ConfigRepo] createAppDataGroup: creating "${id}" with ${backends.length} backend(s)`);
3781
+ log3.log(`[ConfigRepo] createAppDataGroup: creating "${id}" with ${backends.length} backend(s)`);
3662
3782
  const resolvedBackends = [];
3663
3783
  for (const desc of backends) {
3664
3784
  assertValidBackendId(desc.id);
@@ -3685,7 +3805,7 @@ var ConfigRepo = class {
3685
3805
  };
3686
3806
  await this.writeAppDataGroupDescriptorFile(id, descriptor);
3687
3807
  this.appDataGroups.set(id, group);
3688
- log2.log(`[ConfigRepo] createAppDataGroup: "${id}" created`);
3808
+ log3.log(`[ConfigRepo] createAppDataGroup: "${id}" created`);
3689
3809
  return group;
3690
3810
  }
3691
3811
  /**
@@ -3728,7 +3848,7 @@ var ConfigRepo = class {
3728
3848
  try {
3729
3849
  await live.writeOwnGroupDescriptor();
3730
3850
  } catch (err) {
3731
- log2.warn(`[ConfigRepo] updateAppDataGroupName: "${id}" group.json update failed:`, err);
3851
+ log3.warn(`[ConfigRepo] updateAppDataGroupName: "${id}" group.json update failed:`, err);
3732
3852
  }
3733
3853
  }
3734
3854
  const descriptor = {
@@ -3791,7 +3911,7 @@ var ConfigRepo = class {
3791
3911
  return group;
3792
3912
  } catch (err) {
3793
3913
  const reason = err instanceof Error ? err.message : String(err);
3794
- log2.warn(`[ConfigRepo] replaceAppDataGroupBackend: "${backendId}" failed, rolling back:`, err);
3914
+ log3.warn(`[ConfigRepo] replaceAppDataGroupBackend: "${backendId}" failed, rolling back:`, err);
3795
3915
  try {
3796
3916
  const restored = new AppDataGroupImpl(
3797
3917
  groupId,
@@ -3805,7 +3925,7 @@ var ConfigRepo = class {
3805
3925
  await this.updateAppDataGroupDescriptor(groupId, restored.listDeclaredBackends());
3806
3926
  this.appDataGroups.set(groupId, restored);
3807
3927
  } catch (rollbackErr) {
3808
- log2.error("[ConfigRepo] replaceAppDataGroupBackend: rollback ALSO failed:", rollbackErr);
3928
+ log3.error("[ConfigRepo] replaceAppDataGroupBackend: rollback ALSO failed:", rollbackErr);
3809
3929
  }
3810
3930
  throw new Error(`\u66F4\u65B0\u540E\u7AEF\u53C2\u6570\u5931\u8D25\uFF1A${reason}\uFF08\u5DF2\u5C1D\u8BD5\u56DE\u6EDA\u65E7\u53C2\u6570\uFF09`);
3811
3931
  }
@@ -3923,7 +4043,7 @@ var ConfigRepo = class {
3923
4043
  try {
3924
4044
  await this.deleteFile(descPath);
3925
4045
  } catch (err) {
3926
- log2.log(`[ConfigRepo] removeAppDataGroup: deleteFile failed for "${id}" at ${descPath}:`, err);
4046
+ log3.log(`[ConfigRepo] removeAppDataGroup: deleteFile failed for "${id}" at ${descPath}:`, err);
3927
4047
  try {
3928
4048
  await this.cachedFS.unlink(descPath);
3929
4049
  } catch {
@@ -3931,7 +4051,7 @@ var ConfigRepo = class {
3931
4051
  await this.unlinkVersionSidecar(this.cachedFS, descPath);
3932
4052
  }
3933
4053
  }
3934
- log2.log(`[ConfigRepo] removeAppDataGroup: "${id}" removed`);
4054
+ log3.log(`[ConfigRepo] removeAppDataGroup: "${id}" removed`);
3935
4055
  }
3936
4056
  async listAccountBackends() {
3937
4057
  this.assertNotDisposed();
@@ -4106,24 +4226,24 @@ var AppDataGroupImpl = class {
4106
4226
  try {
4107
4227
  const purged = await purgeMtimeSidecars(this.localFS);
4108
4228
  if (purged.removed.length > 0) {
4109
- log2.warn(
4229
+ log3.warn(
4110
4230
  `[AppDataGroup:${this.groupId}] purged ${purged.removed.length} leaked .mtime sidecar(s):`,
4111
4231
  purged.removed
4112
4232
  );
4113
4233
  }
4114
4234
  } catch (err) {
4115
- log2.warn(`[AppDataGroup:${this.groupId}] .mtime purge failed:`, err?.message ?? err);
4235
+ log3.warn(`[AppDataGroup:${this.groupId}] .mtime purge failed:`, err?.message ?? err);
4116
4236
  }
4117
4237
  try {
4118
4238
  const purgedKeep = await purgeKeepFiles(this.localFS);
4119
4239
  if (purgedKeep.removed.length > 0) {
4120
- log2.warn(
4240
+ log3.warn(
4121
4241
  `[AppDataGroup:${this.groupId}] purged ${purgedKeep.removed.length} leaked .keep placeholder(s):`,
4122
4242
  purgedKeep.removed
4123
4243
  );
4124
4244
  }
4125
4245
  } catch (err) {
4126
- log2.warn(`[AppDataGroup:${this.groupId}] .keep purge failed:`, err?.message ?? err);
4246
+ log3.warn(`[AppDataGroup:${this.groupId}] .keep purge failed:`, err?.message ?? err);
4127
4247
  }
4128
4248
  const localSyncable = backendToSyncableFS(this.localFS, `local(${this.groupId})`);
4129
4249
  this.tombstones = new TombstoneStore(this.localFS, this.localBackendId);
@@ -4133,13 +4253,13 @@ var AppDataGroupImpl = class {
4133
4253
  try {
4134
4254
  backendsChanged = await this.loadBackendDescriptors();
4135
4255
  } catch (err) {
4136
- log2.warn(`[AppDataGroup:${this.groupId}] failed to load .meta/backends:`, err);
4256
+ log3.warn(`[AppDataGroup:${this.groupId}] failed to load .meta/backends:`, err);
4137
4257
  this._backends = this._backends ?? [];
4138
4258
  }
4139
4259
  try {
4140
4260
  await this.writeOwnGroupDescriptor();
4141
4261
  } catch (err) {
4142
- log2.warn(`[AppDataGroup:${this.groupId}] failed to write .meta/group.json:`, err);
4262
+ log3.warn(`[AppDataGroup:${this.groupId}] failed to write .meta/group.json:`, err);
4143
4263
  }
4144
4264
  this.fs = createChrootFS(this.localFS, "/", {
4145
4265
  hiddenPrefixes: [META_DIR, CONFIG_DIR],
@@ -4149,7 +4269,7 @@ var AppDataGroupImpl = class {
4149
4269
  });
4150
4270
  const { kept, removed } = dedupeAppDataBackends(this._backends);
4151
4271
  if (removed.length > 0) {
4152
- log2.warn(
4272
+ log3.warn(
4153
4273
  `[AppDataGroup:${this.groupId}] dedupe: removing ${removed.length} duplicate backend(s) (${removed.map((b) => b.id).join(", ")}) \u2014 keeping ${kept.map((b) => b.id).join(", ")}`
4154
4274
  );
4155
4275
  this._backends = kept;
@@ -4163,7 +4283,7 @@ var AppDataGroupImpl = class {
4163
4283
  features: this._declaredFeatures
4164
4284
  });
4165
4285
  } catch (err) {
4166
- log2.warn(`[AppDataGroup:${this.groupId}] failed to persist backend topology:`, err);
4286
+ log3.warn(`[AppDataGroup:${this.groupId}] failed to persist backend topology:`, err);
4167
4287
  }
4168
4288
  }
4169
4289
  for (const desc of this._backends) {
@@ -4195,25 +4315,26 @@ var AppDataGroupImpl = class {
4195
4315
  if (this.features.conflicts) {
4196
4316
  const conflictHandler = (event) => {
4197
4317
  this.archiveConflict(event).catch((err) => {
4198
- log2.warn(`[AppDataGroup:${this.groupId}] conflict archive failed:`, err);
4318
+ log3.warn(`[AppDataGroup:${this.groupId}] conflict archive failed:`, err);
4199
4319
  });
4200
4320
  };
4201
4321
  this.syncEngine.on(pair.pairId, "conflict", conflictHandler);
4202
4322
  }
4203
- log2.log(`[AppDataGroup:${this.groupId}] backend ${desc.id} (${desc.type}) connected, pair=${pair.pairId}`);
4323
+ this.trackSyncErrors(desc.id, pair.pairId);
4324
+ log3.log(`[AppDataGroup:${this.groupId}] backend ${desc.id} (${desc.type}) connected, pair=${pair.pairId}`);
4204
4325
  } catch (err) {
4205
4326
  const message = err instanceof Error ? err.message : String(err);
4206
4327
  this.backendStates.set(desc.id, {
4207
4328
  backendId: desc.id,
4208
4329
  error: { message, timestamp: Date.now() }
4209
4330
  });
4210
- log2.error(`[AppDataGroup:${this.groupId}] Failed to create backend ${desc.id} (${desc.type}):`, err);
4331
+ log3.error(`[AppDataGroup:${this.groupId}] Failed to create backend ${desc.id} (${desc.type}):`, err);
4211
4332
  }
4212
4333
  }
4213
4334
  try {
4214
4335
  await this.syncEngine.syncAll();
4215
4336
  } catch (err) {
4216
- log2.warn(`[AppDataGroup:${this.groupId}] Initial sync failed:`, err);
4337
+ log3.warn(`[AppDataGroup:${this.groupId}] Initial sync failed:`, err);
4217
4338
  }
4218
4339
  this.syncEngine.watchAll();
4219
4340
  }
@@ -4228,13 +4349,31 @@ var AppDataGroupImpl = class {
4228
4349
  try {
4229
4350
  await this.tombstones.gc(this.allBackendIds(), this.tombstoneTargets());
4230
4351
  } catch (err) {
4231
- log2.warn(`[AppDataGroup:${this.groupId}] tombstone GC failed:`, err);
4352
+ log3.warn(`[AppDataGroup:${this.groupId}] tombstone GC failed:`, err);
4232
4353
  }
4233
4354
  return Array.from(results.values());
4234
4355
  }
4235
4356
  getBackendSyncStates() {
4236
4357
  return new Map(this.backendStates);
4237
4358
  }
4359
+ /** Mirror per-pair `sync:error` into `getBackendSyncStates()` (see ConfigRepo). */
4360
+ trackSyncErrors(backendId, pairId) {
4361
+ this.syncEngine.on(pairId, "sync:error", (event) => {
4362
+ const error = event.error;
4363
+ this.backendStates.set(backendId, {
4364
+ backendId,
4365
+ pairId,
4366
+ error: {
4367
+ message: error instanceof Error ? error.message : String(error ?? "sync failed"),
4368
+ timestamp: Date.now()
4369
+ }
4370
+ });
4371
+ });
4372
+ this.syncEngine.on(pairId, "sync:end", () => {
4373
+ const current = this.backendStates.get(backendId);
4374
+ if (current?.error) this.backendStates.set(backendId, { backendId, pairId });
4375
+ });
4376
+ }
4238
4377
  // -----------------------------------------------------------------------
4239
4378
  // Unified SyncGroupHandle — deletion & metadata (data groups)
4240
4379
  // -----------------------------------------------------------------------
@@ -4245,7 +4384,7 @@ var AppDataGroupImpl = class {
4245
4384
  const bytes = typeof data === "string" ? new TextEncoder().encode(data) : toUint8Array2(data);
4246
4385
  await this.versions.record(path, bytes);
4247
4386
  } catch (err) {
4248
- log2.warn(`[AppDataGroup:${this.groupId}] version record failed for ${path}:`, err);
4387
+ log3.warn(`[AppDataGroup:${this.groupId}] version record failed for ${path}:`, err);
4249
4388
  }
4250
4389
  }
4251
4390
  /** Delete tombstoned files on local + every connected backend before/after sync. */
@@ -4253,14 +4392,14 @@ var AppDataGroupImpl = class {
4253
4392
  try {
4254
4393
  await this.tombstones.process(this.tombstoneTargets());
4255
4394
  } catch (err) {
4256
- log2.warn(`[AppDataGroup:${this.groupId}] ${stage} tombstone pass failed:`, err);
4395
+ log3.warn(`[AppDataGroup:${this.groupId}] ${stage} tombstone pass failed:`, err);
4257
4396
  }
4258
4397
  }
4259
4398
  async confirmTombstones() {
4260
4399
  try {
4261
4400
  await this.tombstones.confirm(this.allBackendIds());
4262
4401
  } catch (err) {
4263
- log2.warn(`[AppDataGroup:${this.groupId}] tombstone confirmations failed:`, err);
4402
+ log3.warn(`[AppDataGroup:${this.groupId}] tombstone confirmations failed:`, err);
4264
4403
  }
4265
4404
  }
4266
4405
  /** Write a tombstone for `filePath`. Records metadata only — it never creates the file. */
@@ -4293,7 +4432,7 @@ var AppDataGroupImpl = class {
4293
4432
  }
4294
4433
  await removeDirectoryTree(this.localFS, normalized);
4295
4434
  this.schedulePostDeleteSync();
4296
- log2.log(`[AppDataGroup:${this.groupId}] deleteFile(directory): ${normalized} (${files.length} file(s))`);
4435
+ log3.log(`[AppDataGroup:${this.groupId}] deleteFile(directory): ${normalized} (${files.length} file(s))`);
4297
4436
  return;
4298
4437
  }
4299
4438
  await this.writeTombstoneFor(normalized);
@@ -4332,7 +4471,7 @@ var AppDataGroupImpl = class {
4332
4471
  try {
4333
4472
  await this.syncEngine.syncAll();
4334
4473
  } catch (err) {
4335
- log2.warn(`[AppDataGroup:${this.groupId}] sync after conflict resolve failed:`, err);
4474
+ log3.warn(`[AppDataGroup:${this.groupId}] sync after conflict resolve failed:`, err);
4336
4475
  }
4337
4476
  }
4338
4477
  readConflictBackup(conflictId, fileType) {
@@ -4367,7 +4506,7 @@ var AppDataGroupImpl = class {
4367
4506
  if (this.dataBackends.has(id)) {
4368
4507
  throw new Error(`Backend "${id}" already exists in data group "${this.groupId}"`);
4369
4508
  }
4370
- log2.log(`[AppDataGroup:${this.groupId}] addBackend: creating ${id} (${type})...`);
4509
+ log3.log(`[AppDataGroup:${this.groupId}] addBackend: creating ${id} (${type})...`);
4371
4510
  const instance = await createBackend({ type, options });
4372
4511
  const syncable = backendToSyncableFS(instance, `${type}(${id})`);
4373
4512
  const localSyncable = backendToSyncableFS(this.localFS, `local(${this.groupId})`);
@@ -4395,12 +4534,13 @@ var AppDataGroupImpl = class {
4395
4534
  if (this.features.conflicts) {
4396
4535
  this.syncEngine.on(pair.pairId, "conflict", (event) => {
4397
4536
  this.archiveConflict(event).catch((err) => {
4398
- log2.warn(`[AppDataGroup:${this.groupId}] conflict archive failed:`, err);
4537
+ log3.warn(`[AppDataGroup:${this.groupId}] conflict archive failed:`, err);
4399
4538
  });
4400
4539
  });
4401
4540
  }
4541
+ this.trackSyncErrors(id, pair.pairId);
4402
4542
  this._backends = [...this._backends.filter((b) => b.id !== id), desc];
4403
- log2.log(`[AppDataGroup:${this.groupId}] addBackend: ${id} (${type}) connected, pair=${pair.pairId}`);
4543
+ log3.log(`[AppDataGroup:${this.groupId}] addBackend: ${id} (${type}) connected, pair=${pair.pairId}`);
4404
4544
  try {
4405
4545
  const stale = (await this.tombstones.list()).find(
4406
4546
  (t) => t.path === backendMetaFilePath(id)
@@ -4408,12 +4548,12 @@ var AppDataGroupImpl = class {
4408
4548
  if (stale) await this.tombstones.remove(stale);
4409
4549
  await writeBackendMetaDescriptor(this.localFS, desc);
4410
4550
  } catch (err) {
4411
- log2.warn(`[AppDataGroup:${this.groupId}] addBackend: failed to write .meta/backends/${id}.json:`, err);
4551
+ log3.warn(`[AppDataGroup:${this.groupId}] addBackend: failed to write .meta/backends/${id}.json:`, err);
4412
4552
  }
4413
4553
  try {
4414
4554
  await this.syncEngine.sync(pair.pairId);
4415
4555
  } catch (err) {
4416
- log2.warn(`[AppDataGroup:${this.groupId}] addBackend: initial sync failed for ${id}:`, err);
4556
+ log3.warn(`[AppDataGroup:${this.groupId}] addBackend: initial sync failed for ${id}:`, err);
4417
4557
  }
4418
4558
  this.syncEngine.watch(pair.pairId);
4419
4559
  await this.parent.updateAppDataGroupDescriptor(this.groupId, this._backends, {
@@ -4444,7 +4584,7 @@ var AppDataGroupImpl = class {
4444
4584
  if (backend?.instance?.dispose) {
4445
4585
  await backend.instance.dispose();
4446
4586
  }
4447
- log2.log(`[AppDataGroup:${this.groupId}] removeBackend: ${id} removed`);
4587
+ log3.log(`[AppDataGroup:${this.groupId}] removeBackend: ${id} removed`);
4448
4588
  }
4449
4589
  listBackends() {
4450
4590
  return Array.from(this.dataBackends.values()).map((b) => b.desc);
@@ -4486,44 +4626,44 @@ async function createConfigRepo(appId, options = {}) {
4486
4626
  idbStoreName: options.idbStoreName,
4487
4627
  folderPath: options.folderPath
4488
4628
  });
4489
- log2.log(`[createConfigRepo] Creating local primary (type: ${localPrimary.type})...`);
4629
+ log3.log(`[createConfigRepo] Creating local primary (type: ${localPrimary.type})...`);
4490
4630
  const primaryInstance = await createBackend(localPrimary);
4491
4631
  const cachedFS = primaryInstance;
4492
4632
  if (options.purgeMtimeSidecars !== false) {
4493
4633
  try {
4494
4634
  const purged = await purgeMtimeSidecars(cachedFS);
4495
4635
  if (purged.removed.length > 0) {
4496
- log2.warn(
4636
+ log3.warn(
4497
4637
  `[createConfigRepo] purged ${purged.removed.length} leaked .mtime sidecar(s) from local primary:`,
4498
4638
  purged.removed
4499
4639
  );
4500
4640
  }
4501
4641
  } catch (err) {
4502
- log2.warn(`[createConfigRepo] .mtime purge failed:`, err?.message ?? err);
4642
+ log3.warn(`[createConfigRepo] .mtime purge failed:`, err?.message ?? err);
4503
4643
  }
4504
4644
  }
4505
4645
  if (options.purgeKeepFiles !== false) {
4506
4646
  try {
4507
4647
  const purged = await purgeKeepFiles(cachedFS);
4508
4648
  if (purged.removed.length > 0) {
4509
- log2.warn(
4649
+ log3.warn(
4510
4650
  `[createConfigRepo] purged ${purged.removed.length} leaked .keep placeholder(s) from local primary:`,
4511
4651
  purged.removed
4512
4652
  );
4513
4653
  }
4514
4654
  } catch (err) {
4515
- log2.warn(`[createConfigRepo] .keep purge failed:`, err?.message ?? err);
4655
+ log3.warn(`[createConfigRepo] .keep purge failed:`, err?.message ?? err);
4516
4656
  }
4517
4657
  }
4518
4658
  const cacheOptions = options.cache === false ? void 0 : options.cache ?? {};
4519
4659
  try {
4520
4660
  await primaryInstance.mkdir(META_DIR);
4521
- log2.log(`[createConfigRepo] /.meta/ ready`);
4661
+ log3.log(`[createConfigRepo] /.meta/ ready`);
4522
4662
  } catch (err) {
4523
4663
  const msg = err.message || "";
4524
4664
  if (msg.includes("File exists") || msg.includes("EEXIST") || err.code === "EEXIST") {
4525
4665
  } else {
4526
- log2.error(`[createConfigRepo] Failed to ensure /.meta/:`, err.message);
4666
+ log3.error(`[createConfigRepo] Failed to ensure /.meta/:`, err.message);
4527
4667
  }
4528
4668
  }
4529
4669
  try {
@@ -4534,7 +4674,7 @@ async function createConfigRepo(appId, options = {}) {
4534
4674
  } catch {
4535
4675
  await ensureParentDir2(primaryInstance, path);
4536
4676
  await primaryInstance.writeFile(path, groupTypeBytes);
4537
- log2.log(`[createConfigRepo] group-type set to "config-sync" at ${path}`);
4677
+ log3.log(`[createConfigRepo] group-type set to "config-sync" at ${path}`);
4538
4678
  }
4539
4679
  }
4540
4680
  if (!await readGroupDescriptor(primaryInstance)) {
@@ -4546,7 +4686,7 @@ async function createConfigRepo(appId, options = {}) {
4546
4686
  });
4547
4687
  }
4548
4688
  } catch (err) {
4549
- log2.warn(`[createConfigRepo] Failed to write group metadata:`, err.message);
4689
+ log3.warn(`[createConfigRepo] Failed to write group metadata:`, err.message);
4550
4690
  }
4551
4691
  const tempRepo = new ConfigRepo(
4552
4692
  appId,
@@ -4560,11 +4700,11 @@ async function createConfigRepo(appId, options = {}) {
4560
4700
  );
4561
4701
  const oldBackendsMeta = await tempRepo.readMetaFile(BACKENDS_FILE);
4562
4702
  if (oldBackendsMeta && oldBackendsMeta.backends?.length > 0) {
4563
- log2.log(`[createConfigRepo] Migrating ${oldBackendsMeta.backends.length} backend(s) from backends.json to individual files...`);
4703
+ log3.log(`[createConfigRepo] Migrating ${oldBackendsMeta.backends.length} backend(s) from backends.json to individual files...`);
4564
4704
  await tempRepo.ensureDir(`${BACKENDS_DIR}/.keep`);
4565
4705
  for (const desc of oldBackendsMeta.backends) {
4566
4706
  if (desc.id === LOCAL_IDB_BACKEND_ID) {
4567
- log2.log(`[createConfigRepo] Skipping local backend ${desc.id} during migration`);
4707
+ log3.log(`[createConfigRepo] Skipping local backend ${desc.id} during migration`);
4568
4708
  continue;
4569
4709
  }
4570
4710
  await tempRepo.writeBackendDescriptor(desc);
@@ -4582,7 +4722,7 @@ async function createConfigRepo(appId, options = {}) {
4582
4722
  }
4583
4723
  }
4584
4724
  }
4585
- log2.log(`[createConfigRepo] Migration complete`);
4725
+ log3.log(`[createConfigRepo] Migration complete`);
4586
4726
  }
4587
4727
  let allBackends = await tempRepo.readAllBackendDescriptors();
4588
4728
  if (options.backendInfo) {
@@ -4600,19 +4740,19 @@ async function createConfigRepo(appId, options = {}) {
4600
4740
  type: options.backendInfo.type,
4601
4741
  options: options.backendInfo.options
4602
4742
  });
4603
- log2.log(`[createConfigRepo] Added replica backend: ${replicaId} (${options.backendInfo.type})`);
4743
+ log3.log(`[createConfigRepo] Added replica backend: ${replicaId} (${options.backendInfo.type})`);
4604
4744
  allBackends = [...allBackends, { id: replicaId, type: options.backendInfo.type, options: options.backendInfo.options }];
4605
4745
  } else if (dupConfig) {
4606
- log2.log(`[createConfigRepo] Replica with same config already registered as "${dupConfig.id}", skipping`);
4746
+ log3.log(`[createConfigRepo] Replica with same config already registered as "${dupConfig.id}", skipping`);
4607
4747
  } else {
4608
- log2.log(`[createConfigRepo] Replica ${replicaId} already registered`);
4748
+ log3.log(`[createConfigRepo] Replica ${replicaId} already registered`);
4609
4749
  }
4610
4750
  }
4611
- log2.log(`[createConfigRepo] Replica backends: ${allBackends.map((b) => b.id).join(", ") || "(none)"}`);
4751
+ log3.log(`[createConfigRepo] Replica backends: ${allBackends.map((b) => b.id).join(", ") || "(none)"}`);
4612
4752
  let nodeId = options.nodeId;
4613
4753
  if (!nodeId) {
4614
4754
  nodeId = `node-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`;
4615
- log2.log(`[createConfigRepo] Generated nodeId: ${nodeId}`);
4755
+ log3.log(`[createConfigRepo] Generated nodeId: ${nodeId}`);
4616
4756
  }
4617
4757
  const serializer = createSerializerChain(options.serializer);
4618
4758
  const repo = new ConfigRepo(
@@ -4635,30 +4775,30 @@ async function createConfigRepo(appId, options = {}) {
4635
4775
  try {
4636
4776
  const mig = await repo.migrateLegacyVersionSidecars();
4637
4777
  if (mig.renamed.length === 0 && mig.deleted.length === 0 && mig.remoteDeleted.length === 0) {
4638
- log2.log("[createConfigRepo] no legacy version sidecars to migrate");
4778
+ log3.log("[createConfigRepo] no legacy version sidecars to migrate");
4639
4779
  }
4640
4780
  } catch (err) {
4641
- log2.warn(`[createConfigRepo] version sidecar migration failed:`, err?.message ?? err);
4781
+ log3.warn(`[createConfigRepo] version sidecar migration failed:`, err?.message ?? err);
4642
4782
  }
4643
4783
  }
4644
4784
  await repo.load();
4645
4785
  if (repo.replicaCount > 0) {
4646
- log2.log("[createConfigRepo] Starting background initial sync + dedup...");
4786
+ log3.log("[createConfigRepo] Starting background initial sync + dedup...");
4647
4787
  repo.startBackgroundSync();
4648
4788
  }
4649
4789
  repo.syncMetaToReplicas().catch((err) => {
4650
- log2.error("[createConfigRepo] background syncMetaToReplicas failed:", err);
4790
+ log3.error("[createConfigRepo] background syncMetaToReplicas failed:", err);
4651
4791
  });
4652
4792
  return repo;
4653
4793
  }
4654
4794
 
4655
4795
  // src/connect.ts
4656
4796
  init_backend_registry();
4657
- var log3 = createLogger("connect");
4797
+ var log4 = createLogger("connect");
4658
4798
  var GROUP_TYPE_FILE2 = "/.config/group-type";
4659
4799
  var LEGACY_GROUP_TYPE_FILE2 = "/.meta/group-type";
4660
4800
  async function detectGroupType(type, options) {
4661
- log3(`detectGroupType: connecting to ${type}...`);
4801
+ log4(`detectGroupType: connecting to ${type}...`);
4662
4802
  const tempBackend = await createBackend({ type, options });
4663
4803
  try {
4664
4804
  for (const path of [GROUP_TYPE_FILE2, LEGACY_GROUP_TYPE_FILE2]) {
@@ -4666,15 +4806,15 @@ async function detectGroupType(type, options) {
4666
4806
  const raw = await tempBackend.readFile(path, "utf-8");
4667
4807
  const groupType = raw.trim();
4668
4808
  if (groupType === "config-sync" || groupType === "data-sync") {
4669
- log3(`detectGroupType: detected "${groupType}" at ${path}`);
4809
+ log4(`detectGroupType: detected "${groupType}" at ${path}`);
4670
4810
  return groupType;
4671
4811
  }
4672
- log3(`detectGroupType: unknown group-type value "${groupType}" at ${path}, treating as null`);
4812
+ log4(`detectGroupType: unknown group-type value "${groupType}" at ${path}, treating as null`);
4673
4813
  return null;
4674
4814
  } catch {
4675
4815
  }
4676
4816
  }
4677
- log3(`detectGroupType: no group-type file found (new backend)`);
4817
+ log4(`detectGroupType: no group-type file found (new backend)`);
4678
4818
  return null;
4679
4819
  } finally {
4680
4820
  if (tempBackend?.dispose) {
@@ -4683,7 +4823,7 @@ async function detectGroupType(type, options) {
4683
4823
  }
4684
4824
  }
4685
4825
  async function connect(appId, options = {}) {
4686
- log3(`connect: appId=${appId}`);
4826
+ log4(`connect: appId=${appId}`);
4687
4827
  if (!options.backendInfo) {
4688
4828
  const repo2 = await createConfigRepo(appId, {
4689
4829
  idbStoreName: options.idbStoreName,
@@ -4701,7 +4841,7 @@ async function connect(appId, options = {}) {
4701
4841
  try {
4702
4842
  appDataGroups2.push(await repo2.getAppDataGroup(d.id));
4703
4843
  } catch (err) {
4704
- log3(`connect: failed to load app data group "${d.id}":`, err);
4844
+ log4(`connect: failed to load app data group "${d.id}":`, err);
4705
4845
  }
4706
4846
  }
4707
4847
  let dataGroup2 = appDataGroups2[0];
@@ -4730,7 +4870,7 @@ async function connect(appId, options = {}) {
4730
4870
  groupType = detectedType;
4731
4871
  } else {
4732
4872
  groupType = options.groupType ?? "config-sync";
4733
- log3(`connect: new backend, using groupType="${groupType}"`);
4873
+ log4(`connect: new backend, using groupType="${groupType}"`);
4734
4874
  }
4735
4875
  const repo = await createConfigRepo(
4736
4876
  appId,
@@ -4759,7 +4899,7 @@ async function connect(appId, options = {}) {
4759
4899
  try {
4760
4900
  appDataGroups.push(await repo.getAppDataGroup(d.id));
4761
4901
  } catch (err) {
4762
- log3(`connect: failed to load app data group "${d.id}":`, err);
4902
+ log4(`connect: failed to load app data group "${d.id}":`, err);
4763
4903
  }
4764
4904
  }
4765
4905
  let dataGroup = appDataGroups[0];