engine7 7.1.143 → 7.1.145

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -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) {
@@ -766,7 +766,7 @@ var init_dates = __esm({
766
766
  init_clock();
767
767
  pad = (n) => n.padStart(2, "0");
768
768
  LEGACY_TOPIC_YEAR = 2026;
769
- TOPIC_DATE_RULES_VERSION = 4;
769
+ TOPIC_DATE_RULES_VERSION = 6;
770
770
  }
771
771
  });
772
772
 
@@ -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;
@@ -1001,17 +1001,27 @@ function mem7StartDate(b) {
1001
1001
  }
1002
1002
  function topicBeforeMem7(text2, sourcePath, before, start = 0, end = text2.length) {
1003
1003
  if (!before) return true;
1004
- const events = historicalTopicDates(text2, start, end).map((date2) => date2.value).filter((date2) => !!date2 && validTopicDate(date2));
1005
- if (events.length) return events.some((date2) => date2 < before);
1006
1004
  const metadata2 = /^\uFEFF?---\r?\n([\s\S]*?)\r?\n---/.exec(text2)?.[1] ?? "";
1007
1005
  const kindRecorded = /^date_kind:\s*recorded/m.test(metadata2);
1006
+ const normalize5 = (raw2) => raw2 && /^\d{1,2}-\d{1,2}$/.test(raw2) ? `${LEGACY_TOPIC_YEAR}-${raw2.split("-").map((part) => part.padStart(2, "0")).join("-")}` : raw2;
1007
+ const events = historicalTopicDates(text2, start, end).map((date2) => date2.value).filter((date2) => !!date2 && validTopicDate(date2));
1008
+ if (events.length) {
1009
+ if (events.some((date2) => date2 < before)) return true;
1010
+ if (start === 0 && end >= text2.length && !kindRecorded) {
1011
+ const fm = normalize5(/^date:\s*['"]?([\d/-]+)/m.exec(metadata2)?.[1]?.replace(/\//g, "-"));
1012
+ if (fm && validTopicDate(fm) && fm < before) return true;
1013
+ }
1014
+ return false;
1015
+ }
1008
1016
  if (/^legacy_undated:[ \t]*true[ \t]*$/m.test(metadata2)) return true;
1009
1017
  const timestamp = topicRecordingTime(metadata2);
1010
1018
  const recordedAt = timestamp ? validTopicDate(timestamp) ? timestamp : todayKey(timestamp) : void 0;
1011
1019
  const raw = kindRecorded && recordedAt ? recordedAt : !kindRecorded ? /^date:\s*['"]?([\d/-]+)/m.exec(metadata2)?.[1]?.replace(/\//g, "-") : void 0;
1012
- const recorded = raw && /^\d{1,2}-\d{1,2}$/.test(raw) ? `${LEGACY_TOPIC_YEAR}-${raw.split("-").map((part) => part.padStart(2, "0")).join("-")}` : raw;
1020
+ const recorded = normalize5(raw);
1013
1021
  const filename = /(?<!\d)\d{4}-\d{2}-\d{2}(?!\d)/.exec(sourcePath)?.[0];
1014
- const date = recorded && validTopicDate(recorded) ? recorded : filename && validTopicDate(filename) ? filename : void 0;
1022
+ const recordedDate = recorded && validTopicDate(recorded) ? recorded : void 0;
1023
+ const filenameDate = filename && validTopicDate(filename) ? filename : void 0;
1024
+ const date = filenameDate && (!recordedDate || filenameDate < recordedDate) ? filenameDate : recordedDate;
1015
1025
  return !date || date < before;
1016
1026
  }
1017
1027
  var starts;
@@ -1686,15 +1696,15 @@ var init_sqlite_replication = __esm({
1686
1696
  requireForeignKeys(this.db);
1687
1697
  if (captureGuardHash(this.db) !== this.guardHash) throw new Error("REPLICATION_GUARD_MISMATCH");
1688
1698
  if (sqliteReplicationSchemaHash(this.db) !== this.schemaHash) throw new Error("REPLICATION_SCHEMA_MISMATCH");
1689
- const before = sequences(this.db, this.excludedTables), sessions = [];
1699
+ const before = sequences(this.db, this.excludedTables), sessions2 = [];
1690
1700
  try {
1691
- if (this.sessionTables) for (const table of this.sessionTables) sessions.push(this.db.createSession({ table }));
1692
- 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());
1693
1703
  } catch (error) {
1694
- for (const session of sessions) session.close();
1704
+ for (const session of sessions2) session.close();
1695
1705
  throw error;
1696
1706
  }
1697
- this.active = { sessions, sequences: before, closed: false };
1707
+ this.active = { sessions: sessions2, sequences: before, closed: false };
1698
1708
  return this.active;
1699
1709
  }
1700
1710
  appendCapture(capture) {
@@ -1802,15 +1812,15 @@ import { basename as basename4, dirname as dirname4, join as join6, resolve as r
1802
1812
  function isReplicationFailure(error) {
1803
1813
  return error instanceof Error && /^(?:REPLICATION_|TRAVEL_|CHECKPOINT_BUSY)/.test(error.message);
1804
1814
  }
1805
- function checkKey(component, key3) {
1806
- if (component === "topics-vectors" && typeof key3 === "string" && /^[a-f0-9]{64}$/.test(key3)) return;
1807
- 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;
1808
- 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;
1809
1819
  throw new Error("REPLICATION_REGISTRATION_INVALID");
1810
1820
  }
1811
- function location(stateDir, component, key3) {
1812
- checkKey(component, key3);
1813
- 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");
1814
1824
  }
1815
1825
  function normalize2(input) {
1816
1826
  if (!input || !/^[a-f0-9]{64}$/.test(input.schemaHash)) throw new Error("REPLICATION_REGISTRATION_INVALID");
@@ -1821,8 +1831,8 @@ function directory(path2) {
1821
1831
  if (!info.isDirectory() || info.isSymbolicLink() || realpathSync(path2) !== resolve4(path2) || process.platform !== "win32" && (info.mode & 63 || info.uid !== process.getuid()))
1822
1832
  throw new Error("REPLICATION_REGISTRATION_INVALID");
1823
1833
  }
1824
- function readRuntimeReplicationRegistration(stateDir, component, key3) {
1825
- const file = location(stateDir, component, key3);
1834
+ function readRuntimeReplicationRegistration(stateDir, component, key4) {
1835
+ const file = location(stateDir, component, key4);
1826
1836
  try {
1827
1837
  lstatSync3(dirname4(file));
1828
1838
  } catch (error) {
@@ -1885,8 +1895,8 @@ function checkRuntimeReplicationDatabase(db, registration, component, version, r
1885
1895
  }
1886
1896
  return requested ?? registration?.binding;
1887
1897
  }
1888
- function enrollRuntimeReplication(db, stateDir, component, binding2, key3) {
1889
- 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);
1890
1900
  const version = readSchemaVersion(db);
1891
1901
  if (version?.component !== component) throw new Error("REPLICATION_SCHEMA_MISMATCH");
1892
1902
  checkRuntimeReplicationDatabase(db, old, component, version.version, binding2);
@@ -1899,7 +1909,7 @@ function enrollRuntimeReplication(db, stateDir, component, binding2, key3) {
1899
1909
  writeFileSync5(file, JSON.stringify(input), { mode: 384, flag: "wx", flush: true });
1900
1910
  } catch (error) {
1901
1911
  if (error.code !== "EEXIST") throw error;
1902
- 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");
1903
1913
  }
1904
1914
  if (process.platform !== "win32") {
1905
1915
  const fd = openSync2(dirname4(file), "r");
@@ -2463,8 +2473,8 @@ async function historyRoot(b, strict = false) {
2463
2473
  }
2464
2474
  }
2465
2475
  async function openTopicsVectorStore(b, options = {}) {
2466
- const key3 = digest(canonical(topicsScope(b)));
2467
- 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;
2468
2478
  let db, release;
2469
2479
  try {
2470
2480
  const root = await historyRoot(b, Boolean(registration || options.replication));
@@ -2486,7 +2496,7 @@ async function openTopicsVectorStore(b, options = {}) {
2486
2496
  CREATE TABLE IF NOT EXISTS cache_meta(key TEXT PRIMARY KEY,value TEXT NOT NULL);`) }]);
2487
2497
  normalizeVectorCache(b, db, currentTopicParagraphs(b));
2488
2498
  } else authorizeMemoryWriter(db, 1);
2489
- 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;
2490
2500
  if (source) Object.defineProperty(db, "replication", { value: source });
2491
2501
  const capture = source ? installSQLiteWriteCapture(db, source) : void 0;
2492
2502
  const originalClose = db.close.bind(db);
@@ -3259,10 +3269,14 @@ var init_filters = __esm({
3259
3269
 
3260
3270
  // src/mem7/core/state/temporal.ts
3261
3271
  function instant(value) {
3262
- if (!/^\d{4}-\d{2}-\d{2}T.*(?:Z|[+-]\d{2}:\d{2})$/.test(value)) throw new Error("TIME_REQUIRED: explicit UTC offset required");
3263
- if (!isCalendarDate(value.substring(0, 10))) throw new Error("INVALID_TIME");
3264
- const time = Date.parse(value);
3265
- 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}`);
3266
3280
  return new Date(time).toISOString();
3267
3281
  }
3268
3282
  function isCalendarDate(value) {
@@ -3275,7 +3289,7 @@ function validateTimezone(timezone) {
3275
3289
  try {
3276
3290
  new Intl.DateTimeFormat("en", { timeZone: timezone });
3277
3291
  } catch {
3278
- 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`);
3279
3293
  }
3280
3294
  }
3281
3295
  function localInstant(date, time, timezone) {
@@ -3307,10 +3321,13 @@ function localInstant(date, time, timezone) {
3307
3321
  return new Date([...matches][0]).toISOString();
3308
3322
  }
3309
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
+ }
3310
3327
  const validFrom = value.validFrom === null ? null : instant(value.validFrom);
3311
3328
  const validTo = value.validTo === null ? null : instant(value.validTo);
3312
- if (validFrom !== null && validTo !== null && validFrom >= validTo) throw new Error("INVALID_INTERVAL: expected [from,to)");
3313
- 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");
3314
3331
  if (value.timezone) validateTimezone(value.timezone);
3315
3332
  return { ...value, validFrom, validTo };
3316
3333
  }
@@ -3320,16 +3337,20 @@ function overlaps(a, b) {
3320
3337
  function canonicalJson(value) {
3321
3338
  const normalize5 = (input) => {
3322
3339
  if (Array.isArray(input)) return input.map(normalize5);
3323
- 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)]));
3324
3341
  return input;
3325
3342
  };
3326
3343
  const json = JSON.stringify(normalize5(value));
3327
3344
  if (json === void 0) throw new Error("INVALID_JSON_VALUE");
3328
3345
  return json;
3329
3346
  }
3347
+ var INSTANT, INSTANT_FORMAT, received;
3330
3348
  var init_temporal = __esm({
3331
3349
  "src/mem7/core/state/temporal.ts"() {
3332
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);
3333
3354
  }
3334
3355
  });
3335
3356
 
@@ -3354,8 +3375,8 @@ function contextTimeKey(db, scopeId2, validAt) {
3354
3375
  }
3355
3376
  return `valid-window:${from}:${to}`;
3356
3377
  }
3357
- function assertContextTime(key3, now2 = Date.now()) {
3358
- const match = key3.match(/^valid-window:(-?\d+):(-?\d+)$/);
3378
+ function assertContextTime(key4, now2 = Date.now()) {
3379
+ const match = key4.match(/^valid-window:(-?\d+):(-?\d+)$/);
3359
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");
3360
3381
  if (now2 < Number(match[1]) || now2 >= Number(match[2])) throw new Error("CONTEXT_TIME_EXPIRED");
3361
3382
  }
@@ -3438,9 +3459,9 @@ function append(db, scope, kind, id, payload) {
3438
3459
  return Number(result.lastInsertRowid);
3439
3460
  }
3440
3461
  function recordArtifactBasis(db, scope, kind, id, version, dependencies) {
3441
- const key3 = basisKey(kind, id, version);
3442
- if (!db.prepare("SELECT 1 FROM memory_knowledge_history WHERE scope_id=? AND target_kind='artifact.basis' AND target_id=?").get(scopeId(scope), key3)) {
3443
- 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 });
3444
3465
  }
3445
3466
  }
3446
3467
  var ARTIFACT_HISTORY_SCHEMA, hash2, basisKey, stateKey2, generationKinds, normalizedRefs, ArtifactHistory;
@@ -3590,8 +3611,8 @@ END;
3590
3611
  if (cutoff) return historicalRow(this.db, scope, "artifact.basis", basisKey(kind, id, version), cutoff)?.dependencies ?? null;
3591
3612
  return this.dependencies.version(scope, kind, id) === version ? this.dependencies.refs(scope, kind, id) : null;
3592
3613
  }
3593
- scopeContextRetained(scope, key3) {
3594
- 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);
3595
3616
  if (!basis) return false;
3596
3617
  const atGeneration = historicalRow(this.db, scope, "scope", "state", { historyId: basis.history_id, time: null, complete: true });
3597
3618
  if (!atGeneration) return false;
@@ -3609,15 +3630,15 @@ END;
3609
3630
  WHERE scope_id=? AND source_id=? AND interpretation_status<>'deleted'`).get(scopeKey, sourceId));
3610
3631
  const walk = (kind2, id2, version2) => {
3611
3632
  checkMemoryReadBudget(visited.size);
3612
- const key3 = basisKey(kind2, id2, version2);
3613
- if (memo.has(key3)) return memo.get(key3);
3614
- if (visited.has(key3)) return false;
3615
- 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);
3616
3637
  try {
3617
- 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);
3618
3639
  const refs = basis && JSON.parse(basis.payload_json).dependencies;
3619
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;
3620
- 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;
3621
3642
  const retained = refs.every((ref) => {
3622
3643
  checkMemoryReadBudget(visited.size);
3623
3644
  if (ref.parentKind === "source") return sourceRetained(ref.parentId);
@@ -3637,10 +3658,10 @@ END;
3637
3658
  }
3638
3659
  return true;
3639
3660
  });
3640
- memo.set(key3, retained);
3661
+ memo.set(key4, retained);
3641
3662
  return retained;
3642
3663
  } finally {
3643
- visited.delete(key3);
3664
+ visited.delete(key4);
3644
3665
  }
3645
3666
  };
3646
3667
  return walk(kind, id, version);
@@ -3666,8 +3687,8 @@ END;
3666
3687
  };
3667
3688
  const walk = (parentKind, parentId, parentVersion, ancestors) => {
3668
3689
  checkMemoryReadBudget(ancestors.size);
3669
- const key3 = basisKey(parentKind, parentId, parentVersion);
3670
- if (ancestors.has(key3)) return false;
3690
+ const key4 = basisKey(parentKind, parentId, parentVersion);
3691
+ if (ancestors.has(key4)) return false;
3671
3692
  const state = this.state(scope, parentKind, parentId, cutoff);
3672
3693
  if (state?.state !== "current" || state.version !== parentVersion) return false;
3673
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;
@@ -3682,9 +3703,9 @@ END;
3682
3703
  }
3683
3704
  }
3684
3705
  if (refs.some((ref) => ref.parentKind === "scope" && !ref.parentId.startsWith("valid-window:"))) {
3685
- if (!this.scopeContextRetained(scope, key3)) return false;
3706
+ if (!this.scopeContextRetained(scope, key4)) return false;
3686
3707
  }
3687
- const next = new Set(ancestors).add(key3);
3708
+ const next = new Set(ancestors).add(key4);
3688
3709
  for (const ref of refs) {
3689
3710
  checkMemoryReadBudget(next.size);
3690
3711
  if (ref.parentKind === "source") {
@@ -3831,9 +3852,9 @@ function invalidateChildren(db, scope, pending2, reason) {
3831
3852
  let referencedPlan;
3832
3853
  while (pending2.length) {
3833
3854
  const child = pending2.shift();
3834
- const key3 = JSON.stringify([child.child_kind, child.child_id]);
3835
- if (visited.has(key3) && (visited.get(key3) || !child.deleted)) continue;
3836
- 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));
3837
3858
  if (child.child_kind === "graph_plan") {
3838
3859
  referencedPlan ??= db.prepare(`SELECT 1 WHERE EXISTS (SELECT 1 FROM memory_dependencies
3839
3860
  WHERE scope_id=? AND parent_kind='artifact' AND parent_id=?)
@@ -3914,8 +3935,8 @@ var init_dependencies = __esm({
3914
3935
  this.snapshotStamp = void 0;
3915
3936
  }
3916
3937
  }
3917
- observeTimeBoundary(key3) {
3918
- const match = key3.match(/^valid-window:(-?\d+):(-?\d+)$/);
3938
+ observeTimeBoundary(key4) {
3939
+ const match = key4.match(/^valid-window:(-?\d+):(-?\d+)$/);
3919
3940
  if (!match) return;
3920
3941
  const now2 = Date.now();
3921
3942
  for (const boundary of [Number(match[1]), Number(match[2])]) {
@@ -3997,9 +4018,9 @@ var init_dependencies = __esm({
3997
4018
  }
3998
4019
  artifactTimeCurrent(scope, kind, id, visited = /* @__PURE__ */ new Set(), memo) {
3999
4020
  checkMemoryReadBudget(visited.size);
4000
- const key3 = JSON.stringify([kind, id]);
4001
- if (visited.has(key3)) return false;
4002
- visited.add(key3);
4021
+ const key4 = JSON.stringify([kind, id]);
4022
+ if (visited.has(key4)) return false;
4023
+ visited.add(key4);
4003
4024
  try {
4004
4025
  const refs = this.refs(scope, kind, id);
4005
4026
  for (const ref of refs.filter((ref2) => ref2.parentKind !== "artifact")) {
@@ -4034,7 +4055,7 @@ var init_dependencies = __esm({
4034
4055
  }
4035
4056
  return true;
4036
4057
  } finally {
4037
- visited.delete(key3);
4058
+ visited.delete(key4);
4038
4059
  }
4039
4060
  }
4040
4061
  version(scope, kind, id) {
@@ -4199,6 +4220,28 @@ var init_vector_publications = __esm({
4199
4220
  }
4200
4221
  });
4201
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
+
4202
4245
  // src/mem7/core/vector-store.ts
4203
4246
  import { mkdirSync as mkdirSync11, existsSync as existsSync8 } from "node:fs";
4204
4247
  import { DatabaseSync as DatabaseSync7 } from "node:sqlite";
@@ -4348,6 +4391,7 @@ var init_vector_store = __esm({
4348
4391
  init_read_guard();
4349
4392
  init_timing();
4350
4393
  init_runtime_authority();
4394
+ init_lance_cache();
4351
4395
  isIntelMac = process.platform === "darwin" && process.arch === "x64";
4352
4396
  lancePromise = null;
4353
4397
  mem7VectorWarning = null;
@@ -4434,7 +4478,7 @@ var init_vector_store = __esm({
4434
4478
  /** Reuse expensive dependency walks, but bind each verdict to SQL, time and the actual indexed body. */
4435
4479
  cachedRowVisible(ledger, kind, row, dependencies) {
4436
4480
  if (!dependencies) return vectorRowVisible(ledger, kind, row);
4437
- const key3 = kind + ":" + String(row.id);
4481
+ const key4 = kind + ":" + String(row.id);
4438
4482
  let signature2;
4439
4483
  try {
4440
4484
  signature2 = JSON.stringify([
@@ -4458,11 +4502,11 @@ var init_vector_store = __esm({
4458
4502
  this.visibleCacheVersion = version;
4459
4503
  this.visibleCache.clear();
4460
4504
  }
4461
- const cached = this.visibleCache.get(key3);
4505
+ const cached = this.visibleCache.get(key4);
4462
4506
  if (cached?.signature === signature2) return cached.verdict;
4463
4507
  const verdict = vectorRowVisible(ledger, kind, row, dependencies);
4464
4508
  if (dependencies.cacheRevision() !== version) return false;
4465
- this.visibleCache.set(key3, { signature: signature2, verdict });
4509
+ this.visibleCache.set(key4, { signature: signature2, verdict });
4466
4510
  return verdict;
4467
4511
  }
4468
4512
  visibleCache = /* @__PURE__ */ new Map();
@@ -4483,7 +4527,8 @@ var init_vector_store = __esm({
4483
4527
  assertRuntimeAuthority(this.stateDir, "WRITE");
4484
4528
  mkdirSync11(this.dir, { recursive: true });
4485
4529
  }
4486
- this.db = await lance.connect(this.dir);
4530
+ const session = memoryLanceSession(lance);
4531
+ this.db = await lance.connect(this.dir, session ? { session } : void 0);
4487
4532
  }
4488
4533
  return this.db;
4489
4534
  }
@@ -4960,11 +5005,11 @@ var init_vector_store = __esm({
4960
5005
  const rrf2 = /* @__PURE__ */ new Map();
4961
5006
  const add = (list) => {
4962
5007
  list.forEach((h, i) => {
4963
- const key3 = h.text.replace(/\s+/g, "");
5008
+ const key4 = h.text.replace(/\s+/g, "");
4964
5009
  const contrib = 1 / (RRF_K + i + 1);
4965
- const cur = rrf2.get(key3);
5010
+ const cur = rrf2.get(key4);
4966
5011
  if (cur) cur.score += contrib;
4967
- else rrf2.set(key3, { hit: h, score: contrib });
5012
+ else rrf2.set(key4, { hit: h, score: contrib });
4968
5013
  });
4969
5014
  };
4970
5015
  add(dense);
@@ -5192,8 +5237,8 @@ CREATE INDEX idx_memory_dependency_slot ON memory_dependencies(scope_id,slot_id)
5192
5237
  * 事件重放失败一次即回死信+skip,不重烧 5 轮预算)。先 UPDATE 后记账:中间崩溃只会
5193
5238
  * 多治一次(幂等无害),反过来会出现"记了账但没治"的永久死锁。 */
5194
5239
  reenqueueGapPrefix(sinkId, head, now2 = Date.now()) {
5195
- const key3 = `${sinkId}:${head.scopeId}:${head.eventSeq}`;
5196
- if (this.healedGaps.has(key3)) return;
5240
+ const key4 = `${sinkId}:${head.scopeId}:${head.eventSeq}`;
5241
+ if (this.healedGaps.has(key4)) return;
5197
5242
  const ledgerPath = this.gapHealLedgerPath;
5198
5243
  let ledger = {};
5199
5244
  if (ledgerPath) {
@@ -5201,8 +5246,8 @@ CREATE INDEX idx_memory_dependency_slot ON memory_dependencies(scope_id,slot_id)
5201
5246
  ledger = JSON.parse(readFileSync10(ledgerPath, "utf8"))?.heals ?? {};
5202
5247
  } catch {
5203
5248
  }
5204
- if (Number.isFinite(ledger[key3])) {
5205
- this.healedGaps.add(key3);
5249
+ if (Number.isFinite(ledger[key4])) {
5250
+ this.healedGaps.add(key4);
5206
5251
  return;
5207
5252
  }
5208
5253
  }
@@ -5216,11 +5261,11 @@ CREATE INDEX idx_memory_dependency_slot ON memory_dependencies(scope_id,slot_id)
5216
5261
  const count = Number(result?.changes ?? 0);
5217
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`);
5218
5263
  });
5219
- this.healedGaps.add(key3);
5264
+ this.healedGaps.add(key4);
5220
5265
  if (!ledgerPath) return;
5221
5266
  const cutoff = now2 - _ChangeFeed.GAP_HEAL_RETENTION_MS, retained = {};
5222
5267
  for (const [entry, at] of Object.entries(ledger)) if (Number.isFinite(at) && at >= cutoff) retained[entry] = at;
5223
- retained[key3] = now2;
5268
+ retained[key4] = now2;
5224
5269
  const temp = `${ledgerPath}.${randomUUID9()}.tmp`;
5225
5270
  try {
5226
5271
  writeFileSync9(temp, JSON.stringify({ version: 1, heals: retained }));
@@ -5345,7 +5390,7 @@ function validatePredicateValue(predicate, value) {
5345
5390
  if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error("INVALID_FACT_VALUE");
5346
5391
  const object3 = value;
5347
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"];
5348
- 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");
5349
5394
  if (predicate === "activity.schedule") {
5350
5395
  const schedule = object3;
5351
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");
@@ -5567,8 +5612,8 @@ CREATE TABLE IF NOT EXISTS memory_source_aliases (
5567
5612
  ).all(scopeId(scope), `%${word.replace(/[!%_]/g, (character) => "!" + character)}%`, limit);
5568
5613
  return rows.map((row) => this.source(row));
5569
5614
  }
5570
- snapshotRead(key3, load) {
5571
- 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();
5572
5617
  }
5573
5618
  receive(input, options = {}) {
5574
5619
  const id = scopeId(input.scope);
@@ -5749,8 +5794,8 @@ CREATE TABLE IF NOT EXISTS memory_source_aliases (
5749
5794
  const result = { applied: 0, needsReview: 0, failed: 0, received: 0 };
5750
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));
5751
5796
  for (const row of rows) {
5752
- const key3 = row.state === "needs_review" ? "needsReview" : row.state;
5753
- 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);
5754
5799
  }
5755
5800
  return result;
5756
5801
  }
@@ -6174,13 +6219,13 @@ function purgeRecoveryEvidence(db, graph) {
6174
6219
  db.prepare("UPDATE e7_recovery_items SET result=? WHERE item_id=?").run(JSON.stringify(item), saved.item_id);
6175
6220
  }
6176
6221
  }
6177
- var text, key2, RecoveryDeletionGraph;
6222
+ var text, key3, RecoveryDeletionGraph;
6178
6223
  var init_recovery_deletion = __esm({
6179
6224
  "src/continuity/recovery-deletion.ts"() {
6180
6225
  "use strict";
6181
6226
  init_recovery_deletion_sources();
6182
- text = (row, key3) => row[key3]?.[0] === "text" ? row[key3][1] : void 0;
6183
- 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]);
6184
6229
  RecoveryDeletionGraph = class {
6185
6230
  edges = /* @__PURE__ */ new Map();
6186
6231
  roots = /* @__PURE__ */ new Set();
@@ -6193,10 +6238,10 @@ var init_recovery_deletion = __esm({
6193
6238
  constructor(deletions) {
6194
6239
  if (deletions.length > 1e5) throw new Error("RECOVERY_DEPENDENCY_BUDGET");
6195
6240
  for (const d of deletions) {
6196
- this.roots.add(key2(d.scopeId, "source", d.sourceId));
6241
+ this.roots.add(key3(d.scopeId, "source", d.sourceId));
6197
6242
  if (d.version !== void 0) {
6198
6243
  if (!Number.isSafeInteger(d.version) || d.version < 1) throw new Error("RECOVERY_DELETION_SOURCE_MISMATCH");
6199
- 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);
6200
6245
  if (prior !== void 0 && prior !== d.version) throw new Error("RECOVERY_DELETION_SOURCE_MISMATCH");
6201
6246
  this.deletionVersions.set(sourceKey, d.version);
6202
6247
  }
@@ -6211,7 +6256,7 @@ var init_recovery_deletion = __esm({
6211
6256
  links(table, row) {
6212
6257
  const scope = text(row, "scope_id");
6213
6258
  if (!scope) return { owners: [], parents: [] };
6214
- const node = (kind2, id) => id ? [key2(scope, kind2, id)] : [];
6259
+ const node = (kind2, id) => id ? [key3(scope, kind2, id)] : [];
6215
6260
  const source = text(row, "source_id"), fact = text(row, "assertion_id");
6216
6261
  const artifact = text(row, "artifact_id") ?? text(row, "child_id") ?? text(row, "entry_id");
6217
6262
  const owners = fact ? node("fact", fact) : artifact ? node("artifact", artifact) : source ? node("source", source) : node("entity", text(row, "entity_id"));
@@ -6235,19 +6280,19 @@ var init_recovery_deletion = __esm({
6235
6280
  if (!ref || typeof ref !== "object") continue;
6236
6281
  const refScope = typeof ref.scopeId === "string" ? ref.scopeId : typeof ref.scope_id === "string" ? ref.scope_id : scope;
6237
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"]]) {
6238
- 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]));
6239
6284
  }
6240
- 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));
6241
6286
  pending2.push(...Object.values(ref).filter((value) => value && typeof value === "object"));
6242
6287
  }
6243
6288
  }
6244
6289
  if (table === "memory_knowledge_history") {
6245
6290
  const kind2 = text(row, "target_kind"), target = text(row, "target_id");
6246
- if (kind2 === "source" && target) parents.push(key2(scope, "source", target));
6291
+ if (kind2 === "source" && target) parents.push(key3(scope, "source", target));
6247
6292
  if (kind2?.startsWith("artifact.") && target) {
6248
6293
  try {
6249
6294
  const parts = JSON.parse(target);
6250
- 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]));
6251
6296
  } catch {
6252
6297
  }
6253
6298
  }
@@ -6255,7 +6300,7 @@ var init_recovery_deletion = __esm({
6255
6300
  if (table === "memory_sources" && source) {
6256
6301
  const origin = text(row, "origin_key");
6257
6302
  if (origin) {
6258
- const originNode = key2(scope, "origin", origin), sourceNode = key2(scope, "source", source);
6303
+ const originNode = key3(scope, "origin", origin), sourceNode = key3(scope, "source", source);
6259
6304
  this.edge(sourceNode, originNode);
6260
6305
  this.edge(originNode, sourceNode);
6261
6306
  const version = row.source_version?.[0] === "integer" ? Number(row.source_version[1]) : void 0;
@@ -6265,15 +6310,15 @@ var init_recovery_deletion = __esm({
6265
6310
  if (deletion.version === void 0) continue;
6266
6311
  if (!Number.isSafeInteger(deletion.version) || deletion.version < 1) throw new Error("RECOVERY_DELETION_SOURCE_MISMATCH");
6267
6312
  if (++this.deletionChecks > 1e6) throw new Error("RECOVERY_DEPENDENCY_BUDGET");
6268
- 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);
6269
6314
  }
6270
6315
  this.familyProofs.add(originNode);
6271
6316
  }
6272
- 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));
6273
6318
  }
6274
6319
  if (table === "memory_tombstones") {
6275
6320
  const target = text(row, "target_id"), kind2 = text(row, "target_kind");
6276
- if (target && kind2) this.roots.add(key2(scope, kind2, target));
6321
+ if (target && kind2) this.roots.add(key3(scope, kind2, target));
6277
6322
  }
6278
6323
  return { owners, parents };
6279
6324
  }
@@ -6681,9 +6726,9 @@ ALTER TABLE memory_host_turns ADD COLUMN owner_id TEXT;
6681
6726
  }
6682
6727
  }
6683
6728
  recordCompleted(id, sourceId, sourceVersion, now2) {
6684
- const key3 = JSON.stringify(["host.turn.completed", id, sourceId]);
6729
+ const key4 = JSON.stringify(["host.turn.completed", id, sourceId]);
6685
6730
  this.db.prepare(`INSERT OR IGNORE INTO ome_jobs(kind,payload,status,next_run_at,created_at,job_key,scope_id,completed_at)
6686
- 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);
6687
6732
  }
6688
6733
  };
6689
6734
  }
@@ -7311,7 +7356,7 @@ function recoverLegacySession(db, store, mapping, files, apply = false) {
7311
7356
  return report;
7312
7357
  }
7313
7358
  function recoverLegacyProjections(db, store, input, apply = false) {
7314
- const key3 = scopeId(input.scope);
7359
+ const key4 = scopeId(input.scope);
7315
7360
  const root = realpathSync4(input.root);
7316
7361
  const report = { files: 0, entries: 0, recoverable: 0, alreadyMapped: 0, unavailable: 0, reasons: {}, applied: false };
7317
7362
  const gap = (reason) => {
@@ -7356,7 +7401,7 @@ function recoverLegacyProjections(db, store, input, apply = false) {
7356
7401
  const block = match[0];
7357
7402
  const field = (name) => match[2].match(new RegExp(`^\\*\\*${name}\\*\\*: ([^\\n]*)$`, "m"))?.[1]?.trim();
7358
7403
  const parent = field("parent_id");
7359
- 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);
7360
7405
  if (!mapping || field("parent_type") !== "memcell" || field("owner_id") !== input.scope.ownerId || field("session_id") !== mapping.session_id) {
7361
7406
  gap("projection_parent_provenance_missing");
7362
7407
  continue;
@@ -7373,7 +7418,7 @@ function recoverLegacyProjections(db, store, input, apply = false) {
7373
7418
  gap("projection_body_missing");
7374
7419
  continue;
7375
7420
  }
7376
- 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]);
7377
7422
  const target = join16(store.mem7RootPath(), path2);
7378
7423
  if (previous) {
7379
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)) {
@@ -7425,7 +7470,7 @@ function recoverLegacyProjections(db, store, input, apply = false) {
7425
7470
  role: "supports"
7426
7471
  })));
7427
7472
  const digest4 = hash3(candidate.block.trim());
7428
- 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);
7429
7474
  store.artifacts.publish(input.scope, {
7430
7475
  kind: candidate.kind,
7431
7476
  id: candidate.id,
@@ -7437,7 +7482,7 @@ function recoverLegacyProjections(db, store, input, apply = false) {
7437
7482
  summary: candidate.summary,
7438
7483
  title: candidate.title
7439
7484
  });
7440
- 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);
7441
7486
  }
7442
7487
  });
7443
7488
  report.applied = true;
@@ -7569,10 +7614,10 @@ var init_recall_sources = __esm({
7569
7614
  }
7570
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}`);
7571
7616
  for (let index = 0; index < queue.length; index++) {
7572
- const key3 = queue[index];
7573
- if (this.removed.has(key3)) continue;
7574
- this.removed.add(key3);
7575
- 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) ?? []);
7576
7621
  }
7577
7622
  }
7578
7623
  sources = /* @__PURE__ */ new Map();
@@ -7747,9 +7792,9 @@ CREATE TABLE memory_person_mentions (
7747
7792
  ])];
7748
7793
  if (ids.length > 8192 || this.snapshot.relationships.size > 8192) return result;
7749
7794
  const sourceIds = JSON.stringify(ids.sort());
7750
- const relationshipRefs = JSON.stringify([...this.snapshot.relationships.keys()].sort().map((key3) => {
7751
- const split = key3.lastIndexOf(":");
7752
- 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))];
7753
7798
  }));
7754
7799
  this.snapshotBasis = this.readProvenanceBasis(this.snapshot, sourceIds, relationshipRefs);
7755
7800
  }
@@ -7797,19 +7842,19 @@ CREATE TABLE memory_person_mentions (
7797
7842
  const sourceChecks = new Map(sources.map((row) => [row.id, JSON.stringify(row)]));
7798
7843
  const relationshipRows = /* @__PURE__ */ new Map();
7799
7844
  for (const row of relationships) {
7800
- const key3 = `${row.id}:${row.version}`;
7801
- const rows = relationshipRows.get(key3) ?? [];
7845
+ const key4 = `${row.id}:${row.version}`;
7846
+ const rows = relationshipRows.get(key4) ?? [];
7802
7847
  rows.push(row);
7803
- relationshipRows.set(key3, rows);
7848
+ relationshipRows.set(key4, rows);
7804
7849
  }
7805
- 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")]));
7806
7851
  checkMemoryReadBudget();
7807
7852
  return { sourceIds, relationshipRefs, digest: digest4, sources: sourceChecks, relationships: relationshipChecks };
7808
7853
  }
7809
7854
  provenanceSnapshot(scope, cutoff) {
7810
7855
  const stamp = this.provenanceStamp();
7811
- const key3 = JSON.stringify([scopeId(scope), cutoff ?? null]);
7812
- 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) {
7813
7858
  const previous = this.snapshotBasis;
7814
7859
  const next = this.readProvenanceBasis(this.snapshot, previous.sourceIds, previous.relationshipRefs);
7815
7860
  if (next.digest !== previous.digest) {
@@ -7821,17 +7866,17 @@ CREATE TABLE memory_person_mentions (
7821
7866
  this.snapshot.metadata.delete(id);
7822
7867
  this.snapshot.currentSources.delete(id);
7823
7868
  }
7824
- for (const [key4, check] of previous.relationships) {
7825
- 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);
7826
7871
  }
7827
7872
  }
7828
7873
  this.snapshotBasis = next;
7829
7874
  this.snapshotStamp = stamp;
7830
7875
  }
7831
- 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) {
7832
7877
  this.snapshotStamp = stamp;
7833
7878
  this.snapshotBasis = void 0;
7834
- 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() };
7835
7880
  }
7836
7881
  return this.snapshot;
7837
7882
  }
@@ -7962,21 +8007,21 @@ CREATE TABLE memory_person_mentions (
7962
8007
  provenanceReferenceRetained(scope, ref, visited, cutoff, snapshot) {
7963
8008
  checkMemoryReadBudget(visited.size);
7964
8009
  if (ref.scopeId !== scopeId(scope) || visited.has(ref.sourceId) || ref.relationshipId && visited.has(`${ref.relationshipId}:${ref.semanticVersion}`)) return false;
7965
- const key3 = `reference:${JSON.stringify([ref.sourceId, ref.sourceVersion, ref.relationshipId, ref.semanticVersion])}`;
7966
- 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);
7967
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);
7968
- snapshot.memo.set(key3, retained);
8013
+ snapshot.memo.set(key4, retained);
7969
8014
  return retained;
7970
8015
  }
7971
8016
  /** Authored thoughts remain historical memories when a cited source is corrected; deletion still wins. */
7972
8017
  provenanceRetained(scope, sourceId, visited, cutoff, snapshot) {
7973
8018
  checkMemoryReadBudget(visited.size);
7974
8019
  if (visited.has(sourceId)) return false;
7975
- const key3 = `source:${sourceId}`;
8020
+ const key4 = `source:${sourceId}`;
7976
8021
  const { memo } = snapshot;
7977
- if (memo.has(key3)) return memo.get(key3);
8022
+ if (memo.has(key4)) return memo.get(key4);
7978
8023
  if (!this.provenanceSource(scope, sourceId, cutoff, snapshot) || this.tombstoneRead.get(scopeId(scope), sourceId)) {
7979
- memo.set(key3, false);
8024
+ memo.set(key4, false);
7980
8025
  return false;
7981
8026
  }
7982
8027
  if (!snapshot.metadata.has(sourceId)) snapshot.metadata.set(sourceId, this.metadata(scope, sourceId));
@@ -7985,7 +8030,7 @@ CREATE TABLE memory_person_mentions (
7985
8030
  try {
7986
8031
  const check = (ref) => this.provenanceReferenceRetained(scope, ref, visited, cutoff, snapshot);
7987
8032
  const retained = !metadata2 || metadata2.contextRefs.every(check) && metadata2.basisRefs.every(check);
7988
- memo.set(key3, retained);
8033
+ memo.set(key4, retained);
7989
8034
  return retained;
7990
8035
  } finally {
7991
8036
  visited.delete(sourceId);
@@ -8019,10 +8064,10 @@ CREATE TABLE memory_person_mentions (
8019
8064
  sourceGroundsCurrent(scope, sourceId, visited, cutoff, snapshot) {
8020
8065
  checkMemoryReadBudget(visited.size);
8021
8066
  if (visited.has(sourceId)) return false;
8022
- const key3 = `source:${sourceId}`;
8023
- 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);
8024
8069
  if (!this.sourceCurrent(scope, sourceId, cutoff, snapshot) || !this.provenanceRetained(scope, sourceId, /* @__PURE__ */ new Set(), cutoff, snapshot)) {
8025
- snapshot.grounds.set(key3, false);
8070
+ snapshot.grounds.set(key4, false);
8026
8071
  return false;
8027
8072
  }
8028
8073
  if (!snapshot.metadata.has(sourceId)) snapshot.metadata.set(sourceId, this.metadata(scope, sourceId));
@@ -8030,7 +8075,7 @@ CREATE TABLE memory_person_mentions (
8030
8075
  visited.add(sourceId);
8031
8076
  try {
8032
8077
  const current2 = !metadata2 || metadata2.basisRefs.every((ref) => this.currentReference(scope, ref, visited, cutoff, snapshot));
8033
- snapshot.grounds.set(key3, current2);
8078
+ snapshot.grounds.set(key4, current2);
8034
8079
  return current2;
8035
8080
  } finally {
8036
8081
  visited.delete(sourceId);
@@ -8040,46 +8085,46 @@ CREATE TABLE memory_person_mentions (
8040
8085
  checkMemoryReadBudget(visited.size);
8041
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;
8042
8087
  if (!ref.relationshipId) return true;
8043
- const key3 = `${ref.relationshipId}:${ref.semanticVersion}`;
8044
- if (visited.has(key3)) return false;
8045
- 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"}`;
8046
8091
  if (snapshot.grounds.has(memoKey)) return snapshot.grounds.get(memoKey);
8047
- if (!snapshot.relationships.has(key3)) {
8092
+ if (!snapshot.relationships.has(key4)) {
8048
8093
  this.snapshotBasis = void 0;
8049
- snapshot.relationships.set(key3, this.relationshipReferenceMaterial(scope, ref, cutoff));
8094
+ snapshot.relationships.set(key4, this.relationshipReferenceMaterial(scope, ref, cutoff));
8050
8095
  }
8051
- const material = snapshot.relationships.get(key3);
8096
+ const material = snapshot.relationships.get(key4);
8052
8097
  if (!material || ["deleted", "retracted"].includes(material.state) || ref.purpose !== "historical" && !material.current) return false;
8053
- visited.add(key3);
8098
+ visited.add(key4);
8054
8099
  try {
8055
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));
8056
8101
  snapshot.grounds.set(memoKey, current2);
8057
8102
  return current2;
8058
8103
  } finally {
8059
- visited.delete(key3);
8104
+ visited.delete(key4);
8060
8105
  }
8061
8106
  }
8062
8107
  relationshipReferenceRetained(scope, ref, visited, cutoff, snapshot = this.provenanceSnapshot(scope, cutoff)) {
8063
8108
  checkMemoryReadBudget(visited.size);
8064
8109
  if (!ref.relationshipId) return true;
8065
- const key3 = `${ref.relationshipId}:${ref.semanticVersion}`;
8066
- if (visited.has(key3)) return false;
8067
- const memoKey = `relationship:${key3}`;
8110
+ const key4 = `${ref.relationshipId}:${ref.semanticVersion}`;
8111
+ if (visited.has(key4)) return false;
8112
+ const memoKey = `relationship:${key4}`;
8068
8113
  const { memo } = snapshot;
8069
8114
  if (memo.has(memoKey)) return memo.get(memoKey);
8070
- if (!snapshot.relationships.has(key3)) {
8115
+ if (!snapshot.relationships.has(key4)) {
8071
8116
  this.snapshotBasis = void 0;
8072
- snapshot.relationships.set(key3, this.relationshipReferenceMaterial(scope, ref, cutoff));
8117
+ snapshot.relationships.set(key4, this.relationshipReferenceMaterial(scope, ref, cutoff));
8073
8118
  }
8074
- const material = snapshot.relationships.get(key3);
8119
+ const material = snapshot.relationships.get(key4);
8075
8120
  if (!material) return false;
8076
- visited.add(key3);
8121
+ visited.add(key4);
8077
8122
  try {
8078
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));
8079
8124
  memo.set(memoKey, retained);
8080
8125
  return retained;
8081
8126
  } finally {
8082
- visited.delete(key3);
8127
+ visited.delete(key4);
8083
8128
  }
8084
8129
  }
8085
8130
  relationshipReferenceMaterial(scope, ref, cutoff) {
@@ -8526,16 +8571,16 @@ CREATE TABLE memory_relationship_receipts (
8526
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);
8527
8572
  if (!row) return null;
8528
8573
  if (historicalVersion) Object.assign(row, historicalVersion);
8529
- const key3 = `${relationshipId}:${row.semantic_version}`;
8530
- if (visited.has(key3)) return null;
8531
- 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);
8532
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 }));
8533
8578
  const basisRefs = JSON.parse(row.basis_refs);
8534
8579
  const refs = [...evidence.map((ref) => ({ sourceId: ref.sourceId })), ...basisRefs];
8535
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;
8536
8581
  const value = JSON.parse(row.value_json);
8537
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;
8538
- 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));
8539
8584
  return {
8540
8585
  relationshipId,
8541
8586
  semanticVersion: row.semantic_version,
@@ -8930,10 +8975,10 @@ CREATE TABLE memory_relationship_cognition_results (
8930
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)] : []);
8931
8976
  const groups = /* @__PURE__ */ new Map();
8932
8977
  for (const row of rows) {
8933
- const key3 = canonicalJson([row.scope_id, row.perspective_entity_id, row.group_key, row.generation]);
8934
- 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 };
8935
8980
  if (group.sourceIds.length < 20) group.sourceIds.push(row.source_id);
8936
- groups.set(key3, group);
8981
+ groups.set(key4, group);
8937
8982
  }
8938
8983
  return [...groups.values()];
8939
8984
  }
@@ -9123,9 +9168,9 @@ var init_entities = __esm({
9123
9168
  aliasEvidence(scope, entityId, cutoff) {
9124
9169
  const seen = /* @__PURE__ */ new Set();
9125
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) => {
9126
- const key3 = normalizeAlias(alias.alias);
9127
- 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;
9128
- 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);
9129
9174
  return true;
9130
9175
  }).map((alias) => ({ alias: alias.alias, sourceId: alias.sourceId, sourceVersion: this.sources.get(scope, alias.sourceId, cutoff).sourceVersion }));
9131
9176
  }
@@ -9324,12 +9369,12 @@ function checkNotice(db, sources, social, scope, id, options) {
9324
9369
  return Boolean(source && (version === void 0 || source.sourceVersion === version) && social.readable(memoryScope, sourceId) && social.groundsCurrent(memoryScope, sourceId));
9325
9370
  };
9326
9371
  const relationshipCurrent = (relationshipId, version) => {
9327
- const key3 = `${relationshipId}:${version}`;
9372
+ const key4 = `${relationshipId}:${version}`;
9328
9373
  const row = db.prepare(`SELECT r.*,v.state FROM memory_relationship_versions r JOIN fact_versions v
9329
9374
  ON v.scope_id=r.scope_id AND v.assertion_id=r.assertion_id AND v.system_to_revision IS NULL
9330
9375
  WHERE r.scope_id=? AND r.relationship_id=? AND r.semantic_version=?`).get(scope, relationshipId, version);
9331
9376
  if (!row || ["deleted", "retracted"].includes(row.state)) return false;
9332
- 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);
9333
9378
  if (derivation && derivation.state !== "current") return false;
9334
9379
  const evidence = db.prepare("SELECT source_id FROM fact_evidence WHERE scope_id=? AND assertion_id=?").all(scope, row.assertion_id);
9335
9380
  return evidence.length > 0 && evidence.every((ref) => sourceCurrent(ref.source_id)) && JSON.parse(row.basis_refs).every((ref) => social.referenceCurrent(memoryScope, ref));
@@ -9404,8 +9449,11 @@ CREATE TABLE memory_relationship_notice_versions (
9404
9449
  }
9405
9450
  get(scope, id) {
9406
9451
  const row = this.db.prepare("SELECT * FROM memory_relationship_notices WHERE scope_id=? AND notice_id=?").get(scopeId(scope), id);
9407
- return row ? {
9408
- id,
9452
+ return row ? this.decode(scope, row) : null;
9453
+ }
9454
+ decode(scope, row) {
9455
+ return {
9456
+ id: row.notice_id,
9409
9457
  scope,
9410
9458
  kind: row.kind,
9411
9459
  targetId: row.target_id,
@@ -9415,10 +9463,25 @@ CREATE TABLE memory_relationship_notice_versions (
9415
9463
  state: row.state,
9416
9464
  attempts: row.attempts,
9417
9465
  reason: row.reason
9418
- } : null;
9466
+ };
9419
9467
  }
9420
- list(scope) {
9421
- 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));
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));
9471
+ }
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);
9422
9485
  }
9423
9486
  finish(scope, id, state, reason = "", redact = false) {
9424
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);
@@ -9429,6 +9492,12 @@ CREATE TABLE memory_relationship_notice_versions (
9429
9492
  check(scope, id, options = {}) {
9430
9493
  return checkRelationshipNotice(this.db, scopeId(scope), id, options);
9431
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
+ }
9432
9501
  queue(scope, id) {
9433
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);
9434
9503
  }
@@ -9440,6 +9509,7 @@ CREATE TABLE memory_relationship_notice_versions (
9440
9509
  importantRecords(scope) {
9441
9510
  return this.db.prepare(`SELECT v.relationship_id,v.semantic_version FROM memory_relationship_notice_versions v
9442
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
9443
9513
  WHERE v.scope_id=? AND r.important=1`).all(scopeId(scope)).map((row) => ({ relationshipId: row.relationship_id, semanticVersion: row.semantic_version }));
9444
9514
  }
9445
9515
  recordRoute(scope, sourceId, input) {
@@ -9507,9 +9577,9 @@ function installRelationshipHistory(db) {
9507
9577
  FROM memory_scopes s WHERE EXISTS (SELECT 1 FROM memory_relationship_heads h WHERE h.scope_id=s.scope_id)
9508
9578
  OR EXISTS (SELECT 1 FROM memory_person_sources p WHERE p.scope_id=s.scope_id)
9509
9579
  OR EXISTS (SELECT 1 FROM memory_person_mentions m WHERE m.scope_id=s.scope_id)`);
9510
- for (const { table, kind, key: key3, columns: columns2 } of tables) {
9580
+ for (const { table, kind, key: key4, columns: columns2 } of tables) {
9511
9581
  const payload = (prefix) => `json_object(${columns2.map((column) => `'${column}',${prefix}${column}`).join(",")})`;
9512
- 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}`;
9513
9583
  db.exec(`INSERT INTO memory_knowledge_history(scope_id,target_kind,target_id,entity_revision,fact_revision,context_revision,recorded_at,payload_json)
9514
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.")}
9515
9585
  FROM ${table} t JOIN memory_scopes s ON s.scope_id=t.scope_id`);
@@ -9938,16 +10008,16 @@ var init_snapshot_reads = __esm({
9938
10008
  this.changes = -1;
9939
10009
  }
9940
10010
  }
9941
- read(key3, load) {
10011
+ read(key4, load) {
9942
10012
  if (!this.values || !this.db.isTransaction) return load();
9943
10013
  const changes = this.changesRead.get().n;
9944
10014
  if (changes !== this.changes) {
9945
10015
  this.values.clear();
9946
10016
  this.changes = changes;
9947
10017
  }
9948
- if (this.values.has(key3)) return this.values.get(key3);
10018
+ if (this.values.has(key4)) return this.values.get(key4);
9949
10019
  const value = load();
9950
- if (this.values.size < 8192) this.values.set(key3, value);
10020
+ if (this.values.size < 8192) this.values.set(key4, value);
9951
10021
  return value;
9952
10022
  }
9953
10023
  };
@@ -10073,7 +10143,7 @@ function classifyFactVersions(versions, predicate, time) {
10073
10143
  needsReview: disputed || hypotheses.some((fact) => fact.validFrom === null)
10074
10144
  };
10075
10145
  }
10076
- var hash5, makeSlotId, FactStore;
10146
+ var hash5, makeSlotId, CLOSE_VALIDITY, occurrences, CHANGE_KINDS, CLAIM_KINDS, normalizeChange, FactStore;
10077
10147
  var init_facts = __esm({
10078
10148
  "src/mem7/core/state/facts.ts"() {
10079
10149
  "use strict";
@@ -10085,6 +10155,15 @@ var init_facts = __esm({
10085
10155
  init_basis_check();
10086
10156
  hash5 = (value) => createHash17("sha256").update(canonicalJson(value)).digest("hex");
10087
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 } };
10088
10167
  FactStore = class {
10089
10168
  constructor(db, entities, transaction, readTransaction = transaction) {
10090
10169
  this.db = db;
@@ -10251,6 +10330,8 @@ var init_facts = __esm({
10251
10330
  applyChange(scope, proposal, expectedSlotRevision, requestKey, batch) {
10252
10331
  if (!requestKey || !Number.isSafeInteger(expectedSlotRevision) || expectedSlotRevision < 0) throw new Error("INVALID_FACT_REQUEST");
10253
10332
  const id = scopeId(scope);
10333
+ const located = this.locateEvidence(id, normalizeChange(proposal));
10334
+ proposal = located.proposal;
10254
10335
  const requestHash = hash5([proposal, expectedSlotRevision]);
10255
10336
  const prior = this.db.prepare("SELECT request_hash,result_json FROM fact_changes WHERE scope_id=? AND request_key=?").get(id, requestKey);
10256
10337
  if (prior) {
@@ -10259,21 +10340,22 @@ var init_facts = __esm({
10259
10340
  }
10260
10341
  this.validate(scope, proposal);
10261
10342
  const slot = this.slot(scope, proposal.subjectId, proposal.predicate, proposal.contextKey);
10262
- 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` : ""));
10263
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);
10264
10345
  const before = this.current(id, slot.slotId);
10265
10346
  const targetIds = [...new Set(proposal.targetAssertionIds ?? [])];
10266
10347
  const targets = targetIds.map((targetId) => {
10267
10348
  const target = before.find((fact) => fact.assertionId === targetId);
10268
- 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`);
10269
10350
  return target;
10270
10351
  });
10271
- 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`);
10272
10353
  if (proposal.changeKind === "reinforce" && targets.length !== 1) throw new Error("REINFORCE_REQUIRES_ONE_TARGET");
10273
10354
  if (["assert", "exception"].includes(proposal.changeKind) && targets.length) throw new Error("UNEXPECTED_FACT_TARGET");
10274
10355
  const validity = proposal.validity ? normalizeValidity(proposal.validity) : void 0;
10275
- if (proposal.changeKind === "state_change" && (validity?.validFrom == null || validity.precision !== "exact")) throw new Error("CHANGE_TIME_REQUIRED");
10276
- 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}`);
10277
10359
  if (proposal.changeKind === "reinforce" && (canonicalJson(proposal.value) !== canonicalJson(targets[0].value) || proposal.claimKind !== targets[0].claimKind)) throw new Error("REINFORCE_VALUE_MISMATCH");
10278
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");
10279
10361
  const timestamp = batch?.timestamp ?? (/* @__PURE__ */ new Date()).toISOString();
@@ -10289,8 +10371,8 @@ var init_facts = __esm({
10289
10371
  let state = proposal.changeKind === "correction" || proposal.changeKind === "retract" ? "retracted" : "disputed";
10290
10372
  if (proposal.changeKind === "state_change" || proposal.changeKind === "close") {
10291
10373
  const end = proposal.changeKind === "close" ? validity.validTo : validity.validFrom;
10292
- if (target.validFrom !== null && target.validFrom >= end) throw new Error("CHANGE_BEFORE_TARGET_START: use correction");
10293
- 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`);
10294
10376
  state = target.state;
10295
10377
  nextValidity = { ...target, validTo: end };
10296
10378
  }
@@ -10306,7 +10388,7 @@ var init_facts = __esm({
10306
10388
  }
10307
10389
  if (!["retract", "close"].includes(proposal.changeKind)) {
10308
10390
  let state = proposal.claimKind === "inference" ? "candidate" : proposal.changeKind === "dispute" ? "disputed" : "supported";
10309
- 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");
10310
10392
  const current2 = this.current(id, slot.slotId);
10311
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");
10312
10394
  if (state === "supported" && validity.validFrom === null && !(proposal.predicate === "relation.open" && proposal.value.observedAsCurrentAt)) state = "candidate";
@@ -10338,7 +10420,8 @@ var init_facts = __esm({
10338
10420
  slotId: slot.slotId,
10339
10421
  slotRevision: slot.revision + Number(changed),
10340
10422
  assertionIds: changedIds,
10341
- 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 } : {}
10342
10425
  };
10343
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);
10344
10427
  if (changed) {
@@ -10377,21 +10460,31 @@ var init_facts = __esm({
10377
10460
  });
10378
10461
  }
10379
10462
  validate(scope, proposal) {
10380
- if (!Object.hasOwn(predicates, proposal.predicate)) throw new Error("UNKNOWN_PREDICATE");
10381
- 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");
10382
- 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");
10383
10473
  const subject = this.entities.get(scope, proposal.subjectId);
10384
- 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}`);
10385
10476
  if (proposal.predicate === "relation.family" && !familyRoles.includes(proposal.contextKey)) throw new Error("INVALID_FAMILY_ROLE");
10386
10477
  if (proposal.predicate === "relation.colleague" && (proposal.contextKey !== normalizeOrganization(proposal.contextKey) || proposal.contextKey.length > 200)) throw new Error("INVALID_ORGANIZATION_CONTEXT");
10387
10478
  if (proposal.changeKind === "close") {
10388
- if (!isRelationship(proposal.predicate) || proposal.value !== void 0) throw new Error("INVALID_RELATION_CLOSE");
10389
- 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}`);
10390
10482
  normalizeValidity(proposal.validity);
10391
10483
  }
10392
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`);
10393
10486
  validatePredicateValue(proposal.predicate, proposal.value);
10394
- 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"}');
10395
10488
  normalizeValidity(proposal.validity);
10396
10489
  const objectKind = predicates[proposal.predicate].objectKind;
10397
10490
  if (objectKind && !matchesEntityKind(this.entities.get(scope, proposal.value.entityId)?.kind, objectKind)) throw new Error("OBJECT_SCOPE_MISMATCH");
@@ -10406,7 +10499,7 @@ var init_facts = __esm({
10406
10499
  const targets = (proposal.targetAssertionIds ?? []).map((assertionId) => this.db.prepare(`SELECT a.claim_kind,a.value_json,s.subject_id
10407
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));
10408
10501
  const perspective = value?.relationshipId ? this.entities.get(scope, value.perspectiveEntityId) : subject;
10409
- 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");
10410
10503
  }
10411
10504
  if (proposal.predicate === "activity.schedule" && proposal.changeKind !== "retract") {
10412
10505
  const schedule = proposal.value;
@@ -10414,26 +10507,53 @@ var init_facts = __esm({
10414
10507
  if (proposal.contextKey !== "baseline" && !exception) throw new Error("INVALID_SCHEDULE_CONTEXT");
10415
10508
  if ((exception || proposal.changeKind === "exception") && (!exception || schedule.frequency !== "once")) throw new Error("OCCURRENCE_EXCEPTION_REQUIRED");
10416
10509
  }
10417
- 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}`);
10418
10513
  const source = this.db.prepare(`SELECT text,role,origin_class,interpretation_status FROM memory_sources s WHERE scope_id=? AND source_id=?
10419
10514
  AND NOT EXISTS (SELECT 1 FROM memory_sources newer WHERE newer.scope_id=s.scope_id
10420
- AND newer.origin_key=s.origin_key AND newer.source_version>s.source_version)`).get(scopeId(scope), evidence.sourceId);
10421
- 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`);
10422
10523
  const relationValue = proposal.value;
10423
10524
  if (proposal.predicate === "relation.open" && relationValue?.attribution === "reported" && (proposal.claimKind !== "reported_statement" || !hasReportedAttribution(source.text, relationValue, this.entities.sourceMentions(scope, evidence.sourceId)))) {
10424
- 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");
10425
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`);
10426
10528
  if (proposal.claimKind !== "inference") {
10427
- if (proposal.claimKind === "user_statement" && (source.role !== "user" || !["host_user", "client_reported_user"].includes(source.origin_class))) throw new Error("EVIDENCE_ROLE_MISMATCH");
10428
- 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();
10429
10531
  if (proposal.claimKind === "reported_statement" && (source.role !== "user" || !["third_party_report", "legacy_import"].includes(source.origin_class))) {
10430
10532
  const value = proposal.value;
10431
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));
10432
- if (!attributed) throw new Error("EVIDENCE_ROLE_MISMATCH");
10534
+ if (!attributed) throw roleMismatch();
10433
10535
  }
10434
- 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");
10435
- }
10436
- }
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 };
10437
10557
  }
10438
10558
  current(scope, slotId) {
10439
10559
  return this.versions(scope, slotId);
@@ -10576,7 +10696,7 @@ function summary(input) {
10576
10696
  try {
10577
10697
  const p = JSON.parse(input);
10578
10698
  if (!p || typeof p !== "object" || Array.isArray(p)) return input;
10579
- 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));
10580
10700
  if (!Object.hasOwn(small, "basis") && p.basis?.scope) small.basis = { scope: p.basis.scope };
10581
10701
  return JSON.stringify(small);
10582
10702
  } catch {
@@ -11200,6 +11320,35 @@ CREATE TABLE IF NOT EXISTS cluster_members (
11200
11320
  };
11201
11321
  }, scope, version);
11202
11322
  }
11323
+ /** 1123 跨轮去重(md):entry id 由正文决定、所在文件由日期决定——日期判定跨轮漂移时新块落到
11324
+ * 另一个日期文件,appendMd 的原位替换只扫目标文件,旧块留成孤儿(妹妹 1122 重洗 44 处双份)。
11325
+ * 单遍扫 episodes:id 在本轮写入表里、但所在文件 ≠ 本轮目标日期的块删掉,entry_count 同步。
11326
+ * 不在本轮写入表里的条目不碰(别的来源/原生记忆)。 */
11327
+ purgeEpisodeEntries(ownerId, targetDateById) {
11328
+ if (!targetDateById.size) return 0;
11329
+ const dir = join18(this.root, "users", ownerId, "episodes");
11330
+ if (!existsSync10(dir)) return 0;
11331
+ let removed = 0;
11332
+ for (const name of readdirSync3(dir)) {
11333
+ const fileDate = /^episode-(\d{4}-\d{2}-\d{2})\.md$/.exec(name)?.[1];
11334
+ if (!fileDate) continue;
11335
+ const file = join18(dir, name);
11336
+ let text2 = readFileSync13(file, "utf8"), hit = false;
11337
+ for (const m of text2.matchAll(/<!-- entry:(\S+) -->/g)) {
11338
+ const target = targetDateById.get(m[1]);
11339
+ if (target === void 0 || target === fileDate) continue;
11340
+ text2 = text2.replace(new RegExp(`\\n*<!-- entry:${m[1]} -->[\\s\\S]*?<!-- /entry:${m[1]} -->`), "");
11341
+ removed++;
11342
+ hit = true;
11343
+ }
11344
+ if (!hit) continue;
11345
+ text2 = text2.replace(/entry_count: \d+/, `entry_count: ${(text2.match(/<!-- entry:/g) ?? []).length}`);
11346
+ const tmp = `${file}.${process.pid}.tmp`;
11347
+ writeFileSync10(tmp, text2);
11348
+ renameSync6(tmp, file);
11349
+ }
11350
+ return removed;
11351
+ }
11203
11352
  appendAtomicFacts(ownerId, dateStr, entries, scope, version) {
11204
11353
  const flat = [];
11205
11354
  for (const e of entries) {
@@ -12100,10 +12249,10 @@ ${e.outcome}
12100
12249
  ];
12101
12250
  if (revalidationKinds.length === 0) return 0;
12102
12251
  for (const scope of this.sources.scopes()) {
12103
- const received = this.sources.interpretationProgress(scope).received;
12252
+ const received2 = this.sources.interpretationProgress(scope).received;
12104
12253
  for (const artifact of this.dependencies.dirty(scope)) {
12105
12254
  if (!revalidationKinds.includes(artifact.kind)) continue;
12106
- 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;
12107
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));
12108
12257
  for (const row of previous) {
12109
12258
  const payload = JSON.parse(row.payload);
@@ -12479,11 +12628,11 @@ var init_cross_encoder = __esm({
12479
12628
 
12480
12629
  // src/mem7/search.ts
12481
12630
  function getReadStore(stateDir, knowledgeClock, options = {}) {
12482
- const key3 = options.readOnly ? JSON.stringify(["read-only", stateDir]) : stateDir;
12483
- let s = readStores.get(key3);
12631
+ const key4 = options.readOnly ? JSON.stringify(["read-only", stateDir]) : stateDir;
12632
+ let s = readStores.get(key4);
12484
12633
  if (!s) {
12485
12634
  s = new Mem7Store(stateDir, knowledgeClock, { busyTimeoutMs: 5e3, readOnly: options.readOnly });
12486
- readStores.set(key3, s);
12635
+ readStores.set(key4, s);
12487
12636
  }
12488
12637
  return s;
12489
12638
  }
@@ -12921,35 +13070,45 @@ __export(import_mem7_exports, {
12921
13070
  topicsImported: () => topicsImported
12922
13071
  });
12923
13072
  import { DatabaseSync as DatabaseSync10 } from "node:sqlite";
12924
- import { existsSync as existsSync12, renameSync as renameSync8, statSync as statSync2, writeFileSync as writeFileSync12 } from "node:fs";
13073
+ import { existsSync as existsSync12, readFileSync as readFileSync17, renameSync as renameSync8, statSync as statSync2, writeFileSync as writeFileSync12 } from "node:fs";
12925
13074
  import { join as join22 } from "node:path";
13075
+ function archiveDateOf(b) {
13076
+ const today = todayKey(), cache = /* @__PURE__ */ new Map();
13077
+ const filenameDate = (sourcePath) => {
13078
+ const name = sourcePath;
13079
+ const fromName = /(?<!\d)(\d{4}-\d{2}-\d{2})(?!\d)/.exec(name)?.[1];
13080
+ if (fromName && validTopicDate(fromName)) return fromName;
13081
+ const mmdd = /(?<=_)(0[1-9]|1[0-2])(0[1-9]|[12]\d|3[01])(?!\d)/.exec(name);
13082
+ const stamped = mmdd ? `${LEGACY_TOPIC_YEAR}-${mmdd[1]}-${mmdd[2]}` : null;
13083
+ return stamped && validTopicDate(stamped) ? stamped : null;
13084
+ };
13085
+ return (sourcePath) => {
13086
+ if (cache.has(sourcePath)) return cache.get(sourcePath);
13087
+ let event = null, recorded = null;
13088
+ try {
13089
+ const text2 = readFileSync17(join22(b.topicsDir, sourcePath), "utf8").slice(0, 6e3);
13090
+ const fm = /^\uFEFF?---\r?\n([\s\S]*?)\r?\n---/.exec(text2)?.[1] ?? "";
13091
+ const raw = /^date:\s*['"]?(\d{4}-\d{2}-\d{2})/m.exec(fm)?.[1];
13092
+ if (raw && validTopicDate(raw) && raw <= today) {
13093
+ if (/^date_kind:\s*recorded/m.test(fm)) recorded = raw;
13094
+ else event = raw;
13095
+ }
13096
+ } catch {
13097
+ }
13098
+ const date = event ?? filenameDate(sourcePath) ?? recorded;
13099
+ cache.set(sourcePath, date);
13100
+ return date;
13101
+ };
13102
+ }
12926
13103
  function loadIndexFragments(b) {
13104
+ if (!b.topicsDir) return [];
12927
13105
  const root = topicsHistoryRoot(b);
12928
13106
  const selected = readJson(join22(root, "current.json")).version;
12929
13107
  if (!/^[a-f0-9-]{36}$/.test(selected)) throw new Error("INVALID_HISTORY_VERSION");
13108
+ const archiveDate = archiveDateOf(b);
12930
13109
  const db = new DatabaseSync10(unlinked(join22(root, selected, "history.db")), { readOnly: true });
12931
13110
  try {
12932
- const rows = db.prepare("SELECT ref,body,title,source_path,dates FROM entries").all();
12933
- const explicitDate = (row) => {
12934
- try {
12935
- for (const d of JSON.parse(row.dates ?? "[]")) if (d.value && validTopicDate(d.value)) return d.value;
12936
- } catch {
12937
- }
12938
- return null;
12939
- };
12940
- const filenameDate = (row) => {
12941
- const name = row.source_path ?? "";
12942
- const fromName = /(?<!\d)(\d{4}-\d{2}-\d{2})(?!\d)/.exec(name)?.[1];
12943
- if (fromName && validTopicDate(fromName)) return fromName;
12944
- const mmdd = /(?<=_)(0[1-9]|1[0-2])(0[1-9]|[12]\d|3[01])(?!\d)/.exec(name);
12945
- const stamped = mmdd ? `${LEGACY_TOPIC_YEAR}-${mmdd[1]}-${mmdd[2]}` : null;
12946
- return stamped && validTopicDate(stamped) ? stamped : null;
12947
- };
12948
- const fileMin = /* @__PURE__ */ new Map();
12949
- for (const row of rows) {
12950
- const date = explicitDate(row);
12951
- if (date && (!fileMin.has(row.source_path) || date < fileMin.get(row.source_path))) fileMin.set(row.source_path, date);
12952
- }
13111
+ const rows = db.prepare("SELECT ref,body,title,source_path FROM entries").all();
12953
13112
  const byHash = /* @__PURE__ */ new Map();
12954
13113
  for (const row of rows) {
12955
13114
  const hash7 = digest(String(row.body ?? "").trim());
@@ -12960,7 +13119,7 @@ function loadIndexFragments(b) {
12960
13119
  body: String(row.body ?? ""),
12961
13120
  title: String(row.title || row.source_path || "\u65E7 topics \u6BB5\u843D"),
12962
13121
  sourcePath,
12963
- date: explicitDate(row) ?? fileMin.get(sourcePath) ?? filenameDate(row)
13122
+ date: archiveDate(sourcePath)
12964
13123
  };
12965
13124
  const existing = byHash.get(hash7);
12966
13125
  if (!existing || !!existing.date !== !!fragment.date && !!fragment.date || !!existing.date === !!fragment.date && existing.sourcePath.includes("_root_residue") && !fragment.sourcePath.includes("_root_residue"))
@@ -13007,12 +13166,16 @@ async function importTopicsLocked(b, options) {
13007
13166
  byDate.set(fragment.date, batch);
13008
13167
  }
13009
13168
  const idsByContent = /* @__PURE__ */ new Map();
13010
- if (byDate.size) {
13011
- const table = await store.vectorStore().table("episode");
13012
- const owner = scope.ownerId.replace(/'/g, "''");
13013
- const existing = await table.query().where(`owner_id='${owner}' AND app_id='default' AND project_id='default'`).select(["id", "content_sha256"]).toArray();
13014
- for (const row of existing) if (typeof row.id === "string" && /^tp_[a-f0-9]{12}$/.test(row.id))
13169
+ const existingById = /* @__PURE__ */ new Map();
13170
+ const staleRows = /* @__PURE__ */ new Map();
13171
+ const owner = scope.ownerId.replace(/'/g, "''");
13172
+ const episodeTable = byDate.size ? await store.vectorStore().table("episode") : void 0;
13173
+ if (episodeTable) {
13174
+ const existing = await episodeTable.query().where(`owner_id='${owner}' AND app_id='default' AND project_id='default'`).select(["id", "content_sha256", "md_path"]).toArray();
13175
+ for (const row of existing) if (typeof row.id === "string" && /^tp_[a-f0-9]{12}$/.test(row.id)) {
13015
13176
  idsByContent.set(String(row.content_sha256), row.id);
13177
+ existingById.set(row.id, { sha: String(row.content_sha256), date: /episode-(\d{4}-\d{2}-\d{2})\.md$/.exec(String(row.md_path ?? ""))?.[1] ?? "" });
13178
+ }
13016
13179
  }
13017
13180
  const pendingEmbeddings = [];
13018
13181
  const pendingHashes = [];
@@ -13040,12 +13203,19 @@ async function importTopicsLocked(b, options) {
13040
13203
  }
13041
13204
  }
13042
13205
  }
13206
+ if (episodeTable) for (const r of slice) {
13207
+ const oldSha = staleRows.get(String(r.rowId));
13208
+ if (oldSha === void 0) continue;
13209
+ await episodeTable.delete(`id = '${String(r.rowId).replace(/'/g, "''")}' AND owner_id = '${owner}' AND app_id = 'default' AND project_id = 'default' AND content_sha256 = '${oldSha.replace(/'/g, "''")}'`);
13210
+ staleRows.delete(String(r.rowId));
13211
+ }
13043
13212
  await store.insertEmbeddings(slice);
13044
13213
  completed.push(...pendingHashes.slice(i, i + EMBED_SLICE));
13045
13214
  }
13046
13215
  pendingEmbeddings.length = 0;
13047
13216
  pendingHashes.length = 0;
13048
13217
  };
13218
+ const written = /* @__PURE__ */ new Map();
13049
13219
  for (const [date, batch] of byDate) {
13050
13220
  try {
13051
13221
  const built = batch.map((fragment) => {
@@ -13055,6 +13225,8 @@ async function importTopicsLocked(b, options) {
13055
13225
  ${fragment.body}`;
13056
13226
  const hash7 = contentHash(content);
13057
13227
  const id = idsByContent.get(hash7) ?? `tp_${fragment.hash.slice(0, 12)}`;
13228
+ const prior = existingById.get(id);
13229
+ if (prior && (prior.sha !== hash7 || prior.date !== date)) staleRows.set(id, prior.sha);
13058
13230
  const cached2 = vectors.get(fragment.hash);
13059
13231
  if (!cached2) report.zeroVector++;
13060
13232
  const row = {
@@ -13087,6 +13259,7 @@ ${fragment.body}`;
13087
13259
  return { hash: fragment.hash, row, entry };
13088
13260
  });
13089
13261
  store.appendEpisode(scope.ownerId, date, built.map((b2) => b2.entry));
13262
+ for (const b2 of built) written.set(String(b2.row.rowId), { date, contentHash: String(b2.row.contentHash) });
13090
13263
  report.imported += built.length;
13091
13264
  for (const b2 of built) {
13092
13265
  pendingEmbeddings.push(b2.row);
@@ -13100,9 +13273,12 @@ ${fragment.body}`;
13100
13273
  }
13101
13274
  }
13102
13275
  await flushEmbeddings();
13276
+ const purgedMd = store.purgeEpisodeEntries(scope.ownerId, new Map([...written].map(([id, w]) => [id, w.date])));
13277
+ const purgedVec = await purgeStaleVectorRows(store, scope.ownerId, written);
13278
+ if (purgedMd || purgedVec) console.log(`[topics-import] \u8DE8\u8F6E\u53BB\u91CD: md \u5B64\u513F\u5757 ${purgedMd}\uFF0C\u5411\u91CF\u65E7\u884C ${purgedVec}`);
13103
13279
  if (report.failed === 0 && report.total > 0) {
13104
13280
  const markerTemp = `${doneMarker}.${process.pid}.tmp`;
13105
- writeFileSync12(markerTemp, JSON.stringify({ hashes: [.../* @__PURE__ */ new Set([...done, ...completed])], completedAt: (/* @__PURE__ */ new Date()).toISOString(), report }, null, 1));
13281
+ writeFileSync12(markerTemp, JSON.stringify({ hashes: [.../* @__PURE__ */ new Set([...done, ...completed])], completedAt: (/* @__PURE__ */ new Date()).toISOString(), rulesVersion: TOPIC_DATE_RULES_VERSION, report }, null, 1));
13106
13282
  renameSync8(markerTemp, doneMarker);
13107
13283
  try {
13108
13284
  await completeTopicsImportBackup(b.stateDir, root);
@@ -13116,6 +13292,20 @@ ${fragment.body}`;
13116
13292
  } finally {
13117
13293
  }
13118
13294
  }
13295
+ async function purgeStaleVectorRows(store, ownerId, written) {
13296
+ if (!written.size) return 0;
13297
+ const table = await store.vectorStore().table("episode");
13298
+ const owner = ownerId.replace(/'/g, "''");
13299
+ const existing = await table.query().where(`owner_id='${owner}' AND app_id='default' AND project_id='default'`).select(["id", "content_sha256"]).toArray();
13300
+ let removed = 0;
13301
+ for (const row of existing) {
13302
+ const id = String(row.id), want = written.get(id);
13303
+ if (!want || String(row.content_sha256) === want.contentHash) continue;
13304
+ await table.delete(`id = '${id.replace(/'/g, "''")}' AND owner_id = '${owner}' AND app_id = 'default' AND project_id = 'default' AND content_sha256 = '${String(row.content_sha256).replace(/'/g, "''")}'`);
13305
+ removed++;
13306
+ }
13307
+ return removed;
13308
+ }
13119
13309
  function topicsImported(binding2) {
13120
13310
  if (!binding2.stateDir) return false;
13121
13311
  const marker = join22(topicsHistoryRoot(binding2), "topics-import.json");
@@ -13134,7 +13324,11 @@ function topicsImported(binding2) {
13134
13324
  let imported = false;
13135
13325
  try {
13136
13326
  const done = readJson(marker);
13137
- if ((done.report?.total ?? 0) > 0) imported = true;
13327
+ if (typeof done.rulesVersion === "number" && done.rulesVersion !== TOPIC_DATE_RULES_VERSION) {
13328
+ const retired = join22(topicsHistoryRoot(binding2), `topics-import.stale-rules-${(/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-")}.json`);
13329
+ renameSync8(marker, retired);
13330
+ console.warn(`[topics-import] \u65E5\u671F\u89C4\u5219 v${done.rulesVersion}\u2192v${TOPIC_DATE_RULES_VERSION}\uFF0C\u65E7\u6E05\u5355\u4F5C\u5E9F\u91CD\u5F00 \u2192 ${retired}`);
13331
+ } else if ((done.report?.total ?? 0) > 0) imported = true;
13138
13332
  else {
13139
13333
  const retired = join22(topicsHistoryRoot(binding2), `topics-import.degenerate-${(/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-")}.json`);
13140
13334
  renameSync8(marker, retired);
@@ -13191,7 +13385,8 @@ async function backfillTopicsVectors(b, options) {
13191
13385
  contentHash: r.content_sha256 ? String(r.content_sha256) : contentHash(content),
13192
13386
  content,
13193
13387
  subject: r.subject ? String(r.subject) : void 0,
13194
- refDate: String(r.ref_date ?? todayKey()),
13388
+ refDate: /episode-(\d{4}-\d{2}-\d{2})\.md$/.exec(String(r.md_path ?? ""))?.[1] ?? todayKey(),
13389
+ // 1123:表无 ref_date 列,原写法恒落今天;改从 md_path 取
13195
13390
  sessionId: r.session_id ? String(r.session_id) : "topics-import",
13196
13391
  parentId: r.parent_id ? String(r.parent_id) : void 0,
13197
13392
  senderIds: r.sender_ids ? Array.from(r.sender_ids).map(String) : [scope.ownerId],
@@ -13221,7 +13416,7 @@ var init_import_mem7 = __esm({
13221
13416
  });
13222
13417
 
13223
13418
  // src/memory/topics-history/worker.ts
13224
- import { readFileSync as readFileSync17 } from "node:fs";
13419
+ import { readFileSync as readFileSync18 } from "node:fs";
13225
13420
  import { setTimeout as delay } from "node:timers/promises";
13226
13421
 
13227
13422
  // src/config/secrets-env.ts
@@ -13273,9 +13468,9 @@ function readSecretsEntries(stateDir, configName) {
13273
13468
  function loadSecretsEnv(stateDir, configName, options = {}) {
13274
13469
  const selected = readSecretsEntries(stateDir, configName);
13275
13470
  if (!selected) return null;
13276
- for (const [key3, value] of selected.entries) {
13277
- const current2 = process.env[key3];
13278
- 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;
13279
13474
  }
13280
13475
  return selected.path;
13281
13476
  }
@@ -14783,7 +14978,6 @@ var PLACEHOLDER_THINKING_TEXT = "(no reasoning recorded)";
14783
14978
  var PLACEHOLDER_THINKING_SIGNATURE = "00000000-0000-4000-8000-000000000000";
14784
14979
  var MISSING_TOOL_RESULT_TEXT = "[tool result missing: this tool call has no recorded result in history]";
14785
14980
  var AnthropicProvider = class {
14786
- // 模拟 CC 的 X-Claude-Code-Session-Id
14787
14981
  constructor(config) {
14788
14982
  this.config = config;
14789
14983
  let u = (config.baseUrl || "https://api.anthropic.com").trim();
@@ -14795,6 +14989,8 @@ var AnthropicProvider = class {
14795
14989
  name = "anthropic";
14796
14990
  baseUrl;
14797
14991
  sessionId;
14992
+ // 模拟 CC 的 X-Claude-Code-Session-Id
14993
+ adaptiveModels = /* @__PURE__ */ new Set();
14798
14994
  /** Anthropic: system prompt 单独传,不在 messages 里
14799
14995
  * opts.thinkingEnabled:本次请求是否开着 thinking(streamChat 现算后传入)。
14800
14996
  * 只影响 requireThinkingBlocks 的占位块回填——那个约束只对 thinking 开启的请求成立。 */
@@ -14996,7 +15192,7 @@ var AnthropicProvider = class {
14996
15192
  const stableText = params.systemStable || params.systemPrompt || "";
14997
15193
  const dynamicText = params.systemDynamic || "";
14998
15194
  const supportsThinking = !/haiku/i.test(params.model);
14999
- const adaptiveThinking = params.model.includes("M3.1-Flash");
15195
+ const adaptiveThinking = params.model.includes("M3.1-Flash") || this.adaptiveModels.has(params.model);
15000
15196
  const thinkingEnabled = adaptiveThinking || !params.disableThinking && (this.config.thinking?.enabled ?? supportsThinking);
15001
15197
  const thinkingBudget = this.config.thinking?.budgetTokens || 8192;
15002
15198
  const { messages: formatted } = this.formatMessages(
@@ -15109,6 +15305,12 @@ var AnthropicProvider = class {
15109
15305
  }
15110
15306
  if (!response.ok) {
15111
15307
  const text2 = await response.text();
15308
+ if (response.status === 400 && !adaptiveThinking && /requires adaptive thinking|supports adaptive thinking only/i.test(text2)) {
15309
+ this.adaptiveModels.add(params.model);
15310
+ console.warn(`[anthropic] ${params.model} requires adaptive thinking; retrying the complete request once`);
15311
+ yield* this.streamChat(params);
15312
+ return;
15313
+ }
15112
15314
  yield { type: "error", error: `Anthropic API ${response.status}: ${text2}` };
15113
15315
  return;
15114
15316
  }
@@ -15560,8 +15762,8 @@ function cleanSchemaForGemini(schema) {
15560
15762
  const { additionalProperties, $schema, ...rest } = schema;
15561
15763
  if (rest.properties) {
15562
15764
  rest.properties = {};
15563
- for (const [key3, val] of Object.entries(schema.properties)) {
15564
- rest.properties[key3] = cleanSchemaForGemini(val);
15765
+ for (const [key4, val] of Object.entries(schema.properties)) {
15766
+ rest.properties[key4] = cleanSchemaForGemini(val);
15565
15767
  }
15566
15768
  }
15567
15769
  if (rest.items) {
@@ -15645,6 +15847,11 @@ function createProvider(config) {
15645
15847
  }
15646
15848
  }
15647
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
+
15648
15855
  // src/config/features.ts
15649
15856
  init_live();
15650
15857
 
@@ -15788,7 +15995,7 @@ async function waitForIdle() {
15788
15995
  for (; ; ) {
15789
15996
  try {
15790
15997
  await waitForIdle();
15791
- const raw = JSON.parse(readFileSync17(configPath, "utf8").replace(/^\uFEFF/, ""));
15998
+ const raw = JSON.parse(readFileSync18(configPath, "utf8").replace(/^\uFEFF/, ""));
15792
15999
  loadSecretsEnvForConfig(configPath, { overwrite: true });
15793
16000
  const { liveConfig: liveConfig2 } = await Promise.resolve().then(() => (init_live(), live_exports));
15794
16001
  liveConfig2.init(raw);