engine7 7.1.144 → 7.1.146

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.
@@ -459,10 +459,10 @@ var init_live = __esm({
459
459
  /** 安全取子段('services.voice-chat.start' → current.services.voice-chat.start) */
460
460
  get(dotPath) {
461
461
  if (!this.current) return void 0;
462
- return dotPath.split(".").reduce((acc, key3) => {
462
+ return dotPath.split(".").reduce((acc, key4) => {
463
463
  if (acc == null) return void 0;
464
- if (key3 === "__proto__" || key3 === "constructor" || key3 === "prototype") return void 0;
465
- return acc[key3];
464
+ if (key4 === "__proto__" || key4 === "constructor" || key4 === "prototype") return void 0;
465
+ return acc[key4];
466
466
  }, this.current);
467
467
  }
468
468
  /** reload 时原地更新(Object.assign 保持引用不变)
@@ -633,9 +633,9 @@ function toWall(i = /* @__PURE__ */ new Date()) {
633
633
  return `${p.y}-${p2(p.mo)}-${p2(p.d)} ${p2(p.hh)}:${p2(p.mm)}:${p2(p.ss)}`;
634
634
  }
635
635
  function warnOnce(callSite, shape, sample) {
636
- const key3 = `${callSite}:${shape}`;
637
- if (warned.has(key3)) return;
638
- warned.add(key3);
636
+ const key4 = `${callSite}:${shape}`;
637
+ if (warned.has(key4)) return;
638
+ warned.add(key4);
639
639
  console.warn(`[clock] ${callSite} \u5951\u7EA6\u8FDD\u89C4(${shape})\uFF0C\u6837\u672C: ${String(sample).slice(0, 80)}`);
640
640
  }
641
641
  function zoneOffsetMs(d) {
@@ -871,11 +871,11 @@ var init_tokenizer = __esm({
871
871
  import { createHash as createHash3 } from "node:crypto";
872
872
  function scopeId(scope) {
873
873
  if ([scope.ownerId, scope.appId, scope.projectId].some((value) => typeof value !== "string" || !value.trim())) throw new Error("Invalid memory scope");
874
- const key3 = JSON.stringify([scope.ownerId, scope.appId, scope.projectId]);
875
- const cached = scopeIdMemo.get(key3);
874
+ const key4 = JSON.stringify([scope.ownerId, scope.appId, scope.projectId]);
875
+ const cached = scopeIdMemo.get(key4);
876
876
  if (cached) return cached;
877
877
  const id = "scope_" + createHash3("sha256").update(JSON.stringify([scope.ownerId, scope.appId, scope.projectId])).digest("hex");
878
- scopeIdMemo.set(key3, id);
878
+ scopeIdMemo.set(key4, id);
879
879
  return id;
880
880
  }
881
881
  var scopeIdMemo;
@@ -1696,15 +1696,15 @@ var init_sqlite_replication = __esm({
1696
1696
  requireForeignKeys(this.db);
1697
1697
  if (captureGuardHash(this.db) !== this.guardHash) throw new Error("REPLICATION_GUARD_MISMATCH");
1698
1698
  if (sqliteReplicationSchemaHash(this.db) !== this.schemaHash) throw new Error("REPLICATION_SCHEMA_MISMATCH");
1699
- const before = sequences(this.db, this.excludedTables), sessions = [];
1699
+ const before = sequences(this.db, this.excludedTables), sessions2 = [];
1700
1700
  try {
1701
- if (this.sessionTables) for (const table of this.sessionTables) sessions.push(this.db.createSession({ table }));
1702
- else sessions.push(this.db.createSession());
1701
+ if (this.sessionTables) for (const table of this.sessionTables) sessions2.push(this.db.createSession({ table }));
1702
+ else sessions2.push(this.db.createSession());
1703
1703
  } catch (error) {
1704
- for (const session of sessions) session.close();
1704
+ for (const session of sessions2) session.close();
1705
1705
  throw error;
1706
1706
  }
1707
- this.active = { sessions, sequences: before, closed: false };
1707
+ this.active = { sessions: sessions2, sequences: before, closed: false };
1708
1708
  return this.active;
1709
1709
  }
1710
1710
  appendCapture(capture) {
@@ -1812,15 +1812,15 @@ import { basename as basename4, dirname as dirname4, join as join6, resolve as r
1812
1812
  function isReplicationFailure(error) {
1813
1813
  return error instanceof Error && /^(?:REPLICATION_|TRAVEL_|CHECKPOINT_BUSY)/.test(error.message);
1814
1814
  }
1815
- function checkKey(component, key3) {
1816
- if (component === "topics-vectors" && typeof key3 === "string" && /^[a-f0-9]{64}$/.test(key3)) return;
1817
- 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;
1818
- if (["calendar", "proactive", "session-events"].includes(component) && key3 === void 0) return;
1815
+ function checkKey(component, key4) {
1816
+ if (component === "topics-vectors" && typeof key4 === "string" && /^[a-f0-9]{64}$/.test(key4)) return;
1817
+ if (component === "legacy-memory" && typeof key4 === "string" && /^[A-Za-z0-9][A-Za-z0-9_.-]{0,127}$/.test(key4) && !/[. ]$/.test(key4) && !/^(CON|PRN|AUX|NUL|COM[1-9]|LPT[1-9])(?:\.|$)/i.test(key4)) return;
1818
+ if (["calendar", "proactive", "session-events"].includes(component) && key4 === void 0) return;
1819
1819
  throw new Error("REPLICATION_REGISTRATION_INVALID");
1820
1820
  }
1821
- function location(stateDir, component, key3) {
1822
- checkKey(component, key3);
1823
- return join6(stateDir, ".continuity", component + (key3 === void 0 ? "" : "-" + key3) + "-replication.json");
1821
+ function location(stateDir, component, key4) {
1822
+ checkKey(component, key4);
1823
+ return join6(stateDir, ".continuity", component + (key4 === void 0 ? "" : "-" + key4) + "-replication.json");
1824
1824
  }
1825
1825
  function normalize2(input) {
1826
1826
  if (!input || !/^[a-f0-9]{64}$/.test(input.schemaHash)) throw new Error("REPLICATION_REGISTRATION_INVALID");
@@ -1831,8 +1831,8 @@ function directory(path2) {
1831
1831
  if (!info.isDirectory() || info.isSymbolicLink() || realpathSync(path2) !== resolve4(path2) || process.platform !== "win32" && (info.mode & 63 || info.uid !== process.getuid()))
1832
1832
  throw new Error("REPLICATION_REGISTRATION_INVALID");
1833
1833
  }
1834
- function readRuntimeReplicationRegistration(stateDir, component, key3) {
1835
- const file = location(stateDir, component, key3);
1834
+ function readRuntimeReplicationRegistration(stateDir, component, key4) {
1835
+ const file = location(stateDir, component, key4);
1836
1836
  try {
1837
1837
  lstatSync3(dirname4(file));
1838
1838
  } catch (error) {
@@ -1895,8 +1895,8 @@ function checkRuntimeReplicationDatabase(db, registration, component, version, r
1895
1895
  }
1896
1896
  return requested ?? registration?.binding;
1897
1897
  }
1898
- function enrollRuntimeReplication(db, stateDir, component, binding2, key3) {
1899
- const file = location(stateDir, component, key3), old = readRuntimeReplicationRegistration(stateDir, component, key3);
1898
+ function enrollRuntimeReplication(db, stateDir, component, binding2, key4) {
1899
+ const file = location(stateDir, component, key4), old = readRuntimeReplicationRegistration(stateDir, component, key4);
1900
1900
  const version = readSchemaVersion(db);
1901
1901
  if (version?.component !== component) throw new Error("REPLICATION_SCHEMA_MISMATCH");
1902
1902
  checkRuntimeReplicationDatabase(db, old, component, version.version, binding2);
@@ -1909,7 +1909,7 @@ function enrollRuntimeReplication(db, stateDir, component, binding2, key3) {
1909
1909
  writeFileSync5(file, JSON.stringify(input), { mode: 384, flag: "wx", flush: true });
1910
1910
  } catch (error) {
1911
1911
  if (error.code !== "EEXIST") throw error;
1912
- if (JSON.stringify(readRuntimeReplicationRegistration(stateDir, component, key3)) !== JSON.stringify(input)) throw new Error("REPLICATION_REGISTRATION_MISMATCH");
1912
+ if (JSON.stringify(readRuntimeReplicationRegistration(stateDir, component, key4)) !== JSON.stringify(input)) throw new Error("REPLICATION_REGISTRATION_MISMATCH");
1913
1913
  }
1914
1914
  if (process.platform !== "win32") {
1915
1915
  const fd = openSync2(dirname4(file), "r");
@@ -2473,8 +2473,8 @@ async function historyRoot(b, strict = false) {
2473
2473
  }
2474
2474
  }
2475
2475
  async function openTopicsVectorStore(b, options = {}) {
2476
- const key3 = digest(canonical(topicsScope(b)));
2477
- const registration = b.stateDir ? readRuntimeReplicationRegistration(b.stateDir, "topics-vectors", key3) : null;
2476
+ const key4 = digest(canonical(topicsScope(b)));
2477
+ const registration = b.stateDir ? readRuntimeReplicationRegistration(b.stateDir, "topics-vectors", key4) : null;
2478
2478
  let db, release;
2479
2479
  try {
2480
2480
  const root = await historyRoot(b, Boolean(registration || options.replication));
@@ -2496,7 +2496,7 @@ async function openTopicsVectorStore(b, options = {}) {
2496
2496
  CREATE TABLE IF NOT EXISTS cache_meta(key TEXT PRIMARY KEY,value TEXT NOT NULL);`) }]);
2497
2497
  normalizeVectorCache(b, db, currentTopicParagraphs(b));
2498
2498
  } else authorizeMemoryWriter(db, 1);
2499
- const source = binding2 ? enrollRuntimeReplication(db, b.stateDir, "topics-vectors", binding2, key3) : void 0;
2499
+ const source = binding2 ? enrollRuntimeReplication(db, b.stateDir, "topics-vectors", binding2, key4) : void 0;
2500
2500
  if (source) Object.defineProperty(db, "replication", { value: source });
2501
2501
  const capture = source ? installSQLiteWriteCapture(db, source) : void 0;
2502
2502
  const originalClose = db.close.bind(db);
@@ -3269,10 +3269,14 @@ var init_filters = __esm({
3269
3269
 
3270
3270
  // src/mem7/core/state/temporal.ts
3271
3271
  function instant(value) {
3272
- if (!/^\d{4}-\d{2}-\d{2}T.*(?:Z|[+-]\d{2}:\d{2})$/.test(value)) throw new Error("TIME_REQUIRED: explicit UTC offset required");
3273
- if (!isCalendarDate(value.substring(0, 10))) throw new Error("INVALID_TIME");
3274
- const time = Date.parse(value);
3275
- if (!Number.isFinite(time)) throw new Error("INVALID_TIME");
3272
+ let text2 = value;
3273
+ if (typeof text2 !== "string" || !INSTANT.test(text2)) {
3274
+ text2 = typeof value === "string" ? value.trim().replace(/^(\d{4}-\d{2}-\d{2}) /, "$1T").replace(/([+-]\d{2})(\d{2})$/, "$1:$2") : value;
3275
+ if (typeof text2 !== "string" || !INSTANT.test(text2)) throw new Error(`TIME_REQUIRED: explicit UTC offset required \u2014 \u6536\u5230 ${received(value)}\uFF1B${INSTANT_FORMAT}`);
3276
+ }
3277
+ if (!isCalendarDate(text2.substring(0, 10))) throw new Error(`INVALID_TIME: \u4E0D\u662F\u6709\u6548\u7684\u65E5\u5386\u65E5\u671F \u2014 \u6536\u5230 ${received(value)}`);
3278
+ const time = Date.parse(text2);
3279
+ if (!Number.isFinite(time)) throw new Error(`INVALID_TIME \u2014 \u6536\u5230 ${received(value)}\uFF1B${INSTANT_FORMAT}`);
3276
3280
  return new Date(time).toISOString();
3277
3281
  }
3278
3282
  function isCalendarDate(value) {
@@ -3285,7 +3289,7 @@ function validateTimezone(timezone) {
3285
3289
  try {
3286
3290
  new Intl.DateTimeFormat("en", { timeZone: timezone });
3287
3291
  } catch {
3288
- throw new Error("INVALID_TIMEZONE");
3292
+ throw new Error(`INVALID_TIMEZONE: timezone \u7528 IANA \u65F6\u533A\u540D\uFF0C\u5982 Asia/Shanghai\uFF08\u6536\u5230 ${String(timezone).slice(0, 60)}\uFF09`);
3289
3293
  }
3290
3294
  }
3291
3295
  function localInstant(date, time, timezone) {
@@ -3317,10 +3321,13 @@ function localInstant(date, time, timezone) {
3317
3321
  return new Date([...matches][0]).toISOString();
3318
3322
  }
3319
3323
  function normalizeValidity(value) {
3324
+ for (const field of ["validFrom", "validTo"]) {
3325
+ if (value[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}`);
3326
+ }
3320
3327
  const validFrom = value.validFrom === null ? null : instant(value.validFrom);
3321
3328
  const validTo = value.validTo === null ? null : instant(value.validTo);
3322
- if (validFrom !== null && validTo !== null && validFrom >= validTo) throw new Error("INVALID_INTERVAL: expected [from,to)");
3323
- if (!["exact", "observed", "unknown"].includes(value.precision)) throw new Error("INVALID_PRECISION");
3329
+ 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");
3330
+ if (!["exact", "observed", "unknown"].includes(value.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");
3324
3331
  if (value.timezone) validateTimezone(value.timezone);
3325
3332
  return { ...value, validFrom, validTo };
3326
3333
  }
@@ -3330,16 +3337,20 @@ function overlaps(a, b) {
3330
3337
  function canonicalJson(value) {
3331
3338
  const normalize5 = (input) => {
3332
3339
  if (Array.isArray(input)) return input.map(normalize5);
3333
- 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, normalize5(entry)]));
3340
+ if (input && typeof input === "object") return Object.fromEntries(Object.entries(input).filter(([, entry]) => entry !== void 0).sort(([a], [b]) => a.localeCompare(b)).map(([key4, entry]) => [key4, normalize5(entry)]));
3334
3341
  return input;
3335
3342
  };
3336
3343
  const json = JSON.stringify(normalize5(value));
3337
3344
  if (json === void 0) throw new Error("INVALID_JSON_VALUE");
3338
3345
  return json;
3339
3346
  }
3347
+ var INSTANT, INSTANT_FORMAT, received;
3340
3348
  var init_temporal = __esm({
3341
3349
  "src/mem7/core/state/temporal.ts"() {
3342
3350
  "use strict";
3351
+ INSTANT = /^\d{4}-\d{2}-\d{2}T.*(?:Z|[+-]\d{2}:\d{2})$/;
3352
+ 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';
3353
+ received = (value) => (JSON.stringify(value) ?? String(value)).slice(0, 80);
3343
3354
  }
3344
3355
  });
3345
3356
 
@@ -3364,8 +3375,8 @@ function contextTimeKey(db, scopeId2, validAt) {
3364
3375
  }
3365
3376
  return `valid-window:${from}:${to}`;
3366
3377
  }
3367
- function assertContextTime(key3, now2 = Date.now()) {
3368
- const match = key3.match(/^valid-window:(-?\d+):(-?\d+)$/);
3378
+ function assertContextTime(key4, now2 = Date.now()) {
3379
+ const match = key4.match(/^valid-window:(-?\d+):(-?\d+)$/);
3369
3380
  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");
3370
3381
  if (now2 < Number(match[1]) || now2 >= Number(match[2])) throw new Error("CONTEXT_TIME_EXPIRED");
3371
3382
  }
@@ -3448,9 +3459,9 @@ function append(db, scope, kind, id, payload) {
3448
3459
  return Number(result.lastInsertRowid);
3449
3460
  }
3450
3461
  function recordArtifactBasis(db, scope, kind, id, version, dependencies) {
3451
- const key3 = basisKey(kind, id, version);
3452
- if (!db.prepare("SELECT 1 FROM memory_knowledge_history WHERE scope_id=? AND target_kind='artifact.basis' AND target_id=?").get(scopeId(scope), key3)) {
3453
- append(db, scope, "artifact.basis", key3, { dependencies });
3462
+ const key4 = basisKey(kind, id, version);
3463
+ if (!db.prepare("SELECT 1 FROM memory_knowledge_history WHERE scope_id=? AND target_kind='artifact.basis' AND target_id=?").get(scopeId(scope), key4)) {
3464
+ append(db, scope, "artifact.basis", key4, { dependencies });
3454
3465
  }
3455
3466
  }
3456
3467
  var ARTIFACT_HISTORY_SCHEMA, hash2, basisKey, stateKey2, generationKinds, normalizedRefs, ArtifactHistory;
@@ -3600,8 +3611,8 @@ END;
3600
3611
  if (cutoff) return historicalRow(this.db, scope, "artifact.basis", basisKey(kind, id, version), cutoff)?.dependencies ?? null;
3601
3612
  return this.dependencies.version(scope, kind, id) === version ? this.dependencies.refs(scope, kind, id) : null;
3602
3613
  }
3603
- scopeContextRetained(scope, key3) {
3604
- 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);
3614
+ scopeContextRetained(scope, key4) {
3615
+ 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), key4);
3605
3616
  if (!basis) return false;
3606
3617
  const atGeneration = historicalRow(this.db, scope, "scope", "state", { historyId: basis.history_id, time: null, complete: true });
3607
3618
  if (!atGeneration) return false;
@@ -3619,15 +3630,15 @@ END;
3619
3630
  WHERE scope_id=? AND source_id=? AND interpretation_status<>'deleted'`).get(scopeKey, sourceId));
3620
3631
  const walk = (kind2, id2, version2) => {
3621
3632
  checkMemoryReadBudget(visited.size);
3622
- const key3 = basisKey(kind2, id2, version2);
3623
- if (memo.has(key3)) return memo.get(key3);
3624
- if (visited.has(key3)) return false;
3625
- visited.add(key3);
3633
+ const key4 = basisKey(kind2, id2, version2);
3634
+ if (memo.has(key4)) return memo.get(key4);
3635
+ if (visited.has(key4)) return false;
3636
+ visited.add(key4);
3626
3637
  try {
3627
- 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);
3638
+ 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, key4);
3628
3639
  const refs = basis && JSON.parse(basis.payload_json).dependencies;
3629
3640
  if (!refs || this.db.prepare("SELECT 1 FROM memory_tombstones WHERE scope_id=? AND target_kind=? AND target_id=?").get(scopeKey, kind2, id2)) return false;
3630
- if (refs.some((ref) => ref.parentKind === "scope" && !ref.parentId.startsWith("valid-window:")) && !this.scopeContextRetained(scope, key3)) return false;
3641
+ if (refs.some((ref) => ref.parentKind === "scope" && !ref.parentId.startsWith("valid-window:")) && !this.scopeContextRetained(scope, key4)) return false;
3631
3642
  const retained = refs.every((ref) => {
3632
3643
  checkMemoryReadBudget(visited.size);
3633
3644
  if (ref.parentKind === "source") return sourceRetained(ref.parentId);
@@ -3647,10 +3658,10 @@ END;
3647
3658
  }
3648
3659
  return true;
3649
3660
  });
3650
- memo.set(key3, retained);
3661
+ memo.set(key4, retained);
3651
3662
  return retained;
3652
3663
  } finally {
3653
- visited.delete(key3);
3664
+ visited.delete(key4);
3654
3665
  }
3655
3666
  };
3656
3667
  return walk(kind, id, version);
@@ -3676,8 +3687,8 @@ END;
3676
3687
  };
3677
3688
  const walk = (parentKind, parentId, parentVersion, ancestors) => {
3678
3689
  checkMemoryReadBudget(ancestors.size);
3679
- const key3 = basisKey(parentKind, parentId, parentVersion);
3680
- if (ancestors.has(key3)) return false;
3690
+ const key4 = basisKey(parentKind, parentId, parentVersion);
3691
+ if (ancestors.has(key4)) return false;
3681
3692
  const state = this.state(scope, parentKind, parentId, cutoff);
3682
3693
  if (state?.state !== "current" || state.version !== parentVersion) return false;
3683
3694
  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;
@@ -3692,9 +3703,9 @@ END;
3692
3703
  }
3693
3704
  }
3694
3705
  if (refs.some((ref) => ref.parentKind === "scope" && !ref.parentId.startsWith("valid-window:"))) {
3695
- if (!this.scopeContextRetained(scope, key3)) return false;
3706
+ if (!this.scopeContextRetained(scope, key4)) return false;
3696
3707
  }
3697
- const next = new Set(ancestors).add(key3);
3708
+ const next = new Set(ancestors).add(key4);
3698
3709
  for (const ref of refs) {
3699
3710
  checkMemoryReadBudget(next.size);
3700
3711
  if (ref.parentKind === "source") {
@@ -3841,9 +3852,9 @@ function invalidateChildren(db, scope, pending2, reason) {
3841
3852
  let referencedPlan;
3842
3853
  while (pending2.length) {
3843
3854
  const child = pending2.shift();
3844
- const key3 = JSON.stringify([child.child_kind, child.child_id]);
3845
- if (visited.has(key3) && (visited.get(key3) || !child.deleted)) continue;
3846
- visited.set(key3, Boolean(child.deleted));
3855
+ const key4 = JSON.stringify([child.child_kind, child.child_id]);
3856
+ if (visited.has(key4) && (visited.get(key4) || !child.deleted)) continue;
3857
+ visited.set(key4, Boolean(child.deleted));
3847
3858
  if (child.child_kind === "graph_plan") {
3848
3859
  referencedPlan ??= db.prepare(`SELECT 1 WHERE EXISTS (SELECT 1 FROM memory_dependencies
3849
3860
  WHERE scope_id=? AND parent_kind='artifact' AND parent_id=?)
@@ -3924,8 +3935,8 @@ var init_dependencies = __esm({
3924
3935
  this.snapshotStamp = void 0;
3925
3936
  }
3926
3937
  }
3927
- observeTimeBoundary(key3) {
3928
- const match = key3.match(/^valid-window:(-?\d+):(-?\d+)$/);
3938
+ observeTimeBoundary(key4) {
3939
+ const match = key4.match(/^valid-window:(-?\d+):(-?\d+)$/);
3929
3940
  if (!match) return;
3930
3941
  const now2 = Date.now();
3931
3942
  for (const boundary of [Number(match[1]), Number(match[2])]) {
@@ -4007,9 +4018,9 @@ var init_dependencies = __esm({
4007
4018
  }
4008
4019
  artifactTimeCurrent(scope, kind, id, visited = /* @__PURE__ */ new Set(), memo) {
4009
4020
  checkMemoryReadBudget(visited.size);
4010
- const key3 = JSON.stringify([kind, id]);
4011
- if (visited.has(key3)) return false;
4012
- visited.add(key3);
4021
+ const key4 = JSON.stringify([kind, id]);
4022
+ if (visited.has(key4)) return false;
4023
+ visited.add(key4);
4013
4024
  try {
4014
4025
  const refs = this.refs(scope, kind, id);
4015
4026
  for (const ref of refs.filter((ref2) => ref2.parentKind !== "artifact")) {
@@ -4044,7 +4055,7 @@ var init_dependencies = __esm({
4044
4055
  }
4045
4056
  return true;
4046
4057
  } finally {
4047
- visited.delete(key3);
4058
+ visited.delete(key4);
4048
4059
  }
4049
4060
  }
4050
4061
  version(scope, kind, id) {
@@ -4209,6 +4220,28 @@ var init_vector_publications = __esm({
4209
4220
  }
4210
4221
  });
4211
4222
 
4223
+ // src/mem7/core/lance-cache.ts
4224
+ function memoryLanceSession(lance) {
4225
+ if (typeof lance.Session !== "function") return void 0;
4226
+ let session = sessions.get(lance);
4227
+ if (!session) {
4228
+ session = new lance.Session(BigInt(LANCE_INDEX_CACHE_BYTES), BigInt(LANCE_METADATA_CACHE_BYTES));
4229
+ sessions.set(lance, session);
4230
+ }
4231
+ return session;
4232
+ }
4233
+ var LANCE_INDEX_CACHE_BYTES, LANCE_METADATA_CACHE_BYTES, key2, globals, sessions;
4234
+ var init_lance_cache = __esm({
4235
+ "src/mem7/core/lance-cache.ts"() {
4236
+ "use strict";
4237
+ LANCE_INDEX_CACHE_BYTES = 256 * 1024 * 1024;
4238
+ LANCE_METADATA_CACHE_BYTES = 64 * 1024 * 1024;
4239
+ key2 = Symbol.for("engine7.mem7.lanceCacheSessions");
4240
+ globals = globalThis;
4241
+ sessions = globals[key2] ??= /* @__PURE__ */ new WeakMap();
4242
+ }
4243
+ });
4244
+
4212
4245
  // src/mem7/core/vector-store.ts
4213
4246
  import { mkdirSync as mkdirSync11, existsSync as existsSync8 } from "node:fs";
4214
4247
  import { DatabaseSync as DatabaseSync7 } from "node:sqlite";
@@ -4358,6 +4391,7 @@ var init_vector_store = __esm({
4358
4391
  init_read_guard();
4359
4392
  init_timing();
4360
4393
  init_runtime_authority();
4394
+ init_lance_cache();
4361
4395
  isIntelMac = process.platform === "darwin" && process.arch === "x64";
4362
4396
  lancePromise = null;
4363
4397
  mem7VectorWarning = null;
@@ -4444,7 +4478,7 @@ var init_vector_store = __esm({
4444
4478
  /** Reuse expensive dependency walks, but bind each verdict to SQL, time and the actual indexed body. */
4445
4479
  cachedRowVisible(ledger, kind, row, dependencies) {
4446
4480
  if (!dependencies) return vectorRowVisible(ledger, kind, row);
4447
- const key3 = kind + ":" + String(row.id);
4481
+ const key4 = kind + ":" + String(row.id);
4448
4482
  let signature2;
4449
4483
  try {
4450
4484
  signature2 = JSON.stringify([
@@ -4468,11 +4502,11 @@ var init_vector_store = __esm({
4468
4502
  this.visibleCacheVersion = version;
4469
4503
  this.visibleCache.clear();
4470
4504
  }
4471
- const cached = this.visibleCache.get(key3);
4505
+ const cached = this.visibleCache.get(key4);
4472
4506
  if (cached?.signature === signature2) return cached.verdict;
4473
4507
  const verdict = vectorRowVisible(ledger, kind, row, dependencies);
4474
4508
  if (dependencies.cacheRevision() !== version) return false;
4475
- this.visibleCache.set(key3, { signature: signature2, verdict });
4509
+ this.visibleCache.set(key4, { signature: signature2, verdict });
4476
4510
  return verdict;
4477
4511
  }
4478
4512
  visibleCache = /* @__PURE__ */ new Map();
@@ -4493,7 +4527,8 @@ var init_vector_store = __esm({
4493
4527
  assertRuntimeAuthority(this.stateDir, "WRITE");
4494
4528
  mkdirSync11(this.dir, { recursive: true });
4495
4529
  }
4496
- this.db = await lance.connect(this.dir);
4530
+ const session = memoryLanceSession(lance);
4531
+ this.db = await lance.connect(this.dir, session ? { session } : void 0);
4497
4532
  }
4498
4533
  return this.db;
4499
4534
  }
@@ -4970,11 +5005,11 @@ var init_vector_store = __esm({
4970
5005
  const rrf2 = /* @__PURE__ */ new Map();
4971
5006
  const add = (list) => {
4972
5007
  list.forEach((h, i) => {
4973
- const key3 = h.text.replace(/\s+/g, "");
5008
+ const key4 = h.text.replace(/\s+/g, "");
4974
5009
  const contrib = 1 / (RRF_K + i + 1);
4975
- const cur = rrf2.get(key3);
5010
+ const cur = rrf2.get(key4);
4976
5011
  if (cur) cur.score += contrib;
4977
- else rrf2.set(key3, { hit: h, score: contrib });
5012
+ else rrf2.set(key4, { hit: h, score: contrib });
4978
5013
  });
4979
5014
  };
4980
5015
  add(dense);
@@ -5202,8 +5237,8 @@ CREATE INDEX idx_memory_dependency_slot ON memory_dependencies(scope_id,slot_id)
5202
5237
  * 事件重放失败一次即回死信+skip,不重烧 5 轮预算)。先 UPDATE 后记账:中间崩溃只会
5203
5238
  * 多治一次(幂等无害),反过来会出现"记了账但没治"的永久死锁。 */
5204
5239
  reenqueueGapPrefix(sinkId, head, now2 = Date.now()) {
5205
- const key3 = `${sinkId}:${head.scopeId}:${head.eventSeq}`;
5206
- if (this.healedGaps.has(key3)) return;
5240
+ const key4 = `${sinkId}:${head.scopeId}:${head.eventSeq}`;
5241
+ if (this.healedGaps.has(key4)) return;
5207
5242
  const ledgerPath = this.gapHealLedgerPath;
5208
5243
  let ledger = {};
5209
5244
  if (ledgerPath) {
@@ -5211,8 +5246,8 @@ CREATE INDEX idx_memory_dependency_slot ON memory_dependencies(scope_id,slot_id)
5211
5246
  ledger = JSON.parse(readFileSync10(ledgerPath, "utf8"))?.heals ?? {};
5212
5247
  } catch {
5213
5248
  }
5214
- if (Number.isFinite(ledger[key3])) {
5215
- this.healedGaps.add(key3);
5249
+ if (Number.isFinite(ledger[key4])) {
5250
+ this.healedGaps.add(key4);
5216
5251
  return;
5217
5252
  }
5218
5253
  }
@@ -5226,11 +5261,11 @@ CREATE INDEX idx_memory_dependency_slot ON memory_dependencies(scope_id,slot_id)
5226
5261
  const count = Number(result?.changes ?? 0);
5227
5262
  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`);
5228
5263
  });
5229
- this.healedGaps.add(key3);
5264
+ this.healedGaps.add(key4);
5230
5265
  if (!ledgerPath) return;
5231
5266
  const cutoff = now2 - _ChangeFeed.GAP_HEAL_RETENTION_MS, retained = {};
5232
5267
  for (const [entry, at] of Object.entries(ledger)) if (Number.isFinite(at) && at >= cutoff) retained[entry] = at;
5233
- retained[key3] = now2;
5268
+ retained[key4] = now2;
5234
5269
  const temp = `${ledgerPath}.${randomUUID9()}.tmp`;
5235
5270
  try {
5236
5271
  writeFileSync9(temp, JSON.stringify({ version: 1, heals: retained }));
@@ -5355,7 +5390,7 @@ function validatePredicateValue(predicate, value) {
5355
5390
  if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error("INVALID_FACT_VALUE");
5356
5391
  const object3 = value;
5357
5392
  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"];
5358
- if (Object.keys(object3).some((key3) => !allowed.includes(key3))) throw new Error("INVALID_FACT_VALUE: unknown field");
5393
+ if (Object.keys(object3).some((key4) => !allowed.includes(key4))) throw new Error("INVALID_FACT_VALUE: unknown field");
5359
5394
  if (predicate === "activity.schedule") {
5360
5395
  const schedule = object3;
5361
5396
  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");
@@ -5577,8 +5612,8 @@ CREATE TABLE IF NOT EXISTS memory_source_aliases (
5577
5612
  ).all(scopeId(scope), `%${word.replace(/[!%_]/g, (character) => "!" + character)}%`, limit);
5578
5613
  return rows.map((row) => this.source(row));
5579
5614
  }
5580
- snapshotRead(key3, load) {
5581
- return this.snapshotReads ? this.snapshotReads.read(JSON.stringify(key3), load) : load();
5615
+ snapshotRead(key4, load) {
5616
+ return this.snapshotReads ? this.snapshotReads.read(JSON.stringify(key4), load) : load();
5582
5617
  }
5583
5618
  receive(input, options = {}) {
5584
5619
  const id = scopeId(input.scope);
@@ -5759,8 +5794,8 @@ CREATE TABLE IF NOT EXISTS memory_source_aliases (
5759
5794
  const result = { applied: 0, needsReview: 0, failed: 0, received: 0 };
5760
5795
  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));
5761
5796
  for (const row of rows) {
5762
- const key3 = row.state === "needs_review" ? "needsReview" : row.state;
5763
- if (Object.hasOwn(result, key3)) result[key3] += Number(row.count);
5797
+ const key4 = row.state === "needs_review" ? "needsReview" : row.state;
5798
+ if (Object.hasOwn(result, key4)) result[key4] += Number(row.count);
5764
5799
  }
5765
5800
  return result;
5766
5801
  }
@@ -6184,13 +6219,13 @@ function purgeRecoveryEvidence(db, graph) {
6184
6219
  db.prepare("UPDATE e7_recovery_items SET result=? WHERE item_id=?").run(JSON.stringify(item), saved.item_id);
6185
6220
  }
6186
6221
  }
6187
- var text, key2, RecoveryDeletionGraph;
6222
+ var text, key3, RecoveryDeletionGraph;
6188
6223
  var init_recovery_deletion = __esm({
6189
6224
  "src/continuity/recovery-deletion.ts"() {
6190
6225
  "use strict";
6191
6226
  init_recovery_deletion_sources();
6192
- text = (row, key3) => row[key3]?.[0] === "text" ? row[key3][1] : void 0;
6193
- key2 = (scope, kind, id) => JSON.stringify([scope, kind, id]);
6227
+ text = (row, key4) => row[key4]?.[0] === "text" ? row[key4][1] : void 0;
6228
+ key3 = (scope, kind, id) => JSON.stringify([scope, kind, id]);
6194
6229
  RecoveryDeletionGraph = class {
6195
6230
  edges = /* @__PURE__ */ new Map();
6196
6231
  roots = /* @__PURE__ */ new Set();
@@ -6203,10 +6238,10 @@ var init_recovery_deletion = __esm({
6203
6238
  constructor(deletions) {
6204
6239
  if (deletions.length > 1e5) throw new Error("RECOVERY_DEPENDENCY_BUDGET");
6205
6240
  for (const d of deletions) {
6206
- this.roots.add(key2(d.scopeId, "source", d.sourceId));
6241
+ this.roots.add(key3(d.scopeId, "source", d.sourceId));
6207
6242
  if (d.version !== void 0) {
6208
6243
  if (!Number.isSafeInteger(d.version) || d.version < 1) throw new Error("RECOVERY_DELETION_SOURCE_MISMATCH");
6209
- const sourceKey = key2(d.scopeId, "source", d.sourceId), prior = this.deletionVersions.get(sourceKey);
6244
+ const sourceKey = key3(d.scopeId, "source", d.sourceId), prior = this.deletionVersions.get(sourceKey);
6210
6245
  if (prior !== void 0 && prior !== d.version) throw new Error("RECOVERY_DELETION_SOURCE_MISMATCH");
6211
6246
  this.deletionVersions.set(sourceKey, d.version);
6212
6247
  }
@@ -6221,7 +6256,7 @@ var init_recovery_deletion = __esm({
6221
6256
  links(table, row) {
6222
6257
  const scope = text(row, "scope_id");
6223
6258
  if (!scope) return { owners: [], parents: [] };
6224
- const node = (kind2, id) => id ? [key2(scope, kind2, id)] : [];
6259
+ const node = (kind2, id) => id ? [key3(scope, kind2, id)] : [];
6225
6260
  const source = text(row, "source_id"), fact = text(row, "assertion_id");
6226
6261
  const artifact = text(row, "artifact_id") ?? text(row, "child_id") ?? text(row, "entry_id");
6227
6262
  const owners = fact ? node("fact", fact) : artifact ? node("artifact", artifact) : source ? node("source", source) : node("entity", text(row, "entity_id"));
@@ -6245,19 +6280,19 @@ var init_recovery_deletion = __esm({
6245
6280
  if (!ref || typeof ref !== "object") continue;
6246
6281
  const refScope = typeof ref.scopeId === "string" ? ref.scopeId : typeof ref.scope_id === "string" ? ref.scope_id : scope;
6247
6282
  for (const [field2, kind2] of [["sourceId", "source"], ["source_id", "source"], ["assertionId", "fact"], ["assertion_id", "fact"], ["artifactId", "artifact"], ["artifact_id", "artifact"], ["entryId", "artifact"], ["entry_id", "artifact"]]) {
6248
- if (typeof ref[field2] === "string") parents.push(key2(refScope, kind2, ref[field2]));
6283
+ if (typeof ref[field2] === "string") parents.push(key3(refScope, kind2, ref[field2]));
6249
6284
  }
6250
- if (typeof ref.parentId === "string" && ["source", "fact", "entity", "artifact"].includes(ref.parentKind)) parents.push(key2(refScope, ref.parentKind, ref.parentId));
6285
+ if (typeof ref.parentId === "string" && ["source", "fact", "entity", "artifact"].includes(ref.parentKind)) parents.push(key3(refScope, ref.parentKind, ref.parentId));
6251
6286
  pending2.push(...Object.values(ref).filter((value) => value && typeof value === "object"));
6252
6287
  }
6253
6288
  }
6254
6289
  if (table === "memory_knowledge_history") {
6255
6290
  const kind2 = text(row, "target_kind"), target = text(row, "target_id");
6256
- if (kind2 === "source" && target) parents.push(key2(scope, "source", target));
6291
+ if (kind2 === "source" && target) parents.push(key3(scope, "source", target));
6257
6292
  if (kind2?.startsWith("artifact.") && target) {
6258
6293
  try {
6259
6294
  const parts = JSON.parse(target);
6260
- if (Array.isArray(parts) && typeof parts[1] === "string") parents.push(key2(scope, "artifact", parts[1]));
6295
+ if (Array.isArray(parts) && typeof parts[1] === "string") parents.push(key3(scope, "artifact", parts[1]));
6261
6296
  } catch {
6262
6297
  }
6263
6298
  }
@@ -6265,7 +6300,7 @@ var init_recovery_deletion = __esm({
6265
6300
  if (table === "memory_sources" && source) {
6266
6301
  const origin = text(row, "origin_key");
6267
6302
  if (origin) {
6268
- const originNode = key2(scope, "origin", origin), sourceNode = key2(scope, "source", source);
6303
+ const originNode = key3(scope, "origin", origin), sourceNode = key3(scope, "source", source);
6269
6304
  this.edge(sourceNode, originNode);
6270
6305
  this.edge(originNode, sourceNode);
6271
6306
  const version = row.source_version?.[0] === "integer" ? Number(row.source_version[1]) : void 0;
@@ -6275,15 +6310,15 @@ var init_recovery_deletion = __esm({
6275
6310
  if (deletion.version === void 0) continue;
6276
6311
  if (!Number.isSafeInteger(deletion.version) || deletion.version < 1) throw new Error("RECOVERY_DELETION_SOURCE_MISMATCH");
6277
6312
  if (++this.deletionChecks > 1e6) throw new Error("RECOVERY_DEPENDENCY_BUDGET");
6278
- if (recoveryOriginalSourceId(scope, origin, deletion.version) === deletion.sourceId) this.edge(key2(scope, "source", deletion.sourceId), originNode);
6313
+ if (recoveryOriginalSourceId(scope, origin, deletion.version) === deletion.sourceId) this.edge(key3(scope, "source", deletion.sourceId), originNode);
6279
6314
  }
6280
6315
  this.familyProofs.add(originNode);
6281
6316
  }
6282
- if (text(row, "interpretation_status") === "deleted") this.roots.add(key2(scope, "source", source));
6317
+ if (text(row, "interpretation_status") === "deleted") this.roots.add(key3(scope, "source", source));
6283
6318
  }
6284
6319
  if (table === "memory_tombstones") {
6285
6320
  const target = text(row, "target_id"), kind2 = text(row, "target_kind");
6286
- if (target && kind2) this.roots.add(key2(scope, kind2, target));
6321
+ if (target && kind2) this.roots.add(key3(scope, kind2, target));
6287
6322
  }
6288
6323
  return { owners, parents };
6289
6324
  }
@@ -6691,9 +6726,9 @@ ALTER TABLE memory_host_turns ADD COLUMN owner_id TEXT;
6691
6726
  }
6692
6727
  }
6693
6728
  recordCompleted(id, sourceId, sourceVersion, now2) {
6694
- const key3 = JSON.stringify(["host.turn.completed", id, sourceId]);
6729
+ const key4 = JSON.stringify(["host.turn.completed", id, sourceId]);
6695
6730
  this.db.prepare(`INSERT OR IGNORE INTO ome_jobs(kind,payload,status,next_run_at,created_at,job_key,scope_id,completed_at)
6696
- VALUES ('host.turn.completed',?,'done',?,?,?,?,?)`).run(JSON.stringify({ scopeId: id, sourceId, sourceVersion }), now2, now2, key3, id, now2);
6731
+ VALUES ('host.turn.completed',?,'done',?,?,?,?,?)`).run(JSON.stringify({ scopeId: id, sourceId, sourceVersion }), now2, now2, key4, id, now2);
6697
6732
  }
6698
6733
  };
6699
6734
  }
@@ -7321,7 +7356,7 @@ function recoverLegacySession(db, store, mapping, files, apply = false) {
7321
7356
  return report;
7322
7357
  }
7323
7358
  function recoverLegacyProjections(db, store, input, apply = false) {
7324
- const key3 = scopeId(input.scope);
7359
+ const key4 = scopeId(input.scope);
7325
7360
  const root = realpathSync4(input.root);
7326
7361
  const report = { files: 0, entries: 0, recoverable: 0, alreadyMapped: 0, unavailable: 0, reasons: {}, applied: false };
7327
7362
  const gap = (reason) => {
@@ -7366,7 +7401,7 @@ function recoverLegacyProjections(db, store, input, apply = false) {
7366
7401
  const block = match[0];
7367
7402
  const field = (name) => match[2].match(new RegExp(`^\\*\\*${name}\\*\\*: ([^\\n]*)$`, "m"))?.[1]?.trim();
7368
7403
  const parent = field("parent_id");
7369
- const mapping = db.prepare("SELECT * FROM memory_legacy_cell_maps WHERE cell_id=? AND scope_id=?").get(parent ?? "", key3);
7404
+ const mapping = db.prepare("SELECT * FROM memory_legacy_cell_maps WHERE cell_id=? AND scope_id=?").get(parent ?? "", key4);
7370
7405
  if (!mapping || field("parent_type") !== "memcell" || field("owner_id") !== input.scope.ownerId || field("session_id") !== mapping.session_id) {
7371
7406
  gap("projection_parent_provenance_missing");
7372
7407
  continue;
@@ -7383,7 +7418,7 @@ function recoverLegacyProjections(db, store, input, apply = false) {
7383
7418
  gap("projection_body_missing");
7384
7419
  continue;
7385
7420
  }
7386
- const previous = db.prepare("SELECT * FROM memory_legacy_projection_maps WHERE scope_id=? AND kind=? AND entry_id=?").get(key3, kind, match[1]);
7421
+ const previous = db.prepare("SELECT * FROM memory_legacy_projection_maps WHERE scope_id=? AND kind=? AND entry_id=?").get(key4, kind, match[1]);
7387
7422
  const target = join16(store.mem7RootPath(), path2);
7388
7423
  if (previous) {
7389
7424
  if (previous.source_file_hash !== fileHash || previous.parent_id !== parent || previous.source_relative_path !== path2 || !store.projectionMatches(input.scope, kind, match[1], target, block)) {
@@ -7435,7 +7470,7 @@ function recoverLegacyProjections(db, store, input, apply = false) {
7435
7470
  role: "supports"
7436
7471
  })));
7437
7472
  const digest4 = hash3(candidate.block.trim());
7438
- db.prepare("INSERT INTO memory_projection_entries VALUES (?,?,?,?,?,?)").run(key3, candidate.kind, candidate.id, candidate.relativePath, 1, digest4);
7473
+ db.prepare("INSERT INTO memory_projection_entries VALUES (?,?,?,?,?,?)").run(key4, candidate.kind, candidate.id, candidate.relativePath, 1, digest4);
7439
7474
  store.artifacts.publish(input.scope, {
7440
7475
  kind: candidate.kind,
7441
7476
  id: candidate.id,
@@ -7447,7 +7482,7 @@ function recoverLegacyProjections(db, store, input, apply = false) {
7447
7482
  summary: candidate.summary,
7448
7483
  title: candidate.title
7449
7484
  });
7450
- db.prepare("INSERT INTO memory_legacy_projection_maps VALUES (?,?,?,?,?,?,?)").run(key3, candidate.kind, candidate.id, candidate.fileHash, candidate.relativePath, candidate.parent, 1);
7485
+ db.prepare("INSERT INTO memory_legacy_projection_maps VALUES (?,?,?,?,?,?,?)").run(key4, candidate.kind, candidate.id, candidate.fileHash, candidate.relativePath, candidate.parent, 1);
7451
7486
  }
7452
7487
  });
7453
7488
  report.applied = true;
@@ -7579,10 +7614,10 @@ var init_recall_sources = __esm({
7579
7614
  }
7580
7615
  const queue = db.prepare("SELECT target_id FROM memory_tombstones WHERE scope_id=? AND target_kind='source'").all(id).map((row) => `s:${row.target_id}`);
7581
7616
  for (let index = 0; index < queue.length; index++) {
7582
- const key3 = queue[index];
7583
- if (this.removed.has(key3)) continue;
7584
- this.removed.add(key3);
7585
- queue.push(...dependents.get(key3) ?? []);
7617
+ const key4 = queue[index];
7618
+ if (this.removed.has(key4)) continue;
7619
+ this.removed.add(key4);
7620
+ queue.push(...dependents.get(key4) ?? []);
7586
7621
  }
7587
7622
  }
7588
7623
  sources = /* @__PURE__ */ new Map();
@@ -7757,9 +7792,9 @@ CREATE TABLE memory_person_mentions (
7757
7792
  ])];
7758
7793
  if (ids.length > 8192 || this.snapshot.relationships.size > 8192) return result;
7759
7794
  const sourceIds = JSON.stringify(ids.sort());
7760
- const relationshipRefs = JSON.stringify([...this.snapshot.relationships.keys()].sort().map((key3) => {
7761
- const split = key3.lastIndexOf(":");
7762
- return [key3.slice(0, split), Number(key3.slice(split + 1))];
7795
+ const relationshipRefs = JSON.stringify([...this.snapshot.relationships.keys()].sort().map((key4) => {
7796
+ const split = key4.lastIndexOf(":");
7797
+ return [key4.slice(0, split), Number(key4.slice(split + 1))];
7763
7798
  }));
7764
7799
  this.snapshotBasis = this.readProvenanceBasis(this.snapshot, sourceIds, relationshipRefs);
7765
7800
  }
@@ -7807,19 +7842,19 @@ CREATE TABLE memory_person_mentions (
7807
7842
  const sourceChecks = new Map(sources.map((row) => [row.id, JSON.stringify(row)]));
7808
7843
  const relationshipRows = /* @__PURE__ */ new Map();
7809
7844
  for (const row of relationships) {
7810
- const key3 = `${row.id}:${row.version}`;
7811
- const rows = relationshipRows.get(key3) ?? [];
7845
+ const key4 = `${row.id}:${row.version}`;
7846
+ const rows = relationshipRows.get(key4) ?? [];
7812
7847
  rows.push(row);
7813
- relationshipRows.set(key3, rows);
7848
+ relationshipRows.set(key4, rows);
7814
7849
  }
7815
- const relationshipChecks = new Map([...relationshipRows].map(([key3, rows]) => [key3, createHash14("sha256").update(JSON.stringify(rows)).digest("hex")]));
7850
+ const relationshipChecks = new Map([...relationshipRows].map(([key4, rows]) => [key4, createHash14("sha256").update(JSON.stringify(rows)).digest("hex")]));
7816
7851
  checkMemoryReadBudget();
7817
7852
  return { sourceIds, relationshipRefs, digest: digest4, sources: sourceChecks, relationships: relationshipChecks };
7818
7853
  }
7819
7854
  provenanceSnapshot(scope, cutoff) {
7820
7855
  const stamp = this.provenanceStamp();
7821
- const key3 = JSON.stringify([scopeId(scope), cutoff ?? null]);
7822
- if (stamp !== this.snapshotStamp && this.snapshot?.key === key3 && !cutoff && this.snapshotBasis && this.readSnapshotDepth && this.snapshot.sources.size <= 8192) {
7856
+ const key4 = JSON.stringify([scopeId(scope), cutoff ?? null]);
7857
+ if (stamp !== this.snapshotStamp && this.snapshot?.key === key4 && !cutoff && this.snapshotBasis && this.readSnapshotDepth && this.snapshot.sources.size <= 8192) {
7823
7858
  const previous = this.snapshotBasis;
7824
7859
  const next = this.readProvenanceBasis(this.snapshot, previous.sourceIds, previous.relationshipRefs);
7825
7860
  if (next.digest !== previous.digest) {
@@ -7831,17 +7866,17 @@ CREATE TABLE memory_person_mentions (
7831
7866
  this.snapshot.metadata.delete(id);
7832
7867
  this.snapshot.currentSources.delete(id);
7833
7868
  }
7834
- for (const [key4, check] of previous.relationships) {
7835
- if (next.relationships.get(key4) !== check) this.snapshot.relationships.delete(key4);
7869
+ for (const [key5, check] of previous.relationships) {
7870
+ if (next.relationships.get(key5) !== check) this.snapshot.relationships.delete(key5);
7836
7871
  }
7837
7872
  }
7838
7873
  this.snapshotBasis = next;
7839
7874
  this.snapshotStamp = stamp;
7840
7875
  }
7841
- if (stamp !== this.snapshotStamp || this.snapshot?.key !== key3 || this.snapshot.sources.size > 8192 || this.snapshot.currentSources.size > 8192 || this.snapshot.relationships.size > 8192) {
7876
+ if (stamp !== this.snapshotStamp || this.snapshot?.key !== key4 || this.snapshot.sources.size > 8192 || this.snapshot.currentSources.size > 8192 || this.snapshot.relationships.size > 8192) {
7842
7877
  this.snapshotStamp = stamp;
7843
7878
  this.snapshotBasis = void 0;
7844
- 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() };
7879
+ this.snapshot = { key: key4, memo: /* @__PURE__ */ new Map(), grounds: /* @__PURE__ */ new Map(), currentSources: /* @__PURE__ */ new Map(), sources: /* @__PURE__ */ new Map(), metadata: /* @__PURE__ */ new Map(), relationships: /* @__PURE__ */ new Map() };
7845
7880
  }
7846
7881
  return this.snapshot;
7847
7882
  }
@@ -7972,21 +8007,21 @@ CREATE TABLE memory_person_mentions (
7972
8007
  provenanceReferenceRetained(scope, ref, visited, cutoff, snapshot) {
7973
8008
  checkMemoryReadBudget(visited.size);
7974
8009
  if (ref.scopeId !== scopeId(scope) || visited.has(ref.sourceId) || ref.relationshipId && visited.has(`${ref.relationshipId}:${ref.semanticVersion}`)) return false;
7975
- const key3 = `reference:${JSON.stringify([ref.sourceId, ref.sourceVersion, ref.relationshipId, ref.semanticVersion])}`;
7976
- if (snapshot.memo.has(key3)) return snapshot.memo.get(key3);
8010
+ const key4 = `reference:${JSON.stringify([ref.sourceId, ref.sourceVersion, ref.relationshipId, ref.semanticVersion])}`;
8011
+ if (snapshot.memo.has(key4)) return snapshot.memo.get(key4);
7977
8012
  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);
7978
- snapshot.memo.set(key3, retained);
8013
+ snapshot.memo.set(key4, retained);
7979
8014
  return retained;
7980
8015
  }
7981
8016
  /** Authored thoughts remain historical memories when a cited source is corrected; deletion still wins. */
7982
8017
  provenanceRetained(scope, sourceId, visited, cutoff, snapshot) {
7983
8018
  checkMemoryReadBudget(visited.size);
7984
8019
  if (visited.has(sourceId)) return false;
7985
- const key3 = `source:${sourceId}`;
8020
+ const key4 = `source:${sourceId}`;
7986
8021
  const { memo } = snapshot;
7987
- if (memo.has(key3)) return memo.get(key3);
8022
+ if (memo.has(key4)) return memo.get(key4);
7988
8023
  if (!this.provenanceSource(scope, sourceId, cutoff, snapshot) || this.tombstoneRead.get(scopeId(scope), sourceId)) {
7989
- memo.set(key3, false);
8024
+ memo.set(key4, false);
7990
8025
  return false;
7991
8026
  }
7992
8027
  if (!snapshot.metadata.has(sourceId)) snapshot.metadata.set(sourceId, this.metadata(scope, sourceId));
@@ -7995,7 +8030,7 @@ CREATE TABLE memory_person_mentions (
7995
8030
  try {
7996
8031
  const check = (ref) => this.provenanceReferenceRetained(scope, ref, visited, cutoff, snapshot);
7997
8032
  const retained = !metadata2 || metadata2.contextRefs.every(check) && metadata2.basisRefs.every(check);
7998
- memo.set(key3, retained);
8033
+ memo.set(key4, retained);
7999
8034
  return retained;
8000
8035
  } finally {
8001
8036
  visited.delete(sourceId);
@@ -8029,10 +8064,10 @@ CREATE TABLE memory_person_mentions (
8029
8064
  sourceGroundsCurrent(scope, sourceId, visited, cutoff, snapshot) {
8030
8065
  checkMemoryReadBudget(visited.size);
8031
8066
  if (visited.has(sourceId)) return false;
8032
- const key3 = `source:${sourceId}`;
8033
- if (snapshot.grounds.has(key3)) return snapshot.grounds.get(key3);
8067
+ const key4 = `source:${sourceId}`;
8068
+ if (snapshot.grounds.has(key4)) return snapshot.grounds.get(key4);
8034
8069
  if (!this.sourceCurrent(scope, sourceId, cutoff, snapshot) || !this.provenanceRetained(scope, sourceId, /* @__PURE__ */ new Set(), cutoff, snapshot)) {
8035
- snapshot.grounds.set(key3, false);
8070
+ snapshot.grounds.set(key4, false);
8036
8071
  return false;
8037
8072
  }
8038
8073
  if (!snapshot.metadata.has(sourceId)) snapshot.metadata.set(sourceId, this.metadata(scope, sourceId));
@@ -8040,7 +8075,7 @@ CREATE TABLE memory_person_mentions (
8040
8075
  visited.add(sourceId);
8041
8076
  try {
8042
8077
  const current2 = !metadata2 || metadata2.basisRefs.every((ref) => this.currentReference(scope, ref, visited, cutoff, snapshot));
8043
- snapshot.grounds.set(key3, current2);
8078
+ snapshot.grounds.set(key4, current2);
8044
8079
  return current2;
8045
8080
  } finally {
8046
8081
  visited.delete(sourceId);
@@ -8050,46 +8085,46 @@ CREATE TABLE memory_person_mentions (
8050
8085
  checkMemoryReadBudget(visited.size);
8051
8086
  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;
8052
8087
  if (!ref.relationshipId) return true;
8053
- const key3 = `${ref.relationshipId}:${ref.semanticVersion}`;
8054
- if (visited.has(key3)) return false;
8055
- const memoKey = `relationship:${key3}:${ref.purpose === "historical" ? "historical" : "current"}`;
8088
+ const key4 = `${ref.relationshipId}:${ref.semanticVersion}`;
8089
+ if (visited.has(key4)) return false;
8090
+ const memoKey = `relationship:${key4}:${ref.purpose === "historical" ? "historical" : "current"}`;
8056
8091
  if (snapshot.grounds.has(memoKey)) return snapshot.grounds.get(memoKey);
8057
- if (!snapshot.relationships.has(key3)) {
8092
+ if (!snapshot.relationships.has(key4)) {
8058
8093
  this.snapshotBasis = void 0;
8059
- snapshot.relationships.set(key3, this.relationshipReferenceMaterial(scope, ref, cutoff));
8094
+ snapshot.relationships.set(key4, this.relationshipReferenceMaterial(scope, ref, cutoff));
8060
8095
  }
8061
- const material = snapshot.relationships.get(key3);
8096
+ const material = snapshot.relationships.get(key4);
8062
8097
  if (!material || ["deleted", "retracted"].includes(material.state) || ref.purpose !== "historical" && !material.current) return false;
8063
- visited.add(key3);
8098
+ visited.add(key4);
8064
8099
  try {
8065
8100
  const current2 = material.evidenceSourceIds.every((id) => this.sourceGroundsCurrent(scope, id, visited, cutoff, snapshot)) && material.basisRefs.every((basis) => this.currentReference(scope, basis, visited, cutoff, snapshot));
8066
8101
  snapshot.grounds.set(memoKey, current2);
8067
8102
  return current2;
8068
8103
  } finally {
8069
- visited.delete(key3);
8104
+ visited.delete(key4);
8070
8105
  }
8071
8106
  }
8072
8107
  relationshipReferenceRetained(scope, ref, visited, cutoff, snapshot = this.provenanceSnapshot(scope, cutoff)) {
8073
8108
  checkMemoryReadBudget(visited.size);
8074
8109
  if (!ref.relationshipId) return true;
8075
- const key3 = `${ref.relationshipId}:${ref.semanticVersion}`;
8076
- if (visited.has(key3)) return false;
8077
- const memoKey = `relationship:${key3}`;
8110
+ const key4 = `${ref.relationshipId}:${ref.semanticVersion}`;
8111
+ if (visited.has(key4)) return false;
8112
+ const memoKey = `relationship:${key4}`;
8078
8113
  const { memo } = snapshot;
8079
8114
  if (memo.has(memoKey)) return memo.get(memoKey);
8080
- if (!snapshot.relationships.has(key3)) {
8115
+ if (!snapshot.relationships.has(key4)) {
8081
8116
  this.snapshotBasis = void 0;
8082
- snapshot.relationships.set(key3, this.relationshipReferenceMaterial(scope, ref, cutoff));
8117
+ snapshot.relationships.set(key4, this.relationshipReferenceMaterial(scope, ref, cutoff));
8083
8118
  }
8084
- const material = snapshot.relationships.get(key3);
8119
+ const material = snapshot.relationships.get(key4);
8085
8120
  if (!material) return false;
8086
- visited.add(key3);
8121
+ visited.add(key4);
8087
8122
  try {
8088
8123
  const retained = material.evidenceSourceIds.every((id) => this.provenanceRetained(scope, id, visited, cutoff, snapshot)) && material.basisRefs.every((basis) => this.provenanceReferenceRetained(scope, basis, visited, cutoff, snapshot));
8089
8124
  memo.set(memoKey, retained);
8090
8125
  return retained;
8091
8126
  } finally {
8092
- visited.delete(key3);
8127
+ visited.delete(key4);
8093
8128
  }
8094
8129
  }
8095
8130
  relationshipReferenceMaterial(scope, ref, cutoff) {
@@ -8536,16 +8571,16 @@ CREATE TABLE memory_relationship_receipts (
8536
8571
  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);
8537
8572
  if (!row) return null;
8538
8573
  if (historicalVersion) Object.assign(row, historicalVersion);
8539
- const key3 = `${relationshipId}:${row.semantic_version}`;
8540
- if (visited.has(key3)) return null;
8541
- const next = new Set(visited).add(key3);
8574
+ const key4 = `${relationshipId}:${row.semantic_version}`;
8575
+ if (visited.has(key4)) return null;
8576
+ const next = new Set(visited).add(key4);
8542
8577
  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 }));
8543
8578
  const basisRefs = JSON.parse(row.basis_refs);
8544
8579
  const refs = [...evidence.map((ref) => ({ sourceId: ref.sourceId })), ...basisRefs];
8545
8580
  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;
8546
8581
  const value = JSON.parse(row.value_json);
8547
8582
  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;
8548
- 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)) : refs.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));
8583
+ 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), key4)?.state)) : refs.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));
8549
8584
  return {
8550
8585
  relationshipId,
8551
8586
  semanticVersion: row.semantic_version,
@@ -8940,10 +8975,10 @@ CREATE TABLE memory_relationship_cognition_results (
8940
8975
  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)] : []);
8941
8976
  const groups = /* @__PURE__ */ new Map();
8942
8977
  for (const row of rows) {
8943
- const key3 = canonicalJson([row.scope_id, row.perspective_entity_id, row.group_key, row.generation]);
8944
- const group = groups.get(key3) || { scopeId: row.scope_id, perspectiveEntityId: row.perspective_entity_id, groupKey: row.group_key, sourceIds: [], generation: row.generation };
8978
+ const key4 = canonicalJson([row.scope_id, row.perspective_entity_id, row.group_key, row.generation]);
8979
+ const group = groups.get(key4) || { scopeId: row.scope_id, perspectiveEntityId: row.perspective_entity_id, groupKey: row.group_key, sourceIds: [], generation: row.generation };
8945
8980
  if (group.sourceIds.length < 20) group.sourceIds.push(row.source_id);
8946
- groups.set(key3, group);
8981
+ groups.set(key4, group);
8947
8982
  }
8948
8983
  return [...groups.values()];
8949
8984
  }
@@ -9133,9 +9168,9 @@ var init_entities = __esm({
9133
9168
  aliasEvidence(scope, entityId, cutoff) {
9134
9169
  const seen = /* @__PURE__ */ new Set();
9135
9170
  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) => {
9136
- const key3 = normalizeAlias(alias.alias);
9137
- 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;
9138
- seen.add(key3);
9171
+ const key4 = normalizeAlias(alias.alias);
9172
+ if (seen.has(key4) || 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;
9173
+ seen.add(key4);
9139
9174
  return true;
9140
9175
  }).map((alias) => ({ alias: alias.alias, sourceId: alias.sourceId, sourceVersion: this.sources.get(scope, alias.sourceId, cutoff).sourceVersion }));
9141
9176
  }
@@ -9334,12 +9369,12 @@ function checkNotice(db, sources, social, scope, id, options) {
9334
9369
  return Boolean(source && (version === void 0 || source.sourceVersion === version) && social.readable(memoryScope, sourceId) && social.groundsCurrent(memoryScope, sourceId));
9335
9370
  };
9336
9371
  const relationshipCurrent = (relationshipId, version) => {
9337
- const key3 = `${relationshipId}:${version}`;
9372
+ const key4 = `${relationshipId}:${version}`;
9338
9373
  const row = db.prepare(`SELECT r.*,v.state FROM memory_relationship_versions r JOIN fact_versions v
9339
9374
  ON v.scope_id=r.scope_id AND v.assertion_id=r.assertion_id AND v.system_to_revision IS NULL
9340
9375
  WHERE r.scope_id=? AND r.relationship_id=? AND r.semantic_version=?`).get(scope, relationshipId, version);
9341
9376
  if (!row || ["deleted", "retracted"].includes(row.state)) return false;
9342
- const derivation = db.prepare("SELECT state FROM memory_derivations WHERE scope_id=? AND child_kind='relationship' AND child_id=?").get(scope, key3);
9377
+ const derivation = db.prepare("SELECT state FROM memory_derivations WHERE scope_id=? AND child_kind='relationship' AND child_id=?").get(scope, key4);
9343
9378
  if (derivation && derivation.state !== "current") return false;
9344
9379
  const evidence = db.prepare("SELECT source_id FROM fact_evidence WHERE scope_id=? AND assertion_id=?").all(scope, row.assertion_id);
9345
9380
  return evidence.length > 0 && evidence.every((ref) => sourceCurrent(ref.source_id)) && JSON.parse(row.basis_refs).every((ref) => social.referenceCurrent(memoryScope, ref));
@@ -9414,8 +9449,11 @@ CREATE TABLE memory_relationship_notice_versions (
9414
9449
  }
9415
9450
  get(scope, id) {
9416
9451
  const row = this.db.prepare("SELECT * FROM memory_relationship_notices WHERE scope_id=? AND notice_id=?").get(scopeId(scope), id);
9417
- return row ? {
9418
- id,
9452
+ return row ? this.decode(scope, row) : null;
9453
+ }
9454
+ decode(scope, row) {
9455
+ return {
9456
+ id: row.notice_id,
9419
9457
  scope,
9420
9458
  kind: row.kind,
9421
9459
  targetId: row.target_id,
@@ -9425,10 +9463,25 @@ CREATE TABLE memory_relationship_notice_versions (
9425
9463
  state: row.state,
9426
9464
  attempts: row.attempts,
9427
9465
  reason: row.reason
9428
- } : null;
9466
+ };
9467
+ }
9468
+ list(scope, includeTerminal = true) {
9469
+ return this.db.prepare(`SELECT * FROM memory_relationship_notices WHERE scope_id=?
9470
+ ${includeTerminal ? "" : "AND state NOT IN ('delivered','blocked')"} ORDER BY updated_at,notice_id`).all(scopeId(scope)).map((row) => this.decode(scope, row));
9429
9471
  }
9430
- list(scope) {
9431
- 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));
9472
+ /** Quiet identity work is not notification work. Evidence-backed resolved identities can still be withdrawn. */
9473
+ clarificationCandidates(scope) {
9474
+ const rows = this.db.prepare(`SELECT m.mention_id,m.question,m.mention_kind,m.candidates,m.span_start,m.span_end,s.text
9475
+ FROM memory_person_mentions m JOIN memory_sources s ON s.scope_id=m.scope_id AND s.source_id=m.source_id
9476
+ WHERE m.scope_id=? AND m.question IS NOT NULL AND trim(m.question)<>''
9477
+ AND (m.state='unresolved' OR m.clarification_source_id IS NOT NULL OR m.basis_refs<>'[]')
9478
+ AND (m.mention_kind NOT IN ('description','reference') OR json_array_length(m.candidates)>=2)
9479
+ ORDER BY m.source_id,m.span_start`).all(scopeId(scope));
9480
+ return rows.filter((row) => hasIdentityQuestion(
9481
+ row.question,
9482
+ row.text.slice(row.span_start, row.span_end),
9483
+ { mentionKind: row.mention_kind, candidateEntityIds: JSON.parse(row.candidates) }
9484
+ )).map((row) => row.mention_id);
9432
9485
  }
9433
9486
  finish(scope, id, state, reason = "", redact = false) {
9434
9487
  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(state, reason, (/* @__PURE__ */ new Date()).toISOString(), Number(redact), scopeId(scope), id);
@@ -9439,6 +9492,12 @@ CREATE TABLE memory_relationship_notice_versions (
9439
9492
  check(scope, id, options = {}) {
9440
9493
  return checkRelationshipNotice(this.db, scopeId(scope), id, options);
9441
9494
  }
9495
+ /** The caller holds one transaction; proofs are discarded before any later batch or write. */
9496
+ checkMany(scope, ids, options = {}) {
9497
+ if (!ids.length) return [];
9498
+ const check = createRelationshipNoticeChecker(this.db);
9499
+ return ids.map((id) => check(scopeId(scope), id, options));
9500
+ }
9442
9501
  queue(scope, id) {
9443
9502
  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), id).changes);
9444
9503
  }
@@ -9450,6 +9509,7 @@ CREATE TABLE memory_relationship_notice_versions (
9450
9509
  importantRecords(scope) {
9451
9510
  return this.db.prepare(`SELECT v.relationship_id,v.semantic_version FROM memory_relationship_notice_versions v
9452
9511
  JOIN memory_relationship_cognition_results r ON r.scope_id=v.scope_id AND r.job_id=v.job_id
9512
+ 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
9453
9513
  WHERE v.scope_id=? AND r.important=1`).all(scopeId(scope)).map((row) => ({ relationshipId: row.relationship_id, semanticVersion: row.semantic_version }));
9454
9514
  }
9455
9515
  recordRoute(scope, sourceId, input) {
@@ -9517,9 +9577,9 @@ function installRelationshipHistory(db) {
9517
9577
  FROM memory_scopes s WHERE EXISTS (SELECT 1 FROM memory_relationship_heads h WHERE h.scope_id=s.scope_id)
9518
9578
  OR EXISTS (SELECT 1 FROM memory_person_sources p WHERE p.scope_id=s.scope_id)
9519
9579
  OR EXISTS (SELECT 1 FROM memory_person_mentions m WHERE m.scope_id=s.scope_id)`);
9520
- for (const { table, kind, key: key3, columns: columns2 } of tables) {
9580
+ for (const { table, kind, key: key4, columns: columns2 } of tables) {
9521
9581
  const payload = (prefix) => `json_object(${columns2.map((column) => `'${column}',${prefix}${column}`).join(",")})`;
9522
- const target = (prefix) => key3.startsWith("json_array") ? `json_array(${key3.slice(11, -1).split(",").map((column) => `${prefix}${column}`).join(",")})` : `${prefix}${key3}`;
9582
+ const target = (prefix) => key4.startsWith("json_array") ? `json_array(${key4.slice(11, -1).split(",").map((column) => `${prefix}${column}`).join(",")})` : `${prefix}${key4}`;
9523
9583
  db.exec(`INSERT INTO memory_knowledge_history(scope_id,target_kind,target_id,entity_revision,fact_revision,context_revision,recorded_at,payload_json)
9524
9584
  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.")}
9525
9585
  FROM ${table} t JOIN memory_scopes s ON s.scope_id=t.scope_id`);
@@ -9948,16 +10008,16 @@ var init_snapshot_reads = __esm({
9948
10008
  this.changes = -1;
9949
10009
  }
9950
10010
  }
9951
- read(key3, load) {
10011
+ read(key4, load) {
9952
10012
  if (!this.values || !this.db.isTransaction) return load();
9953
10013
  const changes = this.changesRead.get().n;
9954
10014
  if (changes !== this.changes) {
9955
10015
  this.values.clear();
9956
10016
  this.changes = changes;
9957
10017
  }
9958
- if (this.values.has(key3)) return this.values.get(key3);
10018
+ if (this.values.has(key4)) return this.values.get(key4);
9959
10019
  const value = load();
9960
- if (this.values.size < 8192) this.values.set(key3, value);
10020
+ if (this.values.size < 8192) this.values.set(key4, value);
9961
10021
  return value;
9962
10022
  }
9963
10023
  };
@@ -10083,7 +10143,7 @@ function classifyFactVersions(versions, predicate, time) {
10083
10143
  needsReview: disputed || hypotheses.some((fact) => fact.validFrom === null)
10084
10144
  };
10085
10145
  }
10086
- var hash5, makeSlotId, FactStore;
10146
+ var hash5, makeSlotId, CLOSE_VALIDITY, occurrences, CHANGE_KINDS, CLAIM_KINDS, normalizeChange, FactStore;
10087
10147
  var init_facts = __esm({
10088
10148
  "src/mem7/core/state/facts.ts"() {
10089
10149
  "use strict";
@@ -10095,6 +10155,15 @@ var init_facts = __esm({
10095
10155
  init_basis_check();
10096
10156
  hash5 = (value) => createHash17("sha256").update(canonicalJson(value)).digest("hex");
10097
10157
  makeSlotId = (subjectId, predicate, context) => `slot_${hash5([subjectId, predicate, context]).slice(0, 32)}`;
10158
+ CLOSE_VALIDITY = '{"validFrom":null,"validTo":"\u7ED3\u675F\u65F6\u523B","precision":"exact"}';
10159
+ occurrences = (text2, quote2) => {
10160
+ let count = 0;
10161
+ for (let at = text2.indexOf(quote2); quote2 && at >= 0; at = text2.indexOf(quote2, at + 1)) count++;
10162
+ return count;
10163
+ };
10164
+ CHANGE_KINDS = ["assert", "reinforce", "state_change", "correction", "exception", "dispute", "retract", "close"];
10165
+ CLAIM_KINDS = ["user_statement", "tool_observation", "reported_statement", "inference", "agent_statement"];
10166
+ normalizeChange = (proposal) => !["close", "retract"].includes(proposal.changeKind) || !proposal.validity || proposal.validity.validFrom !== void 0 ? proposal : { ...proposal, validity: { ...proposal.validity, validFrom: null } };
10098
10167
  FactStore = class {
10099
10168
  constructor(db, entities, transaction, readTransaction = transaction) {
10100
10169
  this.db = db;
@@ -10261,6 +10330,8 @@ var init_facts = __esm({
10261
10330
  applyChange(scope, proposal, expectedSlotRevision, requestKey, batch) {
10262
10331
  if (!requestKey || !Number.isSafeInteger(expectedSlotRevision) || expectedSlotRevision < 0) throw new Error("INVALID_FACT_REQUEST");
10263
10332
  const id = scopeId(scope);
10333
+ const located = this.locateEvidence(id, normalizeChange(proposal));
10334
+ proposal = located.proposal;
10264
10335
  const requestHash = hash5([proposal, expectedSlotRevision]);
10265
10336
  const prior = this.db.prepare("SELECT request_hash,result_json FROM fact_changes WHERE scope_id=? AND request_key=?").get(id, requestKey);
10266
10337
  if (prior) {
@@ -10269,21 +10340,22 @@ var init_facts = __esm({
10269
10340
  }
10270
10341
  this.validate(scope, proposal);
10271
10342
  const slot = this.slot(scope, proposal.subjectId, proposal.predicate, proposal.contextKey);
10272
- if (slot.revision !== expectedSlotRevision) throw new Error(`STALE_VERSION: expected slot ${expectedSlotRevision}, current ${slot.revision}`);
10343
+ 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` : ""));
10273
10344
  this.db.prepare("INSERT OR IGNORE INTO fact_slots(scope_id,slot_id,subject_id,predicate,context_key,cardinality) VALUES (?,?,?,?,?,?)").run(id, slot.slotId, proposal.subjectId, proposal.predicate, proposal.contextKey, predicates[proposal.predicate].cardinality);
10274
10345
  const before = this.current(id, slot.slotId);
10275
10346
  const targetIds = [...new Set(proposal.targetAssertionIds ?? [])];
10276
10347
  const targets = targetIds.map((targetId) => {
10277
10348
  const target = before.find((fact) => fact.assertionId === targetId);
10278
- if (!target || ["retracted", "deleted"].includes(target.state)) throw new Error("FACT_TARGET_MISMATCH");
10349
+ 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`);
10279
10350
  return target;
10280
10351
  });
10281
- if (["reinforce", "state_change", "correction", "retract", "close"].includes(proposal.changeKind) && targets.length === 0) throw new Error("FACT_TARGET_REQUIRED");
10352
+ 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`);
10282
10353
  if (proposal.changeKind === "reinforce" && targets.length !== 1) throw new Error("REINFORCE_REQUIRES_ONE_TARGET");
10283
10354
  if (["assert", "exception"].includes(proposal.changeKind) && targets.length) throw new Error("UNEXPECTED_FACT_TARGET");
10284
10355
  const validity = proposal.validity ? normalizeValidity(proposal.validity) : void 0;
10285
- if (proposal.changeKind === "state_change" && (validity?.validFrom == null || validity.precision !== "exact")) throw new Error("CHANGE_TIME_REQUIRED");
10286
- if (proposal.changeKind === "close" && (validity?.validTo == null || validity.validFrom !== null || validity.precision === "unknown")) throw new Error("CHANGE_TIME_REQUIRED");
10356
+ const received2 = JSON.stringify({ validFrom: proposal.validity?.validFrom, validTo: proposal.validity?.validTo, precision: proposal.validity?.precision });
10357
+ 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"`);
10358
+ 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}`);
10287
10359
  if (proposal.changeKind === "reinforce" && (canonicalJson(proposal.value) !== canonicalJson(targets[0].value) || proposal.claimKind !== targets[0].claimKind)) throw new Error("REINFORCE_VALUE_MISMATCH");
10288
10360
  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");
10289
10361
  const timestamp = batch?.timestamp ?? (/* @__PURE__ */ new Date()).toISOString();
@@ -10299,8 +10371,8 @@ var init_facts = __esm({
10299
10371
  let state = proposal.changeKind === "correction" || proposal.changeKind === "retract" ? "retracted" : "disputed";
10300
10372
  if (proposal.changeKind === "state_change" || proposal.changeKind === "close") {
10301
10373
  const end = proposal.changeKind === "close" ? validity.validTo : validity.validFrom;
10302
- if (target.validFrom !== null && target.validFrom >= end) throw new Error("CHANGE_BEFORE_TARGET_START: use correction");
10303
- if (target.validTo !== null && target.validTo <= end) throw new Error("CHANGE_AFTER_TARGET_END");
10374
+ 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`);
10375
+ 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`);
10304
10376
  state = target.state;
10305
10377
  nextValidity = { ...target, validTo: end };
10306
10378
  }
@@ -10316,7 +10388,7 @@ var init_facts = __esm({
10316
10388
  }
10317
10389
  if (!["retract", "close"].includes(proposal.changeKind)) {
10318
10390
  let state = proposal.claimKind === "inference" ? "candidate" : proposal.changeKind === "dispute" ? "disputed" : "supported";
10319
- if (state === "supported" && !proposal.evidence.some((evidence) => evidence.relation === "supports")) throw new Error("SUPPORTING_EVIDENCE_REQUIRED");
10391
+ if (state === "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");
10320
10392
  const current2 = this.current(id, slot.slotId);
10321
10393
  if (predicates[proposal.predicate].cardinality === "single" && state === "supported" && current2.some((fact) => ["supported", "disputed"].includes(fact.state) && overlaps(fact, validity))) throw new Error("FACT_INTERVAL_CONFLICT: explicit correction/change/dispute required");
10322
10394
  if (state === "supported" && validity.validFrom === null && !(proposal.predicate === "relation.open" && proposal.value.observedAsCurrentAt)) state = "candidate";
@@ -10348,7 +10420,8 @@ var init_facts = __esm({
10348
10420
  slotId: slot.slotId,
10349
10421
  slotRevision: slot.revision + Number(changed),
10350
10422
  assertionIds: changedIds,
10351
- outcome: !changed ? "no_change" : after.some((fact) => ["candidate", "disputed"].includes(fact.state) && (!isRelationship(proposal.predicate) || changedIds.includes(fact.assertionId))) ? "needs_review" : "applied"
10423
+ outcome: !changed ? "no_change" : after.some((fact) => ["candidate", "disputed"].includes(fact.state) && (!isRelationship(proposal.predicate) || changedIds.includes(fact.assertionId))) ? "needs_review" : "applied",
10424
+ ...located.aligned.length ? { evidenceAligned: located.aligned } : {}
10352
10425
  };
10353
10426
  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(id, requestKey, requestHash, committedRevision, canonicalJson(result), canonicalJson(proposal), canonicalJson(before), canonicalJson(after), timestamp);
10354
10427
  if (changed) {
@@ -10387,21 +10460,31 @@ var init_facts = __esm({
10387
10460
  });
10388
10461
  }
10389
10462
  validate(scope, proposal) {
10390
- if (!Object.hasOwn(predicates, proposal.predicate)) throw new Error("UNKNOWN_PREDICATE");
10391
- 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");
10392
- if (proposal.claimKind === "inference" && (proposal.changeKind !== "assert" || proposal.targetAssertionIds?.length)) throw new Error("INFERENCE_CANNOT_REVISE_SUPPORTED_FACT");
10463
+ 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`);
10464
+ const invalid = [
10465
+ !CHANGE_KINDS.includes(proposal.changeKind) && "changeKind",
10466
+ !CLAIM_KINDS.includes(proposal.claimKind) && "claimKind",
10467
+ !proposal.contextKey && "contextKey",
10468
+ !proposal.reason && "reason",
10469
+ (!Array.isArray(proposal.evidence) || !proposal.evidence.length) && "evidence"
10470
+ ].filter(Boolean);
10471
+ 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`);
10472
+ 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");
10393
10473
  const subject = this.entities.get(scope, proposal.subjectId);
10394
- if (!subject || !matchesEntityKind(subject.kind, predicates[proposal.predicate].subjectKind)) throw new Error("ENTITY_SCOPE_MISMATCH");
10474
+ const subjectKind = predicates[proposal.predicate].subjectKind;
10475
+ 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}`);
10395
10476
  if (proposal.predicate === "relation.family" && !familyRoles.includes(proposal.contextKey)) throw new Error("INVALID_FAMILY_ROLE");
10396
10477
  if (proposal.predicate === "relation.colleague" && (proposal.contextKey !== normalizeOrganization(proposal.contextKey) || proposal.contextKey.length > 200)) throw new Error("INVALID_ORGANIZATION_CONTEXT");
10397
10478
  if (proposal.changeKind === "close") {
10398
- if (!isRelationship(proposal.predicate) || proposal.value !== void 0) throw new Error("INVALID_RELATION_CLOSE");
10399
- if (!proposal.validity) throw new Error("FACT_VALIDITY_REQUIRED");
10479
+ 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`);
10480
+ 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");
10481
+ if (!proposal.validity) throw new Error(`FACT_VALIDITY_REQUIRED: proposal.validity \u5FC5\u586B \u2014 close \u7528 ${CLOSE_VALIDITY}`);
10400
10482
  normalizeValidity(proposal.validity);
10401
10483
  }
10402
10484
  if (!["retract", "close"].includes(proposal.changeKind)) {
10485
+ 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`);
10403
10486
  validatePredicateValue(proposal.predicate, proposal.value);
10404
- if (!proposal.validity) throw new Error("FACT_VALIDITY_REQUIRED");
10487
+ 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"}');
10405
10488
  normalizeValidity(proposal.validity);
10406
10489
  const objectKind = predicates[proposal.predicate].objectKind;
10407
10490
  if (objectKind && !matchesEntityKind(this.entities.get(scope, proposal.value.entityId)?.kind, objectKind)) throw new Error("OBJECT_SCOPE_MISMATCH");
@@ -10416,7 +10499,7 @@ var init_facts = __esm({
10416
10499
  const targets = (proposal.targetAssertionIds ?? []).map((assertionId) => this.db.prepare(`SELECT a.claim_kind,a.value_json,s.subject_id
10417
10500
  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));
10418
10501
  const perspective = value?.relationshipId ? this.entities.get(scope, value.perspectiveEntityId) : subject;
10419
- if (proposal.predicate !== "relation.open" || perspective?.kind !== "agent" || !["close", "retract"].includes(proposal.changeKind) && value?.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");
10502
+ if (proposal.predicate !== "relation.open" || perspective?.kind !== "agent" || !["close", "retract"].includes(proposal.changeKind) && value?.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");
10420
10503
  }
10421
10504
  if (proposal.predicate === "activity.schedule" && proposal.changeKind !== "retract") {
10422
10505
  const schedule = proposal.value;
@@ -10424,26 +10507,53 @@ var init_facts = __esm({
10424
10507
  if (proposal.contextKey !== "baseline" && !exception) throw new Error("INVALID_SCHEDULE_CONTEXT");
10425
10508
  if ((exception || proposal.changeKind === "exception") && (!exception || schedule.frequency !== "once")) throw new Error("OCCURRENCE_EXCEPTION_REQUIRED");
10426
10509
  }
10427
- for (const evidence of proposal.evidence) {
10510
+ for (const [index, evidence] of proposal.evidence.entries()) {
10511
+ const path2 = `evidence[${index}]`;
10512
+ if (!evidence || typeof evidence !== "object") throw new Error(`INVALID_EVIDENCE_SPAN: ${path2} \u2014 \u6BCF\u6761\u8BC1\u636E\u987B\u662F\u5BF9\u8C61 {sourceId, quote, relation}`);
10428
10513
  const source = this.db.prepare(`SELECT text,role,origin_class,interpretation_status FROM memory_sources s WHERE scope_id=? AND source_id=?
10429
10514
  AND NOT EXISTS (SELECT 1 FROM memory_sources newer WHERE newer.scope_id=s.scope_id
10430
- AND newer.origin_key=s.origin_key AND newer.source_version>s.source_version)`).get(scopeId(scope), evidence.sourceId);
10431
- 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");
10515
+ AND newer.origin_key=s.origin_key AND newer.source_version>s.source_version)`).get(scopeId(scope), evidence.sourceId ?? null);
10516
+ if (!source || source.interpretation_status === "deleted") throw new Error(`INVALID_EVIDENCE_SPAN: ${path2}.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`);
10517
+ if (typeof evidence.quote !== "string" || !evidence.quote) throw new Error(`INVALID_EVIDENCE_SPAN: ${path2}.quote \u2014 quote \u5FC5\u586B\uFF0C\u9010\u5B57\u51FA\u81EA\u6765\u6E90\u539F\u6587`);
10518
+ 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) {
10519
+ const count = occurrences(source.text, evidence.quote);
10520
+ throw new Error(count === 0 ? `INVALID_EVIDENCE_SPAN: ${path2}.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: ${path2} \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`);
10521
+ }
10522
+ if (!["supports", "refutes"].includes(evidence.relation)) throw new Error(`INVALID_EVIDENCE_SPAN: ${path2}.relation \u2014 \u53EA\u80FD\u662F supports\uFF08\u652F\u6301\uFF09\u6216 refutes\uFF08\u53CD\u9A73\uFF09`);
10432
10523
  const relationValue = proposal.value;
10433
10524
  if (proposal.predicate === "relation.open" && relationValue?.attribution === "reported" && (proposal.claimKind !== "reported_statement" || !hasReportedAttribution(source.text, relationValue, this.entities.sourceMentions(scope, evidence.sourceId)))) {
10434
- throw new Error("EVIDENCE_REPORTED_ATTRIBUTION_UNGROUNDED");
10525
+ 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");
10435
10526
  }
10527
+ const roleMismatch = () => new Error(`EVIDENCE_ROLE_MISMATCH: ${path2} \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`);
10436
10528
  if (proposal.claimKind !== "inference") {
10437
- if (proposal.claimKind === "user_statement" && (source.role !== "user" || !["host_user", "client_reported_user"].includes(source.origin_class))) throw new Error("EVIDENCE_ROLE_MISMATCH");
10438
- if (proposal.claimKind === "tool_observation" && (source.role !== "tool" || source.origin_class !== "tool_observation")) throw new Error("EVIDENCE_ROLE_MISMATCH");
10529
+ if (proposal.claimKind === "user_statement" && (source.role !== "user" || !["host_user", "client_reported_user"].includes(source.origin_class))) throw roleMismatch();
10530
+ if (proposal.claimKind === "tool_observation" && (source.role !== "tool" || source.origin_class !== "tool_observation")) throw roleMismatch();
10439
10531
  if (proposal.claimKind === "reported_statement" && (source.role !== "user" || !["third_party_report", "legacy_import"].includes(source.origin_class))) {
10440
10532
  const value = proposal.value;
10441
10533
  const attributed = proposal.predicate === "relation.open" && value?.attribution === "reported" && ["user", "assistant"].includes(source.role) && ["host_user", "client_reported_user", "assistant"].includes(source.origin_class) && hasReportedAttribution(source.text, value, this.entities.sourceMentions(scope, evidence.sourceId));
10442
- if (!attributed) throw new Error("EVIDENCE_ROLE_MISMATCH");
10534
+ if (!attributed) throw roleMismatch();
10443
10535
  }
10444
- 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");
10445
- }
10446
- }
10536
+ 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();
10537
+ }
10538
+ }
10539
+ }
10540
+ /** 1124:UTF-16 下标不是人能数准的——引文在原文中只出现一次时,start/end 可省略或写错,由引擎对齐;没有或重复的留给 validate() 说明。 */
10541
+ locateEvidence(scope, proposal) {
10542
+ const aligned = [];
10543
+ if (!Array.isArray(proposal.evidence)) return { proposal, aligned };
10544
+ const evidence = proposal.evidence.map((ref, index) => {
10545
+ const text2 = this.db.prepare("SELECT text FROM memory_sources WHERE scope_id=? AND source_id=?").get(scope, ref?.sourceId ?? null)?.text;
10546
+ if (typeof text2 !== "string" || typeof ref?.quote !== "string" || !ref.quote || occurrences(text2, ref.quote) !== 1) return ref;
10547
+ const start = text2.indexOf(ref.quote);
10548
+ if (Number.isSafeInteger(ref.start) && ref.start === start && ref.end === start + ref.quote.length) return ref;
10549
+ aligned.push({
10550
+ index,
10551
+ given: [Number.isSafeInteger(ref.start) ? ref.start : null, Number.isSafeInteger(ref.end) ? ref.end : null],
10552
+ located: [start, start + ref.quote.length]
10553
+ });
10554
+ return { ...ref, start, end: start + ref.quote.length };
10555
+ });
10556
+ return { proposal: { ...proposal, evidence }, aligned };
10447
10557
  }
10448
10558
  current(scope, slotId) {
10449
10559
  return this.versions(scope, slotId);
@@ -10586,7 +10696,7 @@ function summary(input) {
10586
10696
  try {
10587
10697
  const p = JSON.parse(input);
10588
10698
  if (!p || typeof p !== "object" || Array.isArray(p)) return input;
10589
- const small = Object.fromEntries(Object.entries(p).filter(([key3, value]) => routing.has(key3) || Buffer.byteLength(JSON.stringify(value)) <= 1024));
10699
+ const small = Object.fromEntries(Object.entries(p).filter(([key4, value]) => routing.has(key4) || Buffer.byteLength(JSON.stringify(value)) <= 1024));
10590
10700
  if (!Object.hasOwn(small, "basis") && p.basis?.scope) small.basis = { scope: p.basis.scope };
10591
10701
  return JSON.stringify(small);
10592
10702
  } catch {
@@ -12139,10 +12249,10 @@ ${e.outcome}
12139
12249
  ];
12140
12250
  if (revalidationKinds.length === 0) return 0;
12141
12251
  for (const scope of this.sources.scopes()) {
12142
- const received = this.sources.interpretationProgress(scope).received;
12252
+ const received2 = this.sources.interpretationProgress(scope).received;
12143
12253
  for (const artifact of this.dependencies.dirty(scope)) {
12144
12254
  if (!revalidationKinds.includes(artifact.kind)) continue;
12145
- if (received > 0 && !(artifact.updatedAt !== null && Date.now() - artifact.updatedAt >= STALE_ARTIFACT_FORCE_MS)) continue;
12255
+ if (received2 > 0 && !(artifact.updatedAt !== null && Date.now() - artifact.updatedAt >= STALE_ARTIFACT_FORCE_MS)) continue;
12146
12256
  const previous = this.db.prepare("SELECT kind,payload FROM ome_jobs WHERE id=?").all(artifactGenerationJobId(this.db, scope, artifact.kind, artifact.id, artifact.version));
12147
12257
  for (const row of previous) {
12148
12258
  const payload = JSON.parse(row.payload);
@@ -12518,11 +12628,11 @@ var init_cross_encoder = __esm({
12518
12628
 
12519
12629
  // src/mem7/search.ts
12520
12630
  function getReadStore(stateDir, knowledgeClock, options = {}) {
12521
- const key3 = options.readOnly ? JSON.stringify(["read-only", stateDir]) : stateDir;
12522
- let s = readStores.get(key3);
12631
+ const key4 = options.readOnly ? JSON.stringify(["read-only", stateDir]) : stateDir;
12632
+ let s = readStores.get(key4);
12523
12633
  if (!s) {
12524
12634
  s = new Mem7Store(stateDir, knowledgeClock, { busyTimeoutMs: 5e3, readOnly: options.readOnly });
12525
- readStores.set(key3, s);
12635
+ readStores.set(key4, s);
12526
12636
  }
12527
12637
  return s;
12528
12638
  }
@@ -13358,9 +13468,9 @@ function readSecretsEntries(stateDir, configName) {
13358
13468
  function loadSecretsEnv(stateDir, configName, options = {}) {
13359
13469
  const selected = readSecretsEntries(stateDir, configName);
13360
13470
  if (!selected) return null;
13361
- for (const [key3, value] of selected.entries) {
13362
- const current2 = process.env[key3];
13363
- if (options.overwrite || current2 === void 0 || current2 === "") process.env[key3] = value;
13471
+ for (const [key4, value] of selected.entries) {
13472
+ const current2 = process.env[key4];
13473
+ if (options.overwrite || current2 === void 0 || current2 === "") process.env[key4] = value;
13364
13474
  }
13365
13475
  return selected.path;
13366
13476
  }
@@ -15652,8 +15762,8 @@ function cleanSchemaForGemini(schema) {
15652
15762
  const { additionalProperties, $schema, ...rest } = schema;
15653
15763
  if (rest.properties) {
15654
15764
  rest.properties = {};
15655
- for (const [key3, val] of Object.entries(schema.properties)) {
15656
- rest.properties[key3] = cleanSchemaForGemini(val);
15765
+ for (const [key4, val] of Object.entries(schema.properties)) {
15766
+ rest.properties[key4] = cleanSchemaForGemini(val);
15657
15767
  }
15658
15768
  }
15659
15769
  if (rest.items) {
@@ -15737,6 +15847,11 @@ function createProvider(config) {
15737
15847
  }
15738
15848
  }
15739
15849
 
15850
+ // src/auth/client.ts
15851
+ var DEFAULT_AUTH_BROKER = "https://auth.engine7.ai/auth/";
15852
+ var LEGACY_AUTH_BROKERS = ["https://www.twinsun.top/auth/"];
15853
+ var OFFICIAL_AUTH_BROKERS = /* @__PURE__ */ new Set([DEFAULT_AUTH_BROKER, ...LEGACY_AUTH_BROKERS]);
15854
+
15740
15855
  // src/config/features.ts
15741
15856
  init_live();
15742
15857