engine7 7.1.147 → 7.1.149

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.
@@ -5273,6 +5273,38 @@ var ChangeFeed = class _ChangeFeed {
5273
5273
  // src/mem7/core/source-store.ts
5274
5274
  init_read_budget();
5275
5275
 
5276
+ // src/mem7/core/state/watermarks.ts
5277
+ var RETRACTED = `kind IN ('evidence.retracted','memory.deleted')`;
5278
+ function readRetractionSeq(db, scope) {
5279
+ return Number(db.prepare(`SELECT COALESCE(MAX(event_seq),0) seq FROM memory_state_outbox WHERE scope_id=? AND ${RETRACTED}`).get(scope)?.seq ?? 0);
5280
+ }
5281
+ function readRetractionsSince(db, scope, sinceSeq) {
5282
+ return db.prepare(`SELECT event_seq, payload_json FROM memory_state_outbox WHERE scope_id=? AND ${RETRACTED} AND event_seq>? ORDER BY event_seq`).all(scope, sinceSeq).map((row) => {
5283
+ const payload = JSON.parse(row.payload_json);
5284
+ const aggregate = !payload.targetKind || payload.targetKind === "source" ? [payload.aggregateId] : [];
5285
+ return { eventSeq: Number(row.event_seq), sourceIds: [.../* @__PURE__ */ new Set([...payload.sourceIds ?? [], ...aggregate])].filter((id2) => Boolean(id2)) };
5286
+ });
5287
+ }
5288
+ function readSourceSeq(db, scope, sourceId) {
5289
+ const row = db.prepare("SELECT source_seq FROM memory_sources WHERE scope_id=? AND source_id=?").get(scope, sourceId);
5290
+ return row && Number.isSafeInteger(row.source_seq) ? Number(row.source_seq) : null;
5291
+ }
5292
+ function deletionHits(db, scope, events, sourceWatermark, sourceSeqs) {
5293
+ return events.some((event) => event.sourceIds.some((id2) => {
5294
+ const key3 = JSON.stringify([scope, id2]);
5295
+ if (!sourceSeqs.has(key3)) sourceSeqs.set(key3, readSourceSeq(db, scope, id2));
5296
+ const seq = sourceSeqs.get(key3);
5297
+ return seq === null || seq <= sourceWatermark;
5298
+ }));
5299
+ }
5300
+ function deletedWithinView(db, scope, sinceSeq, sourceWatermark, cache) {
5301
+ if (!cache.latest.has(scope)) cache.latest.set(scope, readRetractionSeq(db, scope));
5302
+ if (cache.latest.get(scope) <= sinceSeq) return false;
5303
+ const key3 = JSON.stringify([scope, sinceSeq]);
5304
+ if (!cache.events.has(key3)) cache.events.set(key3, readRetractionsSince(db, scope, sinceSeq));
5305
+ return deletionHits(db, scope, cache.events.get(key3), sourceWatermark, cache.sourceSeqs);
5306
+ }
5307
+
5276
5308
  // src/mem7/core/state/predicates.ts
5277
5309
  var familyRoles = ["father", "mother", "child", "sibling", "spouse", "ex_spouse"];
5278
5310
  var relationshipPredicates = ["relation.family", "relation.colleague", "relation.open"];
@@ -5686,6 +5718,20 @@ var SourceStore = class {
5686
5718
  const row = this.db.prepare("SELECT fact_revision,source_seq,interpreted_seq FROM memory_scopes WHERE scope_id=?").get(scopeId(scope));
5687
5719
  return { factRevision: Number(row?.fact_revision ?? 0), sourceSeq: Number(row?.source_seq ?? 0), interpretedSeq: Number(row?.interpreted_seq ?? 0) };
5688
5720
  }
5721
+ /** Latest deletion or retraction event of the scope; 0 when none ever happened. */
5722
+ retractionSeq(scope) {
5723
+ return readRetractionSeq(this.db, scopeId(scope));
5724
+ }
5725
+ /** Sequence of a source whatever its status. get() hides deleted sources; this does not. */
5726
+ sourceSeqOf(scope, sourceId) {
5727
+ return readSourceSeq(this.db, scopeId(scope), sourceId);
5728
+ }
5729
+ /** A deletion after `sinceSeq` removed a source the node could have seen. One indexed lookup per scope
5730
+ * for the latest deletion, then one event query per (scope, watermark) per cache. */
5731
+ deletedWithinView(scope, sinceSeq, sourceWatermark, cache) {
5732
+ checkMemoryReadBudget();
5733
+ return deletedWithinView(this.db, scopeId(scope), sinceSeq, sourceWatermark, cache);
5734
+ }
5689
5735
  contextRevision(scope) {
5690
5736
  return Number(this.db.prepare("SELECT context_revision FROM memory_scopes WHERE scope_id=?").get(scopeId(scope))?.context_revision ?? 0);
5691
5737
  }
@@ -6888,6 +6934,7 @@ var BM25_FIELDS = {
6888
6934
  var RRF_K = 60;
6889
6935
  var warnedFts = /* @__PURE__ */ new Set();
6890
6936
  var warnedVecIdx = /* @__PURE__ */ new Set();
6937
+ var incompatibleIndexSegments = (error) => error instanceof Error && error.message.includes("Index type URL should be present and identical across all segments");
6891
6938
  var bootAt = Date.now();
6892
6939
  function buildSchemas(arrow) {
6893
6940
  const vecField = () => new arrow.Field("vector", new arrow.FixedSizeList(VECTOR_DIM, new arrow.Field("item", new arrow.Float32(), true)), true);
@@ -7153,18 +7200,18 @@ var Mem7VectorStore = class {
7153
7200
  * 快照版本——18:46 实测:香港相关 episode 在库、探针 BM25 可召回,线上 hybrid 却
7154
7201
  * 0 命中,时序与连续 3 次 conflict 吻合)。
7155
7202
  */
7156
- async ensureFtsIndexes(kind, tbl) {
7203
+ async ensureFtsIndexes(kind, tbl, indices) {
7157
7204
  const lance = await loadLance();
7158
7205
  if (!lance) return;
7159
- let existing = null;
7206
+ let existing;
7207
+ try {
7208
+ existing = new Set((indices ?? await tbl.listIndices()).filter((index) => index.indexType === "FTS").flatMap((index) => index.columns));
7209
+ } catch (err) {
7210
+ console.warn(`[mem7] FTS index check failed for ${kind}: ${err instanceof Error ? err.message : err}`);
7211
+ return;
7212
+ }
7160
7213
  for (const col of BM25_FIELDS[kind]) {
7161
7214
  try {
7162
- if (existing === null) {
7163
- existing = /* @__PURE__ */ new Set();
7164
- for (const idx of await tbl.listIndices()) {
7165
- if (idx.indexType === "FTS") for (const c of idx.columns) existing.add(c);
7166
- }
7167
- }
7168
7215
  if (existing.has(col)) continue;
7169
7216
  assertRuntimeAuthority(this.stateDir, "WRITE");
7170
7217
  await tbl.createIndex(col, {
@@ -7183,6 +7230,34 @@ var Mem7VectorStore = class {
7183
7230
  }
7184
7231
  }
7185
7232
  }
7233
+ /** Called by the idle writer. Intel's all-in-one optimize can append an unreadable ANN delta
7234
+ * to a returned table, even with no new rows. Keep the existing ANN and let queries scan its tail. */
7235
+ async maintainIndexes(kind, canStart) {
7236
+ if (this.options.readOnly) throw new Error("MEM7_VECTOR_READ_ONLY");
7237
+ const tbl = await this.table(kind);
7238
+ if (!canStart()) return;
7239
+ let indices;
7240
+ try {
7241
+ indices = await tbl.listIndices();
7242
+ } catch (error) {
7243
+ if (isIntelMac || !incompatibleIndexSegments(error)) throw error;
7244
+ const statsError = await tbl.indexStats("vector_idx").then(() => void 0, (failure) => failure);
7245
+ if (!incompatibleIndexSegments(statsError)) throw error;
7246
+ const lance = await loadLance();
7247
+ if (!lance || typeof lance.Index?.hnswSq !== "function") throw error;
7248
+ if (!canStart()) return;
7249
+ assertRuntimeAuthority(this.stateDir, "WRITE");
7250
+ await tbl.createIndex("vector", { config: lance.Index.hnswSq({ distanceType: "cosine" }), replace: true });
7251
+ if (this.tables.get(kind) === tbl) this.vectorIndexesReady.add(kind);
7252
+ await this.ensureFtsIndexes(kind, tbl, await tbl.listIndices());
7253
+ console.log(`[mem7] ANN \u7D22\u5F15\u517C\u5BB9\u4FEE\u590D\u5B8C\u6210\uFF08${kind}.vector\uFF09`);
7254
+ return "repaired";
7255
+ }
7256
+ if (isIntelMac && indices.some((index) => index.columns.includes("vector"))) return "preserved";
7257
+ if (!canStart()) return;
7258
+ assertRuntimeAuthority(this.stateDir, "WRITE");
7259
+ return tbl.optimize();
7260
+ }
7186
7261
  /**
7187
7262
  * ANN 向量索引(1004 妹妹 review 版):
7188
7263
  * - ★ **HNSW_SQ + distanceType:'cosine'**——距离必须配 cosine,不传默认 L2 与查询不兼容会
@@ -8232,11 +8307,13 @@ var FactStore = class {
8232
8307
  if (subjectIds?.length === 0) return [];
8233
8308
  const placeholders = subjectIds?.map(() => "?").join(",");
8234
8309
  const relations = relationshipPredicates.map((predicate) => `'${predicate}'`).join(",");
8310
+ const key3 = scopeId(scope);
8311
+ const incomingIds = includeIncoming ? subjectIds : void 0;
8235
8312
  return this.readTransaction(() => {
8236
- const slots = this.db.prepare(`SELECT * FROM fact_slots s WHERE scope_id=?${subjectIds ? ` AND (subject_id IN (${placeholders})${includeIncoming ? ` OR (predicate IN (${relations}) AND EXISTS (
8237
- SELECT 1 FROM fact_assertions a WHERE a.scope_id=s.scope_id AND a.slot_id=s.slot_id AND json_extract(a.value_json,'$.entityId') IN (${placeholders})))` : ""})` : ""} ORDER BY slot_id`).all(scopeId(scope), ...subjectIds ?? [], ...includeIncoming ? subjectIds ?? [] : []);
8238
- const assertionsBySlot = this.versionsBySlot(scopeId(scope), knownAtRevision);
8239
- const revisions = knownAtRevision === void 0 ? null : this.slotRevisionsAt(scopeId(scope), knownAtRevision);
8313
+ const slots = this.db.prepare(`SELECT * FROM fact_slots s WHERE scope_id=?${subjectIds ? ` AND (subject_id IN (${placeholders})${incomingIds ? ` OR (predicate IN (${relations}) AND s.slot_id IN (
8314
+ SELECT a.slot_id FROM fact_assertions a WHERE a.scope_id=? AND json_extract(a.value_json,'$.entityId') IN (${placeholders})))` : ""})` : ""} ORDER BY slot_id`).all(key3, ...subjectIds ?? [], ...incomingIds ? [key3, ...incomingIds] : []);
8315
+ const assertionsBySlot = this.versionsBySlot(key3, knownAtRevision);
8316
+ const revisions = knownAtRevision === void 0 ? null : this.slotRevisionsAt(key3, knownAtRevision);
8240
8317
  return slots.map((slot) => ({
8241
8318
  subjectId: slot.subject_id,
8242
8319
  predicate: slot.predicate,
@@ -11023,13 +11100,13 @@ var Mem7Store = class {
11023
11100
  /** Interpretation reads entities, facts and confirmed mentions, independently of later chat intake. */
11024
11101
  interpretationReadStamp(scope, sourceIds, excludedPredicates = []) {
11025
11102
  return this.readTransaction(() => {
11026
- const retractions = this.db.prepare("SELECT COALESCE(MAX(event_seq),0) seq FROM memory_state_outbox WHERE scope_id=? AND kind IN ('evidence.retracted','memory.deleted')").get(scopeId(scope));
11103
+ const retractions = readRetractionSeq(this.db, scopeId(scope));
11027
11104
  const factRevision = excludedPredicates.length ? this.db.prepare(`SELECT slot_id,revision FROM fact_slots
11028
11105
  WHERE scope_id=? AND predicate NOT IN (${excludedPredicates.map(() => "?").join(",")}) ORDER BY slot_id`).all(scopeId(scope), ...excludedPredicates) : this.facts.revision(scope);
11029
11106
  return JSON.stringify([
11030
11107
  this.entities.revision(scope),
11031
11108
  factRevision,
11032
- retractions.seq,
11109
+ retractions,
11033
11110
  sourceIds.map((id2) => this.entities.sourceMentions(scope, id2))
11034
11111
  ]);
11035
11112
  });
@@ -11046,7 +11123,7 @@ var Mem7Store = class {
11046
11123
  }
11047
11124
  /** History retrieval validates each publication; unrelated received/interpreted prose is not its basis. */
11048
11125
  captureHistoricalReadGuard(scope) {
11049
- const stamp2 = () => this.db.prepare("SELECT COALESCE(MAX(event_seq),0) seq FROM memory_state_outbox WHERE scope_id=? AND kind IN ('evidence.retracted','memory.deleted')").get(scopeId(scope)).seq;
11126
+ const stamp2 = () => readRetractionSeq(this.db, scopeId(scope));
11050
11127
  const captured = stamp2();
11051
11128
  return () => {
11052
11129
  if (stamp2() !== captured) throw new MemoryReadSupersededError();
@@ -11887,12 +11964,11 @@ ${e.outcome}
11887
11964
  };
11888
11965
 
11889
11966
  // src/messages/strip-injected.ts
11890
- var SKILL_GATE_HINT_PREFIX = "\u8FD9\u6761\u6D88\u606F\u662F\u5F00\u53D1\u4EFB\u52A1";
11891
11967
  var SYSTEM_REMINDER_BLOCK = /<system-reminder>[\s\S]*?<\/system-reminder>/g;
11892
11968
  var INJECT_SECTION_HEADS = /^(本轮对话|当前情绪状态|当前模式)/;
11893
11969
  var KNOWN_INJECTED_TEXT = [
11894
- SKILL_GATE_HINT_PREFIX,
11895
- // skill-gate hint 默认/自定义前缀(1007 现行)
11970
+ "\u8FD9\u6761\u6D88\u606F\u662F\u5F00\u53D1\u4EFB\u52A1",
11971
+ // 旧版 skill-gate 提示前缀,兼容未打标签的历史
11896
11972
  "\u5F00\u53D1\u4EFB\u52A1\u8DEF\u6807\uFF0C\u6309\u573A\u666F\u5BF9\u53F7\u5165\u5EA7",
11897
11973
  // skill-gate hint(0912 老文案,历史 JSONL 兼容)
11898
11974
  "\u3010\u5B9A\u65F6\u5FC3\u8DF3\u3011\u8BF7 read HEARTBEAT.md"