engine7 7.1.152 → 7.1.154

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.
@@ -1367,6 +1367,7 @@ var tokenizer_exports = {};
1367
1367
  __export(tokenizer_exports, {
1368
1368
  DEFAULT_STOPWORDS: () => DEFAULT_STOPWORDS,
1369
1369
  MIN_TOKEN_LENGTH: () => MIN_TOKEN_LENGTH,
1370
+ TOKENIZER_VERSION: () => TOKENIZER_VERSION,
1370
1371
  cjkBigrams: () => cjkBigrams,
1371
1372
  tokenize: () => tokenize,
1372
1373
  tokenizeCjk: () => tokenizeCjk,
@@ -1379,7 +1380,7 @@ function engine() {
1379
1380
  return jieba;
1380
1381
  }
1381
1382
  function tokenize(text2) {
1382
- const raw = engine().cutForSearch(String(text2 ?? ""));
1383
+ const raw = engine().cutForSearch(String(text2 ?? ""), true);
1383
1384
  const out = [];
1384
1385
  for (const t of raw) {
1385
1386
  const tok = t.trim().toLowerCase();
@@ -1402,7 +1403,7 @@ function cjkBigrams(text2) {
1402
1403
  function tokenizeCjk(text2) {
1403
1404
  return [...tokenize(text2), ...cjkBigrams(text2)];
1404
1405
  }
1405
- var DEFAULT_STOPWORDS, MIN_TOKEN_LENGTH, jieba;
1406
+ var DEFAULT_STOPWORDS, MIN_TOKEN_LENGTH, TOKENIZER_VERSION, jieba;
1406
1407
  var init_tokenizer = __esm({
1407
1408
  "src/mem7/core/tokenizer.ts"() {
1408
1409
  "use strict";
@@ -1474,6 +1475,7 @@ var init_tokenizer = __esm({
1474
1475
  "\u54E6"
1475
1476
  ]);
1476
1477
  MIN_TOKEN_LENGTH = 2;
1478
+ TOKENIZER_VERSION = 2;
1477
1479
  jieba = null;
1478
1480
  }
1479
1481
  });
@@ -2406,6 +2408,10 @@ function invalidateChildren(db, scope, pending, reason) {
2406
2408
  if (!referencedPlan.get(scope, child.child_id, scope, child.child_id)) continue;
2407
2409
  }
2408
2410
  const state = child.deleted ? "deleted" : "needs_revalidation";
2411
+ if (child.child_kind === "foresight" && !child.deleted) {
2412
+ pending.push(...db.prepare(`SELECT child_kind,child_id,role FROM memory_dependencies WHERE scope_id=? AND parent_kind='artifact' AND parent_id=?`).all(scope, child.child_id).map((row) => ({ ...row })));
2413
+ continue;
2414
+ }
2409
2415
  db.prepare(`UPDATE memory_derivations SET state=?,reason=?,updated_at=?
2410
2416
  WHERE scope_id=? AND child_kind=? AND child_id=? AND state IN ('current','needs_revalidation') AND state<>?`).run(state, reason, (/* @__PURE__ */ new Date()).toISOString(), scope, child.child_kind, child.child_id, state);
2411
2417
  result.push(child.child_id);
@@ -2634,12 +2640,14 @@ var init_dependencies = __esm({
2634
2640
  return false;
2635
2641
  }
2636
2642
  }
2637
- dirty(scope) {
2643
+ /** excludeKinds:没有重验消费者的类别不计入(1203:foresight,1015 起不做周期重验,见 invalidateChildren)。 */
2644
+ dirty(scope, options = {}) {
2638
2645
  return this.readTransaction(() => {
2639
2646
  checkMemoryReadBudget();
2640
2647
  const memo = /* @__PURE__ */ new Map();
2641
2648
  return this.db.prepare("SELECT child_kind,child_id,version,state,updated_at FROM memory_derivations WHERE scope_id=? AND state IN ('current','needs_revalidation')").all(scopeId(scope)).filter((row) => {
2642
2649
  checkMemoryReadBudget();
2650
+ if (options.excludeKinds?.has(row.child_kind)) return false;
2643
2651
  return row.state === "needs_revalidation" || !this.artifactTimeCurrent(scope, row.child_kind, row.child_id, /* @__PURE__ */ new Set(), memo);
2644
2652
  }).map((row) => ({
2645
2653
  kind: row.child_kind,
@@ -2649,6 +2657,20 @@ var init_dependencies = __esm({
2649
2657
  }));
2650
2658
  });
2651
2659
  }
2660
+ /** needs_revalidation 的派生件按给定的现势状态归位(1203:foresight 一次性清标记——开窗的回 current、
2661
+ * 过期的 retire、行已不存在的记 deleted)。只动 needs_revalidation,不碰 current/invalid/deleted。 */
2662
+ settleRevalidation(scope, kind, verdicts) {
2663
+ return this.transaction(() => {
2664
+ const rows = this.db.prepare("SELECT child_id FROM memory_derivations WHERE scope_id=? AND child_kind=? AND state='needs_revalidation'").all(scopeId(scope), kind);
2665
+ let settled = 0;
2666
+ for (const row of rows) {
2667
+ const verdict = verdicts.get(row.child_id);
2668
+ if (!verdict) continue;
2669
+ settled += Number(this.db.prepare("UPDATE memory_derivations SET state=?,reason=?,updated_at=? WHERE scope_id=? AND child_kind=? AND child_id=? AND state='needs_revalidation'").run(verdict.state, verdict.reason, (/* @__PURE__ */ new Date()).toISOString(), scopeId(scope), kind, row.child_id).changes);
2670
+ }
2671
+ return settled;
2672
+ });
2673
+ }
2652
2674
  invalidate(scope, kind, id, expectedVersion, reason) {
2653
2675
  this.transaction(() => {
2654
2676
  this.db.prepare("UPDATE memory_derivations SET state='invalid',reason=?,updated_at=? WHERE scope_id=? AND child_kind=? AND child_id=? AND version=? AND state IN ('current','needs_revalidation')").run(reason, (/* @__PURE__ */ new Date()).toISOString(), scopeId(scope), kind, id, expectedVersion);
@@ -2904,11 +2926,17 @@ function loadArrow() {
2904
2926
  }
2905
2927
  return arrowPromise;
2906
2928
  }
2907
- function shortCjkQueryBigrams(text2) {
2908
- const chars = (String(text2 ?? "").match(/[\u4e00-\u9fff]/g) ?? []).length;
2909
- if (!chars || chars > 6) return null;
2910
- const grams = [...new Set(cjkBigrams(text2))].slice(0, 8);
2911
- return grams.length ? grams : null;
2929
+ function plainRow(row) {
2930
+ const out = {};
2931
+ for (const [key4, value] of Object.entries(row)) {
2932
+ if (TIMESTAMP_COLUMNS.has(key4) && typeof value === "number") {
2933
+ out[key4] = new Date(value);
2934
+ continue;
2935
+ }
2936
+ const raw = value !== null && typeof value === "object" && typeof value.toArray === "function" ? value.toArray() : value;
2937
+ out[key4] = raw !== null && typeof raw === "object" && ArrayBuffer.isView(raw) ? Array.from(raw) : raw;
2938
+ }
2939
+ return out;
2912
2940
  }
2913
2941
  function buildSchemas(arrow) {
2914
2942
  const vecField = () => new arrow.Field("vector", new arrow.FixedSizeList(VECTOR_DIM, new arrow.Field("item", new arrow.Float32(), true)), true);
@@ -3006,7 +3034,7 @@ function textColumnOf(kind) {
3006
3034
  return "fact";
3007
3035
  }
3008
3036
  }
3009
- var isIntelMac, lancePromise, mem7VectorWarning, arrowPromise, Mem7VectorUnavailableError, VECTOR_DIM, BM25_FIELDS, BM25_TEXT_FIELDS, sqlLiteral, RRF_K, warnedFts, warnedVecIdx, incompatibleIndexSegments, bootAt, schemasCache, Mem7VectorStore;
3037
+ var isIntelMac, lancePromise, mem7VectorWarning, arrowPromise, Mem7VectorUnavailableError, VECTOR_DIM, BM25_FIELDS, TOKEN_FIELDS, TIMESTAMP_COLUMNS, RRF_K, warnedFts, warnedVecIdx, incompatibleIndexSegments, bootAt, schemasCache, Mem7VectorStore;
3010
3038
  var init_vector_store = __esm({
3011
3039
  "src/mem7/core/vector-store.ts"() {
3012
3040
  "use strict";
@@ -3037,14 +3065,14 @@ var init_vector_store = __esm({
3037
3065
  agent_case: ["task_intent_tokens", "approach_tokens"],
3038
3066
  agent_skill: ["description_tokens", "content_tokens"]
3039
3067
  };
3040
- BM25_TEXT_FIELDS = {
3041
- foresight: ["foresight", "evidence"],
3042
- episode: ["episode"],
3043
- atomic_fact: ["fact"],
3044
- agent_case: ["task_intent", "approach"],
3045
- agent_skill: ["description", "content"]
3068
+ TOKEN_FIELDS = {
3069
+ foresight: [["foresight", "foresight_tokens"], ["evidence", "evidence_tokens"]],
3070
+ episode: [["episode", "episode_tokens"]],
3071
+ atomic_fact: [["fact", "fact_tokens"]],
3072
+ agent_case: [["task_intent", "task_intent_tokens"], ["approach", "approach_tokens"]],
3073
+ agent_skill: [["description", "description_tokens"], ["content", "content_tokens"]]
3046
3074
  };
3047
- sqlLiteral = (value) => value.replace(/'/g, "''");
3075
+ TIMESTAMP_COLUMNS = /* @__PURE__ */ new Set(["created_at", "updated_at", "timestamp", "start_time", "end_time"]);
3048
3076
  RRF_K = 60;
3049
3077
  warnedFts = /* @__PURE__ */ new Set();
3050
3078
  warnedVecIdx = /* @__PURE__ */ new Set();
@@ -3066,6 +3094,8 @@ var init_vector_store = __esm({
3066
3094
  vectorIndexChecks = /* @__PURE__ */ new Map();
3067
3095
  vectorIndexRechecks = /* @__PURE__ */ new Set();
3068
3096
  vectorIndexesReady = /* @__PURE__ */ new Set();
3097
+ /** 自上次 optimize 后有写入的表(bg-worker 每小时收一次,见 optimizePending) */
3098
+ unoptimized = /* @__PURE__ */ new Set();
3069
3099
  ledger = null;
3070
3100
  ledgerPath;
3071
3101
  withProofSnapshot = (operation) => {
@@ -3445,10 +3475,25 @@ var init_vector_store = __esm({
3445
3475
  assertRuntimeAuthority(this.stateDir, "WRITE");
3446
3476
  validate?.();
3447
3477
  await tbl.add(mapped);
3478
+ this.unoptimized.add(kind);
3448
3479
  assertRuntimeAuthority(this.stateDir, "WRITE");
3449
3480
  validate?.();
3450
3481
  void this.ensureVectorIndexes(kind, tbl, true);
3451
3482
  }
3483
+ /**
3484
+ * 有写入的表做一次 optimize。1203 实测:lancedb 新写入片段在 optimize 之前 FTS 匹配不到多字中文词
3485
+ * (MatchQuery('山径') 新行 0 命中 → optimize 后 3;ASCII 词不受影响),新对话的中文词 BM25 要等这一步才看得见。
3486
+ */
3487
+ async optimizePending() {
3488
+ const done = [];
3489
+ for (const kind of [...this.unoptimized]) {
3490
+ const tbl = await this.table(kind);
3491
+ await tbl.optimize();
3492
+ this.unoptimized.delete(kind);
3493
+ done.push(kind);
3494
+ }
3495
+ return done;
3496
+ }
3452
3497
  /**
3453
3498
  * 按 id upsert(everos repo.upsert 语义,1004 read 侧):digest 相同 → 跳过(不重嵌
3454
3499
  * 不重写,everos cascade 的 content_sha256 diff-skip);digest 变了 → 删旧行再插新。
@@ -3469,6 +3514,7 @@ var init_vector_store = __esm({
3469
3514
  assertRuntimeAuthority(this.stateDir, "WRITE");
3470
3515
  validate?.();
3471
3516
  await tbl.delete(`id = '${r.id.replace(/'/g, "''")}'`);
3517
+ this.unoptimized.add(kind);
3472
3518
  assertRuntimeAuthority(this.stateDir, "WRITE");
3473
3519
  validate?.();
3474
3520
  await this.insert(kind, [r], validate);
@@ -3488,6 +3534,49 @@ var init_vector_store = __esm({
3488
3534
  return null;
3489
3535
  }
3490
3536
  }
3537
+ /**
3538
+ * 分词器版本变了(TOKENIZER_VERSION)→ 存量行的 *_tokens 按当前 tokenize() 重切(1203:HMM 开回 everos 默认,
3539
+ * 人名要进索引)。向量不动:整行原样回写只改 tokens 列,按 id 分批 mergeInsert;有改动就 optimize 一次
3540
+ * (新片段不进 ANN/FTS 索引,重切完不 optimize 等于没切)。先取全量 id 再分批——回写会产生新片段,
3541
+ * 边写边按 offset 翻页会漏行/重行。
3542
+ */
3543
+ async retokenize(kind, options = {}) {
3544
+ if (this.options.readOnly) throw new Error("MEM7_VECTOR_READ_ONLY");
3545
+ if (!this.tables.has(kind) && !this.openingTables.has(kind) && !existsSync2(join5(this.dir, `${kind}.lance`))) return { rows: 0, changed: 0 };
3546
+ const tbl = await this.table(kind);
3547
+ const fields = TOKEN_FIELDS[kind];
3548
+ const batchSize = Math.max(1, options.batchSize ?? 500);
3549
+ const ids = [];
3550
+ for (let offset = 0; ; offset += 5e3) {
3551
+ const page = await tbl.query().select(["id"]).limit(5e3).offset(offset).toArray();
3552
+ for (const row of page) ids.push(String(row.id));
3553
+ if (page.length < 5e3) break;
3554
+ }
3555
+ let changed = 0;
3556
+ for (let start = 0; start < ids.length; start += batchSize) {
3557
+ assertRuntimeAuthority(this.stateDir, "WRITE");
3558
+ const slice = ids.slice(start, start + batchSize);
3559
+ const rows = await tbl.query().where(`id IN (${slice.map((id) => `'${id.replace(/'/g, "''")}'`).join(",")})`).toArray();
3560
+ const updates = [];
3561
+ for (const row of rows) {
3562
+ let diff = false;
3563
+ for (const [textCol, tokenCol] of fields) {
3564
+ const next = tokenizeToField(String(row[textCol] ?? ""));
3565
+ if (next !== String(row[tokenCol] ?? "")) {
3566
+ row[tokenCol] = next;
3567
+ diff = true;
3568
+ }
3569
+ }
3570
+ if (!diff) continue;
3571
+ updates.push(plainRow(row));
3572
+ }
3573
+ if (updates.length) await tbl.mergeInsert("id").whenMatchedUpdateAll().execute(updates);
3574
+ changed += updates.length;
3575
+ options.onProgress?.(Math.min(ids.length, start + batchSize), ids.length);
3576
+ }
3577
+ if (changed) await tbl.optimize();
3578
+ return { rows: ids.length, changed };
3579
+ }
3491
3580
  /** KNN(lancedb vectorSearch:cosine 距离,score=1-distance) */
3492
3581
  async readVisibleCandidates(kind, limit, query, method = "scan") {
3493
3582
  let count = Math.max(1, limit);
@@ -3642,28 +3731,6 @@ var init_vector_store = __esm({
3642
3731
  if (!cur || score > Number(cur._score ?? 0)) best.set(rid, r);
3643
3732
  }
3644
3733
  }
3645
- const grams = shortCjkQueryBigrams(queryText);
3646
- if (grams) {
3647
- try {
3648
- const textCols = BM25_TEXT_FIELDS[kind];
3649
- const expr = textCols.map((col) => `(${grams.map((g) => `contains(${col}, '${sqlLiteral(g)}')`).join(" OR ")})`).join(" OR ");
3650
- const where2 = compileFilter(opts.filter);
3651
- const extra = await tbl.query().where(where2 ? `(${where2}) AND (${expr})` : expr).limit(topK * 3).toArray();
3652
- const maxScore = [...best.values()].reduce((max, r) => Math.max(max, Number(r._score ?? 0)), 0);
3653
- for (const r of extra) {
3654
- const rid = String(r.id ?? "");
3655
- if (!rid) continue;
3656
- const text2 = textCols.map((col) => String(r[col] ?? "")).join(" ");
3657
- const matched = grams.filter((gram) => text2.includes(gram)).length;
3658
- if (!matched) continue;
3659
- const score = maxScore + matched / grams.length;
3660
- const cur = best.get(rid);
3661
- if (cur) cur._score = Math.max(Number(cur._score ?? 0), score);
3662
- else best.set(rid, { ...r, _score: score });
3663
- }
3664
- } catch {
3665
- }
3666
- }
3667
3734
  return this.visibleRows(kind, [...best.values()]).filter((r) => Number(r._score ?? 0) > 0).sort((a, b) => Number(b._score ?? 0) - Number(a._score ?? 0)).slice(0, topK).map((r) => ({ ...this.toHit(kind, r), distance: 0, score: Number(r._score ?? 0) }));
3668
3735
  } catch (err) {
3669
3736
  const msg = String(err?.message ?? err);
@@ -15621,7 +15688,8 @@ function buildMemoryContext(store, scope, request, clock = () => (/* @__PURE__ *
15621
15688
  if (!resolved.has(id)) resolved.set(id, store.entities.resolve(scope, id, snapshot.entityRevision, cutoff ?? void 0));
15622
15689
  return resolved.get(id);
15623
15690
  };
15624
- const resolvedSelection = new Set((request.entityRef || matching.length ? matching : entities).map((entity) => resolve13(entity.entityId)?.entityId));
15691
+ const pool = request.entityRef || matching.length ? matching : request.matchedEntitiesOnly ? [] : entities;
15692
+ const resolvedSelection = new Set(pool.map((entity) => resolve13(entity.entityId)?.entityId));
15625
15693
  const selected = new Set(entities.filter((entity) => resolvedSelection.has(resolve13(entity.entityId)?.entityId)).map((entity) => entity.entityId));
15626
15694
  const context = {
15627
15695
  validAt,
@@ -15632,7 +15700,7 @@ function buildMemoryContext(store, scope, request, clock = () => (/* @__PURE__ *
15632
15700
  historicalFacts: [],
15633
15701
  ...request.includeProjectionStatus === false ? {} : { projections: {
15634
15702
  pendingJobs: store.jobStatus(scope).filter((job) => ["pending", "running", "failed"].includes(job.state)).length,
15635
- dirtyArtifacts: store.dependencies.dirty(scope).length,
15703
+ dirtyArtifacts: store.dependencies.dirty(scope, { excludeKinds: NO_REVALIDATION_KINDS }).length,
15636
15704
  ...cutoff ? { asOf: "current" } : {}
15637
15705
  } },
15638
15706
  futureChanges: [],
@@ -15925,6 +15993,7 @@ function attachHistoricalEvidence(store, scope, context, request, episodes) {
15925
15993
  });
15926
15994
  return boundMemoryContext(context, request.maxTokens ?? 3e3);
15927
15995
  }
15996
+ var NO_REVALIDATION_KINDS;
15928
15997
  var init_context = __esm({
15929
15998
  "src/mem7/core/context.ts"() {
15930
15999
  "use strict";
@@ -15937,6 +16006,7 @@ var init_context = __esm({
15937
16006
  init_relationship_context();
15938
16007
  init_read_budget();
15939
16008
  init_fit_prefix();
16009
+ NO_REVALIDATION_KINDS = /* @__PURE__ */ new Set(["foresight"]);
15940
16010
  }
15941
16011
  });
15942
16012
 
@@ -19998,13 +20068,10 @@ var init_intent = __esm({
19998
20068
  }
19999
20069
  });
20000
20070
 
20001
- // src/memory/proactive/sweep.ts
20002
- var init_sweep = __esm({
20003
- "src/memory/proactive/sweep.ts"() {
20071
+ // src/memory/proactive/care-leads.ts
20072
+ var init_care_leads = __esm({
20073
+ "src/memory/proactive/care-leads.ts"() {
20004
20074
  "use strict";
20005
- init_calendar_bridge();
20006
- init_intent();
20007
- init_clock();
20008
20075
  }
20009
20076
  });
20010
20077
 
@@ -20033,7 +20100,8 @@ var init_opportunity = __esm({
20033
20100
  init_read_guard();
20034
20101
  init_scoped_opportunity();
20035
20102
  init_published_basis();
20036
- init_sweep();
20103
+ init_intent();
20104
+ init_care_leads();
20037
20105
  OPPORTUNITY_SCAN_INTERVAL_MS = 6 * 60 * 6e4;
20038
20106
  FORESIGHT_CACHE_TTL_MS = 30 * 6e4;
20039
20107
  OPPORTUNITY_DELAY_MS = 30 * 6e4;
@@ -20057,6 +20125,16 @@ var init_agent = __esm({
20057
20125
  }
20058
20126
  });
20059
20127
 
20128
+ // src/memory/proactive/sweep.ts
20129
+ var init_sweep = __esm({
20130
+ "src/memory/proactive/sweep.ts"() {
20131
+ "use strict";
20132
+ init_calendar_bridge();
20133
+ init_intent();
20134
+ init_clock();
20135
+ }
20136
+ });
20137
+
20060
20138
  // src/memory/proactive/planning-context.ts
20061
20139
  import { DatabaseSync as DatabaseSync13 } from "node:sqlite";
20062
20140
  var init_planning_context = __esm({
@@ -23558,27 +23636,8 @@ function mem7RelationshipContext(binding, args, hostBudget, options = {}) {
23558
23636
  });
23559
23637
  return result;
23560
23638
  }
23561
- function boundSearchResponse(context, episodes, maxTokens, historySearch) {
23562
- const result = { ...context, episodes, ...historySearch ? { historySearch } : {} };
23563
- const budget = maxTokens ?? Math.min(64e3, 3e3 + roughTokenCountEstimation(JSON.stringify(episodes)) + 100);
23564
- const exceeds = () => JSON.stringify(result).length > budget * 4 || roughTokenCountEstimation(JSON.stringify(result)) > budget;
23565
- if (exceeds()) {
23566
- const reserve = budget - 140 - roughTokenCountEstimation(JSON.stringify(result.episodes));
23567
- try {
23568
- const trimmed = boundMemoryContext(context, Math.max(1, reserve));
23569
- Object.assign(result, trimmed);
23570
- if (!trimmed.relationships) delete result.relationships;
23571
- result.truncated = true;
23572
- } catch {
23573
- for (const collection of ["pendingSources", "historicalEvidence", "historicalFacts", "hypotheses", "futureChanges", "people", "currentFacts", "conflicts", "ambiguity", "citations"]) {
23574
- result[collection] = [];
23575
- }
23576
- delete result.relationships;
23577
- result.truncated = true;
23578
- }
23579
- }
23580
- if (result.truncated && historySearch?.status === "complete") historySearch.status = "partial";
23581
- return JSON.stringify(result);
23639
+ function boundSearchResponse(context, episodes, historySearch) {
23640
+ return JSON.stringify({ ...context, episodes, ...historySearch ? { historySearch } : {} });
23582
23641
  }
23583
23642
  function searchResponse(service, request, episodes, historySearch) {
23584
23643
  const retained = episodes.filter((episode) => {
@@ -23622,7 +23681,7 @@ function searchResponse(service, request, episodes, historySearch) {
23622
23681
  ...episode
23623
23682
  }) => episode);
23624
23683
  if (historySearch.status === "complete") historySearch.status = retained.length < episodes.length ? "partial" : retained.length ? "complete" : "empty";
23625
- return boundSearchResponse(context, histories, request.maxTokens, historySearch);
23684
+ return boundSearchResponse(context, histories, historySearch);
23626
23685
  }
23627
23686
  function bindingMemoryService(binding, options = {}) {
23628
23687
  if (binding.backend !== "mem7" || !binding.stateDir) throw new Error("STORAGE_UNAVAILABLE: mem7 binding requires stateDir");
@@ -23698,7 +23757,8 @@ async function mem7Search(binding, args, options = {}) {
23698
23757
  entityRef: args.entity_ref,
23699
23758
  maxTokens: args.max_tokens,
23700
23759
  sessionId: args.session_id,
23701
- includeRelationships: false
23760
+ includeRelationships: false,
23761
+ matchedEntitiesOnly: true
23702
23762
  };
23703
23763
  const fresh = service.store.readTransaction(() => JSON.parse(searchResponse(
23704
23764
  service,
@@ -23711,7 +23771,7 @@ async function mem7Search(binding, args, options = {}) {
23711
23771
  else if (hits.length && ["unavailable", "timeout", "stale"].includes(result.historySearch.status)) result.historySearch.status = "partial";
23712
23772
  result.topicsHistory = { status: retained.some((ep) => ep.history_ref) ? "complete" : "empty", method: topicsImported(binding) ? "imported_native" : hasTopicsHistory(binding) ? "fts5" : "file_selection" };
23713
23773
  const { episodes: _episodes, ...context } = { ...fresh, topicsHistory: result.topicsHistory };
23714
- return boundSearchResponse(context, retained, args.max_tokens, result.historySearch);
23774
+ return boundSearchResponse(context, retained, result.historySearch);
23715
23775
  });
23716
23776
  }
23717
23777
  async function searchBoundMemory(binding, args, options) {
@@ -23728,7 +23788,8 @@ async function searchBoundMemory(binding, args, options) {
23728
23788
  entityRef: args.entity_ref,
23729
23789
  maxTokens: args.max_tokens,
23730
23790
  sessionId: args.session_id,
23731
- includeRelationships: false
23791
+ includeRelationships: false,
23792
+ matchedEntitiesOnly: true
23732
23793
  };
23733
23794
  validateMemoryContextRequest(service.store, service.scope, request);
23734
23795
  recordSearchTiming("validate", validationStarted);
@@ -23752,7 +23813,6 @@ async function searchBoundMemory(binding, args, options) {
23752
23813
  version: evidence.version,
23753
23814
  publishedAt: evidence.publishedAt
23754
23815
  })),
23755
- request.maxTokens,
23756
23816
  { status: context.historicalEvidence.length ? "complete" : "empty", method: "keyword" }
23757
23817
  );
23758
23818
  });
@@ -1039,6 +1039,10 @@ function invalidateChildren(db, scope, pending, reason) {
1039
1039
  if (!referencedPlan.get(scope, child.child_id, scope, child.child_id)) continue;
1040
1040
  }
1041
1041
  const state = child.deleted ? "deleted" : "needs_revalidation";
1042
+ if (child.child_kind === "foresight" && !child.deleted) {
1043
+ pending.push(...db.prepare(`SELECT child_kind,child_id,role FROM memory_dependencies WHERE scope_id=? AND parent_kind='artifact' AND parent_id=?`).all(scope, child.child_id).map((row) => ({ ...row })));
1044
+ continue;
1045
+ }
1042
1046
  db.prepare(`UPDATE memory_derivations SET state=?,reason=?,updated_at=?
1043
1047
  WHERE scope_id=? AND child_kind=? AND child_id=? AND state IN ('current','needs_revalidation') AND state<>?`).run(state, reason, (/* @__PURE__ */ new Date()).toISOString(), scope, child.child_kind, child.child_id, state);
1044
1048
  result.push(child.child_id);
@@ -778,7 +778,7 @@ function engine() {
778
778
  return jieba;
779
779
  }
780
780
  function tokenize(text2) {
781
- const raw = engine().cutForSearch(String(text2 ?? ""));
781
+ const raw = engine().cutForSearch(String(text2 ?? ""), true);
782
782
  const out = [];
783
783
  for (const t of raw) {
784
784
  const tok = t.trim().toLowerCase();
@@ -3910,6 +3910,10 @@ function invalidateChildren(db, scope, pending2, reason) {
3910
3910
  if (!referencedPlan.get(scope, child.child_id, scope, child.child_id)) continue;
3911
3911
  }
3912
3912
  const state = child.deleted ? "deleted" : "needs_revalidation";
3913
+ if (child.child_kind === "foresight" && !child.deleted) {
3914
+ pending2.push(...db.prepare(`SELECT child_kind,child_id,role FROM memory_dependencies WHERE scope_id=? AND parent_kind='artifact' AND parent_id=?`).all(scope, child.child_id).map((row) => ({ ...row })));
3915
+ continue;
3916
+ }
3913
3917
  db.prepare(`UPDATE memory_derivations SET state=?,reason=?,updated_at=?
3914
3918
  WHERE scope_id=? AND child_kind=? AND child_id=? AND state IN ('current','needs_revalidation') AND state<>?`).run(state, reason, (/* @__PURE__ */ new Date()).toISOString(), scope, child.child_kind, child.child_id, state);
3915
3919
  result.push(child.child_id);
@@ -4138,12 +4142,14 @@ var init_dependencies = __esm({
4138
4142
  return false;
4139
4143
  }
4140
4144
  }
4141
- dirty(scope) {
4145
+ /** excludeKinds:没有重验消费者的类别不计入(1203:foresight,1015 起不做周期重验,见 invalidateChildren)。 */
4146
+ dirty(scope, options = {}) {
4142
4147
  return this.readTransaction(() => {
4143
4148
  checkMemoryReadBudget();
4144
4149
  const memo = /* @__PURE__ */ new Map();
4145
4150
  return this.db.prepare("SELECT child_kind,child_id,version,state,updated_at FROM memory_derivations WHERE scope_id=? AND state IN ('current','needs_revalidation')").all(scopeId(scope)).filter((row) => {
4146
4151
  checkMemoryReadBudget();
4152
+ if (options.excludeKinds?.has(row.child_kind)) return false;
4147
4153
  return row.state === "needs_revalidation" || !this.artifactTimeCurrent(scope, row.child_kind, row.child_id, /* @__PURE__ */ new Set(), memo);
4148
4154
  }).map((row) => ({
4149
4155
  kind: row.child_kind,
@@ -4153,6 +4159,20 @@ var init_dependencies = __esm({
4153
4159
  }));
4154
4160
  });
4155
4161
  }
4162
+ /** needs_revalidation 的派生件按给定的现势状态归位(1203:foresight 一次性清标记——开窗的回 current、
4163
+ * 过期的 retire、行已不存在的记 deleted)。只动 needs_revalidation,不碰 current/invalid/deleted。 */
4164
+ settleRevalidation(scope, kind, verdicts) {
4165
+ return this.transaction(() => {
4166
+ const rows = this.db.prepare("SELECT child_id FROM memory_derivations WHERE scope_id=? AND child_kind=? AND state='needs_revalidation'").all(scopeId(scope), kind);
4167
+ let settled = 0;
4168
+ for (const row of rows) {
4169
+ const verdict = verdicts.get(row.child_id);
4170
+ if (!verdict) continue;
4171
+ settled += Number(this.db.prepare("UPDATE memory_derivations SET state=?,reason=?,updated_at=? WHERE scope_id=? AND child_kind=? AND child_id=? AND state='needs_revalidation'").run(verdict.state, verdict.reason, (/* @__PURE__ */ new Date()).toISOString(), scopeId(scope), kind, row.child_id).changes);
4172
+ }
4173
+ return settled;
4174
+ });
4175
+ }
4156
4176
  invalidate(scope, kind, id, expectedVersion, reason) {
4157
4177
  this.transaction(() => {
4158
4178
  this.db.prepare("UPDATE memory_derivations SET state='invalid',reason=?,updated_at=? WHERE scope_id=? AND child_kind=? AND child_id=? AND version=? AND state IN ('current','needs_revalidation')").run(reason, (/* @__PURE__ */ new Date()).toISOString(), scopeId(scope), kind, id, expectedVersion);
@@ -4331,11 +4351,17 @@ function loadArrow() {
4331
4351
  }
4332
4352
  return arrowPromise;
4333
4353
  }
4334
- function shortCjkQueryBigrams(text2) {
4335
- const chars = (String(text2 ?? "").match(/[\u4e00-\u9fff]/g) ?? []).length;
4336
- if (!chars || chars > 6) return null;
4337
- const grams = [...new Set(cjkBigrams(text2))].slice(0, 8);
4338
- return grams.length ? grams : null;
4354
+ function plainRow(row) {
4355
+ const out = {};
4356
+ for (const [key4, value] of Object.entries(row)) {
4357
+ if (TIMESTAMP_COLUMNS.has(key4) && typeof value === "number") {
4358
+ out[key4] = new Date(value);
4359
+ continue;
4360
+ }
4361
+ const raw = value !== null && typeof value === "object" && typeof value.toArray === "function" ? value.toArray() : value;
4362
+ out[key4] = raw !== null && typeof raw === "object" && ArrayBuffer.isView(raw) ? Array.from(raw) : raw;
4363
+ }
4364
+ return out;
4339
4365
  }
4340
4366
  function buildSchemas(arrow) {
4341
4367
  const vecField = () => new arrow.Field("vector", new arrow.FixedSizeList(VECTOR_DIM, new arrow.Field("item", new arrow.Float32(), true)), true);
@@ -4433,7 +4459,7 @@ function textColumnOf(kind) {
4433
4459
  return "fact";
4434
4460
  }
4435
4461
  }
4436
- var isIntelMac, lancePromise, mem7VectorWarning, arrowPromise, Mem7VectorUnavailableError, VECTOR_DIM, BM25_FIELDS, BM25_TEXT_FIELDS, sqlLiteral, RRF_K, warnedFts, warnedVecIdx, incompatibleIndexSegments, bootAt, schemasCache, Mem7VectorStore;
4462
+ var isIntelMac, lancePromise, mem7VectorWarning, arrowPromise, Mem7VectorUnavailableError, VECTOR_DIM, BM25_FIELDS, TOKEN_FIELDS, TIMESTAMP_COLUMNS, RRF_K, warnedFts, warnedVecIdx, incompatibleIndexSegments, bootAt, schemasCache, Mem7VectorStore;
4437
4463
  var init_vector_store = __esm({
4438
4464
  "src/mem7/core/vector-store.ts"() {
4439
4465
  "use strict";
@@ -4464,14 +4490,14 @@ var init_vector_store = __esm({
4464
4490
  agent_case: ["task_intent_tokens", "approach_tokens"],
4465
4491
  agent_skill: ["description_tokens", "content_tokens"]
4466
4492
  };
4467
- BM25_TEXT_FIELDS = {
4468
- foresight: ["foresight", "evidence"],
4469
- episode: ["episode"],
4470
- atomic_fact: ["fact"],
4471
- agent_case: ["task_intent", "approach"],
4472
- agent_skill: ["description", "content"]
4493
+ TOKEN_FIELDS = {
4494
+ foresight: [["foresight", "foresight_tokens"], ["evidence", "evidence_tokens"]],
4495
+ episode: [["episode", "episode_tokens"]],
4496
+ atomic_fact: [["fact", "fact_tokens"]],
4497
+ agent_case: [["task_intent", "task_intent_tokens"], ["approach", "approach_tokens"]],
4498
+ agent_skill: [["description", "description_tokens"], ["content", "content_tokens"]]
4473
4499
  };
4474
- sqlLiteral = (value) => value.replace(/'/g, "''");
4500
+ TIMESTAMP_COLUMNS = /* @__PURE__ */ new Set(["created_at", "updated_at", "timestamp", "start_time", "end_time"]);
4475
4501
  RRF_K = 60;
4476
4502
  warnedFts = /* @__PURE__ */ new Set();
4477
4503
  warnedVecIdx = /* @__PURE__ */ new Set();
@@ -4493,6 +4519,8 @@ var init_vector_store = __esm({
4493
4519
  vectorIndexChecks = /* @__PURE__ */ new Map();
4494
4520
  vectorIndexRechecks = /* @__PURE__ */ new Set();
4495
4521
  vectorIndexesReady = /* @__PURE__ */ new Set();
4522
+ /** 自上次 optimize 后有写入的表(bg-worker 每小时收一次,见 optimizePending) */
4523
+ unoptimized = /* @__PURE__ */ new Set();
4496
4524
  ledger = null;
4497
4525
  ledgerPath;
4498
4526
  withProofSnapshot = (operation) => {
@@ -4872,10 +4900,25 @@ var init_vector_store = __esm({
4872
4900
  assertRuntimeAuthority(this.stateDir, "WRITE");
4873
4901
  validate?.();
4874
4902
  await tbl.add(mapped);
4903
+ this.unoptimized.add(kind);
4875
4904
  assertRuntimeAuthority(this.stateDir, "WRITE");
4876
4905
  validate?.();
4877
4906
  void this.ensureVectorIndexes(kind, tbl, true);
4878
4907
  }
4908
+ /**
4909
+ * 有写入的表做一次 optimize。1203 实测:lancedb 新写入片段在 optimize 之前 FTS 匹配不到多字中文词
4910
+ * (MatchQuery('山径') 新行 0 命中 → optimize 后 3;ASCII 词不受影响),新对话的中文词 BM25 要等这一步才看得见。
4911
+ */
4912
+ async optimizePending() {
4913
+ const done = [];
4914
+ for (const kind of [...this.unoptimized]) {
4915
+ const tbl = await this.table(kind);
4916
+ await tbl.optimize();
4917
+ this.unoptimized.delete(kind);
4918
+ done.push(kind);
4919
+ }
4920
+ return done;
4921
+ }
4879
4922
  /**
4880
4923
  * 按 id upsert(everos repo.upsert 语义,1004 read 侧):digest 相同 → 跳过(不重嵌
4881
4924
  * 不重写,everos cascade 的 content_sha256 diff-skip);digest 变了 → 删旧行再插新。
@@ -4896,6 +4939,7 @@ var init_vector_store = __esm({
4896
4939
  assertRuntimeAuthority(this.stateDir, "WRITE");
4897
4940
  validate?.();
4898
4941
  await tbl.delete(`id = '${r.id.replace(/'/g, "''")}'`);
4942
+ this.unoptimized.add(kind);
4899
4943
  assertRuntimeAuthority(this.stateDir, "WRITE");
4900
4944
  validate?.();
4901
4945
  await this.insert(kind, [r], validate);
@@ -4915,6 +4959,49 @@ var init_vector_store = __esm({
4915
4959
  return null;
4916
4960
  }
4917
4961
  }
4962
+ /**
4963
+ * 分词器版本变了(TOKENIZER_VERSION)→ 存量行的 *_tokens 按当前 tokenize() 重切(1203:HMM 开回 everos 默认,
4964
+ * 人名要进索引)。向量不动:整行原样回写只改 tokens 列,按 id 分批 mergeInsert;有改动就 optimize 一次
4965
+ * (新片段不进 ANN/FTS 索引,重切完不 optimize 等于没切)。先取全量 id 再分批——回写会产生新片段,
4966
+ * 边写边按 offset 翻页会漏行/重行。
4967
+ */
4968
+ async retokenize(kind, options = {}) {
4969
+ if (this.options.readOnly) throw new Error("MEM7_VECTOR_READ_ONLY");
4970
+ if (!this.tables.has(kind) && !this.openingTables.has(kind) && !existsSync8(join15(this.dir, `${kind}.lance`))) return { rows: 0, changed: 0 };
4971
+ const tbl = await this.table(kind);
4972
+ const fields = TOKEN_FIELDS[kind];
4973
+ const batchSize = Math.max(1, options.batchSize ?? 500);
4974
+ const ids = [];
4975
+ for (let offset = 0; ; offset += 5e3) {
4976
+ const page = await tbl.query().select(["id"]).limit(5e3).offset(offset).toArray();
4977
+ for (const row of page) ids.push(String(row.id));
4978
+ if (page.length < 5e3) break;
4979
+ }
4980
+ let changed = 0;
4981
+ for (let start = 0; start < ids.length; start += batchSize) {
4982
+ assertRuntimeAuthority(this.stateDir, "WRITE");
4983
+ const slice = ids.slice(start, start + batchSize);
4984
+ const rows = await tbl.query().where(`id IN (${slice.map((id) => `'${id.replace(/'/g, "''")}'`).join(",")})`).toArray();
4985
+ const updates = [];
4986
+ for (const row of rows) {
4987
+ let diff = false;
4988
+ for (const [textCol, tokenCol] of fields) {
4989
+ const next = tokenizeToField(String(row[textCol] ?? ""));
4990
+ if (next !== String(row[tokenCol] ?? "")) {
4991
+ row[tokenCol] = next;
4992
+ diff = true;
4993
+ }
4994
+ }
4995
+ if (!diff) continue;
4996
+ updates.push(plainRow(row));
4997
+ }
4998
+ if (updates.length) await tbl.mergeInsert("id").whenMatchedUpdateAll().execute(updates);
4999
+ changed += updates.length;
5000
+ options.onProgress?.(Math.min(ids.length, start + batchSize), ids.length);
5001
+ }
5002
+ if (changed) await tbl.optimize();
5003
+ return { rows: ids.length, changed };
5004
+ }
4918
5005
  /** KNN(lancedb vectorSearch:cosine 距离,score=1-distance) */
4919
5006
  async readVisibleCandidates(kind, limit, query, method = "scan") {
4920
5007
  let count = Math.max(1, limit);
@@ -5069,28 +5156,6 @@ var init_vector_store = __esm({
5069
5156
  if (!cur || score > Number(cur._score ?? 0)) best.set(rid, r);
5070
5157
  }
5071
5158
  }
5072
- const grams = shortCjkQueryBigrams(queryText);
5073
- if (grams) {
5074
- try {
5075
- const textCols = BM25_TEXT_FIELDS[kind];
5076
- const expr = textCols.map((col) => `(${grams.map((g) => `contains(${col}, '${sqlLiteral(g)}')`).join(" OR ")})`).join(" OR ");
5077
- const where2 = compileFilter(opts.filter);
5078
- const extra = await tbl.query().where(where2 ? `(${where2}) AND (${expr})` : expr).limit(topK * 3).toArray();
5079
- const maxScore = [...best.values()].reduce((max, r) => Math.max(max, Number(r._score ?? 0)), 0);
5080
- for (const r of extra) {
5081
- const rid = String(r.id ?? "");
5082
- if (!rid) continue;
5083
- const text2 = textCols.map((col) => String(r[col] ?? "")).join(" ");
5084
- const matched = grams.filter((gram) => text2.includes(gram)).length;
5085
- if (!matched) continue;
5086
- const score = maxScore + matched / grams.length;
5087
- const cur = best.get(rid);
5088
- if (cur) cur._score = Math.max(Number(cur._score ?? 0), score);
5089
- else best.set(rid, { ...r, _score: score });
5090
- }
5091
- } catch {
5092
- }
5093
- }
5094
5159
  return this.visibleRows(kind, [...best.values()]).filter((r) => Number(r._score ?? 0) > 0).sort((a, b) => Number(b._score ?? 0) - Number(a._score ?? 0)).slice(0, topK).map((r) => ({ ...this.toHit(kind, r), distance: 0, score: Number(r._score ?? 0) }));
5095
5160
  } catch (err) {
5096
5161
  const msg = String(err?.message ?? err);
@@ -3835,6 +3835,10 @@ function invalidateChildren(db, scope, pending, reason) {
3835
3835
  if (!referencedPlan.get(scope, child.child_id, scope, child.child_id)) continue;
3836
3836
  }
3837
3837
  const state2 = child.deleted ? "deleted" : "needs_revalidation";
3838
+ if (child.child_kind === "foresight" && !child.deleted) {
3839
+ pending.push(...db.prepare(`SELECT child_kind,child_id,role FROM memory_dependencies WHERE scope_id=? AND parent_kind='artifact' AND parent_id=?`).all(scope, child.child_id).map((row) => ({ ...row })));
3840
+ continue;
3841
+ }
3838
3842
  db.prepare(`UPDATE memory_derivations SET state=?,reason=?,updated_at=?
3839
3843
  WHERE scope_id=? AND child_kind=? AND child_id=? AND state IN ('current','needs_revalidation') AND state<>?`).run(state2, reason, (/* @__PURE__ */ new Date()).toISOString(), scope, child.child_kind, child.child_id, state2);
3840
3844
  result.push(child.child_id);