engine7 7.1.153 → 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.
@@ -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();
@@ -801,22 +801,7 @@ function cjkBigrams(text2) {
801
801
  function tokenizeCjk(text2) {
802
802
  return [...tokenize(text2), ...cjkBigrams(text2)];
803
803
  }
804
- function invisibleCjkNeedles(candidates) {
805
- return [...new Set(candidates.map((token) => token.trim()))].filter((token) => /^[\u4e00-\u9fff]{2,}$/.test(token) && tokenize(token).length === 0).slice(0, 8);
806
- }
807
- function literalQueryNeedles(text2) {
808
- const chars = shortCjkCharCount(text2);
809
- if (!chars || chars > 6) return null;
810
- const names = invisibleCjkNeedles(engine().cut(String(text2 ?? ""), true));
811
- return names.length ? names : queryBigramNeedles(text2);
812
- }
813
- function queryBigramNeedles(text2) {
814
- const chars = shortCjkCharCount(text2);
815
- if (!chars || chars > 6) return null;
816
- const grams = [...new Set(cjkBigrams(text2))].slice(0, 8);
817
- return grams.length ? grams : null;
818
- }
819
- var DEFAULT_STOPWORDS, MIN_TOKEN_LENGTH, jieba, shortCjkCharCount;
804
+ var DEFAULT_STOPWORDS, MIN_TOKEN_LENGTH, jieba;
820
805
  var init_tokenizer = __esm({
821
806
  "src/mem7/core/tokenizer.ts"() {
822
807
  "use strict";
@@ -889,7 +874,6 @@ var init_tokenizer = __esm({
889
874
  ]);
890
875
  MIN_TOKEN_LENGTH = 2;
891
876
  jieba = null;
892
- shortCjkCharCount = (text2) => (String(text2 ?? "").match(/[\u4e00-\u9fff]/g) ?? []).length;
893
877
  }
894
878
  });
895
879
 
@@ -3926,6 +3910,10 @@ function invalidateChildren(db, scope, pending2, reason) {
3926
3910
  if (!referencedPlan.get(scope, child.child_id, scope, child.child_id)) continue;
3927
3911
  }
3928
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
+ }
3929
3917
  db.prepare(`UPDATE memory_derivations SET state=?,reason=?,updated_at=?
3930
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);
3931
3919
  result.push(child.child_id);
@@ -4154,12 +4142,14 @@ var init_dependencies = __esm({
4154
4142
  return false;
4155
4143
  }
4156
4144
  }
4157
- dirty(scope) {
4145
+ /** excludeKinds:没有重验消费者的类别不计入(1203:foresight,1015 起不做周期重验,见 invalidateChildren)。 */
4146
+ dirty(scope, options = {}) {
4158
4147
  return this.readTransaction(() => {
4159
4148
  checkMemoryReadBudget();
4160
4149
  const memo = /* @__PURE__ */ new Map();
4161
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) => {
4162
4151
  checkMemoryReadBudget();
4152
+ if (options.excludeKinds?.has(row.child_kind)) return false;
4163
4153
  return row.state === "needs_revalidation" || !this.artifactTimeCurrent(scope, row.child_kind, row.child_id, /* @__PURE__ */ new Set(), memo);
4164
4154
  }).map((row) => ({
4165
4155
  kind: row.child_kind,
@@ -4169,6 +4159,20 @@ var init_dependencies = __esm({
4169
4159
  }));
4170
4160
  });
4171
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
+ }
4172
4176
  invalidate(scope, kind, id, expectedVersion, reason) {
4173
4177
  this.transaction(() => {
4174
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);
@@ -4347,6 +4351,18 @@ function loadArrow() {
4347
4351
  }
4348
4352
  return arrowPromise;
4349
4353
  }
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;
4365
+ }
4350
4366
  function buildSchemas(arrow) {
4351
4367
  const vecField = () => new arrow.Field("vector", new arrow.FixedSizeList(VECTOR_DIM, new arrow.Field("item", new arrow.Float32(), true)), true);
4352
4368
  const commonFields = () => [
@@ -4443,7 +4459,7 @@ function textColumnOf(kind) {
4443
4459
  return "fact";
4444
4460
  }
4445
4461
  }
4446
- 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;
4447
4463
  var init_vector_store = __esm({
4448
4464
  "src/mem7/core/vector-store.ts"() {
4449
4465
  "use strict";
@@ -4474,14 +4490,14 @@ var init_vector_store = __esm({
4474
4490
  agent_case: ["task_intent_tokens", "approach_tokens"],
4475
4491
  agent_skill: ["description_tokens", "content_tokens"]
4476
4492
  };
4477
- BM25_TEXT_FIELDS = {
4478
- foresight: ["foresight", "evidence"],
4479
- episode: ["episode"],
4480
- atomic_fact: ["fact"],
4481
- agent_case: ["task_intent", "approach"],
4482
- 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"]]
4483
4499
  };
4484
- sqlLiteral = (value) => value.replace(/'/g, "''");
4500
+ TIMESTAMP_COLUMNS = /* @__PURE__ */ new Set(["created_at", "updated_at", "timestamp", "start_time", "end_time"]);
4485
4501
  RRF_K = 60;
4486
4502
  warnedFts = /* @__PURE__ */ new Set();
4487
4503
  warnedVecIdx = /* @__PURE__ */ new Set();
@@ -4503,6 +4519,8 @@ var init_vector_store = __esm({
4503
4519
  vectorIndexChecks = /* @__PURE__ */ new Map();
4504
4520
  vectorIndexRechecks = /* @__PURE__ */ new Set();
4505
4521
  vectorIndexesReady = /* @__PURE__ */ new Set();
4522
+ /** 自上次 optimize 后有写入的表(bg-worker 每小时收一次,见 optimizePending) */
4523
+ unoptimized = /* @__PURE__ */ new Set();
4506
4524
  ledger = null;
4507
4525
  ledgerPath;
4508
4526
  withProofSnapshot = (operation) => {
@@ -4882,10 +4900,25 @@ var init_vector_store = __esm({
4882
4900
  assertRuntimeAuthority(this.stateDir, "WRITE");
4883
4901
  validate?.();
4884
4902
  await tbl.add(mapped);
4903
+ this.unoptimized.add(kind);
4885
4904
  assertRuntimeAuthority(this.stateDir, "WRITE");
4886
4905
  validate?.();
4887
4906
  void this.ensureVectorIndexes(kind, tbl, true);
4888
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
+ }
4889
4922
  /**
4890
4923
  * 按 id upsert(everos repo.upsert 语义,1004 read 侧):digest 相同 → 跳过(不重嵌
4891
4924
  * 不重写,everos cascade 的 content_sha256 diff-skip);digest 变了 → 删旧行再插新。
@@ -4906,6 +4939,7 @@ var init_vector_store = __esm({
4906
4939
  assertRuntimeAuthority(this.stateDir, "WRITE");
4907
4940
  validate?.();
4908
4941
  await tbl.delete(`id = '${r.id.replace(/'/g, "''")}'`);
4942
+ this.unoptimized.add(kind);
4909
4943
  assertRuntimeAuthority(this.stateDir, "WRITE");
4910
4944
  validate?.();
4911
4945
  await this.insert(kind, [r], validate);
@@ -4925,6 +4959,49 @@ var init_vector_store = __esm({
4925
4959
  return null;
4926
4960
  }
4927
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
+ }
4928
5005
  /** KNN(lancedb vectorSearch:cosine 距离,score=1-distance) */
4929
5006
  async readVisibleCandidates(kind, limit, query, method = "scan") {
4930
5007
  let count = Math.max(1, limit);
@@ -5079,47 +5156,6 @@ var init_vector_store = __esm({
5079
5156
  if (!cur || score > Number(cur._score ?? 0)) best.set(rid, r);
5080
5157
  }
5081
5158
  }
5082
- const textCols = BM25_TEXT_FIELDS[kind];
5083
- const scan = async (terms, op, limit) => {
5084
- const expr = op === "AND" ? terms.map((g) => `(${textCols.map((col) => `contains(${col}, '${sqlLiteral(g)}')`).join(" OR ")})`).join(" AND ") : textCols.map((col) => `(${terms.map((g) => `contains(${col}, '${sqlLiteral(g)}')`).join(" OR ")})`).join(" OR ");
5085
- const where2 = compileFilter(opts.filter);
5086
- return await tbl.query().where(where2 ? `(${where2}) AND (${expr})` : expr).limit(limit).toArray();
5087
- };
5088
- const maxScore = [...best.values()].reduce((max, r) => Math.max(max, Number(r._score ?? 0)), 0);
5089
- const scoreLiteral = (needles2, rows) => {
5090
- const terms = [.../* @__PURE__ */ new Set([...needles2, ...tokenizeToField(queryText).split(/\s+/).filter(Boolean)])];
5091
- const occurrences2 = (text2, term) => text2.split(term).length - 1;
5092
- for (const r of rows) {
5093
- const rid = String(r.id ?? "");
5094
- if (!rid) continue;
5095
- const text2 = textCols.map((col) => String(r[col] ?? "")).join(" ");
5096
- const matched = terms.filter((term) => text2.includes(term));
5097
- if (!matched.length || matched.every((term) => !needles2.includes(term))) continue;
5098
- const full = matched.length === terms.length;
5099
- const density = matched.reduce((sum, term) => sum + occurrences2(text2, term), 0) / Math.max(text2.length, 1) * 1e3;
5100
- const score = full ? maxScore + 1 + Math.min(0.99, density / 10) : maxScore > 0 ? maxScore * (0.5 + 0.5 * matched.length / terms.length) : matched.length / terms.length;
5101
- const cur = best.get(rid);
5102
- if (cur) {
5103
- if (full) cur._score = Math.max(Number(cur._score ?? 0), score);
5104
- } else best.set(rid, { ...r, _score: score });
5105
- }
5106
- };
5107
- const needles = literalQueryNeedles(queryText);
5108
- if (needles) {
5109
- try {
5110
- const terms = [.../* @__PURE__ */ new Set([...needles, ...tokenizeToField(queryText).split(/\s+/).filter(Boolean)])];
5111
- const [all, any] = await Promise.all([
5112
- terms.length > 1 ? scan(terms, "AND", topK * 10) : Promise.resolve([]),
5113
- scan(needles, "OR", topK * 3)
5114
- ]);
5115
- scoreLiteral(needles, [...all, ...any]);
5116
- if (![...best.values()].some((r) => Number(r._score ?? 0) > maxScore)) {
5117
- const bigrams = [...new Set(needles.flatMap((name) => queryBigramNeedles(name) ?? []))].slice(0, 8);
5118
- if (bigrams.length && JSON.stringify(bigrams) !== JSON.stringify(needles)) scoreLiteral(bigrams, await scan(bigrams, "OR", topK * 3));
5119
- }
5120
- } catch {
5121
- }
5122
- }
5123
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) }));
5124
5160
  } catch (err) {
5125
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);
@@ -1597,7 +1597,7 @@ function engine() {
1597
1597
  return jieba;
1598
1598
  }
1599
1599
  function tokenize(text2) {
1600
- const raw = engine().cutForSearch(String(text2 ?? ""));
1600
+ const raw = engine().cutForSearch(String(text2 ?? ""), true);
1601
1601
  const out = [];
1602
1602
  for (const t of raw) {
1603
1603
  const tok = t.trim().toLowerCase();
@@ -1610,29 +1610,7 @@ function tokenize(text2) {
1610
1610
  function tokenizeToField(text2) {
1611
1611
  return tokenize(text2).join(" ");
1612
1612
  }
1613
- function cjkBigrams(text2) {
1614
- const out = [];
1615
- for (const seg of String(text2 ?? "").match(/[\u4e00-\u9fff]{2,}/g) ?? []) {
1616
- for (let i = 0; i + 1 < seg.length; i++) out.push(seg.slice(i, i + 2));
1617
- }
1618
- return out;
1619
- }
1620
- function invisibleCjkNeedles(candidates2) {
1621
- return [...new Set(candidates2.map((token) => token.trim()))].filter((token) => /^[\u4e00-\u9fff]{2,}$/.test(token) && tokenize(token).length === 0).slice(0, 8);
1622
- }
1623
- function literalQueryNeedles(text2) {
1624
- const chars = shortCjkCharCount(text2);
1625
- if (!chars || chars > 6) return null;
1626
- const names = invisibleCjkNeedles(engine().cut(String(text2 ?? ""), true));
1627
- return names.length ? names : queryBigramNeedles(text2);
1628
- }
1629
- function queryBigramNeedles(text2) {
1630
- const chars = shortCjkCharCount(text2);
1631
- if (!chars || chars > 6) return null;
1632
- const grams = [...new Set(cjkBigrams(text2))].slice(0, 8);
1633
- return grams.length ? grams : null;
1634
- }
1635
- var DEFAULT_STOPWORDS, MIN_TOKEN_LENGTH, jieba, shortCjkCharCount;
1613
+ var DEFAULT_STOPWORDS, MIN_TOKEN_LENGTH, jieba;
1636
1614
  var init_tokenizer = __esm({
1637
1615
  "src/mem7/core/tokenizer.ts"() {
1638
1616
  "use strict";
@@ -1705,7 +1683,6 @@ var init_tokenizer = __esm({
1705
1683
  ]);
1706
1684
  MIN_TOKEN_LENGTH = 2;
1707
1685
  jieba = null;
1708
- shortCjkCharCount = (text2) => (String(text2 ?? "").match(/[\u4e00-\u9fff]/g) ?? []).length;
1709
1686
  }
1710
1687
  });
1711
1688
 
@@ -2824,6 +2801,10 @@ function invalidateChildren(db2, scope, pending, reason) {
2824
2801
  if (!referencedPlan.get(scope, child.child_id, scope, child.child_id)) continue;
2825
2802
  }
2826
2803
  const state = child.deleted ? "deleted" : "needs_revalidation";
2804
+ if (child.child_kind === "foresight" && !child.deleted) {
2805
+ pending.push(...db2.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 })));
2806
+ continue;
2807
+ }
2827
2808
  db2.prepare(`UPDATE memory_derivations SET state=?,reason=?,updated_at=?
2828
2809
  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);
2829
2810
  result.push(child.child_id);
@@ -3052,12 +3033,14 @@ var init_dependencies = __esm({
3052
3033
  return false;
3053
3034
  }
3054
3035
  }
3055
- dirty(scope) {
3036
+ /** excludeKinds:没有重验消费者的类别不计入(1203:foresight,1015 起不做周期重验,见 invalidateChildren)。 */
3037
+ dirty(scope, options = {}) {
3056
3038
  return this.readTransaction(() => {
3057
3039
  checkMemoryReadBudget();
3058
3040
  const memo = /* @__PURE__ */ new Map();
3059
3041
  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) => {
3060
3042
  checkMemoryReadBudget();
3043
+ if (options.excludeKinds?.has(row.child_kind)) return false;
3061
3044
  return row.state === "needs_revalidation" || !this.artifactTimeCurrent(scope, row.child_kind, row.child_id, /* @__PURE__ */ new Set(), memo);
3062
3045
  }).map((row) => ({
3063
3046
  kind: row.child_kind,
@@ -3067,6 +3050,20 @@ var init_dependencies = __esm({
3067
3050
  }));
3068
3051
  });
3069
3052
  }
3053
+ /** needs_revalidation 的派生件按给定的现势状态归位(1203:foresight 一次性清标记——开窗的回 current、
3054
+ * 过期的 retire、行已不存在的记 deleted)。只动 needs_revalidation,不碰 current/invalid/deleted。 */
3055
+ settleRevalidation(scope, kind, verdicts) {
3056
+ return this.transaction(() => {
3057
+ 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);
3058
+ let settled2 = 0;
3059
+ for (const row of rows) {
3060
+ const verdict = verdicts.get(row.child_id);
3061
+ if (!verdict) continue;
3062
+ settled2 += 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);
3063
+ }
3064
+ return settled2;
3065
+ });
3066
+ }
3070
3067
  invalidate(scope, kind, id3, expectedVersion, reason) {
3071
3068
  this.transaction(() => {
3072
3069
  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, id3, expectedVersion);
@@ -3279,6 +3276,18 @@ function loadArrow() {
3279
3276
  }
3280
3277
  return arrowPromise;
3281
3278
  }
3279
+ function plainRow(row) {
3280
+ const out = {};
3281
+ for (const [key4, value] of Object.entries(row)) {
3282
+ if (TIMESTAMP_COLUMNS.has(key4) && typeof value === "number") {
3283
+ out[key4] = new Date(value);
3284
+ continue;
3285
+ }
3286
+ const raw = value !== null && typeof value === "object" && typeof value.toArray === "function" ? value.toArray() : value;
3287
+ out[key4] = raw !== null && typeof raw === "object" && ArrayBuffer.isView(raw) ? Array.from(raw) : raw;
3288
+ }
3289
+ return out;
3290
+ }
3282
3291
  function buildSchemas(arrow) {
3283
3292
  const vecField = () => new arrow.Field("vector", new arrow.FixedSizeList(VECTOR_DIM, new arrow.Field("item", new arrow.Float32(), true)), true);
3284
3293
  const commonFields = () => [
@@ -3375,7 +3384,7 @@ function textColumnOf(kind) {
3375
3384
  return "fact";
3376
3385
  }
3377
3386
  }
3378
- var isIntelMac, lancePromise, mem7VectorWarning, arrowPromise, Mem7VectorUnavailableError, VECTOR_DIM, BM25_FIELDS, BM25_TEXT_FIELDS, sqlLiteral, RRF_K, warnedFts, warnedVecIdx, incompatibleIndexSegments, bootAt, schemasCache, Mem7VectorStore;
3387
+ var isIntelMac, lancePromise, mem7VectorWarning, arrowPromise, Mem7VectorUnavailableError, VECTOR_DIM, BM25_FIELDS, TOKEN_FIELDS, TIMESTAMP_COLUMNS, RRF_K, warnedFts, warnedVecIdx, incompatibleIndexSegments, bootAt, schemasCache, Mem7VectorStore;
3379
3388
  var init_vector_store = __esm({
3380
3389
  "src/mem7/core/vector-store.ts"() {
3381
3390
  "use strict";
@@ -3406,14 +3415,14 @@ var init_vector_store = __esm({
3406
3415
  agent_case: ["task_intent_tokens", "approach_tokens"],
3407
3416
  agent_skill: ["description_tokens", "content_tokens"]
3408
3417
  };
3409
- BM25_TEXT_FIELDS = {
3410
- foresight: ["foresight", "evidence"],
3411
- episode: ["episode"],
3412
- atomic_fact: ["fact"],
3413
- agent_case: ["task_intent", "approach"],
3414
- agent_skill: ["description", "content"]
3418
+ TOKEN_FIELDS = {
3419
+ foresight: [["foresight", "foresight_tokens"], ["evidence", "evidence_tokens"]],
3420
+ episode: [["episode", "episode_tokens"]],
3421
+ atomic_fact: [["fact", "fact_tokens"]],
3422
+ agent_case: [["task_intent", "task_intent_tokens"], ["approach", "approach_tokens"]],
3423
+ agent_skill: [["description", "description_tokens"], ["content", "content_tokens"]]
3415
3424
  };
3416
- sqlLiteral = (value) => value.replace(/'/g, "''");
3425
+ TIMESTAMP_COLUMNS = /* @__PURE__ */ new Set(["created_at", "updated_at", "timestamp", "start_time", "end_time"]);
3417
3426
  RRF_K = 60;
3418
3427
  warnedFts = /* @__PURE__ */ new Set();
3419
3428
  warnedVecIdx = /* @__PURE__ */ new Set();
@@ -3435,6 +3444,8 @@ var init_vector_store = __esm({
3435
3444
  vectorIndexChecks = /* @__PURE__ */ new Map();
3436
3445
  vectorIndexRechecks = /* @__PURE__ */ new Set();
3437
3446
  vectorIndexesReady = /* @__PURE__ */ new Set();
3447
+ /** 自上次 optimize 后有写入的表(bg-worker 每小时收一次,见 optimizePending) */
3448
+ unoptimized = /* @__PURE__ */ new Set();
3438
3449
  ledger = null;
3439
3450
  ledgerPath;
3440
3451
  withProofSnapshot = (operation) => {
@@ -3814,10 +3825,25 @@ var init_vector_store = __esm({
3814
3825
  assertRuntimeAuthority(this.stateDir, "WRITE");
3815
3826
  validate?.();
3816
3827
  await tbl.add(mapped);
3828
+ this.unoptimized.add(kind);
3817
3829
  assertRuntimeAuthority(this.stateDir, "WRITE");
3818
3830
  validate?.();
3819
3831
  void this.ensureVectorIndexes(kind, tbl, true);
3820
3832
  }
3833
+ /**
3834
+ * 有写入的表做一次 optimize。1203 实测:lancedb 新写入片段在 optimize 之前 FTS 匹配不到多字中文词
3835
+ * (MatchQuery('山径') 新行 0 命中 → optimize 后 3;ASCII 词不受影响),新对话的中文词 BM25 要等这一步才看得见。
3836
+ */
3837
+ async optimizePending() {
3838
+ const done = [];
3839
+ for (const kind of [...this.unoptimized]) {
3840
+ const tbl = await this.table(kind);
3841
+ await tbl.optimize();
3842
+ this.unoptimized.delete(kind);
3843
+ done.push(kind);
3844
+ }
3845
+ return done;
3846
+ }
3821
3847
  /**
3822
3848
  * 按 id upsert(everos repo.upsert 语义,1004 read 侧):digest 相同 → 跳过(不重嵌
3823
3849
  * 不重写,everos cascade 的 content_sha256 diff-skip);digest 变了 → 删旧行再插新。
@@ -3838,6 +3864,7 @@ var init_vector_store = __esm({
3838
3864
  assertRuntimeAuthority(this.stateDir, "WRITE");
3839
3865
  validate?.();
3840
3866
  await tbl.delete(`id = '${r.id.replace(/'/g, "''")}'`);
3867
+ this.unoptimized.add(kind);
3841
3868
  assertRuntimeAuthority(this.stateDir, "WRITE");
3842
3869
  validate?.();
3843
3870
  await this.insert(kind, [r], validate);
@@ -3857,6 +3884,49 @@ var init_vector_store = __esm({
3857
3884
  return null;
3858
3885
  }
3859
3886
  }
3887
+ /**
3888
+ * 分词器版本变了(TOKENIZER_VERSION)→ 存量行的 *_tokens 按当前 tokenize() 重切(1203:HMM 开回 everos 默认,
3889
+ * 人名要进索引)。向量不动:整行原样回写只改 tokens 列,按 id 分批 mergeInsert;有改动就 optimize 一次
3890
+ * (新片段不进 ANN/FTS 索引,重切完不 optimize 等于没切)。先取全量 id 再分批——回写会产生新片段,
3891
+ * 边写边按 offset 翻页会漏行/重行。
3892
+ */
3893
+ async retokenize(kind, options = {}) {
3894
+ if (this.options.readOnly) throw new Error("MEM7_VECTOR_READ_ONLY");
3895
+ if (!this.tables.has(kind) && !this.openingTables.has(kind) && !existsSync3(join7(this.dir, `${kind}.lance`))) return { rows: 0, changed: 0 };
3896
+ const tbl = await this.table(kind);
3897
+ const fields = TOKEN_FIELDS[kind];
3898
+ const batchSize = Math.max(1, options.batchSize ?? 500);
3899
+ const ids = [];
3900
+ for (let offset = 0; ; offset += 5e3) {
3901
+ const page = await tbl.query().select(["id"]).limit(5e3).offset(offset).toArray();
3902
+ for (const row of page) ids.push(String(row.id));
3903
+ if (page.length < 5e3) break;
3904
+ }
3905
+ let changed = 0;
3906
+ for (let start = 0; start < ids.length; start += batchSize) {
3907
+ assertRuntimeAuthority(this.stateDir, "WRITE");
3908
+ const slice = ids.slice(start, start + batchSize);
3909
+ const rows = await tbl.query().where(`id IN (${slice.map((id3) => `'${id3.replace(/'/g, "''")}'`).join(",")})`).toArray();
3910
+ const updates = [];
3911
+ for (const row of rows) {
3912
+ let diff = false;
3913
+ for (const [textCol, tokenCol] of fields) {
3914
+ const next = tokenizeToField(String(row[textCol] ?? ""));
3915
+ if (next !== String(row[tokenCol] ?? "")) {
3916
+ row[tokenCol] = next;
3917
+ diff = true;
3918
+ }
3919
+ }
3920
+ if (!diff) continue;
3921
+ updates.push(plainRow(row));
3922
+ }
3923
+ if (updates.length) await tbl.mergeInsert("id").whenMatchedUpdateAll().execute(updates);
3924
+ changed += updates.length;
3925
+ options.onProgress?.(Math.min(ids.length, start + batchSize), ids.length);
3926
+ }
3927
+ if (changed) await tbl.optimize();
3928
+ return { rows: ids.length, changed };
3929
+ }
3860
3930
  /** KNN(lancedb vectorSearch:cosine 距离,score=1-distance) */
3861
3931
  async readVisibleCandidates(kind, limit2, query, method = "scan") {
3862
3932
  let count = Math.max(1, limit2);
@@ -4011,47 +4081,6 @@ var init_vector_store = __esm({
4011
4081
  if (!cur || score > Number(cur._score ?? 0)) best.set(rid, r);
4012
4082
  }
4013
4083
  }
4014
- const textCols = BM25_TEXT_FIELDS[kind];
4015
- const scan = async (terms, op, limit2) => {
4016
- const expr = op === "AND" ? terms.map((g) => `(${textCols.map((col) => `contains(${col}, '${sqlLiteral(g)}')`).join(" OR ")})`).join(" AND ") : textCols.map((col) => `(${terms.map((g) => `contains(${col}, '${sqlLiteral(g)}')`).join(" OR ")})`).join(" OR ");
4017
- const where2 = compileFilter(opts.filter);
4018
- return await tbl.query().where(where2 ? `(${where2}) AND (${expr})` : expr).limit(limit2).toArray();
4019
- };
4020
- const maxScore = [...best.values()].reduce((max, r) => Math.max(max, Number(r._score ?? 0)), 0);
4021
- const scoreLiteral = (needles2, rows) => {
4022
- const terms = [.../* @__PURE__ */ new Set([...needles2, ...tokenizeToField(queryText).split(/\s+/).filter(Boolean)])];
4023
- const occurrences2 = (text2, term) => text2.split(term).length - 1;
4024
- for (const r of rows) {
4025
- const rid = String(r.id ?? "");
4026
- if (!rid) continue;
4027
- const text2 = textCols.map((col) => String(r[col] ?? "")).join(" ");
4028
- const matched = terms.filter((term) => text2.includes(term));
4029
- if (!matched.length || matched.every((term) => !needles2.includes(term))) continue;
4030
- const full = matched.length === terms.length;
4031
- const density = matched.reduce((sum, term) => sum + occurrences2(text2, term), 0) / Math.max(text2.length, 1) * 1e3;
4032
- const score = full ? maxScore + 1 + Math.min(0.99, density / 10) : maxScore > 0 ? maxScore * (0.5 + 0.5 * matched.length / terms.length) : matched.length / terms.length;
4033
- const cur = best.get(rid);
4034
- if (cur) {
4035
- if (full) cur._score = Math.max(Number(cur._score ?? 0), score);
4036
- } else best.set(rid, { ...r, _score: score });
4037
- }
4038
- };
4039
- const needles = literalQueryNeedles(queryText);
4040
- if (needles) {
4041
- try {
4042
- const terms = [.../* @__PURE__ */ new Set([...needles, ...tokenizeToField(queryText).split(/\s+/).filter(Boolean)])];
4043
- const [all, any] = await Promise.all([
4044
- terms.length > 1 ? scan(terms, "AND", topK * 10) : Promise.resolve([]),
4045
- scan(needles, "OR", topK * 3)
4046
- ]);
4047
- scoreLiteral(needles, [...all, ...any]);
4048
- if (![...best.values()].some((r) => Number(r._score ?? 0) > maxScore)) {
4049
- const bigrams = [...new Set(needles.flatMap((name) => queryBigramNeedles(name) ?? []))].slice(0, 8);
4050
- if (bigrams.length && JSON.stringify(bigrams) !== JSON.stringify(needles)) scoreLiteral(bigrams, await scan(bigrams, "OR", topK * 3));
4051
- }
4052
- } catch {
4053
- }
4054
- }
4055
4084
  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) }));
4056
4085
  } catch (err) {
4057
4086
  const msg2 = String(err?.message ?? err);
@@ -28397,7 +28426,7 @@ var OnDemandRecall = class {
28397
28426
  async search(binding, args, run, signal) {
28398
28427
  const status = (value, reason) => JSON.stringify({ historySearch: { status: value, reason } });
28399
28428
  if (signal?.aborted) return status("aborted", "\u672C\u8F6E\u5DF2\u53D6\u6D88\u3002");
28400
- if (args.mode === "agentic") return status("unavailable", "\u60C5\u611F\u8F6E\u8BF7\u7528 keyword \u6216 hybrid \u6709\u754C\u8865\u67E5\u3002");
28429
+ if (args.mode === "agentic") return status("unavailable", "\u60C5\u611F\u8F6E\u8BF7\u7528 hybrid\uFF08\u4E0D\u586B mode\uFF09\u6709\u754C\u8865\u67E5\u3002");
28401
28430
  const bounded = {
28402
28431
  query: String(args.query ?? "").trim(),
28403
28432
  view: args.view ?? "mixed",