engine7 7.1.144 → 7.1.145

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.
@@ -244,7 +244,7 @@ function validateTravelChannelConfiguration(channels) {
244
244
  if (name === "emotion" || value2?.enabled !== true) continue;
245
245
  if (!["feishu", "discord", "wechat"].includes(name)) throw new Error("TRAVEL_CHANNEL_NOT_CONTROLLED");
246
246
  if (value2.mode !== "remote-only") throw new Error("TRAVEL_REMOTE_ONLY_REQUIRED");
247
- const hasPlatformSecret = (block) => block && typeof block === "object" && Object.entries(block).some(([key2, v]) => ["appSecret", "token", "accessToken", "tenantAccessToken", "app_secret", "botToken", "bot_token"].includes(key2) && typeof v === "string" && !!v.trim() || v && typeof v === "object" && hasPlatformSecret(v));
247
+ const hasPlatformSecret = (block) => block && typeof block === "object" && Object.entries(block).some(([key3, v]) => ["appSecret", "token", "accessToken", "tenantAccessToken", "app_secret", "botToken", "bot_token"].includes(key3) && typeof v === "string" && !!v.trim() || v && typeof v === "object" && hasPlatformSecret(v));
248
248
  if (hasPlatformSecret(value2)) throw new Error("TRAVEL_PLATFORM_SECRET_PRESENT");
249
249
  let url;
250
250
  try {
@@ -703,15 +703,15 @@ var init_sqlite_replication = __esm({
703
703
  requireForeignKeys(this.db);
704
704
  if (captureGuardHash(this.db) !== this.guardHash) throw new Error("REPLICATION_GUARD_MISMATCH");
705
705
  if (sqliteReplicationSchemaHash(this.db) !== this.schemaHash) throw new Error("REPLICATION_SCHEMA_MISMATCH");
706
- const before = sequences(this.db, this.excludedTables), sessions = [];
706
+ const before = sequences(this.db, this.excludedTables), sessions2 = [];
707
707
  try {
708
- if (this.sessionTables) for (const table of this.sessionTables) sessions.push(this.db.createSession({ table }));
709
- else sessions.push(this.db.createSession());
708
+ if (this.sessionTables) for (const table of this.sessionTables) sessions2.push(this.db.createSession({ table }));
709
+ else sessions2.push(this.db.createSession());
710
710
  } catch (error) {
711
- for (const session of sessions) session.close();
711
+ for (const session of sessions2) session.close();
712
712
  throw error;
713
713
  }
714
- this.active = { sessions, sequences: before, closed: false };
714
+ this.active = { sessions: sessions2, sequences: before, closed: false };
715
715
  return this.active;
716
716
  }
717
717
  appendCapture(capture2) {
@@ -978,31 +978,31 @@ var init_sqlite_replication = __esm({
978
978
  // src/continuity/runtime-replication.ts
979
979
  import { constants as constants6, lstatSync as lstatSync5, realpathSync as realpathSync2, mkdirSync as mkdirSync4, openSync as openSync5, closeSync as closeSync5, fstatSync as fstatSync4, readFileSync as readFileSync3, writeFileSync as writeFileSync3, fsyncSync as fsyncSync5 } from "node:fs";
980
980
  import { basename as basename2, dirname as dirname5, join as join6, resolve as resolve3 } from "node:path";
981
- function checkKey(component, key2) {
982
- if (component === "topics-vectors" && typeof key2 === "string" && /^[a-f0-9]{64}$/.test(key2)) return;
983
- if (component === "legacy-memory" && typeof key2 === "string" && /^[A-Za-z0-9][A-Za-z0-9_.-]{0,127}$/.test(key2) && !/[. ]$/.test(key2) && !/^(CON|PRN|AUX|NUL|COM[1-9]|LPT[1-9])(?:\.|$)/i.test(key2)) return;
984
- if (["calendar", "proactive", "session-events"].includes(component) && key2 === void 0) return;
981
+ function checkKey(component, key3) {
982
+ if (component === "topics-vectors" && typeof key3 === "string" && /^[a-f0-9]{64}$/.test(key3)) return;
983
+ if (component === "legacy-memory" && typeof key3 === "string" && /^[A-Za-z0-9][A-Za-z0-9_.-]{0,127}$/.test(key3) && !/[. ]$/.test(key3) && !/^(CON|PRN|AUX|NUL|COM[1-9]|LPT[1-9])(?:\.|$)/i.test(key3)) return;
984
+ if (["calendar", "proactive", "session-events"].includes(component) && key3 === void 0) return;
985
985
  throw new Error("REPLICATION_REGISTRATION_INVALID");
986
986
  }
987
- function location2(stateDir, component, key2) {
988
- checkKey(component, key2);
989
- return join6(stateDir, ".continuity", component + (key2 === void 0 ? "" : "-" + key2) + "-replication.json");
987
+ function location2(stateDir, component, key3) {
988
+ checkKey(component, key3);
989
+ return join6(stateDir, ".continuity", component + (key3 === void 0 ? "" : "-" + key3) + "-replication.json");
990
990
  }
991
- function runtimeReplicationFile(stateDir, component, key2) {
992
- checkKey(component, key2);
993
- if (component === "legacy-memory") return join6(stateDir, "agents", key2, "memory", "memory.db");
994
- if (component === "topics-vectors") return join6(stateDir, "topics-history", key2, "vectors.db");
991
+ function runtimeReplicationFile(stateDir, component, key3) {
992
+ checkKey(component, key3);
993
+ if (component === "legacy-memory") return join6(stateDir, "agents", key3, "memory", "memory.db");
994
+ if (component === "topics-vectors") return join6(stateDir, "topics-history", key3, "vectors.db");
995
995
  if (component === "session-events") return join6(stateDir, ".continuity", "session-events.db");
996
996
  return join6(stateDir, "." + component, component + ".db");
997
997
  }
998
998
  function runtimeReplicationLocation(stateDir, component, file) {
999
- const key2 = component === "legacy-memory" ? basename2(dirname5(dirname5(file))) : component === "topics-vectors" ? basename2(dirname5(file)) : void 0;
999
+ const key3 = component === "legacy-memory" ? basename2(dirname5(dirname5(file))) : component === "topics-vectors" ? basename2(dirname5(file)) : void 0;
1000
1000
  try {
1001
- if (resolve3(file) !== resolve3(runtimeReplicationFile(stateDir, component, key2))) throw new Error();
1001
+ if (resolve3(file) !== resolve3(runtimeReplicationFile(stateDir, component, key3))) throw new Error();
1002
1002
  } catch (error) {
1003
1003
  throw new Error("REPLICATION_RUNTIME_PATH_UNSUPPORTED", { cause: error });
1004
1004
  }
1005
- return { component, ...key2 === void 0 ? {} : { key: key2 } };
1005
+ return { component, ...key3 === void 0 ? {} : { key: key3 } };
1006
1006
  }
1007
1007
  function normalize2(input) {
1008
1008
  if (!input || !/^[a-f0-9]{64}$/.test(input.schemaHash)) throw new Error("REPLICATION_REGISTRATION_INVALID");
@@ -1013,8 +1013,8 @@ function directory(path3) {
1013
1013
  if (!info.isDirectory() || info.isSymbolicLink() || realpathSync2(path3) !== resolve3(path3) || process.platform !== "win32" && (info.mode & 63 || info.uid !== process.getuid()))
1014
1014
  throw new Error("REPLICATION_REGISTRATION_INVALID");
1015
1015
  }
1016
- function readRuntimeReplicationRegistration(stateDir, component, key2) {
1017
- const file = location2(stateDir, component, key2);
1016
+ function readRuntimeReplicationRegistration(stateDir, component, key3) {
1017
+ const file = location2(stateDir, component, key3);
1018
1018
  try {
1019
1019
  lstatSync5(dirname5(file));
1020
1020
  } catch (error) {
@@ -1077,8 +1077,8 @@ function checkRuntimeReplicationDatabase(db, registration, component, version, r
1077
1077
  }
1078
1078
  return requested ?? registration?.binding;
1079
1079
  }
1080
- function enrollRuntimeReplication(db, stateDir, component, binding, key2) {
1081
- const file = location2(stateDir, component, key2), old = readRuntimeReplicationRegistration(stateDir, component, key2);
1080
+ function enrollRuntimeReplication(db, stateDir, component, binding, key3) {
1081
+ const file = location2(stateDir, component, key3), old = readRuntimeReplicationRegistration(stateDir, component, key3);
1082
1082
  const version = readSchemaVersion(db);
1083
1083
  if (version?.component !== component) throw new Error("REPLICATION_SCHEMA_MISMATCH");
1084
1084
  checkRuntimeReplicationDatabase(db, old, component, version.version, binding);
@@ -1091,7 +1091,7 @@ function enrollRuntimeReplication(db, stateDir, component, binding, key2) {
1091
1091
  writeFileSync3(file, JSON.stringify(input), { mode: 384, flag: "wx", flush: true });
1092
1092
  } catch (error) {
1093
1093
  if (error.code !== "EEXIST") throw error;
1094
- if (JSON.stringify(readRuntimeReplicationRegistration(stateDir, component, key2)) !== JSON.stringify(input)) throw new Error("REPLICATION_REGISTRATION_MISMATCH");
1094
+ if (JSON.stringify(readRuntimeReplicationRegistration(stateDir, component, key3)) !== JSON.stringify(input)) throw new Error("REPLICATION_REGISTRATION_MISMATCH");
1095
1095
  }
1096
1096
  if (process.platform !== "win32") {
1097
1097
  const fd = openSync5(dirname5(file), "r");
@@ -1116,11 +1116,11 @@ var init_runtime_replication = __esm({
1116
1116
  import { createHash as createHash8 } from "node:crypto";
1117
1117
  function scopeId(scope) {
1118
1118
  if ([scope.ownerId, scope.appId, scope.projectId].some((value2) => typeof value2 !== "string" || !value2.trim())) throw new Error("Invalid memory scope");
1119
- const key2 = JSON.stringify([scope.ownerId, scope.appId, scope.projectId]);
1120
- const cached = scopeIdMemo.get(key2);
1119
+ const key3 = JSON.stringify([scope.ownerId, scope.appId, scope.projectId]);
1120
+ const cached = scopeIdMemo.get(key3);
1121
1121
  if (cached) return cached;
1122
1122
  const id2 = "scope_" + createHash8("sha256").update(JSON.stringify([scope.ownerId, scope.appId, scope.projectId])).digest("hex");
1123
- scopeIdMemo.set(key2, id2);
1123
+ scopeIdMemo.set(key3, id2);
1124
1124
  return id2;
1125
1125
  }
1126
1126
  var scopeIdMemo;
@@ -1294,10 +1294,10 @@ var init_live = __esm({
1294
1294
  /** 安全取子段('services.voice-chat.start' → current.services.voice-chat.start) */
1295
1295
  get(dotPath) {
1296
1296
  if (!this.current) return void 0;
1297
- return dotPath.split(".").reduce((acc, key2) => {
1297
+ return dotPath.split(".").reduce((acc, key3) => {
1298
1298
  if (acc == null) return void 0;
1299
- if (key2 === "__proto__" || key2 === "constructor" || key2 === "prototype") return void 0;
1300
- return acc[key2];
1299
+ if (key3 === "__proto__" || key3 === "constructor" || key3 === "prototype") return void 0;
1300
+ return acc[key3];
1301
1301
  }, this.current);
1302
1302
  }
1303
1303
  /** reload 时原地更新(Object.assign 保持引用不变)
@@ -1463,9 +1463,9 @@ function toWall(i = /* @__PURE__ */ new Date()) {
1463
1463
  return `${p.y}-${p2(p.mo)}-${p2(p.d)} ${p2(p.hh)}:${p2(p.mm)}:${p2(p.ss)}`;
1464
1464
  }
1465
1465
  function warnOnce(callSite, shape, sample) {
1466
- const key2 = `${callSite}:${shape}`;
1467
- if (warned.has(key2)) return;
1468
- warned.add(key2);
1466
+ const key3 = `${callSite}:${shape}`;
1467
+ if (warned.has(key3)) return;
1468
+ warned.add(key3);
1469
1469
  console.warn(`[clock] ${callSite} \u5951\u7EA6\u8FDD\u89C4(${shape})\uFF0C\u6837\u672C: ${String(sample).slice(0, 80)}`);
1470
1470
  }
1471
1471
  function zoneOffsetMs(d) {
@@ -1990,7 +1990,7 @@ function runtimeEngineConfig(original, stateDir, workspace) {
1990
1990
  return value2;
1991
1991
  }
1992
1992
  if (Array.isArray(value2)) return value2.map(relocate);
1993
- if (value2 && typeof value2 === "object") return Object.fromEntries(Object.entries(value2).map(([key2, item]) => [key2, relocate(item)]));
1993
+ if (value2 && typeof value2 === "object") return Object.fromEntries(Object.entries(value2).map(([key3, item]) => [key3, relocate(item)]));
1994
1994
  return value2;
1995
1995
  };
1996
1996
  const copy = relocate(original), copiedAgents = copy.agents;
@@ -2924,9 +2924,9 @@ async function collectInventory(options) {
2924
2924
  continue;
2925
2925
  }
2926
2926
  validateRelativePath(path3);
2927
- const key2 = root + "/" + path3.normalize("NFC").toLowerCase();
2928
- if (aliases.has(key2)) throw new Error("PORTABLE_PATH_COLLISION");
2929
- aliases.add(key2);
2927
+ const key3 = root + "/" + path3.normalize("NFC").toLowerCase();
2928
+ if (aliases.has(key3)) throw new Error("PORTABLE_PATH_COLLISION");
2929
+ aliases.add(key3);
2930
2930
  let info = await lstat(source, { bigint: true }), linkSignature = "";
2931
2931
  if (options.selection === "core" && root === "workspace" && !prefix2 && !CORE_DIRECTORIES.has(name) && (info.isDirectory() || info.isSymbolicLink() && !/\.[a-z0-9]+$/i.test(name))) {
2932
2932
  exclusions.push({ root, path: path3, reason: "optional workspace material; outside core travel" });
@@ -3261,7 +3261,7 @@ var PublicationReplica = class _PublicationReplica {
3261
3261
  const replica = this.replicas.get(commit?.binding?.databaseId);
3262
3262
  if (!replica) throw new Error("PUBLICATION_UNREGISTERED_DATABASE");
3263
3263
  const content = await this.objects.putContent(encoded);
3264
- const received = replica.receive(commit);
3264
+ const received2 = replica.receive(commit);
3265
3265
  this.db.exec("BEGIN IMMEDIATE");
3266
3266
  try {
3267
3267
  const old = this.commitEvidence(commit.binding.databaseId, commit.sequence);
@@ -3276,7 +3276,7 @@ var PublicationReplica = class _PublicationReplica {
3276
3276
  while (this.commitEvidence(commit.binding.databaseId, replica.head().sequence + 1)) {
3277
3277
  if (!replica.applyNext()) break;
3278
3278
  }
3279
- return replica.appliedReceipt(commit.sequence) ?? received;
3279
+ return replica.appliedReceipt(commit.sequence) ?? received2;
3280
3280
  }
3281
3281
  databaseMissing(manifest) {
3282
3282
  const missing = [];
@@ -3486,12 +3486,12 @@ var incarnation = (file) => {
3486
3486
  return `${s.dev}:${s.ino}`;
3487
3487
  };
3488
3488
  function validateRecoveryArchiveEntry(entry, identity) {
3489
- if (!entry || Object.keys(entry).some((key2) => !["format", "id", "kind", "manifest", "databases", "publication", "receipt"].includes(key2)) || entry.format !== FORMAT || !ID2.test(entry.id) || !["COMMON", "LOCAL", "REMOTE"].includes(entry.kind)) throw new Error("RECOVERY_ARCHIVE_CORRUPT");
3489
+ if (!entry || Object.keys(entry).some((key3) => !["format", "id", "kind", "manifest", "databases", "publication", "receipt"].includes(key3)) || entry.format !== FORMAT || !ID2.test(entry.id) || !["COMMON", "LOCAL", "REMOTE"].includes(entry.kind)) throw new Error("RECOVERY_ARCHIVE_CORRUPT");
3490
3490
  const manifest = normalizePublication(entry.manifest), manifestDigest = publicationDigest(manifest);
3491
3491
  if (!same(manifest.profile.identity, identity)) throw new Error("RECOVERY_IDENTITY_MISMATCH");
3492
3492
  if (!Array.isArray(entry.databases) || !same(entry.databases.map((db) => db.databaseId), manifest.profile.databaseIds)) throw new Error("RECOVERY_INCOMPLETE_DATABASES");
3493
3493
  for (const db of entry.databases) {
3494
- if (Object.keys(db).some((key2) => !["databaseId", "role", "schemaHash", "content"].includes(key2)) || db.role !== (entry.kind === "LOCAL" ? "source" : "replica") || !/^[a-f0-9]{64}$/.test(db.schemaHash)) throw new Error("RECOVERY_ARCHIVE_CORRUPT");
3494
+ if (Object.keys(db).some((key3) => !["databaseId", "role", "schemaHash", "content"].includes(key3)) || db.role !== (entry.kind === "LOCAL" ? "source" : "replica") || !/^[a-f0-9]{64}$/.test(db.schemaHash)) throw new Error("RECOVERY_ARCHIVE_CORRUPT");
3495
3495
  validateFileContent(db.content);
3496
3496
  }
3497
3497
  const publication = { state: "PUBLISHED", sequence: manifest.sequence, digest: manifestDigest, deletionWatermark: manifest.deletionWatermark, activationAllowed: false };
@@ -3938,9 +3938,9 @@ function resolveRecoveryDeletionSources(databases, deletions) {
3938
3938
  bytes += Buffer.byteLength(JSON.stringify(row));
3939
3939
  if (count > 1e6 || bytes > 64 * 1024 * 1024) throw new Error("RECOVERY_DEPENDENCY_BUDGET");
3940
3940
  if (!row.scope_id || !row.source_id || !row.origin_key || !Number.isSafeInteger(row.source_version) || row.source_version < 1) throw new Error("RECOVERY_DELETION_SOURCE_MISMATCH");
3941
- const key2 = JSON.stringify([row.scope_id, row.source_id]), prior = originals.get(key2);
3941
+ const key3 = JSON.stringify([row.scope_id, row.source_id]), prior = originals.get(key3);
3942
3942
  if (prior && (prior.origin_key !== row.origin_key || prior.source_version !== row.source_version)) throw new Error("RECOVERY_DELETION_SOURCE_MISMATCH");
3943
- originals.set(key2, row);
3943
+ originals.set(key3, row);
3944
3944
  const familyKey = JSON.stringify([row.scope_id, row.origin_key]), family = families.get(familyKey) ?? { sources: /* @__PURE__ */ new Map(), versions: /* @__PURE__ */ new Map() };
3945
3945
  const versionId = family.versions.get(row.source_version);
3946
3946
  if (versionId !== void 0 && versionId !== row.source_id) throw new Error("RECOVERY_DELETION_SOURCE_MISMATCH");
@@ -3956,18 +3956,18 @@ function resolveRecoveryDeletionSources(databases, deletions) {
3956
3956
  const exact2 = originals.get(JSON.stringify([deletion.scopeId, deletion.sourceId]));
3957
3957
  if (exact2 && exact2.source_version !== deletion.version) throw new Error("RECOVERY_DELETION_SOURCE_MISMATCH");
3958
3958
  let familyKey = exact2 ? JSON.stringify([exact2.scope_id, exact2.origin_key]) : void 0;
3959
- if (!familyKey) for (const [key2, family] of families) {
3959
+ if (!familyKey) for (const [key3, family] of families) {
3960
3960
  const original = family.sources.values().next().value;
3961
3961
  if (original.scope_id !== deletion.scopeId) continue;
3962
3962
  if (++checks > 1e6) throw new Error("RECOVERY_DEPENDENCY_BUDGET");
3963
3963
  if (recoveryOriginalSourceId(original.scope_id, original.origin_key, deletion.version) !== deletion.sourceId) continue;
3964
- if (familyKey && familyKey !== key2) throw new Error("RECOVERY_DELETION_SOURCE_MISMATCH");
3965
- familyKey = key2;
3964
+ if (familyKey && familyKey !== key3) throw new Error("RECOVERY_DELETION_SOURCE_MISMATCH");
3965
+ familyKey = key3;
3966
3966
  }
3967
3967
  if (!familyKey) throw new Error("RECOVERY_DELETION_SOURCE_UNRESOLVED");
3968
3968
  for (const original of families.get(familyKey).sources.values()) {
3969
- const key2 = JSON.stringify([original.scope_id, original.source_id]);
3970
- if (!result.has(key2)) result.set(key2, { scopeId: original.scope_id, sourceId: original.source_id, version: original.source_version, deletionId: deletion.id });
3969
+ const key3 = JSON.stringify([original.scope_id, original.source_id]);
3970
+ if (!result.has(key3)) result.set(key3, { scopeId: original.scope_id, sourceId: original.source_id, version: original.source_version, deletionId: deletion.id });
3971
3971
  }
3972
3972
  }
3973
3973
  return [...result.values()].sort((a, b) => a.scopeId.localeCompare(b.scopeId, "en") || a.version - b.version || a.sourceId.localeCompare(b.sourceId, "en"));
@@ -3975,7 +3975,7 @@ function resolveRecoveryDeletionSources(databases, deletions) {
3975
3975
 
3976
3976
  // src/continuity/recovery-deletion.ts
3977
3977
  import { createHash as createHash7 } from "node:crypto";
3978
- var text = (row, key2) => row[key2]?.[0] === "text" ? row[key2][1] : void 0;
3978
+ var text = (row, key3) => row[key3]?.[0] === "text" ? row[key3][1] : void 0;
3979
3979
  var key = (scope, kind, id2) => JSON.stringify([scope, kind, id2]);
3980
3980
  var RecoveryDeletionGraph = class {
3981
3981
  edges = /* @__PURE__ */ new Map();
@@ -4179,11 +4179,18 @@ import { createHash as createHash10, randomUUID as randomUUID4 } from "node:cryp
4179
4179
  import { existsSync as existsSync4, readFileSync as readFileSync4, renameSync as renameSync2, unlinkSync as unlinkSync3, writeFileSync as writeFileSync6 } from "node:fs";
4180
4180
 
4181
4181
  // src/mem7/core/state/temporal.ts
4182
+ var INSTANT = /^\d{4}-\d{2}-\d{2}T.*(?:Z|[+-]\d{2}:\d{2})$/;
4183
+ var INSTANT_FORMAT = '\u65F6\u95F4\u7528\u5E26\u65F6\u533A\u504F\u79FB\u7684\u5B8C\u6574\u65F6\u523B\uFF0C\u5982 "2026-11-24T09:10:41+08:00"\uFF08\u65E5\u671F\u4E0E\u65F6\u95F4\u4E4B\u95F4\u7528 T \u6216\u7A7A\u683C\uFF0C\u7ED3\u5C3E\u662F Z \u6216 \xB1HH:MM\uFF09';
4184
+ var received = (value2) => (JSON.stringify(value2) ?? String(value2)).slice(0, 80);
4182
4185
  function instant(value2) {
4183
- if (!/^\d{4}-\d{2}-\d{2}T.*(?:Z|[+-]\d{2}:\d{2})$/.test(value2)) throw new Error("TIME_REQUIRED: explicit UTC offset required");
4184
- if (!isCalendarDate(value2.substring(0, 10))) throw new Error("INVALID_TIME");
4185
- const time = Date.parse(value2);
4186
- if (!Number.isFinite(time)) throw new Error("INVALID_TIME");
4186
+ let text2 = value2;
4187
+ if (typeof text2 !== "string" || !INSTANT.test(text2)) {
4188
+ text2 = typeof value2 === "string" ? value2.trim().replace(/^(\d{4}-\d{2}-\d{2}) /, "$1T").replace(/([+-]\d{2})(\d{2})$/, "$1:$2") : value2;
4189
+ if (typeof text2 !== "string" || !INSTANT.test(text2)) throw new Error(`TIME_REQUIRED: explicit UTC offset required \u2014 \u6536\u5230 ${received(value2)}\uFF1B${INSTANT_FORMAT}`);
4190
+ }
4191
+ if (!isCalendarDate(text2.substring(0, 10))) throw new Error(`INVALID_TIME: \u4E0D\u662F\u6709\u6548\u7684\u65E5\u5386\u65E5\u671F \u2014 \u6536\u5230 ${received(value2)}`);
4192
+ const time = Date.parse(text2);
4193
+ if (!Number.isFinite(time)) throw new Error(`INVALID_TIME \u2014 \u6536\u5230 ${received(value2)}\uFF1B${INSTANT_FORMAT}`);
4187
4194
  return new Date(time).toISOString();
4188
4195
  }
4189
4196
  function isCalendarDate(value2) {
@@ -4196,7 +4203,7 @@ function validateTimezone(timezone) {
4196
4203
  try {
4197
4204
  new Intl.DateTimeFormat("en", { timeZone: timezone });
4198
4205
  } catch {
4199
- throw new Error("INVALID_TIMEZONE");
4206
+ throw new Error(`INVALID_TIMEZONE: timezone \u7528 IANA \u65F6\u533A\u540D\uFF0C\u5982 Asia/Shanghai\uFF08\u6536\u5230 ${String(timezone).slice(0, 60)}\uFF09`);
4200
4207
  }
4201
4208
  }
4202
4209
  function localInstant(date, time, timezone) {
@@ -4228,10 +4235,13 @@ function localInstant(date, time, timezone) {
4228
4235
  return new Date([...matches][0]).toISOString();
4229
4236
  }
4230
4237
  function normalizeValidity(value2) {
4238
+ for (const field of ["validFrom", "validTo"]) {
4239
+ if (value2[field] === void 0) throw new Error(`TIME_REQUIRED: validity.${field} \u7F3A\u5931 \u2014 validFrom\u3001validTo\u3001precision \u4E09\u4E2A\u952E\u90FD\u8981\u5199\uFF1BvalidFrom\u3001validTo \u6CA1\u6709\u5C31\u5199 null\uFF0Cprecision \u53EA\u80FD\u662F exact/observed/unknown\uFF1B${INSTANT_FORMAT}`);
4240
+ }
4231
4241
  const validFrom = value2.validFrom === null ? null : instant(value2.validFrom);
4232
4242
  const validTo = value2.validTo === null ? null : instant(value2.validTo);
4233
- if (validFrom !== null && validTo !== null && validFrom >= validTo) throw new Error("INVALID_INTERVAL: expected [from,to)");
4234
- if (!["exact", "observed", "unknown"].includes(value2.precision)) throw new Error("INVALID_PRECISION");
4243
+ if (validFrom !== null && validTo !== null && validFrom >= validTo) throw new Error("INVALID_INTERVAL: \u9700\u8981 [validFrom, validTo) \u4E14 validFrom \u65E9\u4E8E validTo\uFF1B\u6CA1\u6709\u8D77\u70B9\u586B null\uFF0C\u53EA\u7ED3\u675F\u5173\u7CFB\u7528 changeKind=close");
4244
+ if (!["exact", "observed", "unknown"].includes(value2.precision)) throw new Error("INVALID_PRECISION: precision \u53EA\u80FD\u662F exact\uFF08\u786E\u5207\u65F6\u523B\uFF09\u3001observed\uFF08\u89C2\u5BDF\u5230\u7684\u5927\u81F4\u65F6\u95F4\uFF09\u3001unknown\uFF08\u65F6\u95F4\u4E0D\u660E\uFF09");
4235
4245
  if (value2.timezone) validateTimezone(value2.timezone);
4236
4246
  return { ...value2, validFrom, validTo };
4237
4247
  }
@@ -4241,7 +4251,7 @@ function overlaps(a, b) {
4241
4251
  function canonicalJson(value2) {
4242
4252
  const normalize4 = (input) => {
4243
4253
  if (Array.isArray(input)) return input.map(normalize4);
4244
- if (input && typeof input === "object") return Object.fromEntries(Object.entries(input).filter(([, entry]) => entry !== void 0).sort(([a], [b]) => a.localeCompare(b)).map(([key2, entry]) => [key2, normalize4(entry)]));
4254
+ if (input && typeof input === "object") return Object.fromEntries(Object.entries(input).filter(([, entry]) => entry !== void 0).sort(([a], [b]) => a.localeCompare(b)).map(([key3, entry]) => [key3, normalize4(entry)]));
4245
4255
  return input;
4246
4256
  };
4247
4257
  const json = JSON.stringify(normalize4(value2));
@@ -4274,8 +4284,8 @@ function contextTimeKey(db, scopeId2, validAt) {
4274
4284
  }
4275
4285
  return `valid-window:${from}:${to}`;
4276
4286
  }
4277
- function assertContextTime(key2, now2 = Date.now()) {
4278
- const match = key2.match(/^valid-window:(-?\d+):(-?\d+)$/);
4287
+ function assertContextTime(key3, now2 = Date.now()) {
4288
+ const match = key3.match(/^valid-window:(-?\d+):(-?\d+)$/);
4279
4289
  if (!match || !Number.isSafeInteger(Number(match[1])) || !Number.isSafeInteger(Number(match[2])) || Number(match[1]) >= Number(match[2])) throw new Error("INVALID_CONTEXT_TIME_DEPENDENCY");
4280
4290
  if (now2 < Number(match[1]) || now2 >= Number(match[2])) throw new Error("CONTEXT_TIME_EXPIRED");
4281
4291
  }
@@ -4412,9 +4422,9 @@ function append(db, scope, kind, id2, payload) {
4412
4422
  return Number(result.lastInsertRowid);
4413
4423
  }
4414
4424
  function recordArtifactBasis(db, scope, kind, id2, version, dependencies2) {
4415
- const key2 = basisKey(kind, id2, version);
4416
- if (!db.prepare("SELECT 1 FROM memory_knowledge_history WHERE scope_id=? AND target_kind='artifact.basis' AND target_id=?").get(scopeId(scope), key2)) {
4417
- append(db, scope, "artifact.basis", key2, { dependencies: dependencies2 });
4425
+ const key3 = basisKey(kind, id2, version);
4426
+ if (!db.prepare("SELECT 1 FROM memory_knowledge_history WHERE scope_id=? AND target_kind='artifact.basis' AND target_id=?").get(scopeId(scope), key3)) {
4427
+ append(db, scope, "artifact.basis", key3, { dependencies: dependencies2 });
4418
4428
  }
4419
4429
  }
4420
4430
  var ArtifactHistory = class {
@@ -4493,8 +4503,8 @@ var ArtifactHistory = class {
4493
4503
  if (cutoff) return historicalRow(this.db, scope, "artifact.basis", basisKey(kind, id2, version), cutoff)?.dependencies ?? null;
4494
4504
  return this.dependencies.version(scope, kind, id2) === version ? this.dependencies.refs(scope, kind, id2) : null;
4495
4505
  }
4496
- scopeContextRetained(scope, key2) {
4497
- const basis = this.db.prepare("SELECT history_id FROM memory_knowledge_history WHERE scope_id=? AND target_kind='artifact.basis' AND target_id=? ORDER BY history_id LIMIT 1").get(scopeId(scope), key2);
4506
+ scopeContextRetained(scope, key3) {
4507
+ const basis = this.db.prepare("SELECT history_id FROM memory_knowledge_history WHERE scope_id=? AND target_kind='artifact.basis' AND target_id=? ORDER BY history_id LIMIT 1").get(scopeId(scope), key3);
4498
4508
  if (!basis) return false;
4499
4509
  const atGeneration = historicalRow(this.db, scope, "scope", "state", { historyId: basis.history_id, time: null, complete: true });
4500
4510
  if (!atGeneration) return false;
@@ -4512,15 +4522,15 @@ var ArtifactHistory = class {
4512
4522
  WHERE scope_id=? AND source_id=? AND interpretation_status<>'deleted'`).get(scopeKey, sourceId));
4513
4523
  const walk = (kind2, id3, version2) => {
4514
4524
  checkMemoryReadBudget(visited.size);
4515
- const key2 = basisKey(kind2, id3, version2);
4516
- if (memo.has(key2)) return memo.get(key2);
4517
- if (visited.has(key2)) return false;
4518
- visited.add(key2);
4525
+ const key3 = basisKey(kind2, id3, version2);
4526
+ if (memo.has(key3)) return memo.get(key3);
4527
+ if (visited.has(key3)) return false;
4528
+ visited.add(key3);
4519
4529
  try {
4520
- const basis = this.db.prepare("SELECT history_id,payload_json FROM memory_knowledge_history WHERE scope_id=? AND target_kind='artifact.basis' AND target_id=? ORDER BY history_id LIMIT 1").get(scopeKey, key2);
4530
+ const basis = this.db.prepare("SELECT history_id,payload_json FROM memory_knowledge_history WHERE scope_id=? AND target_kind='artifact.basis' AND target_id=? ORDER BY history_id LIMIT 1").get(scopeKey, key3);
4521
4531
  const refs2 = basis && JSON.parse(basis.payload_json).dependencies;
4522
4532
  if (!refs2 || this.db.prepare("SELECT 1 FROM memory_tombstones WHERE scope_id=? AND target_kind=? AND target_id=?").get(scopeKey, kind2, id3)) return false;
4523
- if (refs2.some((ref) => ref.parentKind === "scope" && !ref.parentId.startsWith("valid-window:")) && !this.scopeContextRetained(scope, key2)) return false;
4533
+ if (refs2.some((ref) => ref.parentKind === "scope" && !ref.parentId.startsWith("valid-window:")) && !this.scopeContextRetained(scope, key3)) return false;
4524
4534
  const retained = refs2.every((ref) => {
4525
4535
  checkMemoryReadBudget(visited.size);
4526
4536
  if (ref.parentKind === "source") return sourceRetained(ref.parentId);
@@ -4540,10 +4550,10 @@ var ArtifactHistory = class {
4540
4550
  }
4541
4551
  return true;
4542
4552
  });
4543
- memo.set(key2, retained);
4553
+ memo.set(key3, retained);
4544
4554
  return retained;
4545
4555
  } finally {
4546
- visited.delete(key2);
4556
+ visited.delete(key3);
4547
4557
  }
4548
4558
  };
4549
4559
  return walk(kind, id2, version);
@@ -4569,8 +4579,8 @@ var ArtifactHistory = class {
4569
4579
  };
4570
4580
  const walk = (parentKind, parentId, parentVersion, ancestors) => {
4571
4581
  checkMemoryReadBudget(ancestors.size);
4572
- const key2 = basisKey(parentKind, parentId, parentVersion);
4573
- if (ancestors.has(key2)) return false;
4582
+ const key3 = basisKey(parentKind, parentId, parentVersion);
4583
+ if (ancestors.has(key3)) return false;
4574
4584
  const state2 = this.state(scope, parentKind, parentId, cutoff);
4575
4585
  if (state2?.state !== "current" || state2.version !== parentVersion) return false;
4576
4586
  if (this.db.prepare("SELECT 1 FROM memory_tombstones WHERE scope_id=? AND target_kind=? AND target_id=?").get(scopeId(scope), parentKind, parentId)) return false;
@@ -4585,9 +4595,9 @@ var ArtifactHistory = class {
4585
4595
  }
4586
4596
  }
4587
4597
  if (refs2.some((ref) => ref.parentKind === "scope" && !ref.parentId.startsWith("valid-window:"))) {
4588
- if (!this.scopeContextRetained(scope, key2)) return false;
4598
+ if (!this.scopeContextRetained(scope, key3)) return false;
4589
4599
  }
4590
- const next = new Set(ancestors).add(key2);
4600
+ const next = new Set(ancestors).add(key3);
4591
4601
  for (const ref of refs2) {
4592
4602
  checkMemoryReadBudget(next.size);
4593
4603
  if (ref.parentKind === "source") {
@@ -4734,9 +4744,9 @@ function invalidateChildren(db, scope, pending, reason) {
4734
4744
  let referencedPlan;
4735
4745
  while (pending.length) {
4736
4746
  const child = pending.shift();
4737
- const key2 = JSON.stringify([child.child_kind, child.child_id]);
4738
- if (visited.has(key2) && (visited.get(key2) || !child.deleted)) continue;
4739
- visited.set(key2, Boolean(child.deleted));
4747
+ const key3 = JSON.stringify([child.child_kind, child.child_id]);
4748
+ if (visited.has(key3) && (visited.get(key3) || !child.deleted)) continue;
4749
+ visited.set(key3, Boolean(child.deleted));
4740
4750
  if (child.child_kind === "graph_plan") {
4741
4751
  referencedPlan ??= db.prepare(`SELECT 1 WHERE EXISTS (SELECT 1 FROM memory_dependencies
4742
4752
  WHERE scope_id=? AND parent_kind='artifact' AND parent_id=?)
@@ -4808,8 +4818,8 @@ var MemoryDependencies = class {
4808
4818
  this.snapshotStamp = void 0;
4809
4819
  }
4810
4820
  }
4811
- observeTimeBoundary(key2) {
4812
- const match = key2.match(/^valid-window:(-?\d+):(-?\d+)$/);
4821
+ observeTimeBoundary(key3) {
4822
+ const match = key3.match(/^valid-window:(-?\d+):(-?\d+)$/);
4813
4823
  if (!match) return;
4814
4824
  const now2 = Date.now();
4815
4825
  for (const boundary of [Number(match[1]), Number(match[2])]) {
@@ -4891,9 +4901,9 @@ var MemoryDependencies = class {
4891
4901
  }
4892
4902
  artifactTimeCurrent(scope, kind, id2, visited = /* @__PURE__ */ new Set(), memo) {
4893
4903
  checkMemoryReadBudget(visited.size);
4894
- const key2 = JSON.stringify([kind, id2]);
4895
- if (visited.has(key2)) return false;
4896
- visited.add(key2);
4904
+ const key3 = JSON.stringify([kind, id2]);
4905
+ if (visited.has(key3)) return false;
4906
+ visited.add(key3);
4897
4907
  try {
4898
4908
  const refs2 = this.refs(scope, kind, id2);
4899
4909
  for (const ref of refs2.filter((ref2) => ref2.parentKind !== "artifact")) {
@@ -4928,7 +4938,7 @@ var MemoryDependencies = class {
4928
4938
  }
4929
4939
  return true;
4930
4940
  } finally {
4931
- visited.delete(key2);
4941
+ visited.delete(key3);
4932
4942
  }
4933
4943
  }
4934
4944
  version(scope, kind, id2) {
@@ -5139,8 +5149,8 @@ var ChangeFeed = class _ChangeFeed {
5139
5149
  * 事件重放失败一次即回死信+skip,不重烧 5 轮预算)。先 UPDATE 后记账:中间崩溃只会
5140
5150
  * 多治一次(幂等无害),反过来会出现"记了账但没治"的永久死锁。 */
5141
5151
  reenqueueGapPrefix(sinkId, head, now2 = Date.now()) {
5142
- const key2 = `${sinkId}:${head.scopeId}:${head.eventSeq}`;
5143
- if (this.healedGaps.has(key2)) return;
5152
+ const key3 = `${sinkId}:${head.scopeId}:${head.eventSeq}`;
5153
+ if (this.healedGaps.has(key3)) return;
5144
5154
  const ledgerPath = this.gapHealLedgerPath;
5145
5155
  let ledger = {};
5146
5156
  if (ledgerPath) {
@@ -5148,8 +5158,8 @@ var ChangeFeed = class _ChangeFeed {
5148
5158
  ledger = JSON.parse(readFileSync4(ledgerPath, "utf8"))?.heals ?? {};
5149
5159
  } catch {
5150
5160
  }
5151
- if (Number.isFinite(ledger[key2])) {
5152
- this.healedGaps.add(key2);
5161
+ if (Number.isFinite(ledger[key3])) {
5162
+ this.healedGaps.add(key3);
5153
5163
  return;
5154
5164
  }
5155
5165
  }
@@ -5163,11 +5173,11 @@ var ChangeFeed = class _ChangeFeed {
5163
5173
  const count = Number(result?.changes ?? 0);
5164
5174
  if (count > 0) console.warn(`[mem7] \u5E8F\u5217\u7F3A\u53E3\u81EA\u6108\uFF1Ahead seq=${head.eventSeq} \u524D ${count} \u6761\u5DF2 ack \u6295\u9012\u884C\u91CD\u7F6E\u5F85\u6295\uFF08\u65B0\u56FE\u5982\u5B9E\u91CD\u653E / \u65E7\u56FE\u5E42\u7B49 duplicate-ack\uFF1B\u6B7B\u4FE1\u884C\u4FDD\u7559 attempts\uFF09`);
5165
5175
  });
5166
- this.healedGaps.add(key2);
5176
+ this.healedGaps.add(key3);
5167
5177
  if (!ledgerPath) return;
5168
5178
  const cutoff = now2 - _ChangeFeed.GAP_HEAL_RETENTION_MS, retained = {};
5169
5179
  for (const [entry, at] of Object.entries(ledger)) if (Number.isFinite(at) && at >= cutoff) retained[entry] = at;
5170
- retained[key2] = now2;
5180
+ retained[key3] = now2;
5171
5181
  const temp = `${ledgerPath}.${randomUUID4()}.tmp`;
5172
5182
  try {
5173
5183
  writeFileSync6(temp, JSON.stringify({ version: 1, heals: retained }));
@@ -5316,7 +5326,7 @@ function validatePredicateValue(predicate, value2) {
5316
5326
  if (!value2 || typeof value2 !== "object" || Array.isArray(value2)) throw new Error("INVALID_FACT_VALUE");
5317
5327
  const object4 = value2;
5318
5328
  const allowed = predicate === "activity.schedule" ? ["frequency", "weekday", "date", "localTime", "timezone", "durationMinutes"] : predicate === "person.residence" ? ["place"] : predicate === "relation.open" ? ["entityId", "label", "direction", "perspectiveEntityId", "relationshipId", "semanticVersion", "body", "contentKind", "temporalScope", "certainty", "observedAsCurrentAt", "attribution", "attributionQuote", "realm", "sensitivity"] : ["entityId"];
5319
- if (Object.keys(object4).some((key2) => !allowed.includes(key2))) throw new Error("INVALID_FACT_VALUE: unknown field");
5329
+ if (Object.keys(object4).some((key3) => !allowed.includes(key3))) throw new Error("INVALID_FACT_VALUE: unknown field");
5320
5330
  if (predicate === "activity.schedule") {
5321
5331
  const schedule = object4;
5322
5332
  if (!["weekly", "once"].includes(schedule.frequency) || !/^([01]\d|2[0-3]):[0-5]\d$/.test(schedule.localTime) || !Number.isInteger(schedule.durationMinutes) || schedule.durationMinutes <= 0 || schedule.durationMinutes > 1440) throw new Error("INVALID_SCHEDULE");
@@ -5485,8 +5495,8 @@ var SourceStore = class {
5485
5495
  ).all(scopeId(scope), `%${word.replace(/[!%_]/g, (character) => "!" + character)}%`, limit);
5486
5496
  return rows.map((row) => this.source(row));
5487
5497
  }
5488
- snapshotRead(key2, load) {
5489
- return this.snapshotReads ? this.snapshotReads.read(JSON.stringify(key2), load) : load();
5498
+ snapshotRead(key3, load) {
5499
+ return this.snapshotReads ? this.snapshotReads.read(JSON.stringify(key3), load) : load();
5490
5500
  }
5491
5501
  receive(input, options = {}) {
5492
5502
  const id2 = scopeId(input.scope);
@@ -5667,8 +5677,8 @@ var SourceStore = class {
5667
5677
  const result = { applied: 0, needsReview: 0, failed: 0, received: 0 };
5668
5678
  const rows = cutoff ? historicalRows(this.db, scope, "source", cutoff).map((row) => ({ state: row.state, count: 1 })) : this.db.prepare("SELECT interpretation_status state,COUNT(*) count FROM memory_sources WHERE scope_id=? GROUP BY interpretation_status").all(scopeId(scope));
5669
5679
  for (const row of rows) {
5670
- const key2 = row.state === "needs_review" ? "needsReview" : row.state;
5671
- if (Object.hasOwn(result, key2)) result[key2] += Number(row.count);
5680
+ const key3 = row.state === "needs_review" ? "needsReview" : row.state;
5681
+ if (Object.hasOwn(result, key3)) result[key3] += Number(row.count);
5672
5682
  }
5673
5683
  return result;
5674
5684
  }
@@ -6371,9 +6381,9 @@ var HostTurnStore = class {
6371
6381
  }
6372
6382
  }
6373
6383
  recordCompleted(id2, sourceId, sourceVersion, now2) {
6374
- const key2 = JSON.stringify(["host.turn.completed", id2, sourceId]);
6384
+ const key3 = JSON.stringify(["host.turn.completed", id2, sourceId]);
6375
6385
  this.db.prepare(`INSERT OR IGNORE INTO ome_jobs(kind,payload,status,next_run_at,created_at,job_key,scope_id,completed_at)
6376
- VALUES ('host.turn.completed',?,'done',?,?,?,?,?)`).run(JSON.stringify({ scopeId: id2, sourceId, sourceVersion }), now2, now2, key2, id2, now2);
6386
+ VALUES ('host.turn.completed',?,'done',?,?,?,?,?)`).run(JSON.stringify({ scopeId: id2, sourceId, sourceVersion }), now2, now2, key3, id2, now2);
6377
6387
  }
6378
6388
  };
6379
6389
 
@@ -6802,6 +6812,24 @@ function vectorLogicalId(db, kind, physicalId) {
6802
6812
  init_read_guard();
6803
6813
  init_timing();
6804
6814
  init_runtime_authority();
6815
+
6816
+ // src/mem7/core/lance-cache.ts
6817
+ var LANCE_INDEX_CACHE_BYTES = 256 * 1024 * 1024;
6818
+ var LANCE_METADATA_CACHE_BYTES = 64 * 1024 * 1024;
6819
+ var key2 = Symbol.for("engine7.mem7.lanceCacheSessions");
6820
+ var globals = globalThis;
6821
+ var sessions = globals[key2] ??= /* @__PURE__ */ new WeakMap();
6822
+ function memoryLanceSession(lance) {
6823
+ if (typeof lance.Session !== "function") return void 0;
6824
+ let session = sessions.get(lance);
6825
+ if (!session) {
6826
+ session = new lance.Session(BigInt(LANCE_INDEX_CACHE_BYTES), BigInt(LANCE_METADATA_CACHE_BYTES));
6827
+ sessions.set(lance, session);
6828
+ }
6829
+ return session;
6830
+ }
6831
+
6832
+ // src/mem7/core/vector-store.ts
6805
6833
  var isIntelMac = process.platform === "darwin" && process.arch === "x64";
6806
6834
  function lanceSpecifierFor(platform, arch) {
6807
6835
  return platform === "darwin" && arch === "x64" ? "@engine7/lancedb-intel" : "@lancedb/lancedb";
@@ -7021,7 +7049,7 @@ var Mem7VectorStore = class {
7021
7049
  /** Reuse expensive dependency walks, but bind each verdict to SQL, time and the actual indexed body. */
7022
7050
  cachedRowVisible(ledger, kind, row, dependencies2) {
7023
7051
  if (!dependencies2) return vectorRowVisible(ledger, kind, row);
7024
- const key2 = kind + ":" + String(row.id);
7052
+ const key3 = kind + ":" + String(row.id);
7025
7053
  let signature2;
7026
7054
  try {
7027
7055
  signature2 = JSON.stringify([
@@ -7045,11 +7073,11 @@ var Mem7VectorStore = class {
7045
7073
  this.visibleCacheVersion = version;
7046
7074
  this.visibleCache.clear();
7047
7075
  }
7048
- const cached = this.visibleCache.get(key2);
7076
+ const cached = this.visibleCache.get(key3);
7049
7077
  if (cached?.signature === signature2) return cached.verdict;
7050
7078
  const verdict = vectorRowVisible(ledger, kind, row, dependencies2);
7051
7079
  if (dependencies2.cacheRevision() !== version) return false;
7052
- this.visibleCache.set(key2, { signature: signature2, verdict });
7080
+ this.visibleCache.set(key3, { signature: signature2, verdict });
7053
7081
  return verdict;
7054
7082
  }
7055
7083
  visibleCache = /* @__PURE__ */ new Map();
@@ -7070,7 +7098,8 @@ var Mem7VectorStore = class {
7070
7098
  assertRuntimeAuthority(this.stateDir, "WRITE");
7071
7099
  mkdirSync6(this.dir, { recursive: true });
7072
7100
  }
7073
- this.db = await lance.connect(this.dir);
7101
+ const session = memoryLanceSession(lance);
7102
+ this.db = await lance.connect(this.dir, session ? { session } : void 0);
7074
7103
  }
7075
7104
  return this.db;
7076
7105
  }
@@ -7547,11 +7576,11 @@ var Mem7VectorStore = class {
7547
7576
  const rrf = /* @__PURE__ */ new Map();
7548
7577
  const add = (list) => {
7549
7578
  list.forEach((h, i) => {
7550
- const key2 = h.text.replace(/\s+/g, "");
7579
+ const key3 = h.text.replace(/\s+/g, "");
7551
7580
  const contrib = 1 / (RRF_K + i + 1);
7552
- const cur = rrf.get(key2);
7581
+ const cur = rrf.get(key3);
7553
7582
  if (cur) cur.score += contrib;
7554
- else rrf.set(key2, { hit: h, score: contrib });
7583
+ else rrf.set(key3, { hit: h, score: contrib });
7555
7584
  });
7556
7585
  };
7557
7586
  add(dense);
@@ -7636,16 +7665,16 @@ var SnapshotReads = class {
7636
7665
  this.changes = -1;
7637
7666
  }
7638
7667
  }
7639
- read(key2, load) {
7668
+ read(key3, load) {
7640
7669
  if (!this.values || !this.db.isTransaction) return load();
7641
7670
  const changes = this.changesRead.get().n;
7642
7671
  if (changes !== this.changes) {
7643
7672
  this.values.clear();
7644
7673
  this.changes = changes;
7645
7674
  }
7646
- if (this.values.has(key2)) return this.values.get(key2);
7675
+ if (this.values.has(key3)) return this.values.get(key3);
7647
7676
  const value2 = load();
7648
- if (this.values.size < 8192) this.values.set(key2, value2);
7677
+ if (this.values.size < 8192) this.values.set(key3, value2);
7649
7678
  return value2;
7650
7679
  }
7651
7680
  };
@@ -7810,9 +7839,9 @@ var EntityStore = class {
7810
7839
  aliasEvidence(scope, entityId, cutoff) {
7811
7840
  const seen = /* @__PURE__ */ new Set();
7812
7841
  return (cutoff ? historicalRows(this.db, scope, "alias", cutoff) : this.db.prepare("SELECT entity_id entityId,source_id sourceId,alias FROM entity_aliases WHERE scope_id=? AND entity_id=?").all(scopeId(scope), entityId)).filter((alias) => {
7813
- const key2 = normalizeAlias(alias.alias);
7814
- if (seen.has(key2) || alias.entityId !== entityId || !this.sources.isCurrent(scope, alias.sourceId, cutoff) || !this.aliasIsName(scope, entityId, alias.sourceId, alias.alias, cutoff) || this.aliasReadable && !this.aliasReadable(scope, entityId, alias.sourceId, alias.alias, cutoff)) return false;
7815
- seen.add(key2);
7842
+ const key3 = normalizeAlias(alias.alias);
7843
+ if (seen.has(key3) || alias.entityId !== entityId || !this.sources.isCurrent(scope, alias.sourceId, cutoff) || !this.aliasIsName(scope, entityId, alias.sourceId, alias.alias, cutoff) || this.aliasReadable && !this.aliasReadable(scope, entityId, alias.sourceId, alias.alias, cutoff)) return false;
7844
+ seen.add(key3);
7816
7845
  return true;
7817
7846
  }).map((alias) => ({ alias: alias.alias, sourceId: alias.sourceId, sourceVersion: this.sources.get(scope, alias.sourceId, cutoff).sourceVersion }));
7818
7847
  }
@@ -8099,6 +8128,15 @@ function classifyFactVersions(versions, predicate, time) {
8099
8128
  }
8100
8129
  var hash3 = (value2) => createHash15("sha256").update(canonicalJson(value2)).digest("hex");
8101
8130
  var makeSlotId = (subjectId, predicate, context) => `slot_${hash3([subjectId, predicate, context]).slice(0, 32)}`;
8131
+ var CLOSE_VALIDITY = '{"validFrom":null,"validTo":"\u7ED3\u675F\u65F6\u523B","precision":"exact"}';
8132
+ var occurrences = (text2, quote4) => {
8133
+ let count = 0;
8134
+ for (let at = text2.indexOf(quote4); quote4 && at >= 0; at = text2.indexOf(quote4, at + 1)) count++;
8135
+ return count;
8136
+ };
8137
+ var CHANGE_KINDS = ["assert", "reinforce", "state_change", "correction", "exception", "dispute", "retract", "close"];
8138
+ var CLAIM_KINDS = ["user_statement", "tool_observation", "reported_statement", "inference", "agent_statement"];
8139
+ var normalizeChange = (proposal) => !["close", "retract"].includes(proposal.changeKind) || !proposal.validity || proposal.validity.validFrom !== void 0 ? proposal : { ...proposal, validity: { ...proposal.validity, validFrom: null } };
8102
8140
  var FactStore = class {
8103
8141
  constructor(db, entities, transaction, readTransaction = transaction) {
8104
8142
  this.db = db;
@@ -8265,6 +8303,8 @@ var FactStore = class {
8265
8303
  applyChange(scope, proposal, expectedSlotRevision, requestKey, batch) {
8266
8304
  if (!requestKey || !Number.isSafeInteger(expectedSlotRevision) || expectedSlotRevision < 0) throw new Error("INVALID_FACT_REQUEST");
8267
8305
  const id2 = scopeId(scope);
8306
+ const located = this.locateEvidence(id2, normalizeChange(proposal));
8307
+ proposal = located.proposal;
8268
8308
  const requestHash = hash3([proposal, expectedSlotRevision]);
8269
8309
  const prior = this.db.prepare("SELECT request_hash,result_json FROM fact_changes WHERE scope_id=? AND request_key=?").get(id2, requestKey);
8270
8310
  if (prior) {
@@ -8273,21 +8313,22 @@ var FactStore = class {
8273
8313
  }
8274
8314
  this.validate(scope, proposal);
8275
8315
  const slot = this.slot(scope, proposal.subjectId, proposal.predicate, proposal.contextKey);
8276
- if (slot.revision !== expectedSlotRevision) throw new Error(`STALE_VERSION: expected slot ${expectedSlotRevision}, current ${slot.revision}`);
8316
+ if (slot.revision !== expectedSlotRevision) throw new Error(`STALE_VERSION: expected slot ${expectedSlotRevision}, current ${slot.revision} \u2014 ` + (slot.revision > expectedSlotRevision ? "\u8BE5\u69FD\u5728\u4F60\u8BFB\u53D6\u4E4B\u540E\u6709\u65B0\u7684\u4FEE\u6539" : "\u8FD9\u4E2A\u69FD\u7684\u5199\u5165\u6B21\u6570\u5C11\u4E8E\u4F60\u586B\u7684\u7248\u672C\uFF0C\u591A\u534A\u662F proposal \u6307\u5230\u4E86\u522B\u7684\u69FD") + "\uFF1Bexpected_slot_revision \u586B\u91CD\u65B0\u8BFB\u53D6\u5230\u7684 basis.slotRevision" + (slot.revision < expectedSlotRevision ? `\u3002\u672C\u6B21\u843D\u5230 subjectId=${proposal.subjectId} predicate=${proposal.predicate} contextKey=${proposal.contextKey}\uFF08\u4E09\u8005\u987B\u4E0E\u65AD\u8A00\u4E00\u81F4\uFF1Brelation.open \u505A state_change/correction \u65F6 value \u5E26\u4E0A\u539F\u8BB0\u5F55\u7684 relationshipId\uFF09` : ""));
8277
8317
  this.db.prepare("INSERT OR IGNORE INTO fact_slots(scope_id,slot_id,subject_id,predicate,context_key,cardinality) VALUES (?,?,?,?,?,?)").run(id2, slot.slotId, proposal.subjectId, proposal.predicate, proposal.contextKey, predicates[proposal.predicate].cardinality);
8278
8318
  const before = this.current(id2, slot.slotId);
8279
8319
  const targetIds = [...new Set(proposal.targetAssertionIds ?? [])];
8280
8320
  const targets = targetIds.map((targetId) => {
8281
8321
  const target = before.find((fact) => fact.assertionId === targetId);
8282
- if (!target || ["retracted", "deleted"].includes(target.state)) throw new Error("FACT_TARGET_MISMATCH");
8322
+ if (!target || ["retracted", "deleted"].includes(target.state)) throw new Error(`FACT_TARGET_MISMATCH: ${targetId} \u4E0D\u5728\u8FD9\u4E2A\u69FD\uFF08subject+predicate+contextKey\uFF09\u7684\u5F53\u524D\u65AD\u8A00\u91CC\uFF0C\u6216\u5DF2\u64A4\u56DE/\u5220\u9664\uFF1B\u91CD\u65B0\u8BFB\u53D6\u5E76\u590D\u5236\u4ECD\u6709\u6548\u7684 assertionId`);
8283
8323
  return target;
8284
8324
  });
8285
- if (["reinforce", "state_change", "correction", "retract", "close"].includes(proposal.changeKind) && targets.length === 0) throw new Error("FACT_TARGET_REQUIRED");
8325
+ if (["reinforce", "state_change", "correction", "retract", "close"].includes(proposal.changeKind) && targets.length === 0) throw new Error(`FACT_TARGET_REQUIRED: changeKind=${proposal.changeKind} \u5FC5\u987B\u5E26 targetAssertionIds\uFF08\u88AB\u4FEE\u8BA2\u7684 assertionId\uFF0C\u4ECE\u8BFB\u53D6\u7ED3\u679C\u91CC\u6284\uFF09`);
8286
8326
  if (proposal.changeKind === "reinforce" && targets.length !== 1) throw new Error("REINFORCE_REQUIRES_ONE_TARGET");
8287
8327
  if (["assert", "exception"].includes(proposal.changeKind) && targets.length) throw new Error("UNEXPECTED_FACT_TARGET");
8288
8328
  const validity = proposal.validity ? normalizeValidity(proposal.validity) : void 0;
8289
- if (proposal.changeKind === "state_change" && (validity?.validFrom == null || validity.precision !== "exact")) throw new Error("CHANGE_TIME_REQUIRED");
8290
- if (proposal.changeKind === "close" && (validity?.validTo == null || validity.validFrom !== null || validity.precision === "unknown")) throw new Error("CHANGE_TIME_REQUIRED");
8329
+ const received2 = JSON.stringify({ validFrom: proposal.validity?.validFrom, validTo: proposal.validity?.validTo, precision: proposal.validity?.precision });
8330
+ if (proposal.changeKind === "state_change" && (validity?.validFrom == null || validity.precision !== "exact")) throw new Error(`CHANGE_TIME_REQUIRED: changeKind=state_change \u9700\u8981 validity.validFrom=\u53D8\u5316\u65F6\u523B \u4E14 precision="exact"\uFF08\u65E7\u503C\u5230\u8FD9\u4E00\u523B\u4E3A\u6B62\uFF0C\u65B0 value \u4ECE\u8FD9\u4E00\u523B\u751F\u6548\uFF09\uFF1B\u6536\u5230 ${received2}\u3002\u53EA\u662F\u7ED3\u675F\u5173\u7CFB\uFF1AchangeKind \u6539 "close"`);
8331
+ if (proposal.changeKind === "close" && (validity?.validTo == null || validity.validFrom !== null || validity.precision === "unknown")) throw new Error(`CHANGE_TIME_REQUIRED: changeKind=close \u9700\u8981 validity=${CLOSE_VALIDITY}\uFF08validFrom \u586B null\uFF1Bprecision \u4E5F\u53EF\u7528 observed\uFF09\uFF1B\u6536\u5230 ${received2}`);
8291
8332
  if (proposal.changeKind === "reinforce" && (canonicalJson(proposal.value) !== canonicalJson(targets[0].value) || proposal.claimKind !== targets[0].claimKind)) throw new Error("REINFORCE_VALUE_MISMATCH");
8292
8333
  if (proposal.changeKind === "reinforce" && (validity.validFrom !== targets[0].validFrom || validity.validTo !== targets[0].validTo || proposal.evidence.some((evidence) => evidence.relation !== "supports"))) throw new Error("REINFORCE_INTERVAL_OR_EVIDENCE_MISMATCH");
8293
8334
  const timestamp = batch?.timestamp ?? (/* @__PURE__ */ new Date()).toISOString();
@@ -8303,8 +8344,8 @@ var FactStore = class {
8303
8344
  let state2 = proposal.changeKind === "correction" || proposal.changeKind === "retract" ? "retracted" : "disputed";
8304
8345
  if (proposal.changeKind === "state_change" || proposal.changeKind === "close") {
8305
8346
  const end = proposal.changeKind === "close" ? validity.validTo : validity.validFrom;
8306
- if (target.validFrom !== null && target.validFrom >= end) throw new Error("CHANGE_BEFORE_TARGET_START: use correction");
8307
- if (target.validTo !== null && target.validTo <= end) throw new Error("CHANGE_AFTER_TARGET_END");
8347
+ if (target.validFrom !== null && target.validFrom >= end) throw new Error(`CHANGE_BEFORE_TARGET_START: \u7ED3\u675F\u65F6\u523B ${end} \u4E0D\u665A\u4E8E\u8BE5\u65AD\u8A00\u7684\u5F00\u59CB\u65F6\u95F4 ${target.validFrom}\uFF1B\u4ECE\u4E00\u5F00\u59CB\u5C31\u4E0D\u6210\u7ACB\u7528 changeKind=correction`);
8348
+ if (target.validTo !== null && target.validTo <= end) throw new Error(`CHANGE_AFTER_TARGET_END: \u8BE5\u65AD\u8A00\u5DF2\u4E8E ${target.validTo} \u7ED3\u675F\uFF0C\u65E0\u9700\u518D\u5173\u95ED\uFF08\u6536\u5230 ${end}\uFF09`);
8308
8349
  state2 = target.state;
8309
8350
  nextValidity = { ...target, validTo: end };
8310
8351
  }
@@ -8320,7 +8361,7 @@ var FactStore = class {
8320
8361
  }
8321
8362
  if (!["retract", "close"].includes(proposal.changeKind)) {
8322
8363
  let state2 = proposal.claimKind === "inference" ? "candidate" : proposal.changeKind === "dispute" ? "disputed" : "supported";
8323
- if (state2 === "supported" && !proposal.evidence.some((evidence) => evidence.relation === "supports")) throw new Error("SUPPORTING_EVIDENCE_REQUIRED");
8364
+ if (state2 === "supported" && !proposal.evidence.some((evidence) => evidence.relation === "supports")) throw new Error("SUPPORTING_EVIDENCE_REQUIRED: \u65B0\u767B\u8BB0\u7684\u65AD\u8A00\u81F3\u5C11\u8981\u4E00\u6761 relation=supports \u7684\u539F\u8BDD\u8BC1\u636E");
8324
8365
  const current2 = this.current(id2, slot.slotId);
8325
8366
  if (predicates[proposal.predicate].cardinality === "single" && state2 === "supported" && current2.some((fact) => ["supported", "disputed"].includes(fact.state) && overlaps(fact, validity))) throw new Error("FACT_INTERVAL_CONFLICT: explicit correction/change/dispute required");
8326
8367
  if (state2 === "supported" && validity.validFrom === null && !(proposal.predicate === "relation.open" && proposal.value.observedAsCurrentAt)) state2 = "candidate";
@@ -8352,7 +8393,8 @@ var FactStore = class {
8352
8393
  slotId: slot.slotId,
8353
8394
  slotRevision: slot.revision + Number(changed),
8354
8395
  assertionIds: changedIds,
8355
- outcome: !changed ? "no_change" : after.some((fact) => ["candidate", "disputed"].includes(fact.state) && (!isRelationship(proposal.predicate) || changedIds.includes(fact.assertionId))) ? "needs_review" : "applied"
8396
+ outcome: !changed ? "no_change" : after.some((fact) => ["candidate", "disputed"].includes(fact.state) && (!isRelationship(proposal.predicate) || changedIds.includes(fact.assertionId))) ? "needs_review" : "applied",
8397
+ ...located.aligned.length ? { evidenceAligned: located.aligned } : {}
8356
8398
  };
8357
8399
  this.db.prepare("INSERT INTO fact_changes(scope_id,request_key,request_hash,fact_revision,result_json,proposal_json,before_json,after_json,recorded_at) VALUES (?,?,?,?,?,?,?,?,?)").run(id2, requestKey, requestHash, committedRevision, canonicalJson(result), canonicalJson(proposal), canonicalJson(before), canonicalJson(after), timestamp);
8358
8400
  if (changed) {
@@ -8391,21 +8433,31 @@ var FactStore = class {
8391
8433
  });
8392
8434
  }
8393
8435
  validate(scope, proposal) {
8394
- if (!Object.hasOwn(predicates, proposal.predicate)) throw new Error("UNKNOWN_PREDICATE");
8395
- if (!["assert", "reinforce", "state_change", "correction", "exception", "dispute", "retract", "close"].includes(proposal.changeKind) || !["user_statement", "tool_observation", "reported_statement", "inference", "agent_statement"].includes(proposal.claimKind) || !proposal.contextKey || !proposal.reason || !proposal.evidence.length) throw new Error("INVALID_FACT_PROPOSAL");
8396
- if (proposal.claimKind === "inference" && (proposal.changeKind !== "assert" || proposal.targetAssertionIds?.length)) throw new Error("INFERENCE_CANNOT_REVISE_SUPPORTED_FACT");
8436
+ if (!Object.hasOwn(predicates, proposal.predicate)) throw new Error(`UNKNOWN_PREDICATE: predicate \u53EA\u80FD\u662F ${Object.keys(predicates).join("/")}\uFF08\u6536\u5230 ${String(proposal.predicate)}\uFF09`);
8437
+ const invalid = [
8438
+ !CHANGE_KINDS.includes(proposal.changeKind) && "changeKind",
8439
+ !CLAIM_KINDS.includes(proposal.claimKind) && "claimKind",
8440
+ !proposal.contextKey && "contextKey",
8441
+ !proposal.reason && "reason",
8442
+ (!Array.isArray(proposal.evidence) || !proposal.evidence.length) && "evidence"
8443
+ ].filter(Boolean);
8444
+ if (invalid.length) throw new Error(`INVALID_FACT_PROPOSAL: ${invalid.join("\u3001")} \u7F3A\u5931\u6216\u65E0\u6548 \u2014 changeKind \u53D6 ${CHANGE_KINDS.join("/")}\uFF0CclaimKind \u53D6 ${CLAIM_KINDS.join("/")}\uFF1BcontextKey\u3001reason \u5FC5\u586B\uFF0Cevidence \u81F3\u5C11\u4E00\u6761\u539F\u8BDD\u5F15\u6587`);
8445
+ if (proposal.claimKind === "inference" && (proposal.changeKind !== "assert" || proposal.targetAssertionIds?.length)) throw new Error("INFERENCE_CANNOT_REVISE_SUPPORTED_FACT: inference \u53EA\u80FD\u767B\u8BB0\u65B0\u65AD\u8A00\uFF08changeKind=assert\uFF09\uFF0C\u4E0D\u80FD\u4FEE\u8BA2\u5DF2\u6709\u65AD\u8A00");
8397
8446
  const subject = this.entities.get(scope, proposal.subjectId);
8398
- if (!subject || !matchesEntityKind(subject.kind, predicates[proposal.predicate].subjectKind)) throw new Error("ENTITY_SCOPE_MISMATCH");
8447
+ const subjectKind = predicates[proposal.predicate].subjectKind;
8448
+ if (!subject || !matchesEntityKind(subject.kind, subjectKind)) throw new Error(`ENTITY_SCOPE_MISMATCH: predicate=${proposal.predicate} \u7684\u4E3B\u4F53\u987B\u662F ${typeof subjectKind === "string" ? subjectKind : subjectKind.join("/")}\uFF1B\u6536\u5230 ${proposal.subjectId}`);
8399
8449
  if (proposal.predicate === "relation.family" && !familyRoles.includes(proposal.contextKey)) throw new Error("INVALID_FAMILY_ROLE");
8400
8450
  if (proposal.predicate === "relation.colleague" && (proposal.contextKey !== normalizeOrganization(proposal.contextKey) || proposal.contextKey.length > 200)) throw new Error("INVALID_ORGANIZATION_CONTEXT");
8401
8451
  if (proposal.changeKind === "close") {
8402
- if (!isRelationship(proposal.predicate) || proposal.value !== void 0) throw new Error("INVALID_RELATION_CLOSE");
8403
- if (!proposal.validity) throw new Error("FACT_VALIDITY_REQUIRED");
8452
+ if (!isRelationship(proposal.predicate)) throw new Error(`INVALID_RELATION_CLOSE: close \u53EA\u80FD\u7ED3\u675F\u5173\u7CFB\uFF08relation.family/colleague/open\uFF09\uFF0Cpredicate=${proposal.predicate} \u4E0D\u80FD close\uFF1B\u5176\u5B83\u4E8B\u5B9E\u7528 state_change\uFF08\u5E26\u65B0 value\uFF09\u6216 retract`);
8453
+ if (proposal.value !== void 0) throw new Error("INVALID_RELATION_CLOSE: close \u4E0D\u5E26 value \u2014 \u53BB\u6389 proposal.value\uFF08\u5B83\u53EA\u5199\u7ED3\u675F\u65F6\u523B\uFF0C\u4E0D\u767B\u8BB0\u65B0\u5185\u5BB9\uFF09");
8454
+ if (!proposal.validity) throw new Error(`FACT_VALIDITY_REQUIRED: proposal.validity \u5FC5\u586B \u2014 close \u7528 ${CLOSE_VALIDITY}`);
8404
8455
  normalizeValidity(proposal.validity);
8405
8456
  }
8406
8457
  if (!["retract", "close"].includes(proposal.changeKind)) {
8458
+ if (proposal.value === void 0 || proposal.value === null) throw new Error(isRelationship(proposal.predicate) ? `INVALID_FACT_VALUE: changeKind=${proposal.changeKind} \u5FC5\u987B\u5E26\u65B0 value\uFF08\u65E7\u503C\u5230 validity.validFrom \u4E3A\u6B62\u3001\u65B0 value \u4ECE\u8FD9\u4E00\u523B\u751F\u6548\uFF09\uFF1B\u53EA\u662F\u7ED3\u675F\u5173\u7CFB\uFF1AchangeKind \u6539 "close"\uFF0C\u53BB\u6389 value\uFF0Cvalidity \u7528 ${CLOSE_VALIDITY}` : `INVALID_FACT_VALUE: changeKind=${proposal.changeKind} \u5FC5\u987B\u5E26 value`);
8407
8459
  validatePredicateValue(proposal.predicate, proposal.value);
8408
- if (!proposal.validity) throw new Error("FACT_VALIDITY_REQUIRED");
8460
+ if (!proposal.validity) throw new Error('FACT_VALIDITY_REQUIRED: proposal.validity \u5FC5\u586B \u2014 {"validFrom":\u5F00\u59CB\u65F6\u523B\u6216null,"validTo":\u7ED3\u675F\u65F6\u523B\u6216null,"precision":"exact|observed|unknown"}');
8409
8461
  normalizeValidity(proposal.validity);
8410
8462
  const objectKind = predicates[proposal.predicate].objectKind;
8411
8463
  if (objectKind && !matchesEntityKind(this.entities.get(scope, proposal.value.entityId)?.kind, objectKind)) throw new Error("OBJECT_SCOPE_MISMATCH");
@@ -8420,7 +8472,7 @@ var FactStore = class {
8420
8472
  const targets = (proposal.targetAssertionIds ?? []).map((assertionId) => this.db.prepare(`SELECT a.claim_kind,a.value_json,s.subject_id
8421
8473
  FROM fact_assertions a JOIN fact_slots s ON s.scope_id=a.scope_id AND s.slot_id=a.slot_id WHERE a.scope_id=? AND a.assertion_id=?`).get(scopeId(scope), assertionId));
8422
8474
  const perspective = value2?.relationshipId ? this.entities.get(scope, value2.perspectiveEntityId) : subject;
8423
- if (proposal.predicate !== "relation.open" || perspective?.kind !== "agent" || !["close", "retract"].includes(proposal.changeKind) && value2?.perspectiveEntityId !== perspective.entityId || targets.some((target) => !target || target.claim_kind !== "agent_statement" || target.subject_id !== subject.entityId || JSON.parse(target.value_json).perspectiveEntityId !== perspective.entityId)) throw new Error("INVALID_AGENT_PERSPECTIVE");
8475
+ if (proposal.predicate !== "relation.open" || perspective?.kind !== "agent" || !["close", "retract"].includes(proposal.changeKind) && value2?.perspectiveEntityId !== perspective.entityId || targets.some((target) => target && (target.claim_kind !== "agent_statement" || target.subject_id !== subject.entityId || JSON.parse(target.value_json).perspectiveEntityId !== perspective.entityId))) throw new Error("INVALID_AGENT_PERSPECTIVE: agent_statement \u53EA\u80FD\u7528\u4E8E relation.open\u2014\u2014\u8BC1\u636E\u5FC5\u987B\u662F\u8FD9\u4E2A agent \u81EA\u5DF1\u8BF4\u7684\u8BDD\uFF0C\u76EE\u6807\u65AD\u8A00\u4E5F\u5FC5\u987B\u662F\u540C\u4E00 agent \u767B\u8BB0\u7684 agent_statement");
8424
8476
  }
8425
8477
  if (proposal.predicate === "activity.schedule" && proposal.changeKind !== "retract") {
8426
8478
  const schedule = proposal.value;
@@ -8428,26 +8480,53 @@ var FactStore = class {
8428
8480
  if (proposal.contextKey !== "baseline" && !exception) throw new Error("INVALID_SCHEDULE_CONTEXT");
8429
8481
  if ((exception || proposal.changeKind === "exception") && (!exception || schedule.frequency !== "once")) throw new Error("OCCURRENCE_EXCEPTION_REQUIRED");
8430
8482
  }
8431
- for (const evidence of proposal.evidence) {
8483
+ for (const [index, evidence] of proposal.evidence.entries()) {
8484
+ const path3 = `evidence[${index}]`;
8485
+ if (!evidence || typeof evidence !== "object") throw new Error(`INVALID_EVIDENCE_SPAN: ${path3} \u2014 \u6BCF\u6761\u8BC1\u636E\u987B\u662F\u5BF9\u8C61 {sourceId, quote, relation}`);
8432
8486
  const source = this.db.prepare(`SELECT text,role,origin_class,interpretation_status FROM memory_sources s WHERE scope_id=? AND source_id=?
8433
8487
  AND NOT EXISTS (SELECT 1 FROM memory_sources newer WHERE newer.scope_id=s.scope_id
8434
- AND newer.origin_key=s.origin_key AND newer.source_version>s.source_version)`).get(scopeId(scope), evidence.sourceId);
8435
- if (!source || source.interpretation_status === "deleted" || !Number.isSafeInteger(evidence.start) || !Number.isSafeInteger(evidence.end) || evidence.start < 0 || evidence.end <= evidence.start || evidence.end > source.text.length || source.text.slice(evidence.start, evidence.end) !== evidence.quote || !["supports", "refutes"].includes(evidence.relation)) throw new Error("INVALID_EVIDENCE_SPAN");
8488
+ AND newer.origin_key=s.origin_key AND newer.source_version>s.source_version)`).get(scopeId(scope), evidence.sourceId ?? null);
8489
+ if (!source || source.interpretation_status === "deleted") throw new Error(`INVALID_EVIDENCE_SPAN: ${path3}.sourceId \u2014 \u672C\u6C60\u8BFB\u4E0D\u5230\u8FD9\u6761\u6765\u6E90\uFF08\u4E0D\u5B58\u5728\u3001\u5DF2\u5220\u9664\u6216\u5DF2\u6709\u65B0\u7248\u672C\uFF09\uFF1B\u7528 memory_get({source_id}) \u6838\u5BF9\u5E76\u590D\u5236\u771F\u5B9E\u6765\u6E90 ID`);
8490
+ if (typeof evidence.quote !== "string" || !evidence.quote) throw new Error(`INVALID_EVIDENCE_SPAN: ${path3}.quote \u2014 quote \u5FC5\u586B\uFF0C\u9010\u5B57\u51FA\u81EA\u6765\u6E90\u539F\u6587`);
8491
+ if (!Number.isSafeInteger(evidence.start) || !Number.isSafeInteger(evidence.end) || evidence.start < 0 || evidence.end <= evidence.start || evidence.end > source.text.length || source.text.slice(evidence.start, evidence.end) !== evidence.quote) {
8492
+ const count = occurrences(source.text, evidence.quote);
8493
+ throw new Error(count === 0 ? `INVALID_EVIDENCE_SPAN: ${path3}.quote \u2014 \u5F15\u6587\u5FC5\u987B\u9010\u5B57\u51FA\u81EA\u6765\u6E90\u539F\u6587\uFF08\u539F\u6587\u957F ${source.text.length}\uFF09\uFF1B\u7528 memory_get({source_id}) \u590D\u5236\u539F\u53E5\uFF0C\u4E0D\u8981\u6539\u5199` : `INVALID_EVIDENCE_SPAN: ${path3} \u2014 \u5F15\u6587\u5728\u539F\u6587\u4E2D\u51FA\u73B0 ${count} \u6B21\uFF0C\u8BF7\u7ED9\u51C6\u786E\u7684\u90A3\u4E00\u5904 start/end\uFF08UTF-16 \u4E0B\u6807\uFF0C\u539F\u6587\u957F ${source.text.length}\uFF09`);
8494
+ }
8495
+ if (!["supports", "refutes"].includes(evidence.relation)) throw new Error(`INVALID_EVIDENCE_SPAN: ${path3}.relation \u2014 \u53EA\u80FD\u662F supports\uFF08\u652F\u6301\uFF09\u6216 refutes\uFF08\u53CD\u9A73\uFF09`);
8436
8496
  const relationValue = proposal.value;
8437
8497
  if (proposal.predicate === "relation.open" && relationValue?.attribution === "reported" && (proposal.claimKind !== "reported_statement" || !hasReportedAttribution(source.text, relationValue, this.entities.sourceMentions(scope, evidence.sourceId)))) {
8438
- throw new Error("EVIDENCE_REPORTED_ATTRIBUTION_UNGROUNDED");
8498
+ throw new Error("EVIDENCE_REPORTED_ATTRIBUTION_UNGROUNDED: attribution=reported \u65F6 claimKind \u987B\u4E3A reported_statement\uFF0C\u4E14 attributionQuote \u5FC5\u987B\u662F\u539F\u8BDD\u91CC\u9010\u5B57\u7684\u8F6C\u8FF0\u53E5\uFF08\u5982\u300C\u67D0\u67D0\u8BF4\uFF1A\u300D\uFF09");
8439
8499
  }
8500
+ const roleMismatch = () => new Error(`EVIDENCE_ROLE_MISMATCH: ${path3} \u7684\u4F5C\u8005/\u89D2\u8272\u4E0E claimKind=${proposal.claimKind} \u4E0D\u7B26\uFF08\u6765\u6E90 role=${source.role}, originClass=${source.origin_class}\uFF09 \u2014 \u7528\u6237\u539F\u8BDD\u914D user_statement\u3001\u5DE5\u5177\u7ED3\u679C\u914D tool_observation\u3001\u8F6C\u8FF0\u4ED6\u4EBA\u914D reported_statement\u3001\u4F60\u81EA\u5DF1\u8BF4\u7684\u8BDD\u914D agent_statement\uFF1B\u6362\u5339\u914D\u7684\u6765\u6E90\u6216\u6539 claimKind`);
8440
8501
  if (proposal.claimKind !== "inference") {
8441
- if (proposal.claimKind === "user_statement" && (source.role !== "user" || !["host_user", "client_reported_user"].includes(source.origin_class))) throw new Error("EVIDENCE_ROLE_MISMATCH");
8442
- if (proposal.claimKind === "tool_observation" && (source.role !== "tool" || source.origin_class !== "tool_observation")) throw new Error("EVIDENCE_ROLE_MISMATCH");
8502
+ if (proposal.claimKind === "user_statement" && (source.role !== "user" || !["host_user", "client_reported_user"].includes(source.origin_class))) throw roleMismatch();
8503
+ if (proposal.claimKind === "tool_observation" && (source.role !== "tool" || source.origin_class !== "tool_observation")) throw roleMismatch();
8443
8504
  if (proposal.claimKind === "reported_statement" && (source.role !== "user" || !["third_party_report", "legacy_import"].includes(source.origin_class))) {
8444
8505
  const value2 = proposal.value;
8445
8506
  const attributed = proposal.predicate === "relation.open" && value2?.attribution === "reported" && ["user", "assistant"].includes(source.role) && ["host_user", "client_reported_user", "assistant"].includes(source.origin_class) && hasReportedAttribution(source.text, value2, this.entities.sourceMentions(scope, evidence.sourceId));
8446
- if (!attributed) throw new Error("EVIDENCE_ROLE_MISMATCH");
8507
+ if (!attributed) throw roleMismatch();
8447
8508
  }
8448
- if (proposal.claimKind === "agent_statement" && (source.role !== "assistant" || source.origin_class !== "assistant" || this.entities.speaker(scope, evidence.sourceId)?.entityId !== (proposal.value?.perspectiveEntityId ?? subject.entityId))) throw new Error("EVIDENCE_ROLE_MISMATCH");
8449
- }
8450
- }
8509
+ if (proposal.claimKind === "agent_statement" && (source.role !== "assistant" || source.origin_class !== "assistant" || this.entities.speaker(scope, evidence.sourceId)?.entityId !== (proposal.value?.perspectiveEntityId ?? subject.entityId))) throw roleMismatch();
8510
+ }
8511
+ }
8512
+ }
8513
+ /** 1124:UTF-16 下标不是人能数准的——引文在原文中只出现一次时,start/end 可省略或写错,由引擎对齐;没有或重复的留给 validate() 说明。 */
8514
+ locateEvidence(scope, proposal) {
8515
+ const aligned = [];
8516
+ if (!Array.isArray(proposal.evidence)) return { proposal, aligned };
8517
+ const evidence = proposal.evidence.map((ref, index) => {
8518
+ const text2 = this.db.prepare("SELECT text FROM memory_sources WHERE scope_id=? AND source_id=?").get(scope, ref?.sourceId ?? null)?.text;
8519
+ if (typeof text2 !== "string" || typeof ref?.quote !== "string" || !ref.quote || occurrences(text2, ref.quote) !== 1) return ref;
8520
+ const start = text2.indexOf(ref.quote);
8521
+ if (Number.isSafeInteger(ref.start) && ref.start === start && ref.end === start + ref.quote.length) return ref;
8522
+ aligned.push({
8523
+ index,
8524
+ given: [Number.isSafeInteger(ref.start) ? ref.start : null, Number.isSafeInteger(ref.end) ? ref.end : null],
8525
+ located: [start, start + ref.quote.length]
8526
+ });
8527
+ return { ...ref, start, end: start + ref.quote.length };
8528
+ });
8529
+ return { proposal: { ...proposal, evidence }, aligned };
8451
8530
  }
8452
8531
  current(scope, slotId) {
8453
8532
  return this.versions(scope, slotId);
@@ -8627,10 +8706,10 @@ var RecallSources = class {
8627
8706
  }
8628
8707
  const queue = db.prepare("SELECT target_id FROM memory_tombstones WHERE scope_id=? AND target_kind='source'").all(id2).map((row) => `s:${row.target_id}`);
8629
8708
  for (let index = 0; index < queue.length; index++) {
8630
- const key2 = queue[index];
8631
- if (this.removed.has(key2)) continue;
8632
- this.removed.add(key2);
8633
- queue.push(...dependents.get(key2) ?? []);
8709
+ const key3 = queue[index];
8710
+ if (this.removed.has(key3)) continue;
8711
+ this.removed.add(key3);
8712
+ queue.push(...dependents.get(key3) ?? []);
8634
8713
  }
8635
8714
  }
8636
8715
  sources = /* @__PURE__ */ new Map();
@@ -8792,9 +8871,9 @@ var SocialSourceStore = class {
8792
8871
  ])];
8793
8872
  if (ids.length > 8192 || this.snapshot.relationships.size > 8192) return result;
8794
8873
  const sourceIds = JSON.stringify(ids.sort());
8795
- const relationshipRefs = JSON.stringify([...this.snapshot.relationships.keys()].sort().map((key2) => {
8796
- const split = key2.lastIndexOf(":");
8797
- return [key2.slice(0, split), Number(key2.slice(split + 1))];
8874
+ const relationshipRefs = JSON.stringify([...this.snapshot.relationships.keys()].sort().map((key3) => {
8875
+ const split = key3.lastIndexOf(":");
8876
+ return [key3.slice(0, split), Number(key3.slice(split + 1))];
8798
8877
  }));
8799
8878
  this.snapshotBasis = this.readProvenanceBasis(this.snapshot, sourceIds, relationshipRefs);
8800
8879
  }
@@ -8842,19 +8921,19 @@ var SocialSourceStore = class {
8842
8921
  const sourceChecks = new Map(sources.map((row) => [row.id, JSON.stringify(row)]));
8843
8922
  const relationshipRows = /* @__PURE__ */ new Map();
8844
8923
  for (const row of relationships) {
8845
- const key2 = `${row.id}:${row.version}`;
8846
- const rows = relationshipRows.get(key2) ?? [];
8924
+ const key3 = `${row.id}:${row.version}`;
8925
+ const rows = relationshipRows.get(key3) ?? [];
8847
8926
  rows.push(row);
8848
- relationshipRows.set(key2, rows);
8927
+ relationshipRows.set(key3, rows);
8849
8928
  }
8850
- const relationshipChecks = new Map([...relationshipRows].map(([key2, rows]) => [key2, createHash16("sha256").update(JSON.stringify(rows)).digest("hex")]));
8929
+ const relationshipChecks = new Map([...relationshipRows].map(([key3, rows]) => [key3, createHash16("sha256").update(JSON.stringify(rows)).digest("hex")]));
8851
8930
  checkMemoryReadBudget();
8852
8931
  return { sourceIds, relationshipRefs, digest: digest7, sources: sourceChecks, relationships: relationshipChecks };
8853
8932
  }
8854
8933
  provenanceSnapshot(scope, cutoff) {
8855
8934
  const stamp2 = this.provenanceStamp();
8856
- const key2 = JSON.stringify([scopeId(scope), cutoff ?? null]);
8857
- if (stamp2 !== this.snapshotStamp && this.snapshot?.key === key2 && !cutoff && this.snapshotBasis && this.readSnapshotDepth && this.snapshot.sources.size <= 8192) {
8935
+ const key3 = JSON.stringify([scopeId(scope), cutoff ?? null]);
8936
+ if (stamp2 !== this.snapshotStamp && this.snapshot?.key === key3 && !cutoff && this.snapshotBasis && this.readSnapshotDepth && this.snapshot.sources.size <= 8192) {
8858
8937
  const previous = this.snapshotBasis;
8859
8938
  const next = this.readProvenanceBasis(this.snapshot, previous.sourceIds, previous.relationshipRefs);
8860
8939
  if (next.digest !== previous.digest) {
@@ -8866,17 +8945,17 @@ var SocialSourceStore = class {
8866
8945
  this.snapshot.metadata.delete(id2);
8867
8946
  this.snapshot.currentSources.delete(id2);
8868
8947
  }
8869
- for (const [key3, check] of previous.relationships) {
8870
- if (next.relationships.get(key3) !== check) this.snapshot.relationships.delete(key3);
8948
+ for (const [key4, check] of previous.relationships) {
8949
+ if (next.relationships.get(key4) !== check) this.snapshot.relationships.delete(key4);
8871
8950
  }
8872
8951
  }
8873
8952
  this.snapshotBasis = next;
8874
8953
  this.snapshotStamp = stamp2;
8875
8954
  }
8876
- if (stamp2 !== this.snapshotStamp || this.snapshot?.key !== key2 || this.snapshot.sources.size > 8192 || this.snapshot.currentSources.size > 8192 || this.snapshot.relationships.size > 8192) {
8955
+ if (stamp2 !== this.snapshotStamp || this.snapshot?.key !== key3 || this.snapshot.sources.size > 8192 || this.snapshot.currentSources.size > 8192 || this.snapshot.relationships.size > 8192) {
8877
8956
  this.snapshotStamp = stamp2;
8878
8957
  this.snapshotBasis = void 0;
8879
- this.snapshot = { key: key2, memo: /* @__PURE__ */ new Map(), grounds: /* @__PURE__ */ new Map(), currentSources: /* @__PURE__ */ new Map(), sources: /* @__PURE__ */ new Map(), metadata: /* @__PURE__ */ new Map(), relationships: /* @__PURE__ */ new Map() };
8958
+ this.snapshot = { key: key3, memo: /* @__PURE__ */ new Map(), grounds: /* @__PURE__ */ new Map(), currentSources: /* @__PURE__ */ new Map(), sources: /* @__PURE__ */ new Map(), metadata: /* @__PURE__ */ new Map(), relationships: /* @__PURE__ */ new Map() };
8880
8959
  }
8881
8960
  return this.snapshot;
8882
8961
  }
@@ -9007,21 +9086,21 @@ var SocialSourceStore = class {
9007
9086
  provenanceReferenceRetained(scope, ref, visited, cutoff, snapshot) {
9008
9087
  checkMemoryReadBudget(visited.size);
9009
9088
  if (ref.scopeId !== scopeId(scope) || visited.has(ref.sourceId) || ref.relationshipId && visited.has(`${ref.relationshipId}:${ref.semanticVersion}`)) return false;
9010
- const key2 = `reference:${JSON.stringify([ref.sourceId, ref.sourceVersion, ref.relationshipId, ref.semanticVersion])}`;
9011
- if (snapshot.memo.has(key2)) return snapshot.memo.get(key2);
9089
+ const key3 = `reference:${JSON.stringify([ref.sourceId, ref.sourceVersion, ref.relationshipId, ref.semanticVersion])}`;
9090
+ if (snapshot.memo.has(key3)) return snapshot.memo.get(key3);
9012
9091
  const retained = this.provenanceSource(scope, ref.sourceId, cutoff, snapshot)?.sourceVersion === ref.sourceVersion && this.provenanceRetained(scope, ref.sourceId, visited, cutoff, snapshot) && this.relationshipReferenceRetained(scope, ref, visited, cutoff, snapshot);
9013
- snapshot.memo.set(key2, retained);
9092
+ snapshot.memo.set(key3, retained);
9014
9093
  return retained;
9015
9094
  }
9016
9095
  /** Authored thoughts remain historical memories when a cited source is corrected; deletion still wins. */
9017
9096
  provenanceRetained(scope, sourceId, visited, cutoff, snapshot) {
9018
9097
  checkMemoryReadBudget(visited.size);
9019
9098
  if (visited.has(sourceId)) return false;
9020
- const key2 = `source:${sourceId}`;
9099
+ const key3 = `source:${sourceId}`;
9021
9100
  const { memo } = snapshot;
9022
- if (memo.has(key2)) return memo.get(key2);
9101
+ if (memo.has(key3)) return memo.get(key3);
9023
9102
  if (!this.provenanceSource(scope, sourceId, cutoff, snapshot) || this.tombstoneRead.get(scopeId(scope), sourceId)) {
9024
- memo.set(key2, false);
9103
+ memo.set(key3, false);
9025
9104
  return false;
9026
9105
  }
9027
9106
  if (!snapshot.metadata.has(sourceId)) snapshot.metadata.set(sourceId, this.metadata(scope, sourceId));
@@ -9030,7 +9109,7 @@ var SocialSourceStore = class {
9030
9109
  try {
9031
9110
  const check = (ref) => this.provenanceReferenceRetained(scope, ref, visited, cutoff, snapshot);
9032
9111
  const retained = !metadata4 || metadata4.contextRefs.every(check) && metadata4.basisRefs.every(check);
9033
- memo.set(key2, retained);
9112
+ memo.set(key3, retained);
9034
9113
  return retained;
9035
9114
  } finally {
9036
9115
  visited.delete(sourceId);
@@ -9064,10 +9143,10 @@ var SocialSourceStore = class {
9064
9143
  sourceGroundsCurrent(scope, sourceId, visited, cutoff, snapshot) {
9065
9144
  checkMemoryReadBudget(visited.size);
9066
9145
  if (visited.has(sourceId)) return false;
9067
- const key2 = `source:${sourceId}`;
9068
- if (snapshot.grounds.has(key2)) return snapshot.grounds.get(key2);
9146
+ const key3 = `source:${sourceId}`;
9147
+ if (snapshot.grounds.has(key3)) return snapshot.grounds.get(key3);
9069
9148
  if (!this.sourceCurrent(scope, sourceId, cutoff, snapshot) || !this.provenanceRetained(scope, sourceId, /* @__PURE__ */ new Set(), cutoff, snapshot)) {
9070
- snapshot.grounds.set(key2, false);
9149
+ snapshot.grounds.set(key3, false);
9071
9150
  return false;
9072
9151
  }
9073
9152
  if (!snapshot.metadata.has(sourceId)) snapshot.metadata.set(sourceId, this.metadata(scope, sourceId));
@@ -9075,7 +9154,7 @@ var SocialSourceStore = class {
9075
9154
  visited.add(sourceId);
9076
9155
  try {
9077
9156
  const current2 = !metadata4 || metadata4.basisRefs.every((ref) => this.currentReference(scope, ref, visited, cutoff, snapshot));
9078
- snapshot.grounds.set(key2, current2);
9157
+ snapshot.grounds.set(key3, current2);
9079
9158
  return current2;
9080
9159
  } finally {
9081
9160
  visited.delete(sourceId);
@@ -9085,46 +9164,46 @@ var SocialSourceStore = class {
9085
9164
  checkMemoryReadBudget(visited.size);
9086
9165
  if (ref.scopeId !== scopeId(scope) || this.provenanceSource(scope, ref.sourceId, cutoff, snapshot)?.sourceVersion !== ref.sourceVersion || !this.sourceGroundsCurrent(scope, ref.sourceId, visited, cutoff, snapshot)) return false;
9087
9166
  if (!ref.relationshipId) return true;
9088
- const key2 = `${ref.relationshipId}:${ref.semanticVersion}`;
9089
- if (visited.has(key2)) return false;
9090
- const memoKey = `relationship:${key2}:${ref.purpose === "historical" ? "historical" : "current"}`;
9167
+ const key3 = `${ref.relationshipId}:${ref.semanticVersion}`;
9168
+ if (visited.has(key3)) return false;
9169
+ const memoKey = `relationship:${key3}:${ref.purpose === "historical" ? "historical" : "current"}`;
9091
9170
  if (snapshot.grounds.has(memoKey)) return snapshot.grounds.get(memoKey);
9092
- if (!snapshot.relationships.has(key2)) {
9171
+ if (!snapshot.relationships.has(key3)) {
9093
9172
  this.snapshotBasis = void 0;
9094
- snapshot.relationships.set(key2, this.relationshipReferenceMaterial(scope, ref, cutoff));
9173
+ snapshot.relationships.set(key3, this.relationshipReferenceMaterial(scope, ref, cutoff));
9095
9174
  }
9096
- const material = snapshot.relationships.get(key2);
9175
+ const material = snapshot.relationships.get(key3);
9097
9176
  if (!material || ["deleted", "retracted"].includes(material.state) || ref.purpose !== "historical" && !material.current) return false;
9098
- visited.add(key2);
9177
+ visited.add(key3);
9099
9178
  try {
9100
9179
  const current2 = material.evidenceSourceIds.every((id2) => this.sourceGroundsCurrent(scope, id2, visited, cutoff, snapshot)) && material.basisRefs.every((basis) => this.currentReference(scope, basis, visited, cutoff, snapshot));
9101
9180
  snapshot.grounds.set(memoKey, current2);
9102
9181
  return current2;
9103
9182
  } finally {
9104
- visited.delete(key2);
9183
+ visited.delete(key3);
9105
9184
  }
9106
9185
  }
9107
9186
  relationshipReferenceRetained(scope, ref, visited, cutoff, snapshot = this.provenanceSnapshot(scope, cutoff)) {
9108
9187
  checkMemoryReadBudget(visited.size);
9109
9188
  if (!ref.relationshipId) return true;
9110
- const key2 = `${ref.relationshipId}:${ref.semanticVersion}`;
9111
- if (visited.has(key2)) return false;
9112
- const memoKey = `relationship:${key2}`;
9189
+ const key3 = `${ref.relationshipId}:${ref.semanticVersion}`;
9190
+ if (visited.has(key3)) return false;
9191
+ const memoKey = `relationship:${key3}`;
9113
9192
  const { memo } = snapshot;
9114
9193
  if (memo.has(memoKey)) return memo.get(memoKey);
9115
- if (!snapshot.relationships.has(key2)) {
9194
+ if (!snapshot.relationships.has(key3)) {
9116
9195
  this.snapshotBasis = void 0;
9117
- snapshot.relationships.set(key2, this.relationshipReferenceMaterial(scope, ref, cutoff));
9196
+ snapshot.relationships.set(key3, this.relationshipReferenceMaterial(scope, ref, cutoff));
9118
9197
  }
9119
- const material = snapshot.relationships.get(key2);
9198
+ const material = snapshot.relationships.get(key3);
9120
9199
  if (!material) return false;
9121
- visited.add(key2);
9200
+ visited.add(key3);
9122
9201
  try {
9123
9202
  const retained = material.evidenceSourceIds.every((id2) => this.provenanceRetained(scope, id2, visited, cutoff, snapshot)) && material.basisRefs.every((basis) => this.provenanceReferenceRetained(scope, basis, visited, cutoff, snapshot));
9124
9203
  memo.set(memoKey, retained);
9125
9204
  return retained;
9126
9205
  } finally {
9127
- visited.delete(key2);
9206
+ visited.delete(key3);
9128
9207
  }
9129
9208
  }
9130
9209
  relationshipReferenceMaterial(scope, ref, cutoff) {
@@ -9560,16 +9639,16 @@ var RelationshipStore = class {
9560
9639
  WHERE h.scope_id=? AND h.relationship_id=? AND r.semantic_version=COALESCE(?,h.semantic_version)`).get(...cutoff ? [revision, revision] : [], scopeId(scope), relationshipId, version ?? null);
9561
9640
  if (!row) return null;
9562
9641
  if (historicalVersion) Object.assign(row, historicalVersion);
9563
- const key2 = `${relationshipId}:${row.semantic_version}`;
9564
- if (visited.has(key2)) return null;
9565
- const next = new Set(visited).add(key2);
9642
+ const key3 = `${relationshipId}:${row.semantic_version}`;
9643
+ if (visited.has(key3)) return null;
9644
+ const next = new Set(visited).add(key3);
9566
9645
  const evidence = this.db.prepare("SELECT source_id sourceId,span_start start,span_end end,quote,relation FROM fact_evidence WHERE scope_id=? AND assertion_id=? AND added_revision<=?").all(scopeId(scope), row.assertion_id, revision ?? Number.MAX_SAFE_INTEGER).map((ref) => ({ ...ref }));
9567
9646
  const basisRefs = JSON.parse(row.basis_refs);
9568
9647
  const refs2 = [...evidence.map((ref) => ({ sourceId: ref.sourceId })), ...basisRefs];
9569
9648
  if (recall ? recall.deletedRelationship(relationshipId, row.semantic_version) : evidence.some((ref) => !this.socialSources.retained(scope, ref.sourceId, /* @__PURE__ */ new Set(), cutoff)) || basisRefs.some((ref) => !this.socialSources.referenceRetained(scope, ref, /* @__PURE__ */ new Set(), cutoff))) return null;
9570
9649
  const value2 = JSON.parse(row.value_json);
9571
9650
  const current2 = (historicalHead ?? this.db.prepare("SELECT semantic_version FROM memory_relationship_heads WHERE scope_id=? AND relationship_id=?").get(scopeId(scope), relationshipId)).semantic_version === row.semantic_version;
9572
- const valid = recall ? evidence.length > 0 && evidence.every((ref) => recall.current(ref.sourceId)) && basisRefs.every((ref) => recall.referenceCurrent(ref)) && (cutoff || [void 0, null, "current"].includes(this.db.prepare("SELECT state FROM memory_derivations WHERE scope_id=? AND child_kind='relationship' AND child_id=?").get(scopeId(scope), key2)?.state)) : refs2.every((ref) => this.sources.isCurrent(scope, ref.sourceId, cutoff) && this.socialSources.groundsCurrent(scope, ref.sourceId, /* @__PURE__ */ new Set(), cutoff)) && (cutoff || [void 0, null, "current"].includes(this.dependencies?.state(scope, "relationship", `${relationshipId}:${row.semantic_version}`))) && basisRefs.every((ref) => this.socialSources.referenceCurrent(scope, ref, next, cutoff));
9651
+ const valid = recall ? evidence.length > 0 && evidence.every((ref) => recall.current(ref.sourceId)) && basisRefs.every((ref) => recall.referenceCurrent(ref)) && (cutoff || [void 0, null, "current"].includes(this.db.prepare("SELECT state FROM memory_derivations WHERE scope_id=? AND child_kind='relationship' AND child_id=?").get(scopeId(scope), key3)?.state)) : refs2.every((ref) => this.sources.isCurrent(scope, ref.sourceId, cutoff) && this.socialSources.groundsCurrent(scope, ref.sourceId, /* @__PURE__ */ new Set(), cutoff)) && (cutoff || [void 0, null, "current"].includes(this.dependencies?.state(scope, "relationship", `${relationshipId}:${row.semantic_version}`))) && basisRefs.every((ref) => this.socialSources.referenceCurrent(scope, ref, next, cutoff));
9573
9652
  return {
9574
9653
  relationshipId,
9575
9654
  semanticVersion: row.semantic_version,
@@ -9865,10 +9944,10 @@ var RelationshipCognitionState = class {
9865
9944
  const rows = this.db.prepare(`SELECT * FROM memory_relationship_coverage WHERE state='deferred'${scope ? " AND scope_id=?" : ""} ORDER BY scope_id,group_key,source_id`).all(...scope ? [scopeId(scope)] : []);
9866
9945
  const groups = /* @__PURE__ */ new Map();
9867
9946
  for (const row of rows) {
9868
- const key2 = canonicalJson([row.scope_id, row.perspective_entity_id, row.group_key, row.generation]);
9869
- const group = groups.get(key2) || { scopeId: row.scope_id, perspectiveEntityId: row.perspective_entity_id, groupKey: row.group_key, sourceIds: [], generation: row.generation };
9947
+ const key3 = canonicalJson([row.scope_id, row.perspective_entity_id, row.group_key, row.generation]);
9948
+ const group = groups.get(key3) || { scopeId: row.scope_id, perspectiveEntityId: row.perspective_entity_id, groupKey: row.group_key, sourceIds: [], generation: row.generation };
9870
9949
  if (group.sourceIds.length < 20) group.sourceIds.push(row.source_id);
9871
- groups.set(key2, group);
9950
+ groups.set(key3, group);
9872
9951
  }
9873
9952
  return [...groups.values()];
9874
9953
  }
@@ -9920,12 +9999,12 @@ function checkNotice(db, sources, social, scope, id2, options) {
9920
9999
  return Boolean(source && (version === void 0 || source.sourceVersion === version) && social.readable(memoryScope, sourceId) && social.groundsCurrent(memoryScope, sourceId));
9921
10000
  };
9922
10001
  const relationshipCurrent = (relationshipId, version) => {
9923
- const key2 = `${relationshipId}:${version}`;
10002
+ const key3 = `${relationshipId}:${version}`;
9924
10003
  const row = db.prepare(`SELECT r.*,v.state FROM memory_relationship_versions r JOIN fact_versions v
9925
10004
  ON v.scope_id=r.scope_id AND v.assertion_id=r.assertion_id AND v.system_to_revision IS NULL
9926
10005
  WHERE r.scope_id=? AND r.relationship_id=? AND r.semantic_version=?`).get(scope, relationshipId, version);
9927
10006
  if (!row || ["deleted", "retracted"].includes(row.state)) return false;
9928
- const derivation = db.prepare("SELECT state FROM memory_derivations WHERE scope_id=? AND child_kind='relationship' AND child_id=?").get(scope, key2);
10007
+ const derivation = db.prepare("SELECT state FROM memory_derivations WHERE scope_id=? AND child_kind='relationship' AND child_id=?").get(scope, key3);
9929
10008
  if (derivation && derivation.state !== "current") return false;
9930
10009
  const evidence = db.prepare("SELECT source_id FROM fact_evidence WHERE scope_id=? AND assertion_id=?").all(scope, row.assertion_id);
9931
10010
  return evidence.length > 0 && evidence.every((ref) => sourceCurrent(ref.source_id)) && JSON.parse(row.basis_refs).every((ref) => social.referenceCurrent(memoryScope, ref));
@@ -9984,8 +10063,11 @@ var RelationshipNoticeStore = class {
9984
10063
  }
9985
10064
  get(scope, id2) {
9986
10065
  const row = this.db.prepare("SELECT * FROM memory_relationship_notices WHERE scope_id=? AND notice_id=?").get(scopeId(scope), id2);
9987
- return row ? {
9988
- id: id2,
10066
+ return row ? this.decode(scope, row) : null;
10067
+ }
10068
+ decode(scope, row) {
10069
+ return {
10070
+ id: row.notice_id,
9989
10071
  scope,
9990
10072
  kind: row.kind,
9991
10073
  targetId: row.target_id,
@@ -9995,10 +10077,25 @@ var RelationshipNoticeStore = class {
9995
10077
  state: row.state,
9996
10078
  attempts: row.attempts,
9997
10079
  reason: row.reason
9998
- } : null;
10080
+ };
9999
10081
  }
10000
- list(scope) {
10001
- return this.db.prepare("SELECT notice_id FROM memory_relationship_notices WHERE scope_id=? ORDER BY updated_at,notice_id").all(scopeId(scope)).map((row) => this.get(scope, row.notice_id));
10082
+ list(scope, includeTerminal = true) {
10083
+ return this.db.prepare(`SELECT * FROM memory_relationship_notices WHERE scope_id=?
10084
+ ${includeTerminal ? "" : "AND state NOT IN ('delivered','blocked')"} ORDER BY updated_at,notice_id`).all(scopeId(scope)).map((row) => this.decode(scope, row));
10085
+ }
10086
+ /** Quiet identity work is not notification work. Evidence-backed resolved identities can still be withdrawn. */
10087
+ clarificationCandidates(scope) {
10088
+ const rows = this.db.prepare(`SELECT m.mention_id,m.question,m.mention_kind,m.candidates,m.span_start,m.span_end,s.text
10089
+ FROM memory_person_mentions m JOIN memory_sources s ON s.scope_id=m.scope_id AND s.source_id=m.source_id
10090
+ WHERE m.scope_id=? AND m.question IS NOT NULL AND trim(m.question)<>''
10091
+ AND (m.state='unresolved' OR m.clarification_source_id IS NOT NULL OR m.basis_refs<>'[]')
10092
+ AND (m.mention_kind NOT IN ('description','reference') OR json_array_length(m.candidates)>=2)
10093
+ ORDER BY m.source_id,m.span_start`).all(scopeId(scope));
10094
+ return rows.filter((row) => hasIdentityQuestion(
10095
+ row.question,
10096
+ row.text.slice(row.span_start, row.span_end),
10097
+ { mentionKind: row.mention_kind, candidateEntityIds: JSON.parse(row.candidates) }
10098
+ )).map((row) => row.mention_id);
10002
10099
  }
10003
10100
  finish(scope, id2, state2, reason = "", redact = false) {
10004
10101
  this.db.prepare(`UPDATE memory_relationship_notices SET state=?,reason=?,updated_at=?,message=CASE WHEN ? THEN '[memory unavailable]' ELSE message END WHERE scope_id=? AND notice_id=?`).run(state2, reason, (/* @__PURE__ */ new Date()).toISOString(), Number(redact), scopeId(scope), id2);
@@ -10009,6 +10106,12 @@ var RelationshipNoticeStore = class {
10009
10106
  check(scope, id2, options = {}) {
10010
10107
  return checkRelationshipNotice(this.db, scopeId(scope), id2, options);
10011
10108
  }
10109
+ /** The caller holds one transaction; proofs are discarded before any later batch or write. */
10110
+ checkMany(scope, ids, options = {}) {
10111
+ if (!ids.length) return [];
10112
+ const check = createRelationshipNoticeChecker(this.db);
10113
+ return ids.map((id2) => check(scopeId(scope), id2, options));
10114
+ }
10012
10115
  queue(scope, id2) {
10013
10116
  return Boolean(this.db.prepare("UPDATE memory_relationship_notices SET state='queued',reason='accepted_by_durable_queue',updated_at=? WHERE scope_id=? AND notice_id=? AND state IN ('pending','failed')").run((/* @__PURE__ */ new Date()).toISOString(), scopeId(scope), id2).changes);
10014
10117
  }
@@ -10020,6 +10123,7 @@ var RelationshipNoticeStore = class {
10020
10123
  importantRecords(scope) {
10021
10124
  return this.db.prepare(`SELECT v.relationship_id,v.semantic_version FROM memory_relationship_notice_versions v
10022
10125
  JOIN memory_relationship_cognition_results r ON r.scope_id=v.scope_id AND r.job_id=v.job_id
10126
+ JOIN memory_relationship_heads h ON h.scope_id=v.scope_id AND h.relationship_id=v.relationship_id AND h.semantic_version=v.semantic_version
10023
10127
  WHERE v.scope_id=? AND r.important=1`).all(scopeId(scope)).map((row) => ({ relationshipId: row.relationship_id, semanticVersion: row.semantic_version }));
10024
10128
  }
10025
10129
  recordRoute(scope, sourceId, input) {
@@ -10105,7 +10209,7 @@ function summary(input) {
10105
10209
  try {
10106
10210
  const p = JSON.parse(input);
10107
10211
  if (!p || typeof p !== "object" || Array.isArray(p)) return input;
10108
- const small = Object.fromEntries(Object.entries(p).filter(([key2, value2]) => routing.has(key2) || Buffer.byteLength(JSON.stringify(value2)) <= 1024));
10212
+ const small = Object.fromEntries(Object.entries(p).filter(([key3, value2]) => routing.has(key3) || Buffer.byteLength(JSON.stringify(value2)) <= 1024));
10109
10213
  if (!Object.hasOwn(small, "basis") && p.basis?.scope) small.basis = { scope: p.basis.scope };
10110
10214
  return JSON.stringify(small);
10111
10215
  } catch {
@@ -11561,10 +11665,10 @@ ${e.outcome}
11561
11665
  ];
11562
11666
  if (revalidationKinds.length === 0) return 0;
11563
11667
  for (const scope of this.sources.scopes()) {
11564
- const received = this.sources.interpretationProgress(scope).received;
11668
+ const received2 = this.sources.interpretationProgress(scope).received;
11565
11669
  for (const artifact of this.dependencies.dirty(scope)) {
11566
11670
  if (!revalidationKinds.includes(artifact.kind)) continue;
11567
- if (received > 0 && !(artifact.updatedAt !== null && Date.now() - artifact.updatedAt >= STALE_ARTIFACT_FORCE_MS)) continue;
11671
+ if (received2 > 0 && !(artifact.updatedAt !== null && Date.now() - artifact.updatedAt >= STALE_ARTIFACT_FORCE_MS)) continue;
11568
11672
  const previous = this.db.prepare("SELECT kind,payload FROM ome_jobs WHERE id=?").all(artifactGenerationJobId(this.db, scope, artifact.kind, artifact.id, artifact.version));
11569
11673
  for (const row of previous) {
11570
11674
  const payload = JSON.parse(row.payload);
@@ -12180,7 +12284,7 @@ function recoverLegacySession(db, store, mapping, files, apply = false) {
12180
12284
  return report;
12181
12285
  }
12182
12286
  function recoverLegacyProjections(db, store, input, apply = false) {
12183
- const key2 = scopeId(input.scope);
12287
+ const key3 = scopeId(input.scope);
12184
12288
  const root = realpathSync5(input.root);
12185
12289
  const report = { files: 0, entries: 0, recoverable: 0, alreadyMapped: 0, unavailable: 0, reasons: {}, applied: false };
12186
12290
  const gap = (reason) => {
@@ -12225,7 +12329,7 @@ function recoverLegacyProjections(db, store, input, apply = false) {
12225
12329
  const block = match[0];
12226
12330
  const field = (name) => match[2].match(new RegExp(`^\\*\\*${name}\\*\\*: ([^\\n]*)$`, "m"))?.[1]?.trim();
12227
12331
  const parent = field("parent_id");
12228
- const mapping = db.prepare("SELECT * FROM memory_legacy_cell_maps WHERE cell_id=? AND scope_id=?").get(parent ?? "", key2);
12332
+ const mapping = db.prepare("SELECT * FROM memory_legacy_cell_maps WHERE cell_id=? AND scope_id=?").get(parent ?? "", key3);
12229
12333
  if (!mapping || field("parent_type") !== "memcell" || field("owner_id") !== input.scope.ownerId || field("session_id") !== mapping.session_id) {
12230
12334
  gap("projection_parent_provenance_missing");
12231
12335
  continue;
@@ -12242,7 +12346,7 @@ function recoverLegacyProjections(db, store, input, apply = false) {
12242
12346
  gap("projection_body_missing");
12243
12347
  continue;
12244
12348
  }
12245
- const previous = db.prepare("SELECT * FROM memory_legacy_projection_maps WHERE scope_id=? AND kind=? AND entry_id=?").get(key2, kind, match[1]);
12349
+ const previous = db.prepare("SELECT * FROM memory_legacy_projection_maps WHERE scope_id=? AND kind=? AND entry_id=?").get(key3, kind, match[1]);
12246
12350
  const target = join16(store.mem7RootPath(), path3);
12247
12351
  if (previous) {
12248
12352
  if (previous.source_file_hash !== fileHash || previous.parent_id !== parent || previous.source_relative_path !== path3 || !store.projectionMatches(input.scope, kind, match[1], target, block)) {
@@ -12294,7 +12398,7 @@ function recoverLegacyProjections(db, store, input, apply = false) {
12294
12398
  role: "supports"
12295
12399
  })));
12296
12400
  const digest7 = hash6(candidate.block.trim());
12297
- db.prepare("INSERT INTO memory_projection_entries VALUES (?,?,?,?,?,?)").run(key2, candidate.kind, candidate.id, candidate.relativePath, 1, digest7);
12401
+ db.prepare("INSERT INTO memory_projection_entries VALUES (?,?,?,?,?,?)").run(key3, candidate.kind, candidate.id, candidate.relativePath, 1, digest7);
12298
12402
  store.artifacts.publish(input.scope, {
12299
12403
  kind: candidate.kind,
12300
12404
  id: candidate.id,
@@ -12306,7 +12410,7 @@ function recoverLegacyProjections(db, store, input, apply = false) {
12306
12410
  summary: candidate.summary,
12307
12411
  title: candidate.title
12308
12412
  });
12309
- db.prepare("INSERT INTO memory_legacy_projection_maps VALUES (?,?,?,?,?,?,?)").run(key2, candidate.kind, candidate.id, candidate.fileHash, candidate.relativePath, candidate.parent, 1);
12413
+ db.prepare("INSERT INTO memory_legacy_projection_maps VALUES (?,?,?,?,?,?,?)").run(key3, candidate.kind, candidate.id, candidate.fileHash, candidate.relativePath, candidate.parent, 1);
12310
12414
  }
12311
12415
  });
12312
12416
  report.applied = true;
@@ -12370,9 +12474,9 @@ function installRelationshipHistory(db) {
12370
12474
  FROM memory_scopes s WHERE EXISTS (SELECT 1 FROM memory_relationship_heads h WHERE h.scope_id=s.scope_id)
12371
12475
  OR EXISTS (SELECT 1 FROM memory_person_sources p WHERE p.scope_id=s.scope_id)
12372
12476
  OR EXISTS (SELECT 1 FROM memory_person_mentions m WHERE m.scope_id=s.scope_id)`);
12373
- for (const { table, kind, key: key2, columns: columns2 } of tables2) {
12477
+ for (const { table, kind, key: key3, columns: columns2 } of tables2) {
12374
12478
  const payload = (prefix2) => `json_object(${columns2.map((column) => `'${column}',${prefix2}${column}`).join(",")})`;
12375
- const target = (prefix2) => key2.startsWith("json_array") ? `json_array(${key2.slice(11, -1).split(",").map((column) => `${prefix2}${column}`).join(",")})` : `${prefix2}${key2}`;
12479
+ const target = (prefix2) => key3.startsWith("json_array") ? `json_array(${key3.slice(11, -1).split(",").map((column) => `${prefix2}${column}`).join(",")})` : `${prefix2}${key3}`;
12376
12480
  db.exec(`INSERT INTO memory_knowledge_history(scope_id,target_kind,target_id,entity_revision,fact_revision,context_revision,recorded_at,payload_json)
12377
12481
  SELECT t.scope_id,'${kind}',${target("t.")},s.entity_revision,s.fact_revision,s.context_revision,strftime('%Y-%m-%dT%H:%M:%fZ','now'),${payload("t.")}
12378
12482
  FROM ${table} t JOIN memory_scopes s ON s.scope_id=t.scope_id`);
@@ -12944,11 +13048,11 @@ var EVENT_BYTES = 16 * 1024 * 1024;
12944
13048
  function sessionLimits(options) {
12945
13049
  if (!options || typeof options !== "object" || Array.isArray(options)) throw new Error("REPLICATION_INVALID_LIMIT");
12946
13050
  const limits2 = {};
12947
- for (const key2 of ["maximumPendingBytes", "maximumCommitBytes"]) {
12948
- const value2 = options[key2];
13051
+ for (const key3 of ["maximumPendingBytes", "maximumCommitBytes"]) {
13052
+ const value2 = options[key3];
12949
13053
  if (value2 !== void 0) {
12950
13054
  if (!Number.isSafeInteger(value2) || value2 < 1 || value2 > 256 * 1024 * 1024) throw new Error("REPLICATION_INVALID_LIMIT");
12951
- limits2[key2] = value2;
13055
+ limits2[key3] = value2;
12952
13056
  }
12953
13057
  }
12954
13058
  return limits2;
@@ -13025,16 +13129,16 @@ function* frames(bytes, kind) {
13025
13129
  }
13026
13130
  if (offset !== bytes.length) throw new Error("SESSION_EVENT_TORN_BASELINE");
13027
13131
  }
13028
- function rememberEvent(db, key2, body, kind) {
13132
+ function rememberEvent(db, key3, body, kind) {
13029
13133
  const id2 = eventId(body, kind), digest7 = sha2(body);
13030
- const old = db.prepare("SELECT sequence,digest,body FROM session_events WHERE session_key=? AND event_id=?").get(key2, id2);
13134
+ const old = db.prepare("SELECT sequence,digest,body FROM session_events WHERE session_key=? AND event_id=?").get(key3, id2);
13031
13135
  if (old) {
13032
13136
  if (old.digest !== digest7 || !(old.body instanceof Uint8Array) || !body.equals(Buffer.from(old.body))) throw new Error("SESSION_EVENT_ID_CONFLICT");
13033
13137
  return Number(old.sequence);
13034
13138
  }
13035
13139
  const sequence = Number(db.prepare("SELECT COALESCE(max(sequence),0)+1 n FROM session_events").get().n);
13036
13140
  if (!Number.isSafeInteger(sequence) || sequence < 1) throw new Error("SESSION_EVENT_SEQUENCE_EXHAUSTED");
13037
- db.prepare("INSERT INTO session_events VALUES(?,?,?,?,?)").run(sequence, key2, id2, body, digest7);
13141
+ db.prepare("INSERT INTO session_events VALUES(?,?,?,?,?)").run(sequence, key3, id2, body, digest7);
13038
13142
  return sequence;
13039
13143
  }
13040
13144
  function nextRevision(db) {
@@ -13403,7 +13507,7 @@ async function cleanRecoveryDeletionRuntimeCopies(options) {
13403
13507
  if (!source) throw new Error("RECOVERY_OVERLAY_SOURCE_PROVENANCE");
13404
13508
  originals.set(JSON.stringify([row.scope_id, row.origin_key, row.source_version]), source);
13405
13509
  }
13406
- const deletedOrigins = new Set([...originals].filter(([, row]) => blocked2(String(row.scope_id), String(row.source_id))).map(([key2]) => JSON.stringify(JSON.parse(key2).slice(0, 2))));
13510
+ const deletedOrigins = new Set([...originals].filter(([, row]) => blocked2(String(row.scope_id), String(row.source_id))).map(([key3]) => JSON.stringify(JSON.parse(key3).slice(0, 2))));
13407
13511
  const parse = (text2, limit = 16 * 1024 * 1024) => {
13408
13512
  if (Buffer.byteLength(text2) > limit) throw new Error("RECOVERY_DEPENDENCY_BUDGET");
13409
13513
  try {
@@ -13576,20 +13680,20 @@ async function cleanRecoveryDeletionRuntimeCopies(options) {
13576
13680
  if (++scanned > 1e6 || bytes > 64 * 1024 * 1024) throw new Error("RECOVERY_DEPENDENCY_BUDGET");
13577
13681
  if (!identities.has(JSON.stringify([record.scope_id, record.source_id]))) throw new Error("RECOVERY_OVERLAY_SESSION_PROVENANCE");
13578
13682
  if (!blocked2(String(record.scope_id), String(record.source_id))) continue;
13579
- const key2 = JSON.stringify([record.session_file_id, record.session_id, record.record_id]), group = legacyRecords.get(key2) ?? [];
13683
+ const key3 = JSON.stringify([record.session_file_id, record.session_id, record.record_id]), group = legacyRecords.get(key3) ?? [];
13580
13684
  group.push(record);
13581
- legacyRecords.set(key2, group);
13685
+ legacyRecords.set(key3, group);
13582
13686
  }
13583
13687
  const headers = /* @__PURE__ */ new Map();
13584
13688
  for (const row of db.prepare("SELECT session_key,body,digest FROM session_events WHERE event_id LIKE 'header:%'").iterate()) {
13585
13689
  if (!(row.body instanceof Uint8Array) || sha3(row.body) !== row.digest) throw new Error("SESSION_EVENT_CORRUPT");
13586
13690
  bytes += row.body.byteLength;
13587
13691
  if (++scanned > 1e6 || bytes > 64 * 1024 * 1024) throw new Error("RECOVERY_DEPENDENCY_BUDGET");
13588
- const header = parse(Buffer.from(row.body).toString()), key2 = String(row.session_key);
13692
+ const header = parse(Buffer.from(row.body).toString()), key3 = String(row.session_key);
13589
13693
  if (header.type === "session" && typeof header.id === "string" && typeof header.engineSessionId === "string") {
13590
- const group = headers.get(key2) ?? [];
13694
+ const group = headers.get(key3) ?? [];
13591
13695
  group.push({ id: header.id, sessionId: header.engineSessionId });
13592
- headers.set(key2, group);
13696
+ headers.set(key3, group);
13593
13697
  }
13594
13698
  }
13595
13699
  const updates = [];
@@ -13600,7 +13704,7 @@ async function cleanRecoveryDeletionRuntimeCopies(options) {
13600
13704
  if (sha3(row.body) !== row.digest) throw new Error("SESSION_EVENT_CORRUPT");
13601
13705
  if (String(row.event_id).startsWith("blob:")) continue;
13602
13706
  const event = parse(Buffer.from(row.body).toString("utf8")), message = event?.message;
13603
- const deletedEvent = () => Object.fromEntries(["id", "uuid", "parentId", "parentUuid", "timestamp"].filter((key2) => Object.hasOwn(event, key2)).map((key2) => [key2, event[key2]]));
13707
+ const deletedEvent = () => Object.fromEntries(["id", "uuid", "parentId", "parentUuid", "timestamp"].filter((key3) => Object.hasOwn(event, key3)).map((key3) => [key3, event[key3]]));
13604
13708
  if (object3(message)) {
13605
13709
  if (typeof message.memoryOriginKey === "string" && message.memoryScope !== void 0) {
13606
13710
  const scope = scopeKey(message.memoryScope), version = message.memorySourceVersion ?? (message.role === "assistant" ? 1 : void 0);
@@ -13705,8 +13809,8 @@ async function cleanRecoveryDeletionRuntimeCopies(options) {
13705
13809
  // src/continuity/recovery-deletion-overlay.ts
13706
13810
  var same2 = (a, b) => JSON.stringify(a) === JSON.stringify(b);
13707
13811
  var sha4 = (value2) => createHash26("sha256").update(value2).digest("hex");
13708
- var evidenceRow = (row) => Object.fromEntries(Object.entries(row).map(([key2, value2]) => [
13709
- key2,
13812
+ var evidenceRow = (row) => Object.fromEntries(Object.entries(row).map(([key3, value2]) => [
13813
+ key3,
13710
13814
  value2 === null ? ["null"] : typeof value2 === "string" ? ["text", value2] : typeof value2 === "bigint" ? ["integer", String(value2)] : typeof value2 === "number" ? ["real", String(value2)] : ["blob", Buffer.from(value2).toString("base64")]
13711
13815
  ]));
13712
13816
  var applyRecoveryDeletionRuntimeCopies = (options) => deletionOverlay(options, true);
@@ -14276,7 +14380,7 @@ function supervisedRuntimeEnvironment(config, parent, environmentNames = []) {
14276
14380
  if (match) add(match[1] ?? match[2]);
14277
14381
  } else if (value2 && typeof value2 === "object") for (const child of Object.values(value2)) references(child, depth + 1);
14278
14382
  };
14279
- for (const [key2, value2] of Object.entries(config)) if (key2 !== "channels") references(value2);
14383
+ for (const [key3, value2] of Object.entries(config)) if (key3 !== "channels") references(value2);
14280
14384
  for (const name of environmentNames) add(name);
14281
14385
  const env = {};
14282
14386
  for (const [name, value2] of Object.entries(parent)) if (value2 !== void 0 && (systemEnvironment.has(name.toUpperCase()) || /^LC_[A-Z_]+$/.test(name))) env[name] = value2;
@@ -14879,7 +14983,7 @@ async function restoreRuntimePublication(options) {
14879
14983
  if (!status.published || !status.dataReady) throw new Error("PUBLICATION_NOT_READY");
14880
14984
  if (options.sequence !== void 0 && options.sequence !== status.published.sequence) throw new Error("PUBLICATION_STALE_PUBLICATION");
14881
14985
  const manifest = await receiver.manifest(status.published.sequence), destination = resolve17(options.destination);
14882
- const sessions = [];
14986
+ const sessions2 = [];
14883
14987
  for (const kind of manifest.profile.trees.filter((tree) => tree.kind === "session")) {
14884
14988
  const tree = manifest.trees.find((tree2) => tree2.id === kind.id);
14885
14989
  if (tree.directories.length || tree.files.length !== 1 || tree.files[0].path !== "manifest.json") throw new Error("RUNTIME_INCOMPLETE_SESSIONS");
@@ -14892,7 +14996,7 @@ async function restoreRuntimePublication(options) {
14892
14996
  epoch: manifest.profile.epoch
14893
14997
  });
14894
14998
  if (metadata4.format !== "engine7-session-events-publication-v1" || !database || JSON.stringify(metadata4.binding) !== JSON.stringify(binding) || JSON.stringify(metadata4.head) !== JSON.stringify(database.head)) throw new Error("RUNTIME_INCOMPLETE_SESSIONS");
14895
- sessions.push({ treeId: tree.id, databaseId: database.databaseId, head: database.head, binding });
14999
+ sessions2.push({ treeId: tree.id, databaseId: database.databaseId, head: database.head, binding });
14896
15000
  }
14897
15001
  await restorePublication({ ...options, destination, deferReceipt: true });
14898
15002
  const lance = [], sessionStates = [];
@@ -14906,7 +15010,7 @@ async function restoreRuntimePublication(options) {
14906
15010
  await syncDirectory(join26(destination, "lance"));
14907
15011
  lance.push({ treeId: tree.id, directory: `lance/${tree.id}` });
14908
15012
  }
14909
- for (const session of sessions) {
15013
+ for (const session of sessions2) {
14910
15014
  const directory2 = join26(destination, "sessions", session.treeId), db = new DatabaseSync17(join26(destination, "databases", session.databaseId + ".sqlite"), { readOnly: true });
14911
15015
  try {
14912
15016
  const head = db.prepare("SELECT head,digest FROM e7_replication_control WHERE role='replica'").get();
@@ -14961,7 +15065,7 @@ function canonical2(value2) {
14961
15065
  if (typeof value2 === "number" && Number.isFinite(value2)) return value2;
14962
15066
  if (Array.isArray(value2)) return value2.map(canonical2);
14963
15067
  if (value2 && typeof value2 === "object" && Object.getPrototypeOf(value2) === Object.prototype)
14964
- return Object.fromEntries(Object.keys(value2).sort().map((key2) => [key2, canonical2(value2[key2])]));
15068
+ return Object.fromEntries(Object.keys(value2).sort().map((key3) => [key3, canonical2(value2[key3])]));
14965
15069
  throw new Error("TREE_SOURCE_INVALID_ORIGIN");
14966
15070
  }
14967
15071
  var sha7 = (body) => createHash30("sha256").update(body).digest("hex");
@@ -15967,12 +16071,12 @@ async function fetchTravelKey(options) {
15967
16071
  const wanted = options.identity;
15968
16072
  if (value2?.protocolVersion !== 1 || !value2.identity || ["tenantId", "companionId", "seatId", "keyId", "generation"].some((k) => value2.identity[k] !== wanted[k]) || !Number.isSafeInteger(value2.deletionWatermark) || value2.deletionWatermark < options.minimumDeletionWatermark || typeof value2.key !== "string" || !/^[A-Za-z0-9+/]{43}=$/.test(value2.key))
15969
16073
  throw new Error("KEY_SERVICE_INVALID_RESPONSE");
15970
- const key2 = Buffer.from(value2.key, "base64");
15971
- if (key2.length !== 32 || key2.toString("base64") !== value2.key) {
15972
- key2.fill(0);
16074
+ const key3 = Buffer.from(value2.key, "base64");
16075
+ if (key3.length !== 32 || key3.toString("base64") !== value2.key) {
16076
+ key3.fill(0);
15973
16077
  throw new Error("KEY_SERVICE_INVALID_RESPONSE");
15974
16078
  }
15975
- return { key: key2, deletionWatermark: value2.deletionWatermark };
16079
+ return { key: key3, deletionWatermark: value2.deletionWatermark };
15976
16080
  }
15977
16081
 
15978
16082
  // src/optional/reporting/travel.ts
@@ -16227,7 +16331,7 @@ var RuntimeCheckpointControl = class {
16227
16331
  constructor(options) {
16228
16332
  this.options = options;
16229
16333
  this.profile = normalizePublicationProfile(options.profile);
16230
- if (!hash7(options.parentCheckpointDigest) || ["tenantId", "companionId", "seatId"].some((key2) => this.profile.identity[key2] !== options.principal[key2]) || ![options.bootId, options.authorityBootId, options.principal.nodeId].every((value2) => typeof value2 === "string" && /^[A-Za-z0-9][A-Za-z0-9_.:-]{0,127}$/.test(value2))) throw new Error("TRAVEL_CHECKPOINT_IDENTITY");
16334
+ if (!hash7(options.parentCheckpointDigest) || ["tenantId", "companionId", "seatId"].some((key3) => this.profile.identity[key3] !== options.principal[key3]) || ![options.bootId, options.authorityBootId, options.principal.nodeId].every((value2) => typeof value2 === "string" && /^[A-Za-z0-9][A-Za-z0-9_.:-]{0,127}$/.test(value2))) throw new Error("TRAVEL_CHECKPOINT_IDENTITY");
16231
16335
  this.binding = JSON.stringify([this.profile, options.principal.nodeId, options.bootId, options.authorityBootId, options.parentCheckpointDigest]);
16232
16336
  preparePrivateDirectory(options.directory);
16233
16337
  this.files = ["checkpoints.json", "checkpoint-owner.sqlite", "checkpoints.sqlite"].map((file) => join33(options.directory, file));
@@ -16278,7 +16382,7 @@ var RuntimeCheckpointControl = class {
16278
16382
  }
16279
16383
  permit() {
16280
16384
  const permit = this.options.permit(), p = this.options.principal;
16281
- if (!permit || ["tenantId", "companionId", "seatId", "nodeId"].some((key2) => permit[key2] !== p[key2]) || permit.bootId !== this.options.bootId || permit.authorityBootId !== this.options.authorityBootId || permit.epoch !== this.profile.epoch) throw new Error("TRAVEL_CHECKPOINT_IDENTITY");
16385
+ if (!permit || ["tenantId", "companionId", "seatId", "nodeId"].some((key3) => permit[key3] !== p[key3]) || permit.bootId !== this.options.bootId || permit.authorityBootId !== this.options.authorityBootId || permit.epoch !== this.profile.epoch) throw new Error("TRAVEL_CHECKPOINT_IDENTITY");
16282
16386
  return permit;
16283
16387
  }
16284
16388
  advance(input) {
@@ -16377,9 +16481,9 @@ function validateCatalog(value2) {
16377
16481
  if (!Array.isArray(value2) || value2.length > 4096) throw new Error("RECOVERY_TRANSFER_INVALID_RESPONSE");
16378
16482
  const ids = /* @__PURE__ */ new Set();
16379
16483
  for (const receipt2 of value2) {
16380
- if (!receipt2 || !validId(receipt2.id) || ids.has(receipt2.id) || receipt2.state !== "PRESERVED" || receipt2.activationAllowed !== false || !["COMMON", "LOCAL", "REMOTE"].includes(receipt2.kind) || ![receipt2.digest, receipt2.manifestDigest].every((value3) => typeof value3 === "string" && /^[a-f0-9]{64}$/.test(value3)) || !Number.isSafeInteger(receipt2.deletionWatermark) || receipt2.deletionWatermark < 0 || Object.keys(receipt2).some((key2) => !["id", "state", "kind", "digest", "manifestDigest", "deletionWatermark", "activationAllowed", "publication"].includes(key2))) throw new Error("RECOVERY_TRANSFER_INVALID_RESPONSE");
16484
+ if (!receipt2 || !validId(receipt2.id) || ids.has(receipt2.id) || receipt2.state !== "PRESERVED" || receipt2.activationAllowed !== false || !["COMMON", "LOCAL", "REMOTE"].includes(receipt2.kind) || ![receipt2.digest, receipt2.manifestDigest].every((value3) => typeof value3 === "string" && /^[a-f0-9]{64}$/.test(value3)) || !Number.isSafeInteger(receipt2.deletionWatermark) || receipt2.deletionWatermark < 0 || Object.keys(receipt2).some((key3) => !["id", "state", "kind", "digest", "manifestDigest", "deletionWatermark", "activationAllowed", "publication"].includes(key3))) throw new Error("RECOVERY_TRANSFER_INVALID_RESPONSE");
16381
16485
  const publication = receipt2.publication;
16382
- if (receipt2.kind === "LOCAL" ? publication !== void 0 : !publication || publication.state !== "PUBLISHED" || publication.activationAllowed !== false || publication.digest !== receipt2.manifestDigest || publication.deletionWatermark !== receipt2.deletionWatermark || !Number.isSafeInteger(publication.sequence) || publication.sequence < 1 || Object.keys(publication).some((key2) => !["state", "sequence", "digest", "deletionWatermark", "activationAllowed"].includes(key2))) throw new Error("RECOVERY_TRANSFER_INVALID_RESPONSE");
16486
+ if (receipt2.kind === "LOCAL" ? publication !== void 0 : !publication || publication.state !== "PUBLISHED" || publication.activationAllowed !== false || publication.digest !== receipt2.manifestDigest || publication.deletionWatermark !== receipt2.deletionWatermark || !Number.isSafeInteger(publication.sequence) || publication.sequence < 1 || Object.keys(publication).some((key3) => !["state", "sequence", "digest", "deletionWatermark", "activationAllowed"].includes(key3))) throw new Error("RECOVERY_TRANSFER_INVALID_RESPONSE");
16383
16487
  ids.add(receipt2.id);
16384
16488
  }
16385
16489
  return value2;
@@ -16421,7 +16525,7 @@ function createRecoveryArchiveServer(options) {
16421
16525
  if (!identity || !fixedArchive && !resolveArchive || fixedArchive && resolveArchive) throw new Error("RECOVERY_TRANSFER_CONFIG");
16422
16526
  if (typeof assertAvailable !== "function" || !Number.isSafeInteger(bodyTimeoutMs) || bodyTimeoutMs < 10 || bodyTimeoutMs > 3e4) throw new Error("RECOVERY_TRANSFER_CONFIG");
16423
16527
  const peers = new Map(Object.entries(allowedPeers).map(([fingerprint, credential]) => [fingerprint.replaceAll(":", "").toLowerCase(), credential]));
16424
- if (!peers.size || [...peers.keys()].some((key2) => !/^[a-f0-9]{64}$/.test(key2))) throw new Error("RECOVERY_TRANSFER_CONFIG");
16528
+ if (!peers.size || [...peers.keys()].some((key3) => !/^[a-f0-9]{64}$/.test(key3))) throw new Error("RECOVERY_TRANSFER_CONFIG");
16425
16529
  const busy = /* @__PURE__ */ new Map();
16426
16530
  const server = createServer({ ...tls2, minVersion: "TLSv1.3", requestCert: true, rejectUnauthorized: true }, async (req, res) => {
16427
16531
  const started = Date.now(), timings = {};
@@ -16448,7 +16552,7 @@ function createRecoveryArchiveServer(options) {
16448
16552
  try {
16449
16553
  if (!socket.authorized || !credential) throw new Error();
16450
16554
  [principal] = await Promise.all([authority.authenticate(credential), assertAvailable()]);
16451
- if (["tenantId", "companionId", "seatId"].some((key2) => principal[key2] !== identity[key2])) throw new Error();
16555
+ if (["tenantId", "companionId", "seatId"].some((key3) => principal[key3] !== identity[key3])) throw new Error();
16452
16556
  } catch {
16453
16557
  refuse(403, "RECOVERY_TRANSFER_DENIED");
16454
16558
  req.resume();
@@ -16499,7 +16603,7 @@ function createRecoveryArchiveServer(options) {
16499
16603
  action = ["list", "read", "object", "objects", "parts", "stream", "manifests", "manifest-page"].includes(input?.action) ? input.action : "invalid";
16500
16604
  mark("resolve");
16501
16605
  if (input?.version === 1 && input.action === "list") {
16502
- if (Object.keys(input).some((key2) => !["version", "action"].includes(key2))) throw new Error();
16606
+ if (Object.keys(input).some((key3) => !["version", "action"].includes(key3))) throw new Error();
16503
16607
  const receipts = validateCatalog(await (listReceipts?.() ?? fixedArchive?.list({ maximum: 4096 }) ?? Promise.reject(new Error())));
16504
16608
  const [control3] = await Promise.all([authority.status(principal), assertAvailable()]), current2 = control3.deletionWatermark;
16505
16609
  if (receipts.some((receipt2) => receipt2.deletionWatermark < current2)) throw new Error();
@@ -16511,13 +16615,13 @@ function createRecoveryArchiveServer(options) {
16511
16615
  return;
16512
16616
  }
16513
16617
  const ancestry = ["manifests", "manifest-page"].includes(input?.action), paged = input?.action === "manifest-page";
16514
- if (!input || input.version !== 1 || !["read", "object", "objects", "parts", "stream", "manifests", "manifest-page"].includes(input.action) || !validId(input.id) || Object.keys(input).some((key2) => !["version", "action", "id", ...input.action === "object" ? ["ref"] : ["objects", "stream"].includes(input.action) ? ["refs"] : input.action === "parts" ? ["parts"] : ancestry ? ["common"] : []].includes(key2))) throw new Error();
16618
+ if (!input || input.version !== 1 || !["read", "object", "objects", "parts", "stream", "manifests", "manifest-page"].includes(input.action) || !validId(input.id) || Object.keys(input).some((key3) => !["version", "action", "id", ...input.action === "object" ? ["ref"] : ["objects", "stream"].includes(input.action) ? ["refs"] : input.action === "parts" ? ["parts"] : ancestry ? ["common"] : []].includes(key3))) throw new Error();
16515
16619
  await assertAvailable();
16516
16620
  if (ancestry && !validCommon(input.common)) throw new Error();
16517
16621
  const evidence = ancestry && readManifestEvidence ? await readManifestEvidence(input.id, input.common, paged ? 4 : void 0) : void 0;
16518
16622
  const archive = evidence ? void 0 : resolveArchive ? await resolveArchive(input.id) : fixedArchive;
16519
16623
  mark("entry");
16520
- if (archive && ["tenantId", "companionId", "seatId"].some((key2) => archive.objects.identity[key2] !== identity[key2])) throw new Error();
16624
+ if (archive && ["tenantId", "companionId", "seatId"].some((key3) => archive.objects.identity[key3] !== identity[key3])) throw new Error();
16521
16625
  const entry = evidence?.entry ?? await archive.read(input.id);
16522
16626
  if (entry.id !== input.id) throw new Error();
16523
16627
  if (archiveDigest) {
@@ -17239,7 +17343,7 @@ async function seedRuntimeReplica(options) {
17239
17343
  const identity = manifest.profile.identity, destination = resolve24(options.destination), dataDirectory = resolve24(options.dataDirectory);
17240
17344
  const check = async () => {
17241
17345
  const permit = await (options.permitSupplier?.() ?? options.permit);
17242
- if (!permit || ["tenantId", "companionId", "seatId", "nodeId", "bootId", "authorityBootId", "epoch"].some((key2) => permit[key2] !== options.permit[key2])) throw new Error("TRAVEL_REPLICA_IDENTITY");
17346
+ if (!permit || ["tenantId", "companionId", "seatId", "nodeId", "bootId", "authorityBootId", "epoch"].some((key3) => permit[key3] !== options.permit[key3])) throw new Error("TRAVEL_REPLICA_IDENTITY");
17243
17347
  const status = options.authority.assertPermitWithStatus ? await options.authority.assertPermitWithStatus(permit, "CONTROL") : (await options.authority.assertPermit(permit, "CONTROL"), await options.authority.status(options.principal));
17244
17348
  if (digest7 !== options.expectedDigest || manifest.sequence !== 1 || manifest.parentDigest !== "0".repeat(64)) throw new Error("TRAVEL_REPLICA_CHECKPOINT");
17245
17349
  if (status.checkpointDigest !== controlCheckpoint) await options.authority.verifyAncestor(options.principal, controlCheckpoint, String(status.checkpointDigest));
@@ -17512,7 +17616,7 @@ var RuntimeReplicaRepository = class _RuntimeReplicaRepository {
17512
17616
  this.assertOpen();
17513
17617
  const permit = await (request7.permitSupplier?.() ?? request7.permit);
17514
17618
  const status = request7.authority.assertPermitWithStatus ? await request7.authority.assertPermitWithStatus(permit, "CONTROL") : (await request7.authority.assertPermit(permit, "CONTROL"), await request7.authority.status(request7.principal));
17515
- if (["tenantId", "companionId", "seatId", "nodeId", "bootId", "authorityBootId", "epoch"].some((key2) => permit[key2] !== request7.permit[key2]) || ["tenantId", "companionId", "seatId", "nodeId"].some((key2) => permit[key2] !== request7.principal[key2]) || JSON.stringify(entry.manifest.profile.identity) !== JSON.stringify(this.options.objects.identity) || entry.manifest.profile.epoch !== permit.epoch) throw new Error("TRAVEL_REPLICA_IDENTITY");
17619
+ if (["tenantId", "companionId", "seatId", "nodeId", "bootId", "authorityBootId", "epoch"].some((key3) => permit[key3] !== request7.permit[key3]) || ["tenantId", "companionId", "seatId", "nodeId"].some((key3) => permit[key3] !== request7.principal[key3]) || JSON.stringify(entry.manifest.profile.identity) !== JSON.stringify(this.options.objects.identity) || entry.manifest.profile.epoch !== permit.epoch) throw new Error("TRAVEL_REPLICA_IDENTITY");
17516
17620
  if (status.deletionWatermark !== entry.manifest.deletionWatermark || this.options.deletionWatermark() !== entry.manifest.deletionWatermark) throw new Error("TRAVEL_REPLICA_DELETION_BARRIER");
17517
17621
  if (status.buildManifestId !== entry.manifest.profile.buildManifestId) throw new Error("TRAVEL_REPLICA_BUILD");
17518
17622
  };
@@ -17939,7 +18043,7 @@ async function compareRecoveryArchives(options) {
17939
18043
  if (readSchemaVersion(db)?.component === "legacy-memory") loadLegacySQLiteVectorExtension(db);
17940
18044
  db.exec("PRAGMA temp_store=FILE; PRAGMA cache_size=-8192");
17941
18045
  db.function("e7_recovery_key", { varargs: true, useBigIntArguments: true, deterministic: true }, (...cells) => JSON.stringify(cells.map(value)));
17942
- db.function("e7_recovery_order", { deterministic: true }, (key2) => Buffer.from(String(key2), "utf16le").swap16().toString("hex"));
18046
+ db.function("e7_recovery_order", { deterministic: true }, (key3) => Buffer.from(String(key3), "utf16le").swap16().toString("hex"));
17943
18047
  }
17944
18048
  const schemas = handles.map(tables);
17945
18049
  if (!same9(schemas[0], schemas[1]) || !same9(schemas[0], schemas[2])) throw new Error("RECOVERY_DIFF_SCHEMA_MISMATCH");
@@ -17947,10 +18051,10 @@ async function compareRecoveryArchives(options) {
17947
18051
  for (const table of schemas[0]) {
17948
18052
  await check();
17949
18053
  const records = handles.map((db) => {
17950
- const key2 = "e7_recovery_key(" + table.keys.map(quote2).join(",") + ")";
18054
+ const key3 = "e7_recovery_key(" + table.keys.map(quote2).join(",") + ")";
17951
18055
  const sizes = table.columns.map((column) => "coalesce(length(CAST(" + quote2(column) + " AS BLOB)),0)").join("+");
17952
18056
  if (db.prepare("SELECT 1 FROM " + quote2(table.name) + " WHERE (" + sizes + ")>16777216 LIMIT 1").get()) throw new Error("RECOVERY_DIFF_LIMIT");
17953
- const statement = db.prepare("SELECT " + table.columns.map(quote2).join(",") + " FROM " + quote2(table.name) + " ORDER BY e7_recovery_order(" + key2 + ")");
18057
+ const statement = db.prepare("SELECT " + table.columns.map(quote2).join(",") + " FROM " + quote2(table.name) + " ORDER BY e7_recovery_order(" + key3 + ")");
17954
18058
  statement.setReadBigInts(true);
17955
18059
  return statement.iterate()[Symbol.iterator]();
17956
18060
  });
@@ -17968,11 +18072,11 @@ async function compareRecoveryArchives(options) {
17968
18072
  try {
17969
18073
  const current2 = records.map((_, index) => next(index));
17970
18074
  while (current2.some(Boolean)) {
17971
- const key2 = current2.filter((row) => !!row).map((row) => row.key).sort()[0];
17972
- emit({ databaseId, table: table.name, key: JSON.parse(key2) }, ...current2.map((row) => row?.key === key2 ? row.row : null));
17973
- for (let index = 0; index < current2.length; index++) if (current2[index]?.key === key2) {
17974
- if (previous[index] === key2) throw new Error("RECOVERY_DIFF_INVALID_KEY");
17975
- previous[index] = key2;
18075
+ const key3 = current2.filter((row) => !!row).map((row) => row.key).sort()[0];
18076
+ emit({ databaseId, table: table.name, key: JSON.parse(key3) }, ...current2.map((row) => row?.key === key3 ? row.row : null));
18077
+ for (let index = 0; index < current2.length; index++) if (current2[index]?.key === key3) {
18078
+ if (previous[index] === key3) throw new Error("RECOVERY_DIFF_INVALID_KEY");
18079
+ previous[index] = key3;
17976
18080
  current2[index] = next(index);
17977
18081
  }
17978
18082
  if (scannedRecords % 128 === 0 || performance.now() - lastYield >= 25) {
@@ -18084,7 +18188,7 @@ function authReadinessHistory(body) {
18084
18188
  }
18085
18189
  for (const [id2, value2] of Object.entries(data.connections)) {
18086
18190
  providerId(id2);
18087
- if (!record(value2) || Object.keys(value2).some((key2) => !["status", "key"].includes(key2)) || !["connected", "pending", "not_connected", "disconnected", "expired", "denied", "failed"].includes(value2.status) || value2.key !== void 0 && typeof value2.key !== "string") return false;
18191
+ if (!record(value2) || Object.keys(value2).some((key3) => !["status", "key"].includes(key3)) || !["connected", "pending", "not_connected", "disconnected", "expired", "denied", "failed"].includes(value2.status) || value2.key !== void 0 && typeof value2.key !== "string") return false;
18088
18192
  }
18089
18193
  return true;
18090
18194
  } catch {
@@ -18112,12 +18216,12 @@ function schema4(db, table) {
18112
18216
  if (!columns2.length || table.startsWith("e7_") || table.startsWith("sqlite_")) throw new Error("RECOVERY_UNSUPPORTED_TABLE");
18113
18217
  return { names: columns2.map((c) => String(c.name)), keys: columns2.filter((c) => Number(c.pk) > 0).sort((a, b) => Number(a.pk) - Number(b.pk)).map((c) => String(c.name)) };
18114
18218
  }
18115
- function read(db, table, key2, local) {
18219
+ function read(db, table, key3, local) {
18116
18220
  const s = schema4(db, table);
18117
- if (!s.keys.length || key2.length !== s.keys.length || !same10(s.names.slice().sort(), Object.keys(local).sort())) throw new Error("RECOVERY_SCHEMA_MISMATCH");
18221
+ if (!s.keys.length || key3.length !== s.keys.length || !same10(s.names.slice().sort(), Object.keys(local).sort())) throw new Error("RECOVERY_SCHEMA_MISMATCH");
18118
18222
  const statement = db.prepare("SELECT * FROM " + quote3(table) + " WHERE " + s.keys.map((k) => quote3(k) + "=?").join(" AND "));
18119
18223
  statement.setReadBigInts(true);
18120
- const row = statement.get(...key2.map(decode));
18224
+ const row = statement.get(...key3.map(decode));
18121
18225
  return row ? Object.fromEntries(s.names.map((k) => [k, encode(row[k])])) : null;
18122
18226
  }
18123
18227
  function executable(table) {
@@ -18155,8 +18259,8 @@ function socialReferences(db, table, row, archived) {
18155
18259
  };
18156
18260
  const relation = (id2, version, historical = false) => {
18157
18261
  if (++budget > 4096) return null;
18158
- const key2 = JSON.stringify([id2, version]);
18159
- if (relationships.has(key2)) return null;
18262
+ const key3 = JSON.stringify([id2, version]);
18263
+ if (relationships.has(key3)) return null;
18160
18264
  const value2 = db.prepare(`SELECT h.*,r.assertion_id,r.basis_refs,a.value_json,s.subject_id fact_subject,v.state
18161
18265
  FROM memory_relationship_versions r JOIN memory_relationship_heads h ON h.scope_id=r.scope_id AND h.relationship_id=r.relationship_id
18162
18266
  JOIN fact_assertions a ON a.scope_id=r.scope_id AND a.assertion_id=r.assertion_id
@@ -18166,14 +18270,14 @@ function socialReferences(db, table, row, archived) {
18166
18270
  if (!value2 || !historical && Number(value2.semantic_version) !== version) return null;
18167
18271
  const semantic = JSON.parse(String(value2.value_json));
18168
18272
  if (semantic.relationshipId !== id2 || semantic.semanticVersion !== version || semantic.entityId !== value2.object_id || semantic.perspectiveEntityId !== value2.perspective_entity_id || value2.fact_subject !== value2.subject_id) return null;
18169
- relationships.add(key2);
18273
+ relationships.add(key3);
18170
18274
  try {
18171
18275
  if (!references(String(value2.basis_refs), historical)) return null;
18172
18276
  const evidence = db.prepare("SELECT source_id FROM fact_evidence WHERE scope_id=? AND assertion_id=?").all(scope, value2.assertion_id);
18173
18277
  if (!evidence.length || !evidence.every((e) => source(String(e.source_id), historical))) return null;
18174
18278
  return value2;
18175
18279
  } finally {
18176
- relationships.delete(key2);
18280
+ relationships.delete(key3);
18177
18281
  }
18178
18282
  };
18179
18283
  const references = (json, historical = false) => {
@@ -18235,7 +18339,7 @@ function socialReferences(db, table, row, archived) {
18235
18339
  }
18236
18340
  function nativeReferences(db, table, row, common, branch, scopeProof, originalBinding, archived) {
18237
18341
  if (!socialReferences(db, table, row, archived)) return false;
18238
- const text2 = (key2) => row[key2]?.[0] === "text" ? row[key2][1] : void 0;
18342
+ const text2 = (key3) => row[key3]?.[0] === "text" ? row[key3][1] : void 0;
18239
18343
  const scope = text2("scope_id");
18240
18344
  let refs2 = [];
18241
18345
  if (table === "entity_bindings") {
@@ -18543,7 +18647,7 @@ function recoveryScopeProof(db, common, candidates, branch, originalBinding) {
18543
18647
  if (mapped && Number(mapped.current_value) !== currentVersion) return false;
18544
18648
  for (const table of tables2) {
18545
18649
  if (!common.prepare("SELECT 1 FROM sqlite_master WHERE name=?").get(table) || !db.prepare("SELECT 1 FROM sqlite_master WHERE name=?").get(table)) return false;
18546
- const info = schema4(common, table), identity = JSON.stringify([scope, table, parent === "context"]), key2 = (row) => JSON.stringify(info.keys.map((field) => row[field]));
18650
+ const info = schema4(common, table), identity = JSON.stringify([scope, table, parent === "context"]), key3 = (row) => JSON.stringify(info.keys.map((field) => row[field]));
18547
18651
  let expected = originals.get(identity);
18548
18652
  if (!expected) {
18549
18653
  expected = /* @__PURE__ */ new Map();
@@ -18551,7 +18655,7 @@ function recoveryScopeProof(db, common, candidates, branch, originalBinding) {
18551
18655
  const statement2 = common.prepare("SELECT * FROM " + quote3(table) + " WHERE scope_id=?");
18552
18656
  statement2.setReadBigInts(true);
18553
18657
  for (const value2 of statement2.iterate(scope)) {
18554
- const row = Object.fromEntries(Object.entries(value2).map(([k, v]) => [k, encode(v)])), id2 = key2(row), item = proof(table, row, parent === "context");
18658
+ const row = Object.fromEntries(Object.entries(value2).map(([k, v]) => [k, encode(v)])), id2 = key3(row), item = proof(table, row, parent === "context");
18555
18659
  bytes += Buffer.byteLength(id2) + Buffer.byteLength(JSON.stringify(item));
18556
18660
  if (expected.size >= 1e5 || bytes > 64 * 1024 * 1024) throw new Error("RECOVERY_DEPENDENCY_BUDGET");
18557
18661
  expected.set(id2, { ...item, baseline: item.positions });
@@ -18569,7 +18673,7 @@ function recoveryScopeProof(db, common, candidates, branch, originalBinding) {
18569
18673
  const statement = db.prepare("SELECT * FROM " + quote3(table) + " WHERE scope_id=?");
18570
18674
  statement.setReadBigInts(true);
18571
18675
  for (const value2 of statement.iterate(scope)) {
18572
- const row = Object.fromEntries(Object.entries(value2).map(([k, v]) => [k, encode(v)])), original = expected.get(key2(row));
18676
+ const row = Object.fromEntries(Object.entries(value2).map(([k, v]) => [k, encode(v)])), original = expected.get(key3(row));
18573
18677
  if (!original || original.digest !== proof(table, row, parent === "context", true).digest) return false;
18574
18678
  for (const [field, position] of Object.entries(original.positions)) {
18575
18679
  let projected = position;
@@ -18591,7 +18695,7 @@ function sessionRecovery(db, common, candidates, branch) {
18591
18695
  const originalTables = /* @__PURE__ */ new Map();
18592
18696
  const originalRows = (table) => {
18593
18697
  if (originalTables.has(table)) return originalTables.get(table);
18594
- const keys = schema4(common, table).keys, key2 = (row) => JSON.stringify(keys.map((k) => row[k]));
18698
+ const keys = schema4(common, table).keys, key3 = (row) => JSON.stringify(keys.map((k) => row[k]));
18595
18699
  const s = common.prepare("SELECT * FROM " + quote3(table));
18596
18700
  s.setReadBigInts(true);
18597
18701
  const rows = /* @__PURE__ */ new Map();
@@ -18600,10 +18704,10 @@ function sessionRecovery(db, common, candidates, branch) {
18600
18704
  const row = Object.fromEntries(Object.entries(value2).map(([k, v]) => [k, encode(v)]));
18601
18705
  bytes += Buffer.byteLength(JSON.stringify(row));
18602
18706
  if (rows.size >= 1e5 || bytes > 64 * 1024 * 1024) throw new Error("RECOVERY_DEPENDENCY_BUDGET");
18603
- rows.set(key2(row), row);
18707
+ rows.set(key3(row), row);
18604
18708
  }
18605
18709
  for (const item of candidates.filter((i) => i.table === table)) {
18606
- if (item.local) rows.set(key2(item.local), item.local);
18710
+ if (item.local) rows.set(key3(item.local), item.local);
18607
18711
  else rows.delete(JSON.stringify(item.key));
18608
18712
  }
18609
18713
  const result = [...rows.values()];
@@ -18678,20 +18782,20 @@ function supersededRecords(db, common, candidates) {
18678
18782
  list.push(item);
18679
18783
  byTable.set(item.table, list);
18680
18784
  }
18681
- const text2 = (row, k) => row[k]?.[0] === "text" ? row[k][1] : void 0, key2 = (scope, id2) => JSON.stringify([scope, id2]);
18785
+ const text2 = (row, k) => row[k]?.[0] === "text" ? row[k][1] : void 0, key3 = (scope, id2) => JSON.stringify([scope, id2]);
18682
18786
  const originalSources = /* @__PURE__ */ new Map(), evidence = /* @__PURE__ */ new Map();
18683
18787
  for (const item of byTable.get("memory_sources") ?? []) {
18684
18788
  const row = item.local;
18685
- originalSources.set(key2(text2(row, "scope_id"), text2(row, "source_id")), row);
18789
+ originalSources.set(key3(text2(row, "scope_id"), text2(row, "source_id")), row);
18686
18790
  }
18687
18791
  for (const item of byTable.get("fact_evidence") ?? []) {
18688
- const row = item.local, id2 = key2(text2(row, "scope_id"), text2(row, "assertion_id")), list = evidence.get(id2) ?? [];
18792
+ const row = item.local, id2 = key3(text2(row, "scope_id"), text2(row, "assertion_id")), list = evidence.get(id2) ?? [];
18689
18793
  list.push(row);
18690
18794
  evidence.set(id2, list);
18691
18795
  }
18692
18796
  const olderSources = /* @__PURE__ */ new Map(), historicalFacts = /* @__PURE__ */ new Set(), historicalSlots = /* @__PURE__ */ new Set(), artifacts = /* @__PURE__ */ new Set();
18693
18797
  const older = (scope, id2) => {
18694
- const identity = key2(scope, id2);
18798
+ const identity = key3(scope, id2);
18695
18799
  if (olderSources.has(identity)) return true;
18696
18800
  let row = originalSources.get(identity);
18697
18801
  if (!row) {
@@ -18710,7 +18814,7 @@ function supersededRecords(db, common, candidates) {
18710
18814
  };
18711
18815
  for (const item of byTable.get("fact_assertions") ?? []) {
18712
18816
  const row = item.local, scope = text2(row, "scope_id"), id2 = text2(row, "assertion_id"), slot = text2(row, "slot_id");
18713
- const refs2 = (evidence.get(key2(scope, id2)) ?? []).filter((row2) => row2.relation?.[1] === "supports");
18817
+ const refs2 = (evidence.get(key3(scope, id2)) ?? []).filter((row2) => row2.relation?.[1] === "supports");
18714
18818
  if (!refs2.length || !refs2.every((ref) => older(scope, text2(ref, "source_id")))) continue;
18715
18819
  const current2 = db.prepare(`SELECT s.source_id,s.origin_key,s.source_version,s.actor_id,s.text,e.span_start,e.span_end,e.quote FROM fact_assertions a
18716
18820
  JOIN fact_versions v ON v.scope_id=a.scope_id AND v.assertion_id=a.assertion_id JOIN fact_evidence e ON e.scope_id=a.scope_id AND e.assertion_id=a.assertion_id
@@ -18719,22 +18823,22 @@ function supersededRecords(db, common, candidates) {
18719
18823
  if (current2.some((source) => {
18720
18824
  if (String(source.text).slice(Number(source.span_start), Number(source.span_end)) !== source.quote) return false;
18721
18825
  if (!refs2.every((ref) => {
18722
- const old = olderSources.get(key2(scope, text2(ref, "source_id")));
18826
+ const old = olderSources.get(key3(scope, text2(ref, "source_id")));
18723
18827
  return decode(old.origin_key) === source.origin_key && decode(old.actor_id) === source.actor_id && Number(decode(old.source_version)) < Number(source.source_version);
18724
18828
  })) return false;
18725
18829
  return !!db.prepare(`SELECT 1 FROM fact_changes c,json_each(c.proposal_json,'$.evidence') e WHERE c.scope_id=?
18726
18830
  AND json_extract(c.result_json,'$.slotId')=? AND json_extract(c.proposal_json,'$.changeKind')='correction'
18727
18831
  AND json_extract(e.value,'$.sourceId')=? AND json_extract(e.value,'$.quote')=?`).get(scope, slot, source.source_id, source.quote);
18728
18832
  })) {
18729
- historicalFacts.add(key2(scope, id2));
18730
- historicalSlots.add(key2(scope, slot));
18833
+ historicalFacts.add(key3(scope, id2));
18834
+ historicalSlots.add(key3(scope, slot));
18731
18835
  }
18732
18836
  }
18733
18837
  for (let progress = true; progress; ) {
18734
18838
  progress = false;
18735
18839
  for (const item of byTable.get("memory_dependencies") ?? []) {
18736
- const row = item.local, scope = text2(row, "scope_id"), kind = text2(row, "parent_kind"), parent = text2(row, "parent_id"), child = key2(scope, text2(row, "child_id"));
18737
- if (kind === "source" && older(scope, parent) || kind === "fact" && historicalFacts.has(key2(scope, parent)) || kind === "artifact" && artifacts.has(key2(scope, parent))) {
18840
+ const row = item.local, scope = text2(row, "scope_id"), kind = text2(row, "parent_kind"), parent = text2(row, "parent_id"), child = key3(scope, text2(row, "child_id"));
18841
+ if (kind === "source" && older(scope, parent) || kind === "fact" && historicalFacts.has(key3(scope, parent)) || kind === "artifact" && artifacts.has(key3(scope, parent))) {
18738
18842
  if (!artifacts.has(child)) {
18739
18843
  artifacts.add(child);
18740
18844
  progress = true;
@@ -18746,7 +18850,7 @@ function supersededRecords(db, common, candidates) {
18746
18850
  const scope = text2(row, "scope_id");
18747
18851
  if (!scope) return false;
18748
18852
  const fact = text2(row, "assertion_id"), artifact = text2(row, "artifact_id") ?? text2(row, "child_id") ?? text2(row, "entry_id");
18749
- return !!fact && historicalFacts.has(key2(scope, fact)) || !!artifact && artifacts.has(key2(scope, artifact)) || item.table === "fact_slots" && historicalSlots.has(key2(scope, text2(row, "slot_id")));
18853
+ return !!fact && historicalFacts.has(key3(scope, fact)) || !!artifact && artifacts.has(key3(scope, artifact)) || item.table === "fact_slots" && historicalSlots.has(key3(scope, text2(row, "slot_id")));
18750
18854
  };
18751
18855
  }
18752
18856
  async function admitRecoveryArchives(options) {
@@ -18884,9 +18988,9 @@ async function admitRecoveryArchives(options) {
18884
18988
  return value2 ? Object.fromEntries(Object.entries(value2).map(([k, v]) => [k, encode(v)])) : null;
18885
18989
  };
18886
18990
  const priorRow = (table, current2) => {
18887
- const key2 = schema4(store.db, table).keys.map((field) => current2[field]);
18991
+ const key3 = schema4(store.db, table).keys.map((field) => current2[field]);
18888
18992
  for (const digest7 of chain.slice(1)) {
18889
- const id2 = hash8(JSON.stringify([digest7, databaseId, table, key2]));
18993
+ const id2 = hash8(JSON.stringify([digest7, databaseId, table, key3]));
18890
18994
  const saved = store.db.prepare("SELECT original_hash,result FROM e7_recovery_items WHERE item_id=?").get(id2);
18891
18995
  if (!saved) continue;
18892
18996
  const item = JSON.parse(String(saved.result)), original = item.local;
@@ -18926,8 +19030,8 @@ async function admitRecoveryArchives(options) {
18926
19030
  const historical = supersededRecords(store.db, commonDatabases.get(databaseId), candidates);
18927
19031
  const bindingCache = /* @__PURE__ */ new Map();
18928
19032
  const originalBinding = (row) => {
18929
- const scope = decode(row.scope_id), target = JSON.stringify([decode(row.namespace), decode(row.external_id)]), key2 = JSON.stringify([scope, target]);
18930
- if (bindingCache.has(key2)) return bindingCache.get(key2);
19033
+ const scope = decode(row.scope_id), target = JSON.stringify([decode(row.namespace), decode(row.external_id)]), key3 = JSON.stringify([scope, target]);
19034
+ if (bindingCache.has(key3)) return bindingCache.get(key3);
18931
19035
  const commonDb = commonDatabases.get(databaseId), exists = commonDb.prepare("SELECT 1 FROM sqlite_master WHERE name='memory_knowledge_history'").get();
18932
19036
  if (!exists) return null;
18933
19037
  const statement = commonDb.prepare("SELECT * FROM memory_knowledge_history WHERE scope_id=? AND target_kind='binding' AND target_id=? ORDER BY history_id DESC LIMIT 1");
@@ -18938,7 +19042,7 @@ async function admitRecoveryArchives(options) {
18938
19042
  const history = item.local;
18939
19043
  if (decode(history.scope_id) === scope && decode(history.target_kind) === "binding" && decode(history.target_id) === target && (!latest || BigInt(String(decode(history.history_id))) > BigInt(String(decode(latest.history_id))))) latest = history;
18940
19044
  }
18941
- bindingCache.set(key2, latest);
19045
+ bindingCache.set(key3, latest);
18942
19046
  return latest;
18943
19047
  };
18944
19048
  const scopeProof = recoveryScopeProof(store.db, commonDatabases.get(databaseId), candidates, local.receipt.manifestDigest, originalBinding);
@@ -19286,12 +19390,12 @@ async function projectRecoveryArtifacts(options) {
19286
19390
  };
19287
19391
  try {
19288
19392
  validateProjection();
19289
- const sessions = openSessionEvents(root);
19290
- if (!sessions) throw new Error("RECOVERY_CURRENT_LAYOUT");
19393
+ const sessions2 = openSessionEvents(root);
19394
+ if (!sessions2) throw new Error("RECOVERY_CURRENT_LAYOUT");
19291
19395
  try {
19292
- sessions.projectAll();
19396
+ sessions2.projectAll();
19293
19397
  } finally {
19294
- sessions.close();
19398
+ sessions2.close();
19295
19399
  }
19296
19400
  state2 = "HISTORY";
19297
19401
  reason = "original_session_history_projected";
@@ -19762,10 +19866,10 @@ var TravelNodeAgent = class _TravelNodeAgent {
19762
19866
  await this.refreshKey();
19763
19867
  await this.assertDataAvailable();
19764
19868
  if (token !== this.generationToken) throw new Error("TRAVEL_NODE_CANCELLED");
19765
- const key2 = Buffer.from(input.key);
19869
+ const key3 = Buffer.from(input.key);
19766
19870
  let server;
19767
19871
  try {
19768
- server = await createTravelNodeDataServer({ node: this, authority: this.options.authority, ...input, key: key2 });
19872
+ server = await createTravelNodeDataServer({ node: this, authority: this.options.authority, ...input, key: key3 });
19769
19873
  await new Promise((resolveListen, rejectListen) => {
19770
19874
  server.once("error", rejectListen);
19771
19875
  server.listen(input.port, input.host, () => {
@@ -19777,7 +19881,7 @@ var TravelNodeAgent = class _TravelNodeAgent {
19777
19881
  const address = server.address();
19778
19882
  if (!address || typeof address === "string") throw new Error("TRAVEL_NODE_LISTENER_CONFIG");
19779
19883
  this.dataServer = server;
19780
- this.dataServerKey = key2;
19884
+ this.dataServerKey = key3;
19781
19885
  this.dataServerBinding = binding;
19782
19886
  return this.dataServerAddress = { host: input.host, port: address.port };
19783
19887
  } catch (error) {
@@ -19785,7 +19889,7 @@ var TravelNodeAgent = class _TravelNodeAgent {
19785
19889
  server.closeAllConnections();
19786
19890
  await new Promise((resolveClose) => server.close(() => resolveClose()));
19787
19891
  }
19788
- key2.fill(0);
19892
+ key3.fill(0);
19789
19893
  throw error;
19790
19894
  }
19791
19895
  });
@@ -20307,7 +20411,7 @@ var TravelNodeAgent = class _TravelNodeAgent {
20307
20411
  const boundedCheck = async () => {
20308
20412
  localCheck();
20309
20413
  const permit = currentPermit;
20310
- if (["tenantId", "companionId", "seatId", "nodeId", "bootId", "authorityBootId", "epoch"].some((key2) => permit[key2] !== request7.permit[key2]) || ["tenantId", "companionId", "seatId", "nodeId"].some((key2) => permit[key2] !== request7.principal[key2]) || request7.principal.nodeId === this.principal.nodeId || ["tenantId", "companionId", "seatId"].some((key2) => request7.principal[key2] !== this.principal[key2])) throw new Error("TRAVEL_NODE_IDENTITY");
20414
+ if (["tenantId", "companionId", "seatId", "nodeId", "bootId", "authorityBootId", "epoch"].some((key3) => permit[key3] !== request7.permit[key3]) || ["tenantId", "companionId", "seatId", "nodeId"].some((key3) => permit[key3] !== request7.principal[key3]) || request7.principal.nodeId === this.principal.nodeId || ["tenantId", "companionId", "seatId"].some((key3) => request7.principal[key3] !== this.principal[key3])) throw new Error("TRAVEL_NODE_IDENTITY");
20311
20415
  const authority = this.options.authority, status = authority.assertPermitWithStatus ? await authority.assertPermitWithStatus(permit, "CONTROL") : (await authority.assertPermit(permit, "CONTROL"), await authority.status(this.principal));
20312
20416
  localCheck();
20313
20417
  if (status.expired || status.authorityBootId !== permit.authorityBootId || status.epoch !== permit.epoch || status.activeNodeId !== permit.nodeId || status.activeBootId !== permit.bootId) throw new Error("TRAVEL_NODE_CHECKPOINT");
@@ -21292,12 +21396,12 @@ var RemoteTravelNodeAuthority = class _RemoteTravelNodeAuthority extends RemoteT
21292
21396
  assertPermitWithStatus(...[permit, operation]) {
21293
21397
  const grant = this.nodeGrants.find((value2) => ["tenantId", "companionId", "seatId", "nodeId"].every((field) => permit[field] === value2.principal[field]));
21294
21398
  if (!grant) return Promise.reject(new Error("TRAVEL_AUTH_DENIED"));
21295
- const key2 = JSON.stringify([permit, operation]), pending = this.permitReads.get(key2);
21399
+ const key3 = JSON.stringify([permit, operation]), pending = this.permitReads.get(key3);
21296
21400
  if (pending) return pending;
21297
21401
  const read2 = grant.client.assertPermitWithStatus(permit, operation).then((current2) => current2 === void 0 ? this.status(grant.principal) : current2).finally(() => {
21298
- this.permitReads.delete(key2);
21402
+ this.permitReads.delete(key3);
21299
21403
  });
21300
- this.permitReads.set(key2, read2);
21404
+ this.permitReads.set(key3, read2);
21301
21405
  return read2;
21302
21406
  }
21303
21407
  async handoffStatus(principal, id2) {
@@ -21772,7 +21876,7 @@ var fields2 = {
21772
21876
  synchronize: []
21773
21877
  };
21774
21878
  function exact(value2, allowed, required = allowed) {
21775
- return Object.keys(value2).every((key2) => allowed.includes(key2)) && required.every((key2) => Object.hasOwn(value2, key2));
21879
+ return Object.keys(value2).every((key3) => allowed.includes(key3)) && required.every((key3) => Object.hasOwn(value2, key3));
21776
21880
  }
21777
21881
  var digest6 = (value2) => typeof value2 === "string" && /^[a-f0-9]{64}$/.test(value2);
21778
21882
  function validNodeSupervisorInput(value2) {
@@ -21781,7 +21885,7 @@ function validNodeSupervisorInput(value2) {
21781
21885
  if (!exact(value2, ["version", "nodeId", "bootId", "action", ...required, ...optional], ["version", "nodeId", "action", ...required])) return false;
21782
21886
  if (value2.action !== "observe" && !nodeSupervisorId(value2.bootId) || Object.hasOwn(value2, "bootId") && !nodeSupervisorId(value2.bootId)) return false;
21783
21887
  if (Object.hasOwn(value2, "checkpointDigest") && !digest6(value2.checkpointDigest) || Object.hasOwn(value2, "transferId") && !nodeSupervisorId(value2.transferId)) return false;
21784
- for (const key2 of ["permit", "expectedSource"]) if (Object.hasOwn(value2, key2) && !nodeSupervisorRecord(value2[key2])) return false;
21888
+ for (const key3 of ["permit", "expectedSource"]) if (Object.hasOwn(value2, key3) && !nodeSupervisorRecord(value2[key3])) return false;
21785
21889
  if (value2.action === "connectReplica") {
21786
21890
  const profile = value2.profile;
21787
21891
  if (!nodeSupervisorRecord(profile) || !exact(profile, ["identity", "baselineId", "epoch", "buildManifestId", "databaseIds", "trees"]) || !nodeSupervisorRecord(profile.identity) || !exact(profile.identity, ["tenantId", "companionId", "seatId"]) || !Array.isArray(profile.trees) || profile.trees.some((tree) => !nodeSupervisorRecord(tree) || !exact(tree, ["id", "kind"]))) return false;
@@ -21929,7 +22033,7 @@ var RemoteTravelNodeSupervisor = class {
21929
22033
  return this.observeQuery ??= (async () => {
21930
22034
  try {
21931
22035
  const result = await this.call("observe", {}, true);
21932
- if (!result || ["connected", "running", "busy"].some((key2) => typeof result[key2] !== "boolean")) throw new Error("TRAVEL_NODE_INVALID_RESPONSE");
22036
+ if (!result || ["connected", "running", "busy"].some((key3) => typeof result[key3] !== "boolean")) throw new Error("TRAVEL_NODE_INVALID_RESPONSE");
21933
22037
  return { connected: result.connected, running: result.running, busy: result.busy };
21934
22038
  } catch {
21935
22039
  return { connected: false, running: false, busy: false };
@@ -22000,8 +22104,8 @@ function createTravelNodeSupervisorServer(options) {
22000
22104
  const { node, bootId: bootId2, managementFingerprints, authorize, peer, bodyTimeoutMs = 5e3, ...tls2 } = options;
22001
22105
  const fingerprints = new Set(managementFingerprints.map((value2) => value2.replaceAll(":", "").toLowerCase()));
22002
22106
  if (!nodeSupervisorId(bootId2) || !fingerprints.size || [...fingerprints].some((value2) => !/^[a-f0-9]{64}$/.test(value2)) || !Number.isSafeInteger(bodyTimeoutMs) || bodyTimeoutMs < 100 || bodyTimeoutMs > 3e4) throw new Error("TRAVEL_NODE_LISTENER_CONFIG");
22003
- const samePrincipal = (principal) => ["tenantId", "companionId", "seatId", "nodeId", "role", "credentialHash"].every((key2) => principal[key2] === node.principal[key2]);
22004
- if (peer && (peer.principal.nodeId === node.principal.nodeId || ["tenantId", "companionId", "seatId"].some((key2) => peer.principal[key2] !== node.principal[key2]))) throw new Error("TRAVEL_NODE_LISTENER_IDENTITY");
22107
+ const samePrincipal = (principal) => ["tenantId", "companionId", "seatId", "nodeId", "role", "credentialHash"].every((key3) => principal[key3] === node.principal[key3]);
22108
+ if (peer && (peer.principal.nodeId === node.principal.nodeId || ["tenantId", "companionId", "seatId"].some((key3) => peer.principal[key3] !== node.principal[key3]))) throw new Error("TRAVEL_NODE_LISTENER_IDENTITY");
22005
22109
  const active = { read: 0, operation: 0, stop: 0 };
22006
22110
  const server = createServer5({ ...tls2, minVersion: "TLSv1.3", requestCert: true, rejectUnauthorized: true }, async (req, res) => {
22007
22111
  res.setHeader("Content-Type", "application/json");
@@ -22097,7 +22201,7 @@ function createTravelNodeSupervisorServer(options) {
22097
22201
  break;
22098
22202
  case "bootstrapReplica": {
22099
22203
  const request7 = input.request;
22100
- if (!peer || !node.bootstrapReplica || ["tenantId", "companionId", "seatId", "nodeId", "role", "credentialHash"].some((key2) => request7.principal[key2] !== peer.principal[key2])) throw new Error("TRAVEL_NODE_IDENTITY");
22204
+ if (!peer || !node.bootstrapReplica || ["tenantId", "companionId", "seatId", "nodeId", "role", "credentialHash"].some((key3) => request7.principal[key3] !== peer.principal[key3])) throw new Error("TRAVEL_NODE_IDENTITY");
22101
22205
  await node.bootstrapReplica({ ...request7, permitSupplier: () => peer.permit() });
22102
22206
  break;
22103
22207
  }