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.mjs CHANGED
@@ -423,7 +423,7 @@ async function defaultNodeDir(appId, kind, groupId) {
423
423
  }
424
424
 
425
425
  // src/config-repo.ts
426
- import { createLogger as createLogger2 } from "@richard432/localstorage-logger";
426
+ import { createLogger as createLogger3 } from "@richard432/localstorage-logger";
427
427
 
428
428
  // src/version.ts
429
429
  function versionPathFor(configFilePath) {
@@ -909,6 +909,9 @@ async function migrateVersionSidecars(fs, options = {}) {
909
909
  return result;
910
910
  }
911
911
 
912
+ // src/group-meta.ts
913
+ import { createLogger as createLogger2 } from "@richard432/localstorage-logger";
914
+
912
915
  // src/canonical-json.ts
913
916
  var FEATURE_ORDER = ["tombstones", "versions", "conflicts", "configHost", "appData"];
914
917
  var GROUP_DESCRIPTOR_ORDER = ["schemaVersion", "kind", "id", "name", "features"];
@@ -982,6 +985,7 @@ function mergeDescriptorCreatedAt(descriptor, existing) {
982
985
  }
983
986
 
984
987
  // src/group-meta.ts
988
+ var log2 = createLogger2("zen-fs-config:tombstones");
985
989
  var META_DIR = "/.meta";
986
990
  var GROUP_DESCRIPTOR_FILE = `${META_DIR}/group.json`;
987
991
  var META_BACKENDS_DIR = `${META_DIR}/backends`;
@@ -1052,6 +1056,141 @@ function encodeMetaPath(filePath) {
1052
1056
  const normalized = filePath.startsWith("/") ? filePath : `/${filePath}`;
1053
1057
  return normalized.replace(/^\//, "").replace(/\//g, "__").replace(/\./g, "++");
1054
1058
  }
1059
+ function decodeMetaPath(entry) {
1060
+ if (!entry.endsWith(".json")) return null;
1061
+ const encoded = entry.slice(0, -".json".length);
1062
+ if (!encoded) return null;
1063
+ return `/${encoded.replace(/__/g, "/").replace(/\+\+/g, ".")}`;
1064
+ }
1065
+ function fallbackTombstone(path) {
1066
+ return { path, deletedAt: 0, deletedBy: "unknown", confirmedBy: [] };
1067
+ }
1068
+ function normalizeTombstoneRecord(value, fallbackPath) {
1069
+ if (!value || typeof value !== "object" || Array.isArray(value)) return null;
1070
+ const record = value;
1071
+ const rawPath = typeof record.path === "string" ? record.path : fallbackPath;
1072
+ if (!rawPath) return null;
1073
+ const path = rawPath.startsWith("/") ? rawPath : `/${rawPath}`;
1074
+ const confirmedBy = Array.isArray(record.confirmedBy) ? record.confirmedBy.filter((id) => typeof id === "string") : [];
1075
+ return {
1076
+ path,
1077
+ deletedAt: typeof record.deletedAt === "number" ? record.deletedAt : 0,
1078
+ deletedBy: typeof record.deletedBy === "string" ? record.deletedBy : "unknown",
1079
+ confirmedBy
1080
+ };
1081
+ }
1082
+ function extractJsonObjects(raw) {
1083
+ const objects = [];
1084
+ let depth = 0;
1085
+ let start = -1;
1086
+ let inString = false;
1087
+ let escaped = false;
1088
+ for (let i = 0; i < raw.length; i++) {
1089
+ const ch = raw[i];
1090
+ if (inString) {
1091
+ if (escaped) escaped = false;
1092
+ else if (ch === "\\") escaped = true;
1093
+ else if (ch === '"') inString = false;
1094
+ continue;
1095
+ }
1096
+ if (ch === '"') {
1097
+ inString = true;
1098
+ continue;
1099
+ }
1100
+ if (ch === "{") {
1101
+ if (depth === 0) start = i;
1102
+ depth++;
1103
+ continue;
1104
+ }
1105
+ if (ch === "}") {
1106
+ if (depth === 0) continue;
1107
+ depth--;
1108
+ if (depth === 0 && start >= 0) {
1109
+ objects.push(raw.slice(start, i + 1));
1110
+ start = -1;
1111
+ }
1112
+ }
1113
+ }
1114
+ return objects;
1115
+ }
1116
+ function parseTombstoneFile(raw, fallbackPath) {
1117
+ const problems = [];
1118
+ const text = raw.trim();
1119
+ if (text === "") {
1120
+ problems.push("empty body");
1121
+ if (fallbackPath) {
1122
+ problems.push("path derived from filename");
1123
+ return { tombstones: [fallbackTombstone(fallbackPath)], problems };
1124
+ }
1125
+ problems.push("no path derivable from filename \u2014 skipped");
1126
+ return { tombstones: [], problems };
1127
+ }
1128
+ try {
1129
+ const parsed = normalizeTombstoneRecord(JSON.parse(text), fallbackPath);
1130
+ if (parsed) return { tombstones: [parsed], problems: [] };
1131
+ problems.push('JSON parsed but has no usable "path"');
1132
+ } catch (err) {
1133
+ problems.push(`JSON parse error: ${err instanceof Error ? err.message : String(err)}`);
1134
+ }
1135
+ const recovered = extractJsonObjects(text).map((chunk) => {
1136
+ try {
1137
+ return normalizeTombstoneRecord(JSON.parse(chunk));
1138
+ } catch {
1139
+ return null;
1140
+ }
1141
+ }).filter((t) => t !== null);
1142
+ if (recovered.length > 0) {
1143
+ if (recovered.length > 1) problems.push(`${recovered.length} concatenated documents recovered`);
1144
+ return { tombstones: recovered, problems };
1145
+ }
1146
+ if (fallbackPath) {
1147
+ problems.push("no recoverable document; path derived from filename");
1148
+ return { tombstones: [fallbackTombstone(fallbackPath)], problems };
1149
+ }
1150
+ problems.push("no recoverable document and no path derivable from filename \u2014 skipped");
1151
+ return { tombstones: [], problems };
1152
+ }
1153
+ function mergeTombstone(byPath, tombstone) {
1154
+ const prev = byPath.get(tombstone.path);
1155
+ if (!prev) {
1156
+ byPath.set(tombstone.path, tombstone);
1157
+ return;
1158
+ }
1159
+ for (const id of tombstone.confirmedBy) {
1160
+ if (!prev.confirmedBy.includes(id)) prev.confirmedBy.push(id);
1161
+ }
1162
+ }
1163
+ async function readTombstonesFromFs(fs, warn) {
1164
+ const byPath = /* @__PURE__ */ new Map();
1165
+ for (const dir of [TOMBSTONES_DIR, LEGACY_TOMBSTONES_DIR]) {
1166
+ let entries;
1167
+ try {
1168
+ entries = await fs.readdir(dir);
1169
+ } catch {
1170
+ continue;
1171
+ }
1172
+ for (const entry of entries) {
1173
+ if (!entry.endsWith(".json")) continue;
1174
+ const filePath = `${dir}/${entry}`;
1175
+ let raw;
1176
+ try {
1177
+ raw = new TextDecoder().decode(toBytes(await fs.readFile(filePath)));
1178
+ } catch (err) {
1179
+ warn(
1180
+ `[Tombstones] unreadable tombstone ${filePath}: ${err instanceof Error ? err.message : String(err)} \u2014 skipped`
1181
+ );
1182
+ continue;
1183
+ }
1184
+ const { tombstones, problems } = parseTombstoneFile(raw, decodeMetaPath(entry) ?? void 0);
1185
+ if (problems.length > 0) {
1186
+ const action = tombstones.length > 0 ? tombstones.map((t) => `"${t.path}" treated as deleted`).join(", ") : "skipped";
1187
+ warn(`[Tombstones] corrupt tombstone ${filePath}: ${problems.join("; ")} \u2192 ${action}`);
1188
+ }
1189
+ for (const tombstone of tombstones) mergeTombstone(byPath, tombstone);
1190
+ }
1191
+ }
1192
+ return Array.from(byPath.values());
1193
+ }
1055
1194
  async function readGroupDescriptor(fs) {
1056
1195
  const parsed = await readJson(fs, GROUP_DESCRIPTOR_FILE);
1057
1196
  if (!parsed) return null;
@@ -1129,29 +1268,7 @@ var TombstoneStore = class {
1129
1268
  }
1130
1269
  /** All tombstones, new path first, legacy only for paths not already seen. */
1131
1270
  async list() {
1132
- const byPath = /* @__PURE__ */ new Map();
1133
- for (const dir of [TOMBSTONES_DIR, LEGACY_TOMBSTONES_DIR]) {
1134
- let entries;
1135
- try {
1136
- entries = await this.fs.readdir(dir);
1137
- } catch {
1138
- continue;
1139
- }
1140
- for (const entry of entries) {
1141
- if (!entry.endsWith(".json")) continue;
1142
- const data = await readJson(this.fs, `${dir}/${entry}`);
1143
- if (!data || typeof data.path !== "string") continue;
1144
- const prev = byPath.get(data.path);
1145
- if (prev) {
1146
- for (const id of data.confirmedBy ?? []) {
1147
- if (!prev.confirmedBy.includes(id)) prev.confirmedBy.push(id);
1148
- }
1149
- } else {
1150
- byPath.set(data.path, data);
1151
- }
1152
- }
1153
- }
1154
- return Array.from(byPath.values());
1271
+ return readTombstonesFromFs(this.fs, (message) => log2.warn(message));
1155
1272
  }
1156
1273
  /** Write a tombstone (new + legacy mirror). */
1157
1274
  async write(tombstone) {
@@ -1383,7 +1500,7 @@ var ConflictStore = class {
1383
1500
  };
1384
1501
 
1385
1502
  // src/config-repo.ts
1386
- var log2 = createLogger2("zen-fs-config:config-repo");
1503
+ var log3 = createLogger3("zen-fs-config:config-repo");
1387
1504
  var GROUP_DESCRIPTOR_FILE2 = `${META_DIR}/group.json`;
1388
1505
  var GROUP_TYPE_FILE = `${CONFIG_DIR}/group-type`;
1389
1506
  var LEGACY_GROUP_TYPE_FILE = `${META_DIR}/group-type`;
@@ -1636,7 +1753,7 @@ var ConfigRepo = class {
1636
1753
  const bytes = this.serializer.serialize(data, fullPath);
1637
1754
  this.configCache.set(fullPath, data);
1638
1755
  this.persistConfig(fullPath, bytes).catch((err) => {
1639
- log2.error(`[zen-fs-config] Failed to persist ${fullPath}:`, err);
1756
+ log3.error(`[zen-fs-config] Failed to persist ${fullPath}:`, err);
1640
1757
  });
1641
1758
  }
1642
1759
  // -----------------------------------------------------------------------
@@ -1790,7 +1907,7 @@ var ConfigRepo = class {
1790
1907
  await removeDirectoryTree(this.cachedFS, normalizedPath);
1791
1908
  this.invalidateTombstoneCache();
1792
1909
  this.schedulePostDeleteSync();
1793
- log2.log(`[ConfigRepo] deleteFile(directory): ${normalizedPath} (${files.length} file(s))`);
1910
+ log3.log(`[ConfigRepo] deleteFile(directory): ${normalizedPath} (${files.length} file(s))`);
1794
1911
  return;
1795
1912
  }
1796
1913
  await this.writeTombstoneFor(normalizedPath);
@@ -1811,7 +1928,7 @@ var ConfigRepo = class {
1811
1928
  } catch {
1812
1929
  }
1813
1930
  }
1814
- log2.log(`[ConfigRepo] deleteFile: ${normalizedPath} (tombstone at ${tombstonePathFor(normalizedPath)})`);
1931
+ log3.log(`[ConfigRepo] deleteFile: ${normalizedPath} (tombstone at ${tombstonePathFor(normalizedPath)})`);
1815
1932
  this.invalidateTombstoneCache();
1816
1933
  this.schedulePostDeleteSync();
1817
1934
  }
@@ -1829,7 +1946,7 @@ var ConfigRepo = class {
1829
1946
  this.postDeleteSyncTimer = void 0;
1830
1947
  if (this.disposed) return;
1831
1948
  this.syncEngine.syncAll().catch((err) => {
1832
- log2.warn("[ConfigRepo] post-delete sync failed:", err);
1949
+ log3.warn("[ConfigRepo] post-delete sync failed:", err);
1833
1950
  });
1834
1951
  }, 500);
1835
1952
  }
@@ -1841,32 +1958,7 @@ var ConfigRepo = class {
1841
1958
  if (this.tombstoneCache !== null) {
1842
1959
  return this.tombstoneCache;
1843
1960
  }
1844
- const byPath = /* @__PURE__ */ new Map();
1845
- for (const dir of [TOMBSTONES_DIR, LEGACY_TOMBSTONES_DIR]) {
1846
- let entries;
1847
- try {
1848
- entries = await this.cachedFS.readdir(dir);
1849
- } catch {
1850
- continue;
1851
- }
1852
- for (const entry of entries) {
1853
- if (!entry.endsWith(".json")) continue;
1854
- try {
1855
- const raw = await this.cachedFS.readFile(`${dir}/${entry}`);
1856
- const data = JSON.parse(new TextDecoder().decode(toUint8Array2(raw)));
1857
- const prev = byPath.get(data.path);
1858
- if (prev) {
1859
- for (const id of data.confirmedBy ?? []) {
1860
- if (!prev.confirmedBy.includes(id)) prev.confirmedBy.push(id);
1861
- }
1862
- } else {
1863
- byPath.set(data.path, data);
1864
- }
1865
- } catch {
1866
- }
1867
- }
1868
- }
1869
- this.tombstoneCache = Array.from(byPath.values());
1961
+ this.tombstoneCache = await readTombstonesFromFs(this.cachedFS, (message) => log3.warn(message));
1870
1962
  return this.tombstoneCache;
1871
1963
  }
1872
1964
  /** Invalidate the tombstone cache — call after tombstones are modified. */
@@ -1891,11 +1983,11 @@ var ConfigRepo = class {
1891
1983
  for (const tombstone of tombstones) {
1892
1984
  const forceDelete = isMtimeSidecar(tombstone.path);
1893
1985
  const tVersionPath = forceDelete ? null : versionPathFor(tombstone.path);
1894
- log2.log(`[TOMB-TRACE] processing tombstone: path=${tombstone.path} versionPath=${tVersionPath ?? "null"} forceDelete=${forceDelete}`);
1986
+ log3.log(`[TOMB-TRACE] processing tombstone: path=${tombstone.path} versionPath=${tVersionPath ?? "null"} forceDelete=${forceDelete}`);
1895
1987
  const existedOnPrimary = forceDelete || await this.safeExists(this.cachedFS, tombstone.path);
1896
- log2.log(`[TOMB-TRACE] primary safeExists(${tombstone.path}) \u2192 ${existedOnPrimary}`);
1988
+ log3.log(`[TOMB-TRACE] primary safeExists(${tombstone.path}) \u2192 ${existedOnPrimary}`);
1897
1989
  if (existedOnPrimary) {
1898
- log2.log(`[TOMB-TRACE] tombstone check: ${tombstone.path} on primary \u2192 EXISTS`);
1990
+ log3.log(`[TOMB-TRACE] tombstone check: ${tombstone.path} on primary \u2192 EXISTS`);
1899
1991
  }
1900
1992
  if (existedOnPrimary) {
1901
1993
  try {
@@ -1906,7 +1998,7 @@ var ConfigRepo = class {
1906
1998
  }
1907
1999
  if (tVersionPath) {
1908
2000
  const vExistedOnPrimary = await this.safeExists(this.cachedFS, tVersionPath);
1909
- log2.log(`[TOMB-TRACE] primary safeExists(${tVersionPath}) \u2192 ${vExistedOnPrimary}`);
2001
+ log3.log(`[TOMB-TRACE] primary safeExists(${tVersionPath}) \u2192 ${vExistedOnPrimary}`);
1910
2002
  if (vExistedOnPrimary) {
1911
2003
  try {
1912
2004
  await this.cachedFS.unlink(tVersionPath);
@@ -1915,40 +2007,40 @@ var ConfigRepo = class {
1915
2007
  }
1916
2008
  }
1917
2009
  for (const [replicaId, replica] of this.replicaBackends) {
1918
- log2.log(`[TOMB-TRACE] checking replica: ${replicaId} for ${tombstone.path}`);
2010
+ log3.log(`[TOMB-TRACE] checking replica: ${replicaId} for ${tombstone.path}`);
1919
2011
  const existed = forceDelete || await this.safeExists(replica.instance, tombstone.path);
1920
- log2.log(`[TOMB-TRACE] replica ${replicaId} safeExists(${tombstone.path}) \u2192 ${existed}`);
2012
+ log3.log(`[TOMB-TRACE] replica ${replicaId} safeExists(${tombstone.path}) \u2192 ${existed}`);
1921
2013
  if (existed) {
1922
- log2.log(`[TOMB-TRACE] tombstone check: ${tombstone.path} on ${replicaId} \u2192 EXISTS`);
2014
+ log3.log(`[TOMB-TRACE] tombstone check: ${tombstone.path} on ${replicaId} \u2192 EXISTS`);
1923
2015
  try {
1924
- log2.log(`[TOMB-TRACE] calling unlink(${tombstone.path}) on ${replicaId}`);
2016
+ log3.log(`[TOMB-TRACE] calling unlink(${tombstone.path}) on ${replicaId}`);
1925
2017
  await replica.instance.unlink(tombstone.path);
1926
- log2.log(`[TOMB-TRACE] tombstone ${tombstone.path}: deleted on ${replicaId}`);
2018
+ log3.log(`[TOMB-TRACE] tombstone ${tombstone.path}: deleted on ${replicaId}`);
1927
2019
  processed++;
1928
2020
  } catch (err) {
1929
- log2.log(`[TOMB-TRACE] unlink(${tombstone.path}) on ${replicaId} FAILED: ${err}`);
2021
+ log3.log(`[TOMB-TRACE] unlink(${tombstone.path}) on ${replicaId} FAILED: ${err}`);
1930
2022
  alreadyDeleted++;
1931
2023
  }
1932
2024
  } else {
1933
- log2.log(`[TOMB-TRACE] replica ${replicaId}: already gone, skipping unlink`);
2025
+ log3.log(`[TOMB-TRACE] replica ${replicaId}: already gone, skipping unlink`);
1934
2026
  alreadyDeleted++;
1935
2027
  }
1936
2028
  if (tVersionPath) {
1937
2029
  const vExisted = await this.safeExists(replica.instance, tVersionPath);
1938
- log2.log(`[TOMB-TRACE] replica ${replicaId} safeExists(${tVersionPath}) \u2192 ${vExisted}`);
2030
+ log3.log(`[TOMB-TRACE] replica ${replicaId} safeExists(${tVersionPath}) \u2192 ${vExisted}`);
1939
2031
  if (vExisted) {
1940
2032
  try {
1941
- log2.log(`[TOMB-TRACE] calling unlink(${tVersionPath}) on ${replicaId}`);
2033
+ log3.log(`[TOMB-TRACE] calling unlink(${tVersionPath}) on ${replicaId}`);
1942
2034
  await replica.instance.unlink(tVersionPath);
1943
2035
  } catch (err) {
1944
- log2.log(`[TOMB-TRACE] unlink(${tVersionPath}) on ${replicaId} FAILED: ${err}`);
2036
+ log3.log(`[TOMB-TRACE] unlink(${tVersionPath}) on ${replicaId} FAILED: ${err}`);
1945
2037
  }
1946
2038
  }
1947
2039
  }
1948
2040
  }
1949
2041
  }
1950
2042
  if (processed > 0 || alreadyDeleted > 0) {
1951
- log2.log(`[TOMB-TRACE] processTombstones: ${tombstones.length} tombstone(s), ${processed} deleted, ${alreadyDeleted} already gone`);
2043
+ log3.log(`[TOMB-TRACE] processTombstones: ${tombstones.length} tombstone(s), ${processed} deleted, ${alreadyDeleted} already gone`);
1952
2044
  }
1953
2045
  }
1954
2046
  /**
@@ -1964,21 +2056,21 @@ var ConfigRepo = class {
1964
2056
  const innerBackendName = fs?.inner?.backendName;
1965
2057
  const directBackendName = fs?.backendName;
1966
2058
  const backendLabel = innerBackendName ?? directBackendName ?? innerBackend ?? ctorName;
1967
- log2.log(`[TOMB-TRACE] safeExists(${path}): fs type=${ctorName} backend=${backendLabel} hasExists=${hasExists} hasStat=${hasStat} inner=${innerBackend ?? "N/A"}`);
2059
+ log3.log(`[TOMB-TRACE] safeExists(${path}): fs type=${ctorName} backend=${backendLabel} hasExists=${hasExists} hasStat=${hasStat} inner=${innerBackend ?? "N/A"}`);
1968
2060
  if (hasExists) {
1969
- log2.log(`[TOMB-TRACE] safeExists(${path}): \u2192 calling fs.exists() [backend=${backendLabel}]`);
2061
+ log3.log(`[TOMB-TRACE] safeExists(${path}): \u2192 calling fs.exists() [backend=${backendLabel}]`);
1970
2062
  const result = await fs.exists(path);
1971
- log2.log(`[TOMB-TRACE] safeExists(${path}): \u2190 fs.exists() [backend=${backendLabel}] \u2192 ${result}`);
2063
+ log3.log(`[TOMB-TRACE] safeExists(${path}): \u2190 fs.exists() [backend=${backendLabel}] \u2192 ${result}`);
1972
2064
  return result;
1973
2065
  }
1974
- log2.log(`[TOMB-TRACE] safeExists(${path}): no exists(), calling fs.stat() [backend=${backendLabel}]`);
2066
+ log3.log(`[TOMB-TRACE] safeExists(${path}): no exists(), calling fs.stat() [backend=${backendLabel}]`);
1975
2067
  await fs.stat(path);
1976
- log2.log(`[TOMB-TRACE] safeExists(${path}): \u2190 fs.stat() [backend=${backendLabel}] \u2192 OK (exists)`);
2068
+ log3.log(`[TOMB-TRACE] safeExists(${path}): \u2190 fs.stat() [backend=${backendLabel}] \u2192 OK (exists)`);
1977
2069
  return true;
1978
2070
  } catch (err) {
1979
2071
  const errCode = err?.code ?? err?.status ?? "";
1980
2072
  const errName = err?.constructor?.name ?? "";
1981
- log2.log(`[TOMB-TRACE] safeExists(${path}): \u2190 ERROR ${errName} ${errCode} ${err?.message ?? err}`);
2073
+ log3.log(`[TOMB-TRACE] safeExists(${path}): \u2190 ERROR ${errName} ${errCode} ${err?.message ?? err}`);
1982
2074
  return false;
1983
2075
  }
1984
2076
  }
@@ -2005,13 +2097,13 @@ var ConfigRepo = class {
2005
2097
  this.assertNotDisposed();
2006
2098
  const result = await purgeMtimeSidecars(this.cachedFS, options);
2007
2099
  if (result.removed.length > 0) {
2008
- log2.log(
2100
+ log3.log(
2009
2101
  `[ConfigRepo] purged ${result.removed.length} .mtime sidecar(s) from local primary` + (options?.dryRun ? " (dry run)" : ""),
2010
2102
  result.removed
2011
2103
  );
2012
2104
  }
2013
2105
  if (result.failed.length > 0) {
2014
- log2.warn(`[ConfigRepo] failed to purge ${result.failed.length} .mtime sidecar(s):`, result.failed);
2106
+ log3.warn(`[ConfigRepo] failed to purge ${result.failed.length} .mtime sidecar(s):`, result.failed);
2015
2107
  }
2016
2108
  return result;
2017
2109
  }
@@ -2031,13 +2123,13 @@ var ConfigRepo = class {
2031
2123
  this.assertNotDisposed();
2032
2124
  const result = await purgeKeepFiles(this.cachedFS, options);
2033
2125
  if (result.removed.length > 0) {
2034
- log2.log(
2126
+ log3.log(
2035
2127
  `[ConfigRepo] purged ${result.removed.length} .keep placeholder(s) from local primary` + (options?.dryRun ? " (dry run)" : ""),
2036
2128
  result.removed
2037
2129
  );
2038
2130
  }
2039
2131
  if (result.failed.length > 0) {
2040
- log2.warn(`[ConfigRepo] failed to purge ${result.failed.length} .keep placeholder(s):`, result.failed);
2132
+ log3.warn(`[ConfigRepo] failed to purge ${result.failed.length} .keep placeholder(s):`, result.failed);
2041
2133
  }
2042
2134
  return result;
2043
2135
  }
@@ -2056,24 +2148,24 @@ var ConfigRepo = class {
2056
2148
  }));
2057
2149
  const result = await migrateVersionSidecars(this.cachedFS, { replicas });
2058
2150
  if (result.renamed.length > 0) {
2059
- log2.log(
2151
+ log3.log(
2060
2152
  `[ConfigRepo] migrated ${result.renamed.length} legacy version sidecar(s) to new naming`,
2061
2153
  result.renamed
2062
2154
  );
2063
2155
  }
2064
2156
  if (result.deleted.length > 0) {
2065
- log2.log(
2157
+ log3.log(
2066
2158
  `[ConfigRepo] removed ${result.deleted.length} orphaned legacy version sidecar(s)`,
2067
2159
  result.deleted
2068
2160
  );
2069
2161
  }
2070
2162
  if (result.remoteDeleted.length > 0) {
2071
- log2.log(
2163
+ log3.log(
2072
2164
  `[ConfigRepo] removed ${result.remoteDeleted.length} remote residual legacy version sidecar(s)`
2073
2165
  );
2074
2166
  }
2075
2167
  if (result.failed.length > 0) {
2076
- log2.warn(`[ConfigRepo] failed to migrate ${result.failed.length} legacy version sidecar(s):`, result.failed);
2168
+ log3.warn(`[ConfigRepo] failed to migrate ${result.failed.length} legacy version sidecar(s):`, result.failed);
2077
2169
  }
2078
2170
  return result;
2079
2171
  }
@@ -2096,9 +2188,9 @@ var ConfigRepo = class {
2096
2188
  */
2097
2189
  startBackgroundSync() {
2098
2190
  this.initialSyncPromise = this.initialSyncAndDedup().then(() => {
2099
- log2.log("[ConfigRepo] Background initial sync complete");
2191
+ log3.log("[ConfigRepo] Background initial sync complete");
2100
2192
  }).catch((err) => {
2101
- log2.error("[ConfigRepo] Background initial sync failed:", err);
2193
+ log3.error("[ConfigRepo] Background initial sync failed:", err);
2102
2194
  }).finally(() => {
2103
2195
  this.initialSyncPromise = null;
2104
2196
  });
@@ -2132,7 +2224,7 @@ var ConfigRepo = class {
2132
2224
  }
2133
2225
  }
2134
2226
  }
2135
- log2.log(`[ConfigRepo] updateTombstoneConfirmations: ${modified} tombstone(s) updated`);
2227
+ log3.log(`[ConfigRepo] updateTombstoneConfirmations: ${modified} tombstone(s) updated`);
2136
2228
  if (modified > 0) this.invalidateTombstoneCache();
2137
2229
  }
2138
2230
  /**
@@ -2164,7 +2256,7 @@ var ConfigRepo = class {
2164
2256
  }
2165
2257
  }
2166
2258
  }
2167
- log2.log(`[ConfigRepo] gcTombstones: removed ${tombstonePath} (all ${allBackendIds.length} backends confirmed)`);
2259
+ log3.log(`[ConfigRepo] gcTombstones: removed ${tombstonePath} (all ${allBackendIds.length} backends confirmed)`);
2168
2260
  }
2169
2261
  }
2170
2262
  }
@@ -2181,7 +2273,7 @@ var ConfigRepo = class {
2181
2273
  this.assertNotDisposed();
2182
2274
  const results = await this.flush();
2183
2275
  for (const result of results) {
2184
- log2.log(
2276
+ log3.log(
2185
2277
  `[ConfigRepo] syncMetaToReplicas: ${result.pairId} +${result.filesCreated}/~${result.filesUpdated}/-${result.filesDeleted} skip:${result.filesSkipped} ${result.durationMs}ms`
2186
2278
  );
2187
2279
  }
@@ -2198,6 +2290,32 @@ var ConfigRepo = class {
2198
2290
  this.assertNotDisposed();
2199
2291
  return new Map(this.backendStates);
2200
2292
  }
2293
+ /**
2294
+ * Mirror per-pair `sync:error` into `getBackendSyncStates()`.
2295
+ *
2296
+ * `SyncEngine.syncAll()` catches per-pair exceptions and substitutes an empty
2297
+ * result, so a failed replica otherwise only shows up as a missing
2298
+ * `lastResult`. Recording the real error lets callers report the actual
2299
+ * status (401/403/404/timeout) instead of guessing "remote unreachable or
2300
+ * invalid credentials".
2301
+ */
2302
+ trackSyncErrors(backendId, pairId) {
2303
+ this.syncEngine.on(pairId, "sync:error", (event) => {
2304
+ const error = event.error;
2305
+ this.backendStates.set(backendId, {
2306
+ backendId,
2307
+ pairId,
2308
+ error: {
2309
+ message: error instanceof Error ? error.message : String(error ?? "sync failed"),
2310
+ timestamp: Date.now()
2311
+ }
2312
+ });
2313
+ });
2314
+ this.syncEngine.on(pairId, "sync:end", () => {
2315
+ const current = this.backendStates.get(backendId);
2316
+ if (current?.error) this.backendStates.set(backendId, { backendId, pairId });
2317
+ });
2318
+ }
2201
2319
  /** Registered replica backend descriptors (excludes the implicit local primary). */
2202
2320
  listBackends() {
2203
2321
  this.assertNotDisposed();
@@ -2328,21 +2446,21 @@ var ConfigRepo = class {
2328
2446
  // Internal — Setup
2329
2447
  // -----------------------------------------------------------------------
2330
2448
  async setupSync(backends, primaryBackendId, pollIntervalMs) {
2331
- log2.log(`[ConfigRepo] setupSync: ${backends.length} backends, primary=${primaryBackendId} pollInterval=${pollIntervalMs ?? "default"}ms`);
2449
+ log3.log(`[ConfigRepo] setupSync: ${backends.length} backends, primary=${primaryBackendId} pollInterval=${pollIntervalMs ?? "default"}ms`);
2332
2450
  for (const desc of backends) {
2333
2451
  if (desc.id === primaryBackendId) continue;
2334
2452
  if (desc.enabled === false) {
2335
- log2.log(`[ConfigRepo] Skipping disabled replica: ${desc.id}`);
2453
+ log3.log(`[ConfigRepo] Skipping disabled replica: ${desc.id}`);
2336
2454
  continue;
2337
2455
  }
2338
- log2.log(`[ConfigRepo] Creating replica backend: id=${desc.id}, type=${desc.type}`);
2456
+ log3.log(`[ConfigRepo] Creating replica backend: id=${desc.id}, type=${desc.type}`);
2339
2457
  try {
2340
2458
  const instance = await createBackend(desc);
2341
2459
  let fsInstance = instance;
2342
2460
  if (this.cacheOptions) {
2343
2461
  const { wrapWithCache } = await import("./cache-wrapper-S5HRLRQX.mjs");
2344
2462
  fsInstance = wrapWithCache(instance, desc.id, this.cacheOptions);
2345
- log2.log(`[ConfigRepo] Replica ${desc.id} wrapped with CachedFileSystem (store=${this.cacheOptions.storeType ?? "IdbCacheStore"})`);
2463
+ log3.log(`[ConfigRepo] Replica ${desc.id} wrapped with CachedFileSystem (store=${this.cacheOptions.storeType ?? "IdbCacheStore"})`);
2346
2464
  }
2347
2465
  const syncable = backendToSyncableFS(fsInstance, `${desc.type}(${desc.id})`);
2348
2466
  const pair = this.syncEngine.addPair(
@@ -2357,7 +2475,7 @@ var ConfigRepo = class {
2357
2475
  this.invalidateTombstoneCache();
2358
2476
  await this.processTombstones();
2359
2477
  } catch (err) {
2360
- log2.warn("[ConfigRepo] preSyncHook processTombstones failed:", err);
2478
+ log3.warn("[ConfigRepo] preSyncHook processTombstones failed:", err);
2361
2479
  }
2362
2480
  },
2363
2481
  postSyncHook: async () => {
@@ -2366,7 +2484,7 @@ var ConfigRepo = class {
2366
2484
  await this.processTombstones();
2367
2485
  await this.updateTombstoneConfirmations();
2368
2486
  } catch (err) {
2369
- log2.warn("[ConfigRepo] postSyncHook tombstone processing failed:", err);
2487
+ log3.warn("[ConfigRepo] postSyncHook tombstone processing failed:", err);
2370
2488
  }
2371
2489
  }
2372
2490
  },
@@ -2378,9 +2496,10 @@ var ConfigRepo = class {
2378
2496
  this.handleConflict(event);
2379
2497
  };
2380
2498
  this.syncEngine.on(pair.pairId, "conflict", conflictHandler);
2381
- log2.log(`[ConfigRepo] Replica ${desc.id} created, sync pair=${pair.pairId}`);
2499
+ this.trackSyncErrors(desc.id, pair.pairId);
2500
+ log3.log(`[ConfigRepo] Replica ${desc.id} created, sync pair=${pair.pairId}`);
2382
2501
  } catch (err) {
2383
- log2.error(`[ConfigRepo] Failed to create replica ${desc.id} (${desc.type}):`, err);
2502
+ log3.error(`[ConfigRepo] Failed to create replica ${desc.id} (${desc.type}):`, err);
2384
2503
  this.backendStates.set(desc.id, {
2385
2504
  backendId: desc.id,
2386
2505
  error: {
@@ -2390,8 +2509,8 @@ var ConfigRepo = class {
2390
2509
  });
2391
2510
  }
2392
2511
  }
2393
- log2.log(`[ConfigRepo] setupSync complete. Replicas:`, Array.from(this.replicaBackends.keys()));
2394
- log2.log(`[ConfigRepo] Sync statuses:`, this.getSyncStatuses());
2512
+ log3.log(`[ConfigRepo] setupSync complete. Replicas:`, Array.from(this.replicaBackends.keys()));
2513
+ log3.log(`[ConfigRepo] Sync statuses:`, this.getSyncStatuses());
2395
2514
  }
2396
2515
  // -----------------------------------------------------------------------
2397
2516
  // Internal — Persistence
@@ -2403,12 +2522,12 @@ var ConfigRepo = class {
2403
2522
  try {
2404
2523
  const existing = await readVersion(this.fullFS, vPath);
2405
2524
  if (existing && existing.hash === version.hash) {
2406
- log2.log("[ConfigRepo] skip version sidecar (hash unchanged):", vPath);
2525
+ log3.log("[ConfigRepo] skip version sidecar (hash unchanged):", vPath);
2407
2526
  return;
2408
2527
  }
2409
2528
  } catch {
2410
2529
  }
2411
- log2.log("[ConfigRepo] write version sidecar:", vPath, "v" + version.version);
2530
+ log3.log("[ConfigRepo] write version sidecar:", vPath, "v" + version.version);
2412
2531
  await this.ensureDir(vPath);
2413
2532
  await writeVersion(this.fullFS, vPath, version);
2414
2533
  }
@@ -2512,7 +2631,7 @@ var ConfigRepo = class {
2512
2631
  await this.resolveConflict(`${conflictId}/meta.json`, customMerge);
2513
2632
  }
2514
2633
  } catch (err) {
2515
- log2.error("[zen-fs-config] Conflict handler error:", err);
2634
+ log3.error("[zen-fs-config] Conflict handler error:", err);
2516
2635
  }
2517
2636
  }
2518
2637
  }
@@ -2624,11 +2743,11 @@ var ConfigRepo = class {
2624
2743
  }
2625
2744
  return { kind: "ok", desc, mtime };
2626
2745
  } else {
2627
- log2.warn(`[ConfigRepo] Backend descriptor ${entry} is missing id/type fields, marking for cleanup`);
2746
+ log3.warn(`[ConfigRepo] Backend descriptor ${entry} is missing id/type fields, marking for cleanup`);
2628
2747
  return { kind: "corrupt", filePath };
2629
2748
  }
2630
2749
  } catch (parseErr) {
2631
- log2.warn(`[ConfigRepo] Backend descriptor ${entry} has corrupted JSON: ${parseErr}. Marking for cleanup.`);
2750
+ log3.warn(`[ConfigRepo] Backend descriptor ${entry} has corrupted JSON: ${parseErr}. Marking for cleanup.`);
2632
2751
  return { kind: "corrupt", filePath };
2633
2752
  }
2634
2753
  })
@@ -2699,7 +2818,7 @@ var ConfigRepo = class {
2699
2818
  }
2700
2819
  }
2701
2820
  if (duplicates.length > 0) {
2702
- log2.log(
2821
+ log3.log(
2703
2822
  `[ConfigRepo] readAllBackendDescriptors: removing ${duplicates.length} duplicate(s): ${duplicates.join(", ")}`
2704
2823
  );
2705
2824
  for (const dupId of duplicates) {
@@ -2830,7 +2949,7 @@ var ConfigRepo = class {
2830
2949
  * Shared by addBackend() and replaceBackend().
2831
2950
  */
2832
2951
  async setupReplica(id, type, options, description) {
2833
- log2.log(`[ConfigRepo] addBackend: creating ${id} (${type})...`);
2952
+ log3.log(`[ConfigRepo] addBackend: creating ${id} (${type})...`);
2834
2953
  const instance = await createBackend({ type, options });
2835
2954
  const syncable = backendToSyncableFS(instance, `${type}(${id})`);
2836
2955
  const desc = { id, type, options, description };
@@ -2846,7 +2965,7 @@ var ConfigRepo = class {
2846
2965
  this.invalidateTombstoneCache();
2847
2966
  await this.processTombstones();
2848
2967
  } catch (err) {
2849
- log2.warn("[ConfigRepo] preSyncHook processTombstones failed:", err);
2968
+ log3.warn("[ConfigRepo] preSyncHook processTombstones failed:", err);
2850
2969
  }
2851
2970
  },
2852
2971
  postSyncHook: async () => {
@@ -2855,7 +2974,7 @@ var ConfigRepo = class {
2855
2974
  await this.processTombstones();
2856
2975
  await this.updateTombstoneConfirmations();
2857
2976
  } catch (err) {
2858
- log2.warn("[ConfigRepo] postSyncHook tombstone processing failed:", err);
2977
+ log3.warn("[ConfigRepo] postSyncHook tombstone processing failed:", err);
2859
2978
  }
2860
2979
  }
2861
2980
  },
@@ -2867,7 +2986,8 @@ var ConfigRepo = class {
2867
2986
  this.handleConflict(event);
2868
2987
  };
2869
2988
  this.syncEngine.on(pair.pairId, "conflict", conflictHandler);
2870
- log2.log(`[ConfigRepo] addBackend: ${id} (${type}) added, sync pair=${pair.pairId}`);
2989
+ this.trackSyncErrors(id, pair.pairId);
2990
+ log3.log(`[ConfigRepo] addBackend: ${id} (${type}) added, sync pair=${pair.pairId}`);
2871
2991
  await this.syncMetaToReplicas();
2872
2992
  this.syncEngine.watch(pair.pairId);
2873
2993
  return pair.pairId;
@@ -2893,13 +3013,13 @@ var ConfigRepo = class {
2893
3013
  }
2894
3014
  }
2895
3015
  this.syncEngine.removePair(replica.pairId);
2896
- log2.log(`[ConfigRepo] removeBackend: sync pair ${replica.pairId} removed`);
3016
+ log3.log(`[ConfigRepo] removeBackend: sync pair ${replica.pairId} removed`);
2897
3017
  this.replicaBackends.delete(id);
2898
3018
  if (replica.instance?.dispose) {
2899
3019
  await replica.instance.dispose();
2900
3020
  }
2901
3021
  } else {
2902
- log2.log(`[ConfigRepo] removeBackend: "${id}" not in replicaBackends, cleaning up descriptor only`);
3022
+ log3.log(`[ConfigRepo] removeBackend: "${id}" not in replicaBackends, cleaning up descriptor only`);
2903
3023
  for (const descPath of descPaths) {
2904
3024
  try {
2905
3025
  await this.deleteFile(descPath);
@@ -2910,7 +3030,7 @@ var ConfigRepo = class {
2910
3030
  }
2911
3031
  this.backendStates.delete(id);
2912
3032
  this.schedulePostDeleteSync();
2913
- log2.log(`[ConfigRepo] removeBackend: ${id} removed (tombstone written, remote cleaned)`);
3033
+ log3.log(`[ConfigRepo] removeBackend: ${id} removed (tombstone written, remote cleaned)`);
2914
3034
  }
2915
3035
  /**
2916
3036
  * Replace a config-sync backend's parameters in place (same id).
@@ -2957,11 +3077,11 @@ var ConfigRepo = class {
2957
3077
  await this.setupReplica(id, type, options, description ?? before.description);
2958
3078
  } catch (err) {
2959
3079
  const reason = err instanceof Error ? err.message : String(err);
2960
- log2.warn(`[ConfigRepo] replaceBackend: "${id}" failed, rolling back old options:`, err);
3080
+ log3.warn(`[ConfigRepo] replaceBackend: "${id}" failed, rolling back old options:`, err);
2961
3081
  try {
2962
3082
  await this.setupReplica(id, before.type, before.options, before.description);
2963
3083
  } catch (rollbackErr) {
2964
- log2.error(`[ConfigRepo] replaceBackend: rollback for "${id}" ALSO failed:`, rollbackErr);
3084
+ log3.error(`[ConfigRepo] replaceBackend: rollback for "${id}" ALSO failed:`, rollbackErr);
2965
3085
  }
2966
3086
  throw new Error(`\u66F4\u65B0\u540E\u7AEF\u53C2\u6570\u5931\u8D25\uFF1A${reason}\uFF08\u5DF2\u5C1D\u8BD5\u56DE\u6EDA\u65E7\u53C2\u6570\uFF09`);
2967
3087
  }
@@ -2977,7 +3097,7 @@ var ConfigRepo = class {
2977
3097
  const existing = await this.cachedFS.readFile(path, "utf-8");
2978
3098
  const current = existing.trim();
2979
3099
  if (current && current !== type) {
2980
- log2.warn(`[ConfigRepo] group-type already set to "${current}" at ${path}, ignoring request to set "${type}"`);
3100
+ log3.warn(`[ConfigRepo] group-type already set to "${current}" at ${path}, ignoring request to set "${type}"`);
2981
3101
  return;
2982
3102
  }
2983
3103
  } catch {
@@ -3008,7 +3128,7 @@ var ConfigRepo = class {
3008
3128
  features: existingDescriptor.features ?? CONFIG_GROUP_FEATURES
3009
3129
  });
3010
3130
  }
3011
- log2.log(`[ConfigRepo] group-type set to "${type}"`);
3131
+ log3.log(`[ConfigRepo] group-type set to "${type}"`);
3012
3132
  }
3013
3133
  /** Read the group-type marker. Returns null if not set (new path, then legacy). */
3014
3134
  async getGroupType() {
@@ -3103,7 +3223,7 @@ var ConfigRepo = class {
3103
3223
  if (this.appDataGroups.has(id)) {
3104
3224
  throw new Error(`App data group "${id}" already exists. Use removeAppDataGroup() first.`);
3105
3225
  }
3106
- log2.log(`[ConfigRepo] createAppDataGroup: creating "${id}" with ${backends.length} backend(s)`);
3226
+ log3.log(`[ConfigRepo] createAppDataGroup: creating "${id}" with ${backends.length} backend(s)`);
3107
3227
  const resolvedBackends = [];
3108
3228
  for (const desc of backends) {
3109
3229
  assertValidBackendId(desc.id);
@@ -3130,7 +3250,7 @@ var ConfigRepo = class {
3130
3250
  };
3131
3251
  await this.writeAppDataGroupDescriptorFile(id, descriptor);
3132
3252
  this.appDataGroups.set(id, group);
3133
- log2.log(`[ConfigRepo] createAppDataGroup: "${id}" created`);
3253
+ log3.log(`[ConfigRepo] createAppDataGroup: "${id}" created`);
3134
3254
  return group;
3135
3255
  }
3136
3256
  /**
@@ -3173,7 +3293,7 @@ var ConfigRepo = class {
3173
3293
  try {
3174
3294
  await live.writeOwnGroupDescriptor();
3175
3295
  } catch (err) {
3176
- log2.warn(`[ConfigRepo] updateAppDataGroupName: "${id}" group.json update failed:`, err);
3296
+ log3.warn(`[ConfigRepo] updateAppDataGroupName: "${id}" group.json update failed:`, err);
3177
3297
  }
3178
3298
  }
3179
3299
  const descriptor = {
@@ -3236,7 +3356,7 @@ var ConfigRepo = class {
3236
3356
  return group;
3237
3357
  } catch (err) {
3238
3358
  const reason = err instanceof Error ? err.message : String(err);
3239
- log2.warn(`[ConfigRepo] replaceAppDataGroupBackend: "${backendId}" failed, rolling back:`, err);
3359
+ log3.warn(`[ConfigRepo] replaceAppDataGroupBackend: "${backendId}" failed, rolling back:`, err);
3240
3360
  try {
3241
3361
  const restored = new AppDataGroupImpl(
3242
3362
  groupId,
@@ -3250,7 +3370,7 @@ var ConfigRepo = class {
3250
3370
  await this.updateAppDataGroupDescriptor(groupId, restored.listDeclaredBackends());
3251
3371
  this.appDataGroups.set(groupId, restored);
3252
3372
  } catch (rollbackErr) {
3253
- log2.error("[ConfigRepo] replaceAppDataGroupBackend: rollback ALSO failed:", rollbackErr);
3373
+ log3.error("[ConfigRepo] replaceAppDataGroupBackend: rollback ALSO failed:", rollbackErr);
3254
3374
  }
3255
3375
  throw new Error(`\u66F4\u65B0\u540E\u7AEF\u53C2\u6570\u5931\u8D25\uFF1A${reason}\uFF08\u5DF2\u5C1D\u8BD5\u56DE\u6EDA\u65E7\u53C2\u6570\uFF09`);
3256
3376
  }
@@ -3368,7 +3488,7 @@ var ConfigRepo = class {
3368
3488
  try {
3369
3489
  await this.deleteFile(descPath);
3370
3490
  } catch (err) {
3371
- log2.log(`[ConfigRepo] removeAppDataGroup: deleteFile failed for "${id}" at ${descPath}:`, err);
3491
+ log3.log(`[ConfigRepo] removeAppDataGroup: deleteFile failed for "${id}" at ${descPath}:`, err);
3372
3492
  try {
3373
3493
  await this.cachedFS.unlink(descPath);
3374
3494
  } catch {
@@ -3376,7 +3496,7 @@ var ConfigRepo = class {
3376
3496
  await this.unlinkVersionSidecar(this.cachedFS, descPath);
3377
3497
  }
3378
3498
  }
3379
- log2.log(`[ConfigRepo] removeAppDataGroup: "${id}" removed`);
3499
+ log3.log(`[ConfigRepo] removeAppDataGroup: "${id}" removed`);
3380
3500
  }
3381
3501
  async listAccountBackends() {
3382
3502
  this.assertNotDisposed();
@@ -3551,24 +3671,24 @@ var AppDataGroupImpl = class {
3551
3671
  try {
3552
3672
  const purged = await purgeMtimeSidecars(this.localFS);
3553
3673
  if (purged.removed.length > 0) {
3554
- log2.warn(
3674
+ log3.warn(
3555
3675
  `[AppDataGroup:${this.groupId}] purged ${purged.removed.length} leaked .mtime sidecar(s):`,
3556
3676
  purged.removed
3557
3677
  );
3558
3678
  }
3559
3679
  } catch (err) {
3560
- log2.warn(`[AppDataGroup:${this.groupId}] .mtime purge failed:`, err?.message ?? err);
3680
+ log3.warn(`[AppDataGroup:${this.groupId}] .mtime purge failed:`, err?.message ?? err);
3561
3681
  }
3562
3682
  try {
3563
3683
  const purgedKeep = await purgeKeepFiles(this.localFS);
3564
3684
  if (purgedKeep.removed.length > 0) {
3565
- log2.warn(
3685
+ log3.warn(
3566
3686
  `[AppDataGroup:${this.groupId}] purged ${purgedKeep.removed.length} leaked .keep placeholder(s):`,
3567
3687
  purgedKeep.removed
3568
3688
  );
3569
3689
  }
3570
3690
  } catch (err) {
3571
- log2.warn(`[AppDataGroup:${this.groupId}] .keep purge failed:`, err?.message ?? err);
3691
+ log3.warn(`[AppDataGroup:${this.groupId}] .keep purge failed:`, err?.message ?? err);
3572
3692
  }
3573
3693
  const localSyncable = backendToSyncableFS(this.localFS, `local(${this.groupId})`);
3574
3694
  this.tombstones = new TombstoneStore(this.localFS, this.localBackendId);
@@ -3578,13 +3698,13 @@ var AppDataGroupImpl = class {
3578
3698
  try {
3579
3699
  backendsChanged = await this.loadBackendDescriptors();
3580
3700
  } catch (err) {
3581
- log2.warn(`[AppDataGroup:${this.groupId}] failed to load .meta/backends:`, err);
3701
+ log3.warn(`[AppDataGroup:${this.groupId}] failed to load .meta/backends:`, err);
3582
3702
  this._backends = this._backends ?? [];
3583
3703
  }
3584
3704
  try {
3585
3705
  await this.writeOwnGroupDescriptor();
3586
3706
  } catch (err) {
3587
- log2.warn(`[AppDataGroup:${this.groupId}] failed to write .meta/group.json:`, err);
3707
+ log3.warn(`[AppDataGroup:${this.groupId}] failed to write .meta/group.json:`, err);
3588
3708
  }
3589
3709
  this.fs = createChrootFS(this.localFS, "/", {
3590
3710
  hiddenPrefixes: [META_DIR, CONFIG_DIR],
@@ -3594,7 +3714,7 @@ var AppDataGroupImpl = class {
3594
3714
  });
3595
3715
  const { kept, removed } = dedupeAppDataBackends(this._backends);
3596
3716
  if (removed.length > 0) {
3597
- log2.warn(
3717
+ log3.warn(
3598
3718
  `[AppDataGroup:${this.groupId}] dedupe: removing ${removed.length} duplicate backend(s) (${removed.map((b) => b.id).join(", ")}) \u2014 keeping ${kept.map((b) => b.id).join(", ")}`
3599
3719
  );
3600
3720
  this._backends = kept;
@@ -3608,7 +3728,7 @@ var AppDataGroupImpl = class {
3608
3728
  features: this._declaredFeatures
3609
3729
  });
3610
3730
  } catch (err) {
3611
- log2.warn(`[AppDataGroup:${this.groupId}] failed to persist backend topology:`, err);
3731
+ log3.warn(`[AppDataGroup:${this.groupId}] failed to persist backend topology:`, err);
3612
3732
  }
3613
3733
  }
3614
3734
  for (const desc of this._backends) {
@@ -3640,25 +3760,26 @@ var AppDataGroupImpl = class {
3640
3760
  if (this.features.conflicts) {
3641
3761
  const conflictHandler = (event) => {
3642
3762
  this.archiveConflict(event).catch((err) => {
3643
- log2.warn(`[AppDataGroup:${this.groupId}] conflict archive failed:`, err);
3763
+ log3.warn(`[AppDataGroup:${this.groupId}] conflict archive failed:`, err);
3644
3764
  });
3645
3765
  };
3646
3766
  this.syncEngine.on(pair.pairId, "conflict", conflictHandler);
3647
3767
  }
3648
- log2.log(`[AppDataGroup:${this.groupId}] backend ${desc.id} (${desc.type}) connected, pair=${pair.pairId}`);
3768
+ this.trackSyncErrors(desc.id, pair.pairId);
3769
+ log3.log(`[AppDataGroup:${this.groupId}] backend ${desc.id} (${desc.type}) connected, pair=${pair.pairId}`);
3649
3770
  } catch (err) {
3650
3771
  const message = err instanceof Error ? err.message : String(err);
3651
3772
  this.backendStates.set(desc.id, {
3652
3773
  backendId: desc.id,
3653
3774
  error: { message, timestamp: Date.now() }
3654
3775
  });
3655
- log2.error(`[AppDataGroup:${this.groupId}] Failed to create backend ${desc.id} (${desc.type}):`, err);
3776
+ log3.error(`[AppDataGroup:${this.groupId}] Failed to create backend ${desc.id} (${desc.type}):`, err);
3656
3777
  }
3657
3778
  }
3658
3779
  try {
3659
3780
  await this.syncEngine.syncAll();
3660
3781
  } catch (err) {
3661
- log2.warn(`[AppDataGroup:${this.groupId}] Initial sync failed:`, err);
3782
+ log3.warn(`[AppDataGroup:${this.groupId}] Initial sync failed:`, err);
3662
3783
  }
3663
3784
  this.syncEngine.watchAll();
3664
3785
  }
@@ -3673,13 +3794,31 @@ var AppDataGroupImpl = class {
3673
3794
  try {
3674
3795
  await this.tombstones.gc(this.allBackendIds(), this.tombstoneTargets());
3675
3796
  } catch (err) {
3676
- log2.warn(`[AppDataGroup:${this.groupId}] tombstone GC failed:`, err);
3797
+ log3.warn(`[AppDataGroup:${this.groupId}] tombstone GC failed:`, err);
3677
3798
  }
3678
3799
  return Array.from(results.values());
3679
3800
  }
3680
3801
  getBackendSyncStates() {
3681
3802
  return new Map(this.backendStates);
3682
3803
  }
3804
+ /** Mirror per-pair `sync:error` into `getBackendSyncStates()` (see ConfigRepo). */
3805
+ trackSyncErrors(backendId, pairId) {
3806
+ this.syncEngine.on(pairId, "sync:error", (event) => {
3807
+ const error = event.error;
3808
+ this.backendStates.set(backendId, {
3809
+ backendId,
3810
+ pairId,
3811
+ error: {
3812
+ message: error instanceof Error ? error.message : String(error ?? "sync failed"),
3813
+ timestamp: Date.now()
3814
+ }
3815
+ });
3816
+ });
3817
+ this.syncEngine.on(pairId, "sync:end", () => {
3818
+ const current = this.backendStates.get(backendId);
3819
+ if (current?.error) this.backendStates.set(backendId, { backendId, pairId });
3820
+ });
3821
+ }
3683
3822
  // -----------------------------------------------------------------------
3684
3823
  // Unified SyncGroupHandle — deletion & metadata (data groups)
3685
3824
  // -----------------------------------------------------------------------
@@ -3690,7 +3829,7 @@ var AppDataGroupImpl = class {
3690
3829
  const bytes = typeof data === "string" ? new TextEncoder().encode(data) : toUint8Array2(data);
3691
3830
  await this.versions.record(path, bytes);
3692
3831
  } catch (err) {
3693
- log2.warn(`[AppDataGroup:${this.groupId}] version record failed for ${path}:`, err);
3832
+ log3.warn(`[AppDataGroup:${this.groupId}] version record failed for ${path}:`, err);
3694
3833
  }
3695
3834
  }
3696
3835
  /** Delete tombstoned files on local + every connected backend before/after sync. */
@@ -3698,14 +3837,14 @@ var AppDataGroupImpl = class {
3698
3837
  try {
3699
3838
  await this.tombstones.process(this.tombstoneTargets());
3700
3839
  } catch (err) {
3701
- log2.warn(`[AppDataGroup:${this.groupId}] ${stage} tombstone pass failed:`, err);
3840
+ log3.warn(`[AppDataGroup:${this.groupId}] ${stage} tombstone pass failed:`, err);
3702
3841
  }
3703
3842
  }
3704
3843
  async confirmTombstones() {
3705
3844
  try {
3706
3845
  await this.tombstones.confirm(this.allBackendIds());
3707
3846
  } catch (err) {
3708
- log2.warn(`[AppDataGroup:${this.groupId}] tombstone confirmations failed:`, err);
3847
+ log3.warn(`[AppDataGroup:${this.groupId}] tombstone confirmations failed:`, err);
3709
3848
  }
3710
3849
  }
3711
3850
  /** Write a tombstone for `filePath`. Records metadata only — it never creates the file. */
@@ -3738,7 +3877,7 @@ var AppDataGroupImpl = class {
3738
3877
  }
3739
3878
  await removeDirectoryTree(this.localFS, normalized);
3740
3879
  this.schedulePostDeleteSync();
3741
- log2.log(`[AppDataGroup:${this.groupId}] deleteFile(directory): ${normalized} (${files.length} file(s))`);
3880
+ log3.log(`[AppDataGroup:${this.groupId}] deleteFile(directory): ${normalized} (${files.length} file(s))`);
3742
3881
  return;
3743
3882
  }
3744
3883
  await this.writeTombstoneFor(normalized);
@@ -3777,7 +3916,7 @@ var AppDataGroupImpl = class {
3777
3916
  try {
3778
3917
  await this.syncEngine.syncAll();
3779
3918
  } catch (err) {
3780
- log2.warn(`[AppDataGroup:${this.groupId}] sync after conflict resolve failed:`, err);
3919
+ log3.warn(`[AppDataGroup:${this.groupId}] sync after conflict resolve failed:`, err);
3781
3920
  }
3782
3921
  }
3783
3922
  readConflictBackup(conflictId, fileType) {
@@ -3812,7 +3951,7 @@ var AppDataGroupImpl = class {
3812
3951
  if (this.dataBackends.has(id)) {
3813
3952
  throw new Error(`Backend "${id}" already exists in data group "${this.groupId}"`);
3814
3953
  }
3815
- log2.log(`[AppDataGroup:${this.groupId}] addBackend: creating ${id} (${type})...`);
3954
+ log3.log(`[AppDataGroup:${this.groupId}] addBackend: creating ${id} (${type})...`);
3816
3955
  const instance = await createBackend({ type, options });
3817
3956
  const syncable = backendToSyncableFS(instance, `${type}(${id})`);
3818
3957
  const localSyncable = backendToSyncableFS(this.localFS, `local(${this.groupId})`);
@@ -3840,12 +3979,13 @@ var AppDataGroupImpl = class {
3840
3979
  if (this.features.conflicts) {
3841
3980
  this.syncEngine.on(pair.pairId, "conflict", (event) => {
3842
3981
  this.archiveConflict(event).catch((err) => {
3843
- log2.warn(`[AppDataGroup:${this.groupId}] conflict archive failed:`, err);
3982
+ log3.warn(`[AppDataGroup:${this.groupId}] conflict archive failed:`, err);
3844
3983
  });
3845
3984
  });
3846
3985
  }
3986
+ this.trackSyncErrors(id, pair.pairId);
3847
3987
  this._backends = [...this._backends.filter((b) => b.id !== id), desc];
3848
- log2.log(`[AppDataGroup:${this.groupId}] addBackend: ${id} (${type}) connected, pair=${pair.pairId}`);
3988
+ log3.log(`[AppDataGroup:${this.groupId}] addBackend: ${id} (${type}) connected, pair=${pair.pairId}`);
3849
3989
  try {
3850
3990
  const stale = (await this.tombstones.list()).find(
3851
3991
  (t) => t.path === backendMetaFilePath(id)
@@ -3853,12 +3993,12 @@ var AppDataGroupImpl = class {
3853
3993
  if (stale) await this.tombstones.remove(stale);
3854
3994
  await writeBackendMetaDescriptor(this.localFS, desc);
3855
3995
  } catch (err) {
3856
- log2.warn(`[AppDataGroup:${this.groupId}] addBackend: failed to write .meta/backends/${id}.json:`, err);
3996
+ log3.warn(`[AppDataGroup:${this.groupId}] addBackend: failed to write .meta/backends/${id}.json:`, err);
3857
3997
  }
3858
3998
  try {
3859
3999
  await this.syncEngine.sync(pair.pairId);
3860
4000
  } catch (err) {
3861
- log2.warn(`[AppDataGroup:${this.groupId}] addBackend: initial sync failed for ${id}:`, err);
4001
+ log3.warn(`[AppDataGroup:${this.groupId}] addBackend: initial sync failed for ${id}:`, err);
3862
4002
  }
3863
4003
  this.syncEngine.watch(pair.pairId);
3864
4004
  await this.parent.updateAppDataGroupDescriptor(this.groupId, this._backends, {
@@ -3889,7 +4029,7 @@ var AppDataGroupImpl = class {
3889
4029
  if (backend?.instance?.dispose) {
3890
4030
  await backend.instance.dispose();
3891
4031
  }
3892
- log2.log(`[AppDataGroup:${this.groupId}] removeBackend: ${id} removed`);
4032
+ log3.log(`[AppDataGroup:${this.groupId}] removeBackend: ${id} removed`);
3893
4033
  }
3894
4034
  listBackends() {
3895
4035
  return Array.from(this.dataBackends.values()).map((b) => b.desc);
@@ -3931,44 +4071,44 @@ async function createConfigRepo(appId, options = {}) {
3931
4071
  idbStoreName: options.idbStoreName,
3932
4072
  folderPath: options.folderPath
3933
4073
  });
3934
- log2.log(`[createConfigRepo] Creating local primary (type: ${localPrimary.type})...`);
4074
+ log3.log(`[createConfigRepo] Creating local primary (type: ${localPrimary.type})...`);
3935
4075
  const primaryInstance = await createBackend(localPrimary);
3936
4076
  const cachedFS = primaryInstance;
3937
4077
  if (options.purgeMtimeSidecars !== false) {
3938
4078
  try {
3939
4079
  const purged = await purgeMtimeSidecars(cachedFS);
3940
4080
  if (purged.removed.length > 0) {
3941
- log2.warn(
4081
+ log3.warn(
3942
4082
  `[createConfigRepo] purged ${purged.removed.length} leaked .mtime sidecar(s) from local primary:`,
3943
4083
  purged.removed
3944
4084
  );
3945
4085
  }
3946
4086
  } catch (err) {
3947
- log2.warn(`[createConfigRepo] .mtime purge failed:`, err?.message ?? err);
4087
+ log3.warn(`[createConfigRepo] .mtime purge failed:`, err?.message ?? err);
3948
4088
  }
3949
4089
  }
3950
4090
  if (options.purgeKeepFiles !== false) {
3951
4091
  try {
3952
4092
  const purged = await purgeKeepFiles(cachedFS);
3953
4093
  if (purged.removed.length > 0) {
3954
- log2.warn(
4094
+ log3.warn(
3955
4095
  `[createConfigRepo] purged ${purged.removed.length} leaked .keep placeholder(s) from local primary:`,
3956
4096
  purged.removed
3957
4097
  );
3958
4098
  }
3959
4099
  } catch (err) {
3960
- log2.warn(`[createConfigRepo] .keep purge failed:`, err?.message ?? err);
4100
+ log3.warn(`[createConfigRepo] .keep purge failed:`, err?.message ?? err);
3961
4101
  }
3962
4102
  }
3963
4103
  const cacheOptions = options.cache === false ? void 0 : options.cache ?? {};
3964
4104
  try {
3965
4105
  await primaryInstance.mkdir(META_DIR);
3966
- log2.log(`[createConfigRepo] /.meta/ ready`);
4106
+ log3.log(`[createConfigRepo] /.meta/ ready`);
3967
4107
  } catch (err) {
3968
4108
  const msg = err.message || "";
3969
4109
  if (msg.includes("File exists") || msg.includes("EEXIST") || err.code === "EEXIST") {
3970
4110
  } else {
3971
- log2.error(`[createConfigRepo] Failed to ensure /.meta/:`, err.message);
4111
+ log3.error(`[createConfigRepo] Failed to ensure /.meta/:`, err.message);
3972
4112
  }
3973
4113
  }
3974
4114
  try {
@@ -3979,7 +4119,7 @@ async function createConfigRepo(appId, options = {}) {
3979
4119
  } catch {
3980
4120
  await ensureParentDir2(primaryInstance, path);
3981
4121
  await primaryInstance.writeFile(path, groupTypeBytes);
3982
- log2.log(`[createConfigRepo] group-type set to "config-sync" at ${path}`);
4122
+ log3.log(`[createConfigRepo] group-type set to "config-sync" at ${path}`);
3983
4123
  }
3984
4124
  }
3985
4125
  if (!await readGroupDescriptor(primaryInstance)) {
@@ -3991,7 +4131,7 @@ async function createConfigRepo(appId, options = {}) {
3991
4131
  });
3992
4132
  }
3993
4133
  } catch (err) {
3994
- log2.warn(`[createConfigRepo] Failed to write group metadata:`, err.message);
4134
+ log3.warn(`[createConfigRepo] Failed to write group metadata:`, err.message);
3995
4135
  }
3996
4136
  const tempRepo = new ConfigRepo(
3997
4137
  appId,
@@ -4005,11 +4145,11 @@ async function createConfigRepo(appId, options = {}) {
4005
4145
  );
4006
4146
  const oldBackendsMeta = await tempRepo.readMetaFile(BACKENDS_FILE);
4007
4147
  if (oldBackendsMeta && oldBackendsMeta.backends?.length > 0) {
4008
- log2.log(`[createConfigRepo] Migrating ${oldBackendsMeta.backends.length} backend(s) from backends.json to individual files...`);
4148
+ log3.log(`[createConfigRepo] Migrating ${oldBackendsMeta.backends.length} backend(s) from backends.json to individual files...`);
4009
4149
  await tempRepo.ensureDir(`${BACKENDS_DIR}/.keep`);
4010
4150
  for (const desc of oldBackendsMeta.backends) {
4011
4151
  if (desc.id === LOCAL_IDB_BACKEND_ID) {
4012
- log2.log(`[createConfigRepo] Skipping local backend ${desc.id} during migration`);
4152
+ log3.log(`[createConfigRepo] Skipping local backend ${desc.id} during migration`);
4013
4153
  continue;
4014
4154
  }
4015
4155
  await tempRepo.writeBackendDescriptor(desc);
@@ -4027,7 +4167,7 @@ async function createConfigRepo(appId, options = {}) {
4027
4167
  }
4028
4168
  }
4029
4169
  }
4030
- log2.log(`[createConfigRepo] Migration complete`);
4170
+ log3.log(`[createConfigRepo] Migration complete`);
4031
4171
  }
4032
4172
  let allBackends = await tempRepo.readAllBackendDescriptors();
4033
4173
  if (options.backendInfo) {
@@ -4045,19 +4185,19 @@ async function createConfigRepo(appId, options = {}) {
4045
4185
  type: options.backendInfo.type,
4046
4186
  options: options.backendInfo.options
4047
4187
  });
4048
- log2.log(`[createConfigRepo] Added replica backend: ${replicaId} (${options.backendInfo.type})`);
4188
+ log3.log(`[createConfigRepo] Added replica backend: ${replicaId} (${options.backendInfo.type})`);
4049
4189
  allBackends = [...allBackends, { id: replicaId, type: options.backendInfo.type, options: options.backendInfo.options }];
4050
4190
  } else if (dupConfig) {
4051
- log2.log(`[createConfigRepo] Replica with same config already registered as "${dupConfig.id}", skipping`);
4191
+ log3.log(`[createConfigRepo] Replica with same config already registered as "${dupConfig.id}", skipping`);
4052
4192
  } else {
4053
- log2.log(`[createConfigRepo] Replica ${replicaId} already registered`);
4193
+ log3.log(`[createConfigRepo] Replica ${replicaId} already registered`);
4054
4194
  }
4055
4195
  }
4056
- log2.log(`[createConfigRepo] Replica backends: ${allBackends.map((b) => b.id).join(", ") || "(none)"}`);
4196
+ log3.log(`[createConfigRepo] Replica backends: ${allBackends.map((b) => b.id).join(", ") || "(none)"}`);
4057
4197
  let nodeId = options.nodeId;
4058
4198
  if (!nodeId) {
4059
4199
  nodeId = `node-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`;
4060
- log2.log(`[createConfigRepo] Generated nodeId: ${nodeId}`);
4200
+ log3.log(`[createConfigRepo] Generated nodeId: ${nodeId}`);
4061
4201
  }
4062
4202
  const serializer = createSerializerChain(options.serializer);
4063
4203
  const repo = new ConfigRepo(
@@ -4080,29 +4220,29 @@ async function createConfigRepo(appId, options = {}) {
4080
4220
  try {
4081
4221
  const mig = await repo.migrateLegacyVersionSidecars();
4082
4222
  if (mig.renamed.length === 0 && mig.deleted.length === 0 && mig.remoteDeleted.length === 0) {
4083
- log2.log("[createConfigRepo] no legacy version sidecars to migrate");
4223
+ log3.log("[createConfigRepo] no legacy version sidecars to migrate");
4084
4224
  }
4085
4225
  } catch (err) {
4086
- log2.warn(`[createConfigRepo] version sidecar migration failed:`, err?.message ?? err);
4226
+ log3.warn(`[createConfigRepo] version sidecar migration failed:`, err?.message ?? err);
4087
4227
  }
4088
4228
  }
4089
4229
  await repo.load();
4090
4230
  if (repo.replicaCount > 0) {
4091
- log2.log("[createConfigRepo] Starting background initial sync + dedup...");
4231
+ log3.log("[createConfigRepo] Starting background initial sync + dedup...");
4092
4232
  repo.startBackgroundSync();
4093
4233
  }
4094
4234
  repo.syncMetaToReplicas().catch((err) => {
4095
- log2.error("[createConfigRepo] background syncMetaToReplicas failed:", err);
4235
+ log3.error("[createConfigRepo] background syncMetaToReplicas failed:", err);
4096
4236
  });
4097
4237
  return repo;
4098
4238
  }
4099
4239
 
4100
4240
  // src/connect.ts
4101
- var log3 = createLogger("connect");
4241
+ var log4 = createLogger("connect");
4102
4242
  var GROUP_TYPE_FILE2 = "/.config/group-type";
4103
4243
  var LEGACY_GROUP_TYPE_FILE2 = "/.meta/group-type";
4104
4244
  async function detectGroupType(type, options) {
4105
- log3(`detectGroupType: connecting to ${type}...`);
4245
+ log4(`detectGroupType: connecting to ${type}...`);
4106
4246
  const tempBackend = await createBackend({ type, options });
4107
4247
  try {
4108
4248
  for (const path of [GROUP_TYPE_FILE2, LEGACY_GROUP_TYPE_FILE2]) {
@@ -4110,15 +4250,15 @@ async function detectGroupType(type, options) {
4110
4250
  const raw = await tempBackend.readFile(path, "utf-8");
4111
4251
  const groupType = raw.trim();
4112
4252
  if (groupType === "config-sync" || groupType === "data-sync") {
4113
- log3(`detectGroupType: detected "${groupType}" at ${path}`);
4253
+ log4(`detectGroupType: detected "${groupType}" at ${path}`);
4114
4254
  return groupType;
4115
4255
  }
4116
- log3(`detectGroupType: unknown group-type value "${groupType}" at ${path}, treating as null`);
4256
+ log4(`detectGroupType: unknown group-type value "${groupType}" at ${path}, treating as null`);
4117
4257
  return null;
4118
4258
  } catch {
4119
4259
  }
4120
4260
  }
4121
- log3(`detectGroupType: no group-type file found (new backend)`);
4261
+ log4(`detectGroupType: no group-type file found (new backend)`);
4122
4262
  return null;
4123
4263
  } finally {
4124
4264
  if (tempBackend?.dispose) {
@@ -4127,7 +4267,7 @@ async function detectGroupType(type, options) {
4127
4267
  }
4128
4268
  }
4129
4269
  async function connect(appId, options = {}) {
4130
- log3(`connect: appId=${appId}`);
4270
+ log4(`connect: appId=${appId}`);
4131
4271
  if (!options.backendInfo) {
4132
4272
  const repo2 = await createConfigRepo(appId, {
4133
4273
  idbStoreName: options.idbStoreName,
@@ -4145,7 +4285,7 @@ async function connect(appId, options = {}) {
4145
4285
  try {
4146
4286
  appDataGroups2.push(await repo2.getAppDataGroup(d.id));
4147
4287
  } catch (err) {
4148
- log3(`connect: failed to load app data group "${d.id}":`, err);
4288
+ log4(`connect: failed to load app data group "${d.id}":`, err);
4149
4289
  }
4150
4290
  }
4151
4291
  let dataGroup2 = appDataGroups2[0];
@@ -4174,7 +4314,7 @@ async function connect(appId, options = {}) {
4174
4314
  groupType = detectedType;
4175
4315
  } else {
4176
4316
  groupType = options.groupType ?? "config-sync";
4177
- log3(`connect: new backend, using groupType="${groupType}"`);
4317
+ log4(`connect: new backend, using groupType="${groupType}"`);
4178
4318
  }
4179
4319
  const repo = await createConfigRepo(
4180
4320
  appId,
@@ -4203,7 +4343,7 @@ async function connect(appId, options = {}) {
4203
4343
  try {
4204
4344
  appDataGroups.push(await repo.getAppDataGroup(d.id));
4205
4345
  } catch (err) {
4206
- log3(`connect: failed to load app data group "${d.id}":`, err);
4346
+ log4(`connect: failed to load app data group "${d.id}":`, err);
4207
4347
  }
4208
4348
  }
4209
4349
  let dataGroup = appDataGroups[0];