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.
@@ -1787,7 +1787,7 @@ function engine() {
1787
1787
  return jieba;
1788
1788
  }
1789
1789
  function tokenize(text2) {
1790
- const raw = engine().cutForSearch(String(text2 ?? ""));
1790
+ const raw = engine().cutForSearch(String(text2 ?? ""), true);
1791
1791
  const out = [];
1792
1792
  for (const t of raw) {
1793
1793
  const tok = t.trim().toLowerCase();
@@ -1800,13 +1800,6 @@ function tokenize(text2) {
1800
1800
  function tokenizeToField(text2) {
1801
1801
  return tokenize(text2).join(" ");
1802
1802
  }
1803
- function cjkBigrams(text2) {
1804
- const out = [];
1805
- for (const seg of String(text2 ?? "").match(/[\u4e00-\u9fff]{2,}/g) ?? []) {
1806
- for (let i = 0; i + 1 < seg.length; i++) out.push(seg.slice(i, i + 2));
1807
- }
1808
- return out;
1809
- }
1810
1803
  var DEFAULT_STOPWORDS, MIN_TOKEN_LENGTH, jieba;
1811
1804
  var init_tokenizer = __esm({
1812
1805
  "src/mem7/core/tokenizer.ts"() {
@@ -4762,6 +4755,10 @@ function invalidateChildren(db, scope, pending, reason) {
4762
4755
  if (!referencedPlan.get(scope, child.child_id, scope, child.child_id)) continue;
4763
4756
  }
4764
4757
  const state2 = child.deleted ? "deleted" : "needs_revalidation";
4758
+ if (child.child_kind === "foresight" && !child.deleted) {
4759
+ 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 })));
4760
+ continue;
4761
+ }
4765
4762
  db.prepare(`UPDATE memory_derivations SET state=?,reason=?,updated_at=?
4766
4763
  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);
4767
4764
  result.push(child.child_id);
@@ -4981,12 +4978,14 @@ var MemoryDependencies = class {
4981
4978
  return false;
4982
4979
  }
4983
4980
  }
4984
- dirty(scope) {
4981
+ /** excludeKinds:没有重验消费者的类别不计入(1203:foresight,1015 起不做周期重验,见 invalidateChildren)。 */
4982
+ dirty(scope, options = {}) {
4985
4983
  return this.readTransaction(() => {
4986
4984
  checkMemoryReadBudget();
4987
4985
  const memo = /* @__PURE__ */ new Map();
4988
4986
  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) => {
4989
4987
  checkMemoryReadBudget();
4988
+ if (options.excludeKinds?.has(row.child_kind)) return false;
4990
4989
  return row.state === "needs_revalidation" || !this.artifactTimeCurrent(scope, row.child_kind, row.child_id, /* @__PURE__ */ new Set(), memo);
4991
4990
  }).map((row) => ({
4992
4991
  kind: row.child_kind,
@@ -4996,6 +4995,20 @@ var MemoryDependencies = class {
4996
4995
  }));
4997
4996
  });
4998
4997
  }
4998
+ /** needs_revalidation 的派生件按给定的现势状态归位(1203:foresight 一次性清标记——开窗的回 current、
4999
+ * 过期的 retire、行已不存在的记 deleted)。只动 needs_revalidation,不碰 current/invalid/deleted。 */
5000
+ settleRevalidation(scope, kind, verdicts) {
5001
+ return this.transaction(() => {
5002
+ 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);
5003
+ let settled = 0;
5004
+ for (const row of rows) {
5005
+ const verdict = verdicts.get(row.child_id);
5006
+ if (!verdict) continue;
5007
+ 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);
5008
+ }
5009
+ return settled;
5010
+ });
5011
+ }
4999
5012
  invalidate(scope, kind, id2, expectedVersion, reason) {
5000
5013
  this.transaction(() => {
5001
5014
  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, id2, expectedVersion);
@@ -6940,20 +6953,26 @@ var BM25_FIELDS = {
6940
6953
  agent_case: ["task_intent_tokens", "approach_tokens"],
6941
6954
  agent_skill: ["description_tokens", "content_tokens"]
6942
6955
  };
6943
- var BM25_TEXT_FIELDS = {
6944
- foresight: ["foresight", "evidence"],
6945
- episode: ["episode"],
6946
- atomic_fact: ["fact"],
6947
- agent_case: ["task_intent", "approach"],
6948
- agent_skill: ["description", "content"]
6956
+ var TOKEN_FIELDS = {
6957
+ foresight: [["foresight", "foresight_tokens"], ["evidence", "evidence_tokens"]],
6958
+ episode: [["episode", "episode_tokens"]],
6959
+ atomic_fact: [["fact", "fact_tokens"]],
6960
+ agent_case: [["task_intent", "task_intent_tokens"], ["approach", "approach_tokens"]],
6961
+ agent_skill: [["description", "description_tokens"], ["content", "content_tokens"]]
6949
6962
  };
6950
- function shortCjkQueryBigrams(text2) {
6951
- const chars = (String(text2 ?? "").match(/[\u4e00-\u9fff]/g) ?? []).length;
6952
- if (!chars || chars > 6) return null;
6953
- const grams = [...new Set(cjkBigrams(text2))].slice(0, 8);
6954
- return grams.length ? grams : null;
6963
+ var TIMESTAMP_COLUMNS = /* @__PURE__ */ new Set(["created_at", "updated_at", "timestamp", "start_time", "end_time"]);
6964
+ function plainRow(row) {
6965
+ const out = {};
6966
+ for (const [key3, value2] of Object.entries(row)) {
6967
+ if (TIMESTAMP_COLUMNS.has(key3) && typeof value2 === "number") {
6968
+ out[key3] = new Date(value2);
6969
+ continue;
6970
+ }
6971
+ const raw = value2 !== null && typeof value2 === "object" && typeof value2.toArray === "function" ? value2.toArray() : value2;
6972
+ out[key3] = raw !== null && typeof raw === "object" && ArrayBuffer.isView(raw) ? Array.from(raw) : raw;
6973
+ }
6974
+ return out;
6955
6975
  }
6956
- var sqlLiteral = (value2) => value2.replace(/'/g, "''");
6957
6976
  var RRF_K = 60;
6958
6977
  var warnedFts = /* @__PURE__ */ new Set();
6959
6978
  var warnedVecIdx = /* @__PURE__ */ new Set();
@@ -7071,6 +7090,8 @@ var Mem7VectorStore = class {
7071
7090
  vectorIndexChecks = /* @__PURE__ */ new Map();
7072
7091
  vectorIndexRechecks = /* @__PURE__ */ new Set();
7073
7092
  vectorIndexesReady = /* @__PURE__ */ new Set();
7093
+ /** 自上次 optimize 后有写入的表(bg-worker 每小时收一次,见 optimizePending) */
7094
+ unoptimized = /* @__PURE__ */ new Set();
7074
7095
  ledger = null;
7075
7096
  ledgerPath;
7076
7097
  withProofSnapshot = (operation) => {
@@ -7450,10 +7471,25 @@ var Mem7VectorStore = class {
7450
7471
  assertRuntimeAuthority(this.stateDir, "WRITE");
7451
7472
  validate?.();
7452
7473
  await tbl.add(mapped);
7474
+ this.unoptimized.add(kind);
7453
7475
  assertRuntimeAuthority(this.stateDir, "WRITE");
7454
7476
  validate?.();
7455
7477
  void this.ensureVectorIndexes(kind, tbl, true);
7456
7478
  }
7479
+ /**
7480
+ * 有写入的表做一次 optimize。1203 实测:lancedb 新写入片段在 optimize 之前 FTS 匹配不到多字中文词
7481
+ * (MatchQuery('山径') 新行 0 命中 → optimize 后 3;ASCII 词不受影响),新对话的中文词 BM25 要等这一步才看得见。
7482
+ */
7483
+ async optimizePending() {
7484
+ const done = [];
7485
+ for (const kind of [...this.unoptimized]) {
7486
+ const tbl = await this.table(kind);
7487
+ await tbl.optimize();
7488
+ this.unoptimized.delete(kind);
7489
+ done.push(kind);
7490
+ }
7491
+ return done;
7492
+ }
7457
7493
  /**
7458
7494
  * 按 id upsert(everos repo.upsert 语义,1004 read 侧):digest 相同 → 跳过(不重嵌
7459
7495
  * 不重写,everos cascade 的 content_sha256 diff-skip);digest 变了 → 删旧行再插新。
@@ -7474,6 +7510,7 @@ var Mem7VectorStore = class {
7474
7510
  assertRuntimeAuthority(this.stateDir, "WRITE");
7475
7511
  validate?.();
7476
7512
  await tbl.delete(`id = '${r.id.replace(/'/g, "''")}'`);
7513
+ this.unoptimized.add(kind);
7477
7514
  assertRuntimeAuthority(this.stateDir, "WRITE");
7478
7515
  validate?.();
7479
7516
  await this.insert(kind, [r], validate);
@@ -7493,6 +7530,49 @@ var Mem7VectorStore = class {
7493
7530
  return null;
7494
7531
  }
7495
7532
  }
7533
+ /**
7534
+ * 分词器版本变了(TOKENIZER_VERSION)→ 存量行的 *_tokens 按当前 tokenize() 重切(1203:HMM 开回 everos 默认,
7535
+ * 人名要进索引)。向量不动:整行原样回写只改 tokens 列,按 id 分批 mergeInsert;有改动就 optimize 一次
7536
+ * (新片段不进 ANN/FTS 索引,重切完不 optimize 等于没切)。先取全量 id 再分批——回写会产生新片段,
7537
+ * 边写边按 offset 翻页会漏行/重行。
7538
+ */
7539
+ async retokenize(kind, options = {}) {
7540
+ if (this.options.readOnly) throw new Error("MEM7_VECTOR_READ_ONLY");
7541
+ if (!this.tables.has(kind) && !this.openingTables.has(kind) && !existsSync5(join13(this.dir, `${kind}.lance`))) return { rows: 0, changed: 0 };
7542
+ const tbl = await this.table(kind);
7543
+ const fields3 = TOKEN_FIELDS[kind];
7544
+ const batchSize = Math.max(1, options.batchSize ?? 500);
7545
+ const ids = [];
7546
+ for (let offset = 0; ; offset += 5e3) {
7547
+ const page = await tbl.query().select(["id"]).limit(5e3).offset(offset).toArray();
7548
+ for (const row of page) ids.push(String(row.id));
7549
+ if (page.length < 5e3) break;
7550
+ }
7551
+ let changed = 0;
7552
+ for (let start = 0; start < ids.length; start += batchSize) {
7553
+ assertRuntimeAuthority(this.stateDir, "WRITE");
7554
+ const slice = ids.slice(start, start + batchSize);
7555
+ const rows = await tbl.query().where(`id IN (${slice.map((id2) => `'${id2.replace(/'/g, "''")}'`).join(",")})`).toArray();
7556
+ const updates = [];
7557
+ for (const row of rows) {
7558
+ let diff = false;
7559
+ for (const [textCol, tokenCol] of fields3) {
7560
+ const next = tokenizeToField(String(row[textCol] ?? ""));
7561
+ if (next !== String(row[tokenCol] ?? "")) {
7562
+ row[tokenCol] = next;
7563
+ diff = true;
7564
+ }
7565
+ }
7566
+ if (!diff) continue;
7567
+ updates.push(plainRow(row));
7568
+ }
7569
+ if (updates.length) await tbl.mergeInsert("id").whenMatchedUpdateAll().execute(updates);
7570
+ changed += updates.length;
7571
+ options.onProgress?.(Math.min(ids.length, start + batchSize), ids.length);
7572
+ }
7573
+ if (changed) await tbl.optimize();
7574
+ return { rows: ids.length, changed };
7575
+ }
7496
7576
  /** KNN(lancedb vectorSearch:cosine 距离,score=1-distance) */
7497
7577
  async readVisibleCandidates(kind, limit, query, method = "scan") {
7498
7578
  let count = Math.max(1, limit);
@@ -7647,28 +7727,6 @@ var Mem7VectorStore = class {
7647
7727
  if (!cur || score > Number(cur._score ?? 0)) best.set(rid, r);
7648
7728
  }
7649
7729
  }
7650
- const grams = shortCjkQueryBigrams(queryText);
7651
- if (grams) {
7652
- try {
7653
- const textCols = BM25_TEXT_FIELDS[kind];
7654
- const expr = textCols.map((col) => `(${grams.map((g) => `contains(${col}, '${sqlLiteral(g)}')`).join(" OR ")})`).join(" OR ");
7655
- const where2 = compileFilter(opts.filter);
7656
- const extra = await tbl.query().where(where2 ? `(${where2}) AND (${expr})` : expr).limit(topK * 3).toArray();
7657
- const maxScore = [...best.values()].reduce((max, r) => Math.max(max, Number(r._score ?? 0)), 0);
7658
- for (const r of extra) {
7659
- const rid = String(r.id ?? "");
7660
- if (!rid) continue;
7661
- const text2 = textCols.map((col) => String(r[col] ?? "")).join(" ");
7662
- const matched = grams.filter((gram) => text2.includes(gram)).length;
7663
- if (!matched) continue;
7664
- const score = maxScore + matched / grams.length;
7665
- const cur = best.get(rid);
7666
- if (cur) cur._score = Math.max(Number(cur._score ?? 0), score);
7667
- else best.set(rid, { ...r, _score: score });
7668
- }
7669
- } catch {
7670
- }
7671
- }
7672
7730
  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) }));
7673
7731
  } catch (err) {
7674
7732
  const msg = String(err?.message ?? err);
@@ -1802,7 +1802,7 @@ function engine() {
1802
1802
  return jieba;
1803
1803
  }
1804
1804
  function tokenize(text2) {
1805
- const raw = engine().cutForSearch(String(text2 ?? ""));
1805
+ const raw = engine().cutForSearch(String(text2 ?? ""), true);
1806
1806
  const out = [];
1807
1807
  for (const t of raw) {
1808
1808
  const tok = t.trim().toLowerCase();
@@ -1815,13 +1815,6 @@ function tokenize(text2) {
1815
1815
  function tokenizeToField(text2) {
1816
1816
  return tokenize(text2).join(" ");
1817
1817
  }
1818
- function cjkBigrams(text2) {
1819
- const out = [];
1820
- for (const seg of String(text2 ?? "").match(/[\u4e00-\u9fff]{2,}/g) ?? []) {
1821
- for (let i = 0; i + 1 < seg.length; i++) out.push(seg.slice(i, i + 2));
1822
- }
1823
- return out;
1824
- }
1825
1818
  var DEFAULT_STOPWORDS, MIN_TOKEN_LENGTH, jieba;
1826
1819
  var init_tokenizer = __esm({
1827
1820
  "src/mem7/core/tokenizer.ts"() {
@@ -3013,6 +3006,10 @@ function invalidateChildren(db2, scope, pending, reason) {
3013
3006
  if (!referencedPlan.get(scope, child.child_id, scope, child.child_id)) continue;
3014
3007
  }
3015
3008
  const state = child.deleted ? "deleted" : "needs_revalidation";
3009
+ if (child.child_kind === "foresight" && !child.deleted) {
3010
+ 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 })));
3011
+ continue;
3012
+ }
3016
3013
  db2.prepare(`UPDATE memory_derivations SET state=?,reason=?,updated_at=?
3017
3014
  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);
3018
3015
  result.push(child.child_id);
@@ -3241,12 +3238,14 @@ var init_dependencies = __esm({
3241
3238
  return false;
3242
3239
  }
3243
3240
  }
3244
- dirty(scope) {
3241
+ /** excludeKinds:没有重验消费者的类别不计入(1203:foresight,1015 起不做周期重验,见 invalidateChildren)。 */
3242
+ dirty(scope, options = {}) {
3245
3243
  return this.readTransaction(() => {
3246
3244
  checkMemoryReadBudget();
3247
3245
  const memo = /* @__PURE__ */ new Map();
3248
3246
  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) => {
3249
3247
  checkMemoryReadBudget();
3248
+ if (options.excludeKinds?.has(row.child_kind)) return false;
3250
3249
  return row.state === "needs_revalidation" || !this.artifactTimeCurrent(scope, row.child_kind, row.child_id, /* @__PURE__ */ new Set(), memo);
3251
3250
  }).map((row) => ({
3252
3251
  kind: row.child_kind,
@@ -3256,6 +3255,20 @@ var init_dependencies = __esm({
3256
3255
  }));
3257
3256
  });
3258
3257
  }
3258
+ /** needs_revalidation 的派生件按给定的现势状态归位(1203:foresight 一次性清标记——开窗的回 current、
3259
+ * 过期的 retire、行已不存在的记 deleted)。只动 needs_revalidation,不碰 current/invalid/deleted。 */
3260
+ settleRevalidation(scope, kind, verdicts) {
3261
+ return this.transaction(() => {
3262
+ 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);
3263
+ let settled2 = 0;
3264
+ for (const row of rows) {
3265
+ const verdict = verdicts.get(row.child_id);
3266
+ if (!verdict) continue;
3267
+ 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);
3268
+ }
3269
+ return settled2;
3270
+ });
3271
+ }
3259
3272
  invalidate(scope, kind, id3, expectedVersion, reason) {
3260
3273
  this.transaction(() => {
3261
3274
  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);
@@ -3468,11 +3481,17 @@ function loadArrow() {
3468
3481
  }
3469
3482
  return arrowPromise;
3470
3483
  }
3471
- function shortCjkQueryBigrams(text2) {
3472
- const chars = (String(text2 ?? "").match(/[\u4e00-\u9fff]/g) ?? []).length;
3473
- if (!chars || chars > 6) return null;
3474
- const grams = [...new Set(cjkBigrams(text2))].slice(0, 8);
3475
- return grams.length ? grams : null;
3484
+ function plainRow(row) {
3485
+ const out = {};
3486
+ for (const [key4, value] of Object.entries(row)) {
3487
+ if (TIMESTAMP_COLUMNS.has(key4) && typeof value === "number") {
3488
+ out[key4] = new Date(value);
3489
+ continue;
3490
+ }
3491
+ const raw = value !== null && typeof value === "object" && typeof value.toArray === "function" ? value.toArray() : value;
3492
+ out[key4] = raw !== null && typeof raw === "object" && ArrayBuffer.isView(raw) ? Array.from(raw) : raw;
3493
+ }
3494
+ return out;
3476
3495
  }
3477
3496
  function buildSchemas(arrow) {
3478
3497
  const vecField = () => new arrow.Field("vector", new arrow.FixedSizeList(VECTOR_DIM, new arrow.Field("item", new arrow.Float32(), true)), true);
@@ -3570,7 +3589,7 @@ function textColumnOf(kind) {
3570
3589
  return "fact";
3571
3590
  }
3572
3591
  }
3573
- var isIntelMac, lancePromise, mem7VectorWarning, arrowPromise, Mem7VectorUnavailableError, VECTOR_DIM, BM25_FIELDS, BM25_TEXT_FIELDS, sqlLiteral, RRF_K, warnedFts, warnedVecIdx, incompatibleIndexSegments, bootAt, schemasCache, Mem7VectorStore;
3592
+ var isIntelMac, lancePromise, mem7VectorWarning, arrowPromise, Mem7VectorUnavailableError, VECTOR_DIM, BM25_FIELDS, TOKEN_FIELDS, TIMESTAMP_COLUMNS, RRF_K, warnedFts, warnedVecIdx, incompatibleIndexSegments, bootAt, schemasCache, Mem7VectorStore;
3574
3593
  var init_vector_store = __esm({
3575
3594
  "src/mem7/core/vector-store.ts"() {
3576
3595
  "use strict";
@@ -3601,14 +3620,14 @@ var init_vector_store = __esm({
3601
3620
  agent_case: ["task_intent_tokens", "approach_tokens"],
3602
3621
  agent_skill: ["description_tokens", "content_tokens"]
3603
3622
  };
3604
- BM25_TEXT_FIELDS = {
3605
- foresight: ["foresight", "evidence"],
3606
- episode: ["episode"],
3607
- atomic_fact: ["fact"],
3608
- agent_case: ["task_intent", "approach"],
3609
- agent_skill: ["description", "content"]
3623
+ TOKEN_FIELDS = {
3624
+ foresight: [["foresight", "foresight_tokens"], ["evidence", "evidence_tokens"]],
3625
+ episode: [["episode", "episode_tokens"]],
3626
+ atomic_fact: [["fact", "fact_tokens"]],
3627
+ agent_case: [["task_intent", "task_intent_tokens"], ["approach", "approach_tokens"]],
3628
+ agent_skill: [["description", "description_tokens"], ["content", "content_tokens"]]
3610
3629
  };
3611
- sqlLiteral = (value) => value.replace(/'/g, "''");
3630
+ TIMESTAMP_COLUMNS = /* @__PURE__ */ new Set(["created_at", "updated_at", "timestamp", "start_time", "end_time"]);
3612
3631
  RRF_K = 60;
3613
3632
  warnedFts = /* @__PURE__ */ new Set();
3614
3633
  warnedVecIdx = /* @__PURE__ */ new Set();
@@ -3630,6 +3649,8 @@ var init_vector_store = __esm({
3630
3649
  vectorIndexChecks = /* @__PURE__ */ new Map();
3631
3650
  vectorIndexRechecks = /* @__PURE__ */ new Set();
3632
3651
  vectorIndexesReady = /* @__PURE__ */ new Set();
3652
+ /** 自上次 optimize 后有写入的表(bg-worker 每小时收一次,见 optimizePending) */
3653
+ unoptimized = /* @__PURE__ */ new Set();
3633
3654
  ledger = null;
3634
3655
  ledgerPath;
3635
3656
  withProofSnapshot = (operation) => {
@@ -4009,10 +4030,25 @@ var init_vector_store = __esm({
4009
4030
  assertRuntimeAuthority(this.stateDir, "WRITE");
4010
4031
  validate?.();
4011
4032
  await tbl.add(mapped);
4033
+ this.unoptimized.add(kind);
4012
4034
  assertRuntimeAuthority(this.stateDir, "WRITE");
4013
4035
  validate?.();
4014
4036
  void this.ensureVectorIndexes(kind, tbl, true);
4015
4037
  }
4038
+ /**
4039
+ * 有写入的表做一次 optimize。1203 实测:lancedb 新写入片段在 optimize 之前 FTS 匹配不到多字中文词
4040
+ * (MatchQuery('山径') 新行 0 命中 → optimize 后 3;ASCII 词不受影响),新对话的中文词 BM25 要等这一步才看得见。
4041
+ */
4042
+ async optimizePending() {
4043
+ const done = [];
4044
+ for (const kind of [...this.unoptimized]) {
4045
+ const tbl = await this.table(kind);
4046
+ await tbl.optimize();
4047
+ this.unoptimized.delete(kind);
4048
+ done.push(kind);
4049
+ }
4050
+ return done;
4051
+ }
4016
4052
  /**
4017
4053
  * 按 id upsert(everos repo.upsert 语义,1004 read 侧):digest 相同 → 跳过(不重嵌
4018
4054
  * 不重写,everos cascade 的 content_sha256 diff-skip);digest 变了 → 删旧行再插新。
@@ -4033,6 +4069,7 @@ var init_vector_store = __esm({
4033
4069
  assertRuntimeAuthority(this.stateDir, "WRITE");
4034
4070
  validate?.();
4035
4071
  await tbl.delete(`id = '${r.id.replace(/'/g, "''")}'`);
4072
+ this.unoptimized.add(kind);
4036
4073
  assertRuntimeAuthority(this.stateDir, "WRITE");
4037
4074
  validate?.();
4038
4075
  await this.insert(kind, [r], validate);
@@ -4052,6 +4089,49 @@ var init_vector_store = __esm({
4052
4089
  return null;
4053
4090
  }
4054
4091
  }
4092
+ /**
4093
+ * 分词器版本变了(TOKENIZER_VERSION)→ 存量行的 *_tokens 按当前 tokenize() 重切(1203:HMM 开回 everos 默认,
4094
+ * 人名要进索引)。向量不动:整行原样回写只改 tokens 列,按 id 分批 mergeInsert;有改动就 optimize 一次
4095
+ * (新片段不进 ANN/FTS 索引,重切完不 optimize 等于没切)。先取全量 id 再分批——回写会产生新片段,
4096
+ * 边写边按 offset 翻页会漏行/重行。
4097
+ */
4098
+ async retokenize(kind, options = {}) {
4099
+ if (this.options.readOnly) throw new Error("MEM7_VECTOR_READ_ONLY");
4100
+ if (!this.tables.has(kind) && !this.openingTables.has(kind) && !existsSync3(join8(this.dir, `${kind}.lance`))) return { rows: 0, changed: 0 };
4101
+ const tbl = await this.table(kind);
4102
+ const fields = TOKEN_FIELDS[kind];
4103
+ const batchSize = Math.max(1, options.batchSize ?? 500);
4104
+ const ids = [];
4105
+ for (let offset = 0; ; offset += 5e3) {
4106
+ const page = await tbl.query().select(["id"]).limit(5e3).offset(offset).toArray();
4107
+ for (const row of page) ids.push(String(row.id));
4108
+ if (page.length < 5e3) break;
4109
+ }
4110
+ let changed = 0;
4111
+ for (let start = 0; start < ids.length; start += batchSize) {
4112
+ assertRuntimeAuthority(this.stateDir, "WRITE");
4113
+ const slice = ids.slice(start, start + batchSize);
4114
+ const rows = await tbl.query().where(`id IN (${slice.map((id3) => `'${id3.replace(/'/g, "''")}'`).join(",")})`).toArray();
4115
+ const updates = [];
4116
+ for (const row of rows) {
4117
+ let diff = false;
4118
+ for (const [textCol, tokenCol] of fields) {
4119
+ const next = tokenizeToField(String(row[textCol] ?? ""));
4120
+ if (next !== String(row[tokenCol] ?? "")) {
4121
+ row[tokenCol] = next;
4122
+ diff = true;
4123
+ }
4124
+ }
4125
+ if (!diff) continue;
4126
+ updates.push(plainRow(row));
4127
+ }
4128
+ if (updates.length) await tbl.mergeInsert("id").whenMatchedUpdateAll().execute(updates);
4129
+ changed += updates.length;
4130
+ options.onProgress?.(Math.min(ids.length, start + batchSize), ids.length);
4131
+ }
4132
+ if (changed) await tbl.optimize();
4133
+ return { rows: ids.length, changed };
4134
+ }
4055
4135
  /** KNN(lancedb vectorSearch:cosine 距离,score=1-distance) */
4056
4136
  async readVisibleCandidates(kind, limit2, query, method = "scan") {
4057
4137
  let count = Math.max(1, limit2);
@@ -4206,28 +4286,6 @@ var init_vector_store = __esm({
4206
4286
  if (!cur || score > Number(cur._score ?? 0)) best.set(rid, r);
4207
4287
  }
4208
4288
  }
4209
- const grams = shortCjkQueryBigrams(queryText);
4210
- if (grams) {
4211
- try {
4212
- const textCols = BM25_TEXT_FIELDS[kind];
4213
- const expr = textCols.map((col) => `(${grams.map((g) => `contains(${col}, '${sqlLiteral(g)}')`).join(" OR ")})`).join(" OR ");
4214
- const where2 = compileFilter(opts.filter);
4215
- const extra = await tbl.query().where(where2 ? `(${where2}) AND (${expr})` : expr).limit(topK * 3).toArray();
4216
- const maxScore = [...best.values()].reduce((max, r) => Math.max(max, Number(r._score ?? 0)), 0);
4217
- for (const r of extra) {
4218
- const rid = String(r.id ?? "");
4219
- if (!rid) continue;
4220
- const text2 = textCols.map((col) => String(r[col] ?? "")).join(" ");
4221
- const matched = grams.filter((gram) => text2.includes(gram)).length;
4222
- if (!matched) continue;
4223
- const score = maxScore + matched / grams.length;
4224
- const cur = best.get(rid);
4225
- if (cur) cur._score = Math.max(Number(cur._score ?? 0), score);
4226
- else best.set(rid, { ...r, _score: score });
4227
- }
4228
- } catch {
4229
- }
4230
- }
4231
4289
  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) }));
4232
4290
  } catch (err) {
4233
4291
  const msg2 = String(err?.message ?? err);
@@ -28657,7 +28715,7 @@ var OnDemandRecall = class {
28657
28715
  async search(binding, args, run, signal) {
28658
28716
  const status = (value, reason) => JSON.stringify({ historySearch: { status: value, reason } });
28659
28717
  if (signal?.aborted) return status("aborted", "\u672C\u8F6E\u5DF2\u53D6\u6D88\u3002");
28660
- if (args.mode === "agentic") return status("unavailable", "\u60C5\u611F\u8F6E\u8BF7\u7528 keyword \u6216 hybrid \u6709\u754C\u8865\u67E5\u3002");
28718
+ if (args.mode === "agentic") return status("unavailable", "\u60C5\u611F\u8F6E\u8BF7\u7528 hybrid\uFF08\u4E0D\u586B mode\uFF09\u6709\u754C\u8865\u67E5\u3002");
28661
28719
  const bounded = {
28662
28720
  query: String(args.query ?? "").trim(),
28663
28721
  view: args.view ?? "mixed",
@@ -4125,7 +4125,7 @@ function selfieReferences(config) {
4125
4125
 
4126
4126
  // src/travel/exclusions.ts
4127
4127
  var EXCLUDED_NAMES = /* @__PURE__ */ new Set(["node_modules", ".venv", ".venvs", "venv", ".git", "__pycache__", ".cache", "cache", "caches", "tmp", "temp", ".playwright-mcp", ".DS_Store"]);
4128
- var EXCLUDED_TOP = /* @__PURE__ */ new Set(["logs", "diagnostics", "node_modules", "CogniFold", "everos-venv", "ollama-models", ".log-baseline.txt"]);
4128
+ var EXCLUDED_TOP = /* @__PURE__ */ new Set(["logs", "diagnostics", "node_modules", "CogniFold", "everos-venv", "ollama-models", ".log-baseline.txt", "instances"]);
4129
4129
  function excludeReason(relPath, isDir) {
4130
4130
  const parts = relPath.split("/");
4131
4131
  for (let i = 0; i < parts.length - 1; i++) {
@@ -4189,6 +4189,7 @@ function syncExcludeWith(mediaPolicy) {
4189
4189
  const name = parts[parts.length - 1];
4190
4190
  if (isTopicsCleaningWorkPath(relPath)) return "\u8BDD\u9898\u6E05\u6D17\u4E2D\u95F4\u6587\u4EF6\u7559\u5728\u539F\u673A";
4191
4191
  if (parts[0] === "runtime") return "\u5F15\u64CE\u5B89\u88C5\u526F\u672C\u4E0D\u968F\u884C\uFF08\u4E91\u7AEF\u72EC\u7ACB\u5B89\u88C5\u5F53\u524D\u5F15\u64CE\uFF09";
4192
+ if (parts[0] === "instances") return "\u672C\u673A\u4E13\u5C5E\u5B9E\u4F8B\u4E0D\u968F\u884C\uFF08instances/ \u662F\u8FD9\u53F0\u673A\u5668\u81EA\u5DF1\u7684 CC \u4F19\u4F34 hub \u4E0E\u4EFB\u52A1\u5B9E\u4F8B\uFF0C\u4E0D\u662F\u8BB0\u5FC6\uFF09";
4192
4193
  if (!relPath.includes("/") && (relPath === "config.json" || relPath === "secrets.env")) {
4193
4194
  return "\u5BF9\u7AEF\u5B89\u88C5\u4EA7\u7269\u4FDD\u62A4\uFF08config \u8D70 config-remap\uFF0Csecrets \u8D70 travel-setup\uFF09";
4194
4195
  }