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.
@@ -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,29 +7986,7 @@ 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
- function invisibleCjkNeedles(candidates) {
7977
- return [...new Set(candidates.map((token) => token.trim()))].filter((token) => /^[\u4e00-\u9fff]{2,}$/.test(token) && tokenize(token).length === 0).slice(0, 8);
7978
- }
7979
- function literalQueryNeedles(text2) {
7980
- const chars = shortCjkCharCount(text2);
7981
- if (!chars || chars > 6) return null;
7982
- const names2 = invisibleCjkNeedles(engine().cut(String(text2 ?? ""), true));
7983
- return names2.length ? names2 : queryBigramNeedles(text2);
7984
- }
7985
- function queryBigramNeedles(text2) {
7986
- const chars = shortCjkCharCount(text2);
7987
- if (!chars || chars > 6) return null;
7988
- const grams = [...new Set(cjkBigrams(text2))].slice(0, 8);
7989
- return grams.length ? grams : null;
7990
- }
7991
- var DEFAULT_STOPWORDS, MIN_TOKEN_LENGTH, jieba, shortCjkCharCount;
7989
+ var DEFAULT_STOPWORDS, MIN_TOKEN_LENGTH, jieba;
7992
7990
  var init_tokenizer = __esm({
7993
7991
  "src/mem7/core/tokenizer.ts"() {
7994
7992
  "use strict";
@@ -8061,7 +8059,6 @@ var init_tokenizer = __esm({
8061
8059
  ]);
8062
8060
  MIN_TOKEN_LENGTH = 2;
8063
8061
  jieba = null;
8064
- shortCjkCharCount = (text2) => (String(text2 ?? "").match(/[\u4e00-\u9fff]/g) ?? []).length;
8065
8062
  }
8066
8063
  });
8067
8064
 
@@ -12234,6 +12231,18 @@ function loadArrow() {
12234
12231
  }
12235
12232
  return arrowPromise;
12236
12233
  }
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;
12245
+ }
12237
12246
  function buildSchemas(arrow) {
12238
12247
  const vecField = () => new arrow.Field("vector", new arrow.FixedSizeList(VECTOR_DIM, new arrow.Field("item", new arrow.Float32(), true)), true);
12239
12248
  const commonFields = () => [
@@ -12330,7 +12339,7 @@ function textColumnOf(kind) {
12330
12339
  return "fact";
12331
12340
  }
12332
12341
  }
12333
- 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;
12334
12343
  var init_vector_store = __esm({
12335
12344
  "src/mem7/core/vector-store.ts"() {
12336
12345
  "use strict";
@@ -12361,14 +12370,14 @@ var init_vector_store = __esm({
12361
12370
  agent_case: ["task_intent_tokens", "approach_tokens"],
12362
12371
  agent_skill: ["description_tokens", "content_tokens"]
12363
12372
  };
12364
- BM25_TEXT_FIELDS = {
12365
- foresight: ["foresight", "evidence"],
12366
- episode: ["episode"],
12367
- atomic_fact: ["fact"],
12368
- agent_case: ["task_intent", "approach"],
12369
- 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"]]
12370
12379
  };
12371
- sqlLiteral = (value2) => value2.replace(/'/g, "''");
12380
+ TIMESTAMP_COLUMNS = /* @__PURE__ */ new Set(["created_at", "updated_at", "timestamp", "start_time", "end_time"]);
12372
12381
  RRF_K = 60;
12373
12382
  warnedFts = /* @__PURE__ */ new Set();
12374
12383
  warnedVecIdx = /* @__PURE__ */ new Set();
@@ -12390,6 +12399,8 @@ var init_vector_store = __esm({
12390
12399
  vectorIndexChecks = /* @__PURE__ */ new Map();
12391
12400
  vectorIndexRechecks = /* @__PURE__ */ new Set();
12392
12401
  vectorIndexesReady = /* @__PURE__ */ new Set();
12402
+ /** 自上次 optimize 后有写入的表(bg-worker 每小时收一次,见 optimizePending) */
12403
+ unoptimized = /* @__PURE__ */ new Set();
12393
12404
  ledger = null;
12394
12405
  ledgerPath;
12395
12406
  withProofSnapshot = (operation) => {
@@ -12769,10 +12780,25 @@ var init_vector_store = __esm({
12769
12780
  assertRuntimeAuthority(this.stateDir, "WRITE");
12770
12781
  validate?.();
12771
12782
  await tbl.add(mapped);
12783
+ this.unoptimized.add(kind);
12772
12784
  assertRuntimeAuthority(this.stateDir, "WRITE");
12773
12785
  validate?.();
12774
12786
  void this.ensureVectorIndexes(kind, tbl, true);
12775
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
+ }
12776
12802
  /**
12777
12803
  * 按 id upsert(everos repo.upsert 语义,1004 read 侧):digest 相同 → 跳过(不重嵌
12778
12804
  * 不重写,everos cascade 的 content_sha256 diff-skip);digest 变了 → 删旧行再插新。
@@ -12793,6 +12819,7 @@ var init_vector_store = __esm({
12793
12819
  assertRuntimeAuthority(this.stateDir, "WRITE");
12794
12820
  validate?.();
12795
12821
  await tbl.delete(`id = '${r.id.replace(/'/g, "''")}'`);
12822
+ this.unoptimized.add(kind);
12796
12823
  assertRuntimeAuthority(this.stateDir, "WRITE");
12797
12824
  validate?.();
12798
12825
  await this.insert(kind, [r], validate);
@@ -12812,6 +12839,49 @@ var init_vector_store = __esm({
12812
12839
  return null;
12813
12840
  }
12814
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
+ }
12815
12885
  /** KNN(lancedb vectorSearch:cosine 距离,score=1-distance) */
12816
12886
  async readVisibleCandidates(kind, limit, query, method = "scan") {
12817
12887
  let count = Math.max(1, limit);
@@ -12966,47 +13036,6 @@ var init_vector_store = __esm({
12966
13036
  if (!cur || score > Number(cur._score ?? 0)) best.set(rid, r);
12967
13037
  }
12968
13038
  }
12969
- const textCols = BM25_TEXT_FIELDS[kind];
12970
- const scan = async (terms, op, limit) => {
12971
- 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 ");
12972
- const where2 = compileFilter(opts.filter);
12973
- return await tbl.query().where(where2 ? `(${where2}) AND (${expr})` : expr).limit(limit).toArray();
12974
- };
12975
- const maxScore = [...best.values()].reduce((max, r) => Math.max(max, Number(r._score ?? 0)), 0);
12976
- const scoreLiteral = (needles2, rows) => {
12977
- const terms = [.../* @__PURE__ */ new Set([...needles2, ...tokenizeToField(queryText).split(/\s+/).filter(Boolean)])];
12978
- const occurrences2 = (text2, term) => text2.split(term).length - 1;
12979
- for (const r of rows) {
12980
- const rid = String(r.id ?? "");
12981
- if (!rid) continue;
12982
- const text2 = textCols.map((col) => String(r[col] ?? "")).join(" ");
12983
- const matched = terms.filter((term) => text2.includes(term));
12984
- if (!matched.length || matched.every((term) => !needles2.includes(term))) continue;
12985
- const full = matched.length === terms.length;
12986
- const density = matched.reduce((sum, term) => sum + occurrences2(text2, term), 0) / Math.max(text2.length, 1) * 1e3;
12987
- 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;
12988
- const cur = best.get(rid);
12989
- if (cur) {
12990
- if (full) cur._score = Math.max(Number(cur._score ?? 0), score);
12991
- } else best.set(rid, { ...r, _score: score });
12992
- }
12993
- };
12994
- const needles = literalQueryNeedles(queryText);
12995
- if (needles) {
12996
- try {
12997
- const terms = [.../* @__PURE__ */ new Set([...needles, ...tokenizeToField(queryText).split(/\s+/).filter(Boolean)])];
12998
- const [all, any] = await Promise.all([
12999
- terms.length > 1 ? scan(terms, "AND", topK * 10) : Promise.resolve([]),
13000
- scan(needles, "OR", topK * 3)
13001
- ]);
13002
- scoreLiteral(needles, [...all, ...any]);
13003
- if (![...best.values()].some((r) => Number(r._score ?? 0) > maxScore)) {
13004
- const bigrams = [...new Set(needles.flatMap((name) => queryBigramNeedles(name) ?? []))].slice(0, 8);
13005
- if (bigrams.length && JSON.stringify(bigrams) !== JSON.stringify(needles)) scoreLiteral(bigrams, await scan(bigrams, "OR", topK * 3));
13006
- }
13007
- } catch {
13008
- }
13009
- }
13010
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) }));
13011
13040
  } catch (err) {
13012
13041
  const msg2 = String(err?.message ?? err);
@@ -15029,6 +15058,36 @@ var init_peer_tunnel = __esm({
15029
15058
  }
15030
15059
  });
15031
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
+
15032
15091
  // src/tools/cc-peer.ts
15033
15092
  import { execFile as execFile4 } from "node:child_process";
15034
15093
  import { randomUUID as randomUUID13 } from "node:crypto";
@@ -15070,15 +15129,15 @@ function callPeer(peer, ctx, input, signal) {
15070
15129
  "ClearAllForwardings=yes",
15071
15130
  peer.host,
15072
15131
  "cc-peer"
15073
- ], { timeout: 8e3, maxBuffer: 160 * 1024, signal }, (error, stdout) => {
15132
+ ], { timeout: 8e3, maxBuffer: 160 * 1024, signal }, (error, stdout, stderr) => {
15074
15133
  if (error) {
15075
- 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))));
15076
15135
  return;
15077
15136
  }
15078
15137
  try {
15079
15138
  const reply = JSON.parse(stdout);
15080
15139
  if (!reply || typeof reply !== "object") throw new Error("\u8FDC\u7A0B CC \u56DE\u6267\u683C\u5F0F\u65E0\u6548");
15081
- if (reply.error) throw new Error(reply.error);
15140
+ if (reply.error) throw new Error(describePeerError(reply.error));
15082
15141
  resolve47(reply);
15083
15142
  } catch (cause) {
15084
15143
  reject(cause);
@@ -15136,6 +15195,7 @@ var init_cc_peer = __esm({
15136
15195
  "use strict";
15137
15196
  init_live();
15138
15197
  init_peer_tunnel();
15198
+ init_peer_probe();
15139
15199
  validAlias = (s) => /^[a-z0-9_-]{1,32}$/.test(s);
15140
15200
  peerConfig = () => liveConfig.get("channels.ccDriver.remoteTargets");
15141
15201
  asError = (error) => ({ content: error.message, isError: true });
@@ -21947,7 +22007,7 @@ var init_on_demand_recall = __esm({
21947
22007
  async search(binding, args, run, signal) {
21948
22008
  const status = (value2, reason) => JSON.stringify({ historySearch: { status: value2, reason } });
21949
22009
  if (signal?.aborted) return status("aborted", "\u672C\u8F6E\u5DF2\u53D6\u6D88\u3002");
21950
- 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");
21951
22011
  const bounded = {
21952
22012
  query: String(args.query ?? "").trim(),
21953
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);
@@ -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,29 +1800,7 @@ 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
- function invisibleCjkNeedles(candidates) {
1811
- return [...new Set(candidates.map((token) => token.trim()))].filter((token) => /^[\u4e00-\u9fff]{2,}$/.test(token) && tokenize(token).length === 0).slice(0, 8);
1812
- }
1813
- function literalQueryNeedles(text2) {
1814
- const chars = shortCjkCharCount(text2);
1815
- if (!chars || chars > 6) return null;
1816
- const names = invisibleCjkNeedles(engine().cut(String(text2 ?? ""), true));
1817
- return names.length ? names : queryBigramNeedles(text2);
1818
- }
1819
- function queryBigramNeedles(text2) {
1820
- const chars = shortCjkCharCount(text2);
1821
- if (!chars || chars > 6) return null;
1822
- const grams = [...new Set(cjkBigrams(text2))].slice(0, 8);
1823
- return grams.length ? grams : null;
1824
- }
1825
- var DEFAULT_STOPWORDS, MIN_TOKEN_LENGTH, jieba, shortCjkCharCount;
1803
+ var DEFAULT_STOPWORDS, MIN_TOKEN_LENGTH, jieba;
1826
1804
  var init_tokenizer = __esm({
1827
1805
  "src/mem7/core/tokenizer.ts"() {
1828
1806
  "use strict";
@@ -1895,7 +1873,6 @@ var init_tokenizer = __esm({
1895
1873
  ]);
1896
1874
  MIN_TOKEN_LENGTH = 2;
1897
1875
  jieba = null;
1898
- shortCjkCharCount = (text2) => (String(text2 ?? "").match(/[\u4e00-\u9fff]/g) ?? []).length;
1899
1876
  }
1900
1877
  });
1901
1878
 
@@ -4778,6 +4755,10 @@ function invalidateChildren(db, scope, pending, reason) {
4778
4755
  if (!referencedPlan.get(scope, child.child_id, scope, child.child_id)) continue;
4779
4756
  }
4780
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
+ }
4781
4762
  db.prepare(`UPDATE memory_derivations SET state=?,reason=?,updated_at=?
4782
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);
4783
4764
  result.push(child.child_id);
@@ -4997,12 +4978,14 @@ var MemoryDependencies = class {
4997
4978
  return false;
4998
4979
  }
4999
4980
  }
5000
- dirty(scope) {
4981
+ /** excludeKinds:没有重验消费者的类别不计入(1203:foresight,1015 起不做周期重验,见 invalidateChildren)。 */
4982
+ dirty(scope, options = {}) {
5001
4983
  return this.readTransaction(() => {
5002
4984
  checkMemoryReadBudget();
5003
4985
  const memo = /* @__PURE__ */ new Map();
5004
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) => {
5005
4987
  checkMemoryReadBudget();
4988
+ if (options.excludeKinds?.has(row.child_kind)) return false;
5006
4989
  return row.state === "needs_revalidation" || !this.artifactTimeCurrent(scope, row.child_kind, row.child_id, /* @__PURE__ */ new Set(), memo);
5007
4990
  }).map((row) => ({
5008
4991
  kind: row.child_kind,
@@ -5012,6 +4995,20 @@ var MemoryDependencies = class {
5012
4995
  }));
5013
4996
  });
5014
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
+ }
5015
5012
  invalidate(scope, kind, id2, expectedVersion, reason) {
5016
5013
  this.transaction(() => {
5017
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);
@@ -6956,14 +6953,26 @@ var BM25_FIELDS = {
6956
6953
  agent_case: ["task_intent_tokens", "approach_tokens"],
6957
6954
  agent_skill: ["description_tokens", "content_tokens"]
6958
6955
  };
6959
- var BM25_TEXT_FIELDS = {
6960
- foresight: ["foresight", "evidence"],
6961
- episode: ["episode"],
6962
- atomic_fact: ["fact"],
6963
- agent_case: ["task_intent", "approach"],
6964
- 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"]]
6965
6962
  };
6966
- var sqlLiteral = (value2) => value2.replace(/'/g, "''");
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;
6975
+ }
6967
6976
  var RRF_K = 60;
6968
6977
  var warnedFts = /* @__PURE__ */ new Set();
6969
6978
  var warnedVecIdx = /* @__PURE__ */ new Set();
@@ -7081,6 +7090,8 @@ var Mem7VectorStore = class {
7081
7090
  vectorIndexChecks = /* @__PURE__ */ new Map();
7082
7091
  vectorIndexRechecks = /* @__PURE__ */ new Set();
7083
7092
  vectorIndexesReady = /* @__PURE__ */ new Set();
7093
+ /** 自上次 optimize 后有写入的表(bg-worker 每小时收一次,见 optimizePending) */
7094
+ unoptimized = /* @__PURE__ */ new Set();
7084
7095
  ledger = null;
7085
7096
  ledgerPath;
7086
7097
  withProofSnapshot = (operation) => {
@@ -7460,10 +7471,25 @@ var Mem7VectorStore = class {
7460
7471
  assertRuntimeAuthority(this.stateDir, "WRITE");
7461
7472
  validate?.();
7462
7473
  await tbl.add(mapped);
7474
+ this.unoptimized.add(kind);
7463
7475
  assertRuntimeAuthority(this.stateDir, "WRITE");
7464
7476
  validate?.();
7465
7477
  void this.ensureVectorIndexes(kind, tbl, true);
7466
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
+ }
7467
7493
  /**
7468
7494
  * 按 id upsert(everos repo.upsert 语义,1004 read 侧):digest 相同 → 跳过(不重嵌
7469
7495
  * 不重写,everos cascade 的 content_sha256 diff-skip);digest 变了 → 删旧行再插新。
@@ -7484,6 +7510,7 @@ var Mem7VectorStore = class {
7484
7510
  assertRuntimeAuthority(this.stateDir, "WRITE");
7485
7511
  validate?.();
7486
7512
  await tbl.delete(`id = '${r.id.replace(/'/g, "''")}'`);
7513
+ this.unoptimized.add(kind);
7487
7514
  assertRuntimeAuthority(this.stateDir, "WRITE");
7488
7515
  validate?.();
7489
7516
  await this.insert(kind, [r], validate);
@@ -7503,6 +7530,49 @@ var Mem7VectorStore = class {
7503
7530
  return null;
7504
7531
  }
7505
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
+ }
7506
7576
  /** KNN(lancedb vectorSearch:cosine 距离,score=1-distance) */
7507
7577
  async readVisibleCandidates(kind, limit, query, method = "scan") {
7508
7578
  let count = Math.max(1, limit);
@@ -7657,47 +7727,6 @@ var Mem7VectorStore = class {
7657
7727
  if (!cur || score > Number(cur._score ?? 0)) best.set(rid, r);
7658
7728
  }
7659
7729
  }
7660
- const textCols = BM25_TEXT_FIELDS[kind];
7661
- const scan = async (terms, op, limit) => {
7662
- 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 ");
7663
- const where2 = compileFilter(opts.filter);
7664
- return await tbl.query().where(where2 ? `(${where2}) AND (${expr})` : expr).limit(limit).toArray();
7665
- };
7666
- const maxScore = [...best.values()].reduce((max, r) => Math.max(max, Number(r._score ?? 0)), 0);
7667
- const scoreLiteral = (needles2, rows) => {
7668
- const terms = [.../* @__PURE__ */ new Set([...needles2, ...tokenizeToField(queryText).split(/\s+/).filter(Boolean)])];
7669
- const occurrences2 = (text2, term) => text2.split(term).length - 1;
7670
- for (const r of rows) {
7671
- const rid = String(r.id ?? "");
7672
- if (!rid) continue;
7673
- const text2 = textCols.map((col) => String(r[col] ?? "")).join(" ");
7674
- const matched = terms.filter((term) => text2.includes(term));
7675
- if (!matched.length || matched.every((term) => !needles2.includes(term))) continue;
7676
- const full = matched.length === terms.length;
7677
- const density = matched.reduce((sum, term) => sum + occurrences2(text2, term), 0) / Math.max(text2.length, 1) * 1e3;
7678
- 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;
7679
- const cur = best.get(rid);
7680
- if (cur) {
7681
- if (full) cur._score = Math.max(Number(cur._score ?? 0), score);
7682
- } else best.set(rid, { ...r, _score: score });
7683
- }
7684
- };
7685
- const needles = literalQueryNeedles(queryText);
7686
- if (needles) {
7687
- try {
7688
- const terms = [.../* @__PURE__ */ new Set([...needles, ...tokenizeToField(queryText).split(/\s+/).filter(Boolean)])];
7689
- const [all, any] = await Promise.all([
7690
- terms.length > 1 ? scan(terms, "AND", topK * 10) : Promise.resolve([]),
7691
- scan(needles, "OR", topK * 3)
7692
- ]);
7693
- scoreLiteral(needles, [...all, ...any]);
7694
- if (![...best.values()].some((r) => Number(r._score ?? 0) > maxScore)) {
7695
- const bigrams = [...new Set(needles.flatMap((name) => queryBigramNeedles(name) ?? []))].slice(0, 8);
7696
- if (bigrams.length && JSON.stringify(bigrams) !== JSON.stringify(needles)) scoreLiteral(bigrams, await scan(bigrams, "OR", topK * 3));
7697
- }
7698
- } catch {
7699
- }
7700
- }
7701
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) }));
7702
7731
  } catch (err) {
7703
7732
  const msg = String(err?.message ?? err);