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.
@@ -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,13 +1610,6 @@ 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
1613
  var DEFAULT_STOPWORDS, MIN_TOKEN_LENGTH, jieba;
1621
1614
  var init_tokenizer = __esm({
1622
1615
  "src/mem7/core/tokenizer.ts"() {
@@ -2808,6 +2801,10 @@ function invalidateChildren(db2, scope, pending, reason) {
2808
2801
  if (!referencedPlan.get(scope, child.child_id, scope, child.child_id)) continue;
2809
2802
  }
2810
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
+ }
2811
2808
  db2.prepare(`UPDATE memory_derivations SET state=?,reason=?,updated_at=?
2812
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);
2813
2810
  result.push(child.child_id);
@@ -3036,12 +3033,14 @@ var init_dependencies = __esm({
3036
3033
  return false;
3037
3034
  }
3038
3035
  }
3039
- dirty(scope) {
3036
+ /** excludeKinds:没有重验消费者的类别不计入(1203:foresight,1015 起不做周期重验,见 invalidateChildren)。 */
3037
+ dirty(scope, options = {}) {
3040
3038
  return this.readTransaction(() => {
3041
3039
  checkMemoryReadBudget();
3042
3040
  const memo = /* @__PURE__ */ new Map();
3043
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) => {
3044
3042
  checkMemoryReadBudget();
3043
+ if (options.excludeKinds?.has(row.child_kind)) return false;
3045
3044
  return row.state === "needs_revalidation" || !this.artifactTimeCurrent(scope, row.child_kind, row.child_id, /* @__PURE__ */ new Set(), memo);
3046
3045
  }).map((row) => ({
3047
3046
  kind: row.child_kind,
@@ -3051,6 +3050,20 @@ var init_dependencies = __esm({
3051
3050
  }));
3052
3051
  });
3053
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
+ }
3054
3067
  invalidate(scope, kind, id3, expectedVersion, reason) {
3055
3068
  this.transaction(() => {
3056
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);
@@ -3263,11 +3276,17 @@ function loadArrow() {
3263
3276
  }
3264
3277
  return arrowPromise;
3265
3278
  }
3266
- function shortCjkQueryBigrams(text2) {
3267
- const chars = (String(text2 ?? "").match(/[\u4e00-\u9fff]/g) ?? []).length;
3268
- if (!chars || chars > 6) return null;
3269
- const grams = [...new Set(cjkBigrams(text2))].slice(0, 8);
3270
- return grams.length ? grams : null;
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;
3271
3290
  }
3272
3291
  function buildSchemas(arrow) {
3273
3292
  const vecField = () => new arrow.Field("vector", new arrow.FixedSizeList(VECTOR_DIM, new arrow.Field("item", new arrow.Float32(), true)), true);
@@ -3365,7 +3384,7 @@ function textColumnOf(kind) {
3365
3384
  return "fact";
3366
3385
  }
3367
3386
  }
3368
- 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;
3369
3388
  var init_vector_store = __esm({
3370
3389
  "src/mem7/core/vector-store.ts"() {
3371
3390
  "use strict";
@@ -3396,14 +3415,14 @@ var init_vector_store = __esm({
3396
3415
  agent_case: ["task_intent_tokens", "approach_tokens"],
3397
3416
  agent_skill: ["description_tokens", "content_tokens"]
3398
3417
  };
3399
- BM25_TEXT_FIELDS = {
3400
- foresight: ["foresight", "evidence"],
3401
- episode: ["episode"],
3402
- atomic_fact: ["fact"],
3403
- agent_case: ["task_intent", "approach"],
3404
- 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"]]
3405
3424
  };
3406
- sqlLiteral = (value) => value.replace(/'/g, "''");
3425
+ TIMESTAMP_COLUMNS = /* @__PURE__ */ new Set(["created_at", "updated_at", "timestamp", "start_time", "end_time"]);
3407
3426
  RRF_K = 60;
3408
3427
  warnedFts = /* @__PURE__ */ new Set();
3409
3428
  warnedVecIdx = /* @__PURE__ */ new Set();
@@ -3425,6 +3444,8 @@ var init_vector_store = __esm({
3425
3444
  vectorIndexChecks = /* @__PURE__ */ new Map();
3426
3445
  vectorIndexRechecks = /* @__PURE__ */ new Set();
3427
3446
  vectorIndexesReady = /* @__PURE__ */ new Set();
3447
+ /** 自上次 optimize 后有写入的表(bg-worker 每小时收一次,见 optimizePending) */
3448
+ unoptimized = /* @__PURE__ */ new Set();
3428
3449
  ledger = null;
3429
3450
  ledgerPath;
3430
3451
  withProofSnapshot = (operation) => {
@@ -3804,10 +3825,25 @@ var init_vector_store = __esm({
3804
3825
  assertRuntimeAuthority(this.stateDir, "WRITE");
3805
3826
  validate?.();
3806
3827
  await tbl.add(mapped);
3828
+ this.unoptimized.add(kind);
3807
3829
  assertRuntimeAuthority(this.stateDir, "WRITE");
3808
3830
  validate?.();
3809
3831
  void this.ensureVectorIndexes(kind, tbl, true);
3810
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
+ }
3811
3847
  /**
3812
3848
  * 按 id upsert(everos repo.upsert 语义,1004 read 侧):digest 相同 → 跳过(不重嵌
3813
3849
  * 不重写,everos cascade 的 content_sha256 diff-skip);digest 变了 → 删旧行再插新。
@@ -3828,6 +3864,7 @@ var init_vector_store = __esm({
3828
3864
  assertRuntimeAuthority(this.stateDir, "WRITE");
3829
3865
  validate?.();
3830
3866
  await tbl.delete(`id = '${r.id.replace(/'/g, "''")}'`);
3867
+ this.unoptimized.add(kind);
3831
3868
  assertRuntimeAuthority(this.stateDir, "WRITE");
3832
3869
  validate?.();
3833
3870
  await this.insert(kind, [r], validate);
@@ -3847,6 +3884,49 @@ var init_vector_store = __esm({
3847
3884
  return null;
3848
3885
  }
3849
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
+ }
3850
3930
  /** KNN(lancedb vectorSearch:cosine 距离,score=1-distance) */
3851
3931
  async readVisibleCandidates(kind, limit2, query, method = "scan") {
3852
3932
  let count = Math.max(1, limit2);
@@ -4001,28 +4081,6 @@ var init_vector_store = __esm({
4001
4081
  if (!cur || score > Number(cur._score ?? 0)) best.set(rid, r);
4002
4082
  }
4003
4083
  }
4004
- const grams = shortCjkQueryBigrams(queryText);
4005
- if (grams) {
4006
- try {
4007
- const textCols = BM25_TEXT_FIELDS[kind];
4008
- const expr = textCols.map((col) => `(${grams.map((g) => `contains(${col}, '${sqlLiteral(g)}')`).join(" OR ")})`).join(" OR ");
4009
- const where2 = compileFilter(opts.filter);
4010
- const extra = await tbl.query().where(where2 ? `(${where2}) AND (${expr})` : expr).limit(topK * 3).toArray();
4011
- const maxScore = [...best.values()].reduce((max, r) => Math.max(max, Number(r._score ?? 0)), 0);
4012
- for (const r of extra) {
4013
- const rid = String(r.id ?? "");
4014
- if (!rid) continue;
4015
- const text2 = textCols.map((col) => String(r[col] ?? "")).join(" ");
4016
- const matched = grams.filter((gram) => text2.includes(gram)).length;
4017
- if (!matched) continue;
4018
- const score = maxScore + matched / grams.length;
4019
- const cur = best.get(rid);
4020
- if (cur) cur._score = Math.max(Number(cur._score ?? 0), score);
4021
- else best.set(rid, { ...r, _score: score });
4022
- }
4023
- } catch {
4024
- }
4025
- }
4026
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) }));
4027
4085
  } catch (err) {
4028
4086
  const msg2 = String(err?.message ?? err);
@@ -28368,7 +28426,7 @@ var OnDemandRecall = class {
28368
28426
  async search(binding, args, run, signal) {
28369
28427
  const status = (value, reason) => JSON.stringify({ historySearch: { status: value, reason } });
28370
28428
  if (signal?.aborted) return status("aborted", "\u672C\u8F6E\u5DF2\u53D6\u6D88\u3002");
28371
- 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");
28372
28430
  const bounded = {
28373
28431
  query: String(args.query ?? "").trim(),
28374
28432
  view: args.view ?? "mixed",
@@ -3727,6 +3727,10 @@ function invalidateChildren(db2, scope, pending, reason) {
3727
3727
  if (!referencedPlan.get(scope, child.child_id, scope, child.child_id)) continue;
3728
3728
  }
3729
3729
  const state2 = child.deleted ? "deleted" : "needs_revalidation";
3730
+ if (child.child_kind === "foresight" && !child.deleted) {
3731
+ 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 })));
3732
+ continue;
3733
+ }
3730
3734
  db2.prepare(`UPDATE memory_derivations SET state=?,reason=?,updated_at=?
3731
3735
  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);
3732
3736
  result.push(child.child_id);
@@ -3955,12 +3959,14 @@ var init_dependencies = __esm({
3955
3959
  return false;
3956
3960
  }
3957
3961
  }
3958
- dirty(scope) {
3962
+ /** excludeKinds:没有重验消费者的类别不计入(1203:foresight,1015 起不做周期重验,见 invalidateChildren)。 */
3963
+ dirty(scope, options = {}) {
3959
3964
  return this.readTransaction(() => {
3960
3965
  checkMemoryReadBudget();
3961
3966
  const memo = /* @__PURE__ */ new Map();
3962
3967
  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) => {
3963
3968
  checkMemoryReadBudget();
3969
+ if (options.excludeKinds?.has(row.child_kind)) return false;
3964
3970
  return row.state === "needs_revalidation" || !this.artifactTimeCurrent(scope, row.child_kind, row.child_id, /* @__PURE__ */ new Set(), memo);
3965
3971
  }).map((row) => ({
3966
3972
  kind: row.child_kind,
@@ -3970,6 +3976,20 @@ var init_dependencies = __esm({
3970
3976
  }));
3971
3977
  });
3972
3978
  }
3979
+ /** needs_revalidation 的派生件按给定的现势状态归位(1203:foresight 一次性清标记——开窗的回 current、
3980
+ * 过期的 retire、行已不存在的记 deleted)。只动 needs_revalidation,不碰 current/invalid/deleted。 */
3981
+ settleRevalidation(scope, kind, verdicts) {
3982
+ return this.transaction(() => {
3983
+ 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);
3984
+ let settled = 0;
3985
+ for (const row of rows) {
3986
+ const verdict = verdicts.get(row.child_id);
3987
+ if (!verdict) continue;
3988
+ 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);
3989
+ }
3990
+ return settled;
3991
+ });
3992
+ }
3973
3993
  invalidate(scope, kind, id2, expectedVersion, reason) {
3974
3994
  this.transaction(() => {
3975
3995
  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);
@@ -7953,7 +7973,7 @@ function engine() {
7953
7973
  return jieba;
7954
7974
  }
7955
7975
  function tokenize(text2) {
7956
- const raw = engine().cutForSearch(String(text2 ?? ""));
7976
+ const raw = engine().cutForSearch(String(text2 ?? ""), true);
7957
7977
  const out = [];
7958
7978
  for (const t of raw) {
7959
7979
  const tok = t.trim().toLowerCase();
@@ -7966,13 +7986,6 @@ function tokenize(text2) {
7966
7986
  function tokenizeToField(text2) {
7967
7987
  return tokenize(text2).join(" ");
7968
7988
  }
7969
- function cjkBigrams(text2) {
7970
- const out = [];
7971
- for (const seg of String(text2 ?? "").match(/[\u4e00-\u9fff]{2,}/g) ?? []) {
7972
- for (let i = 0; i + 1 < seg.length; i++) out.push(seg.slice(i, i + 2));
7973
- }
7974
- return out;
7975
- }
7976
7989
  var DEFAULT_STOPWORDS, MIN_TOKEN_LENGTH, jieba;
7977
7990
  var init_tokenizer = __esm({
7978
7991
  "src/mem7/core/tokenizer.ts"() {
@@ -12218,11 +12231,17 @@ function loadArrow() {
12218
12231
  }
12219
12232
  return arrowPromise;
12220
12233
  }
12221
- function shortCjkQueryBigrams(text2) {
12222
- const chars = (String(text2 ?? "").match(/[\u4e00-\u9fff]/g) ?? []).length;
12223
- if (!chars || chars > 6) return null;
12224
- const grams = [...new Set(cjkBigrams(text2))].slice(0, 8);
12225
- return grams.length ? grams : null;
12234
+ function plainRow(row) {
12235
+ const out = {};
12236
+ for (const [key3, value2] of Object.entries(row)) {
12237
+ if (TIMESTAMP_COLUMNS.has(key3) && typeof value2 === "number") {
12238
+ out[key3] = new Date(value2);
12239
+ continue;
12240
+ }
12241
+ const raw = value2 !== null && typeof value2 === "object" && typeof value2.toArray === "function" ? value2.toArray() : value2;
12242
+ out[key3] = raw !== null && typeof raw === "object" && ArrayBuffer.isView(raw) ? Array.from(raw) : raw;
12243
+ }
12244
+ return out;
12226
12245
  }
12227
12246
  function buildSchemas(arrow) {
12228
12247
  const vecField = () => new arrow.Field("vector", new arrow.FixedSizeList(VECTOR_DIM, new arrow.Field("item", new arrow.Float32(), true)), true);
@@ -12320,7 +12339,7 @@ function textColumnOf(kind) {
12320
12339
  return "fact";
12321
12340
  }
12322
12341
  }
12323
- var isIntelMac, lancePromise, mem7VectorWarning, arrowPromise, Mem7VectorUnavailableError, VECTOR_DIM, BM25_FIELDS, BM25_TEXT_FIELDS, sqlLiteral, RRF_K, warnedFts, warnedVecIdx, incompatibleIndexSegments, bootAt, schemasCache, Mem7VectorStore;
12342
+ var isIntelMac, lancePromise, mem7VectorWarning, arrowPromise, Mem7VectorUnavailableError, VECTOR_DIM, BM25_FIELDS, TOKEN_FIELDS, TIMESTAMP_COLUMNS, RRF_K, warnedFts, warnedVecIdx, incompatibleIndexSegments, bootAt, schemasCache, Mem7VectorStore;
12324
12343
  var init_vector_store = __esm({
12325
12344
  "src/mem7/core/vector-store.ts"() {
12326
12345
  "use strict";
@@ -12351,14 +12370,14 @@ var init_vector_store = __esm({
12351
12370
  agent_case: ["task_intent_tokens", "approach_tokens"],
12352
12371
  agent_skill: ["description_tokens", "content_tokens"]
12353
12372
  };
12354
- BM25_TEXT_FIELDS = {
12355
- foresight: ["foresight", "evidence"],
12356
- episode: ["episode"],
12357
- atomic_fact: ["fact"],
12358
- agent_case: ["task_intent", "approach"],
12359
- agent_skill: ["description", "content"]
12373
+ TOKEN_FIELDS = {
12374
+ foresight: [["foresight", "foresight_tokens"], ["evidence", "evidence_tokens"]],
12375
+ episode: [["episode", "episode_tokens"]],
12376
+ atomic_fact: [["fact", "fact_tokens"]],
12377
+ agent_case: [["task_intent", "task_intent_tokens"], ["approach", "approach_tokens"]],
12378
+ agent_skill: [["description", "description_tokens"], ["content", "content_tokens"]]
12360
12379
  };
12361
- sqlLiteral = (value2) => value2.replace(/'/g, "''");
12380
+ TIMESTAMP_COLUMNS = /* @__PURE__ */ new Set(["created_at", "updated_at", "timestamp", "start_time", "end_time"]);
12362
12381
  RRF_K = 60;
12363
12382
  warnedFts = /* @__PURE__ */ new Set();
12364
12383
  warnedVecIdx = /* @__PURE__ */ new Set();
@@ -12380,6 +12399,8 @@ var init_vector_store = __esm({
12380
12399
  vectorIndexChecks = /* @__PURE__ */ new Map();
12381
12400
  vectorIndexRechecks = /* @__PURE__ */ new Set();
12382
12401
  vectorIndexesReady = /* @__PURE__ */ new Set();
12402
+ /** 自上次 optimize 后有写入的表(bg-worker 每小时收一次,见 optimizePending) */
12403
+ unoptimized = /* @__PURE__ */ new Set();
12383
12404
  ledger = null;
12384
12405
  ledgerPath;
12385
12406
  withProofSnapshot = (operation) => {
@@ -12759,10 +12780,25 @@ var init_vector_store = __esm({
12759
12780
  assertRuntimeAuthority(this.stateDir, "WRITE");
12760
12781
  validate?.();
12761
12782
  await tbl.add(mapped);
12783
+ this.unoptimized.add(kind);
12762
12784
  assertRuntimeAuthority(this.stateDir, "WRITE");
12763
12785
  validate?.();
12764
12786
  void this.ensureVectorIndexes(kind, tbl, true);
12765
12787
  }
12788
+ /**
12789
+ * 有写入的表做一次 optimize。1203 实测:lancedb 新写入片段在 optimize 之前 FTS 匹配不到多字中文词
12790
+ * (MatchQuery('山径') 新行 0 命中 → optimize 后 3;ASCII 词不受影响),新对话的中文词 BM25 要等这一步才看得见。
12791
+ */
12792
+ async optimizePending() {
12793
+ const done = [];
12794
+ for (const kind of [...this.unoptimized]) {
12795
+ const tbl = await this.table(kind);
12796
+ await tbl.optimize();
12797
+ this.unoptimized.delete(kind);
12798
+ done.push(kind);
12799
+ }
12800
+ return done;
12801
+ }
12766
12802
  /**
12767
12803
  * 按 id upsert(everos repo.upsert 语义,1004 read 侧):digest 相同 → 跳过(不重嵌
12768
12804
  * 不重写,everos cascade 的 content_sha256 diff-skip);digest 变了 → 删旧行再插新。
@@ -12783,6 +12819,7 @@ var init_vector_store = __esm({
12783
12819
  assertRuntimeAuthority(this.stateDir, "WRITE");
12784
12820
  validate?.();
12785
12821
  await tbl.delete(`id = '${r.id.replace(/'/g, "''")}'`);
12822
+ this.unoptimized.add(kind);
12786
12823
  assertRuntimeAuthority(this.stateDir, "WRITE");
12787
12824
  validate?.();
12788
12825
  await this.insert(kind, [r], validate);
@@ -12802,6 +12839,49 @@ var init_vector_store = __esm({
12802
12839
  return null;
12803
12840
  }
12804
12841
  }
12842
+ /**
12843
+ * 分词器版本变了(TOKENIZER_VERSION)→ 存量行的 *_tokens 按当前 tokenize() 重切(1203:HMM 开回 everos 默认,
12844
+ * 人名要进索引)。向量不动:整行原样回写只改 tokens 列,按 id 分批 mergeInsert;有改动就 optimize 一次
12845
+ * (新片段不进 ANN/FTS 索引,重切完不 optimize 等于没切)。先取全量 id 再分批——回写会产生新片段,
12846
+ * 边写边按 offset 翻页会漏行/重行。
12847
+ */
12848
+ async retokenize(kind, options = {}) {
12849
+ if (this.options.readOnly) throw new Error("MEM7_VECTOR_READ_ONLY");
12850
+ if (!this.tables.has(kind) && !this.openingTables.has(kind) && !existsSync7(join17(this.dir, `${kind}.lance`))) return { rows: 0, changed: 0 };
12851
+ const tbl = await this.table(kind);
12852
+ const fields3 = TOKEN_FIELDS[kind];
12853
+ const batchSize = Math.max(1, options.batchSize ?? 500);
12854
+ const ids = [];
12855
+ for (let offset = 0; ; offset += 5e3) {
12856
+ const page = await tbl.query().select(["id"]).limit(5e3).offset(offset).toArray();
12857
+ for (const row of page) ids.push(String(row.id));
12858
+ if (page.length < 5e3) break;
12859
+ }
12860
+ let changed = 0;
12861
+ for (let start = 0; start < ids.length; start += batchSize) {
12862
+ assertRuntimeAuthority(this.stateDir, "WRITE");
12863
+ const slice = ids.slice(start, start + batchSize);
12864
+ const rows = await tbl.query().where(`id IN (${slice.map((id2) => `'${id2.replace(/'/g, "''")}'`).join(",")})`).toArray();
12865
+ const updates = [];
12866
+ for (const row of rows) {
12867
+ let diff = false;
12868
+ for (const [textCol, tokenCol] of fields3) {
12869
+ const next = tokenizeToField(String(row[textCol] ?? ""));
12870
+ if (next !== String(row[tokenCol] ?? "")) {
12871
+ row[tokenCol] = next;
12872
+ diff = true;
12873
+ }
12874
+ }
12875
+ if (!diff) continue;
12876
+ updates.push(plainRow(row));
12877
+ }
12878
+ if (updates.length) await tbl.mergeInsert("id").whenMatchedUpdateAll().execute(updates);
12879
+ changed += updates.length;
12880
+ options.onProgress?.(Math.min(ids.length, start + batchSize), ids.length);
12881
+ }
12882
+ if (changed) await tbl.optimize();
12883
+ return { rows: ids.length, changed };
12884
+ }
12805
12885
  /** KNN(lancedb vectorSearch:cosine 距离,score=1-distance) */
12806
12886
  async readVisibleCandidates(kind, limit, query, method = "scan") {
12807
12887
  let count = Math.max(1, limit);
@@ -12956,28 +13036,6 @@ var init_vector_store = __esm({
12956
13036
  if (!cur || score > Number(cur._score ?? 0)) best.set(rid, r);
12957
13037
  }
12958
13038
  }
12959
- const grams = shortCjkQueryBigrams(queryText);
12960
- if (grams) {
12961
- try {
12962
- const textCols = BM25_TEXT_FIELDS[kind];
12963
- const expr = textCols.map((col) => `(${grams.map((g) => `contains(${col}, '${sqlLiteral(g)}')`).join(" OR ")})`).join(" OR ");
12964
- const where2 = compileFilter(opts.filter);
12965
- const extra = await tbl.query().where(where2 ? `(${where2}) AND (${expr})` : expr).limit(topK * 3).toArray();
12966
- const maxScore = [...best.values()].reduce((max, r) => Math.max(max, Number(r._score ?? 0)), 0);
12967
- for (const r of extra) {
12968
- const rid = String(r.id ?? "");
12969
- if (!rid) continue;
12970
- const text2 = textCols.map((col) => String(r[col] ?? "")).join(" ");
12971
- const matched = grams.filter((gram) => text2.includes(gram)).length;
12972
- if (!matched) continue;
12973
- const score = maxScore + matched / grams.length;
12974
- const cur = best.get(rid);
12975
- if (cur) cur._score = Math.max(Number(cur._score ?? 0), score);
12976
- else best.set(rid, { ...r, _score: score });
12977
- }
12978
- } catch {
12979
- }
12980
- }
12981
13039
  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) }));
12982
13040
  } catch (err) {
12983
13041
  const msg2 = String(err?.message ?? err);
@@ -15000,6 +15058,36 @@ var init_peer_tunnel = __esm({
15000
15058
  }
15001
15059
  });
15002
15060
 
15061
+ // src/cc-driver/peer-probe.ts
15062
+ function classifyPeerError(message) {
15063
+ if (/远程接入已关闭|未授权/.test(message)) return "disabled";
15064
+ if (/binding unavailable/i.test(message)) return "unbound";
15065
+ if (/fetch failed|ECONNREFUSED|ECONNRESET|EPIPE|timed? ?out|timeout|socket hang up|CC partner configuration|not configured/i.test(message)) return "hub";
15066
+ return "unknown";
15067
+ }
15068
+ function describePeerError(message) {
15069
+ switch (classifyPeerError(message)) {
15070
+ case "disabled":
15071
+ return `${message}\u2014\u2014\u8FDC\u7A0B\u63A5\u5165\u5728 CC \u4F19\u4F34\u90A3\u53F0\u673A\u5668\u4E0A\u662F\u5173\u7740\u7684\uFF0C\u53BB\u90A3\u53F0\u673A\u5668\u7684 CC \u4F19\u4F34\u9875\u70B9\u300C\u91CD\u5EFA\u8FDE\u63A5\u300D`;
15072
+ case "unbound":
15073
+ return `${message}\u2014\u2014CC \u4F19\u4F34\u90A3\u53F0\u673A\u5668\u4E0A\u6CA1\u6709\u7ED9\u8FD9\u4F4D\u4F19\u4F34\u7ED1\u5B9A CC`;
15074
+ case "hub":
15075
+ return `CC \u4F19\u4F34\u90A3\u53F0\u673A\u5668\u4E0A\u7684 hub \u6CA1\u5E94\u7B54\uFF1A${message}`;
15076
+ default:
15077
+ return message;
15078
+ }
15079
+ }
15080
+ function describeSshFailure(host, stderr) {
15081
+ return `\u8FDC\u7A0B CC \u94FE\u8DEF\u4E0D\u901A\uFF08${host}\uFF09\uFF1A${lastLine(stderr) || "SSH \u8FDE\u63A5\u5931\u8D25"}\u2014\u2014\u96A7\u9053\u65AD\u4E86\u6216 CC \u4F19\u4F34\u90A3\u53F0\u673A\u5668\u4E0A\u7684 hub \u6CA1\u5728\u8DD1\uFF0C\u6062\u590D\u540E\u4F1A\u81EA\u52A8\u8FDE\u4E0A\uFF1B\u63A7\u5236\u53F0\u300CCC \u4F19\u4F34\u300D\u9875\u53EF\u91CD\u65B0\u68C0\u6D4B`;
15082
+ }
15083
+ var lastLine;
15084
+ var init_peer_probe = __esm({
15085
+ "src/cc-driver/peer-probe.ts"() {
15086
+ "use strict";
15087
+ lastLine = (text2) => text2.split("\n").map((s) => s.trim()).filter(Boolean).at(-1) ?? "";
15088
+ }
15089
+ });
15090
+
15003
15091
  // src/tools/cc-peer.ts
15004
15092
  import { execFile as execFile4 } from "node:child_process";
15005
15093
  import { randomUUID as randomUUID13 } from "node:crypto";
@@ -15041,15 +15129,15 @@ function callPeer(peer, ctx, input, signal) {
15041
15129
  "ClearAllForwardings=yes",
15042
15130
  peer.host,
15043
15131
  "cc-peer"
15044
- ], { timeout: 8e3, maxBuffer: 160 * 1024, signal }, (error, stdout) => {
15132
+ ], { timeout: 8e3, maxBuffer: 160 * 1024, signal }, (error, stdout, stderr) => {
15045
15133
  if (error) {
15046
- reject(new Error("\u8FDC\u7A0B CC \u94FE\u8DEF\u4E0D\u53EF\u7528\u6216\u672A\u786E\u8BA4\u56DE\u6267"));
15134
+ reject(new Error(describeSshFailure(peer.host, String(stderr))));
15047
15135
  return;
15048
15136
  }
15049
15137
  try {
15050
15138
  const reply = JSON.parse(stdout);
15051
15139
  if (!reply || typeof reply !== "object") throw new Error("\u8FDC\u7A0B CC \u56DE\u6267\u683C\u5F0F\u65E0\u6548");
15052
- if (reply.error) throw new Error(reply.error);
15140
+ if (reply.error) throw new Error(describePeerError(reply.error));
15053
15141
  resolve47(reply);
15054
15142
  } catch (cause) {
15055
15143
  reject(cause);
@@ -15107,6 +15195,7 @@ var init_cc_peer = __esm({
15107
15195
  "use strict";
15108
15196
  init_live();
15109
15197
  init_peer_tunnel();
15198
+ init_peer_probe();
15110
15199
  validAlias = (s) => /^[a-z0-9_-]{1,32}$/.test(s);
15111
15200
  peerConfig = () => liveConfig.get("channels.ccDriver.remoteTargets");
15112
15201
  asError = (error) => ({ content: error.message, isError: true });
@@ -21918,7 +22007,7 @@ var init_on_demand_recall = __esm({
21918
22007
  async search(binding, args, run, signal) {
21919
22008
  const status = (value2, reason) => JSON.stringify({ historySearch: { status: value2, reason } });
21920
22009
  if (signal?.aborted) return status("aborted", "\u672C\u8F6E\u5DF2\u53D6\u6D88\u3002");
21921
- if (args.mode === "agentic") return status("unavailable", "\u60C5\u611F\u8F6E\u8BF7\u7528 keyword \u6216 hybrid \u6709\u754C\u8865\u67E5\u3002");
22010
+ if (args.mode === "agentic") return status("unavailable", "\u60C5\u611F\u8F6E\u8BF7\u7528 hybrid\uFF08\u4E0D\u586B mode\uFF09\u6709\u754C\u8865\u67E5\u3002");
21922
22011
  const bounded = {
21923
22012
  query: String(args.query ?? "").trim(),
21924
22013
  view: args.view ?? "mixed",
@@ -3457,6 +3457,10 @@ function invalidateChildren(db, scope, pending, reason) {
3457
3457
  if (!referencedPlan.get(scope, child.child_id, scope, child.child_id)) continue;
3458
3458
  }
3459
3459
  const state = child.deleted ? "deleted" : "needs_revalidation";
3460
+ if (child.child_kind === "foresight" && !child.deleted) {
3461
+ 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 })));
3462
+ continue;
3463
+ }
3460
3464
  db.prepare(`UPDATE memory_derivations SET state=?,reason=?,updated_at=?
3461
3465
  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);
3462
3466
  result.push(child.child_id);
@@ -2749,6 +2749,10 @@ function invalidateChildren(db, scope, pending, reason) {
2749
2749
  if (!referencedPlan.get(scope, child.child_id, scope, child.child_id)) continue;
2750
2750
  }
2751
2751
  const state = child.deleted ? "deleted" : "needs_revalidation";
2752
+ if (child.child_kind === "foresight" && !child.deleted) {
2753
+ 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 })));
2754
+ continue;
2755
+ }
2752
2756
  db.prepare(`UPDATE memory_derivations SET state=?,reason=?,updated_at=?
2753
2757
  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);
2754
2758
  result.push(child.child_id);