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.
@@ -1367,9 +1367,8 @@ var tokenizer_exports = {};
1367
1367
  __export(tokenizer_exports, {
1368
1368
  DEFAULT_STOPWORDS: () => DEFAULT_STOPWORDS,
1369
1369
  MIN_TOKEN_LENGTH: () => MIN_TOKEN_LENGTH,
1370
+ TOKENIZER_VERSION: () => TOKENIZER_VERSION,
1370
1371
  cjkBigrams: () => cjkBigrams,
1371
- literalQueryNeedles: () => literalQueryNeedles,
1372
- queryBigramNeedles: () => queryBigramNeedles,
1373
1372
  tokenize: () => tokenize,
1374
1373
  tokenizeCjk: () => tokenizeCjk,
1375
1374
  tokenizeToField: () => tokenizeToField
@@ -1381,7 +1380,7 @@ function engine() {
1381
1380
  return jieba;
1382
1381
  }
1383
1382
  function tokenize(text2) {
1384
- const raw = engine().cutForSearch(String(text2 ?? ""));
1383
+ const raw = engine().cutForSearch(String(text2 ?? ""), true);
1385
1384
  const out = [];
1386
1385
  for (const t of raw) {
1387
1386
  const tok = t.trim().toLowerCase();
@@ -1404,22 +1403,7 @@ function cjkBigrams(text2) {
1404
1403
  function tokenizeCjk(text2) {
1405
1404
  return [...tokenize(text2), ...cjkBigrams(text2)];
1406
1405
  }
1407
- function invisibleCjkNeedles(candidates) {
1408
- return [...new Set(candidates.map((token) => token.trim()))].filter((token) => /^[\u4e00-\u9fff]{2,}$/.test(token) && tokenize(token).length === 0).slice(0, 8);
1409
- }
1410
- function literalQueryNeedles(text2) {
1411
- const chars = shortCjkCharCount(text2);
1412
- if (!chars || chars > 6) return null;
1413
- const names = invisibleCjkNeedles(engine().cut(String(text2 ?? ""), true));
1414
- return names.length ? names : queryBigramNeedles(text2);
1415
- }
1416
- function queryBigramNeedles(text2) {
1417
- const chars = shortCjkCharCount(text2);
1418
- if (!chars || chars > 6) return null;
1419
- const grams = [...new Set(cjkBigrams(text2))].slice(0, 8);
1420
- return grams.length ? grams : null;
1421
- }
1422
- var DEFAULT_STOPWORDS, MIN_TOKEN_LENGTH, jieba, shortCjkCharCount;
1406
+ var DEFAULT_STOPWORDS, MIN_TOKEN_LENGTH, TOKENIZER_VERSION, jieba;
1423
1407
  var init_tokenizer = __esm({
1424
1408
  "src/mem7/core/tokenizer.ts"() {
1425
1409
  "use strict";
@@ -1491,8 +1475,8 @@ var init_tokenizer = __esm({
1491
1475
  "\u54E6"
1492
1476
  ]);
1493
1477
  MIN_TOKEN_LENGTH = 2;
1478
+ TOKENIZER_VERSION = 2;
1494
1479
  jieba = null;
1495
- shortCjkCharCount = (text2) => (String(text2 ?? "").match(/[\u4e00-\u9fff]/g) ?? []).length;
1496
1480
  }
1497
1481
  });
1498
1482
 
@@ -2424,6 +2408,10 @@ function invalidateChildren(db, scope, pending, reason) {
2424
2408
  if (!referencedPlan.get(scope, child.child_id, scope, child.child_id)) continue;
2425
2409
  }
2426
2410
  const state = child.deleted ? "deleted" : "needs_revalidation";
2411
+ if (child.child_kind === "foresight" && !child.deleted) {
2412
+ pending.push(...db.prepare(`SELECT child_kind,child_id,role FROM memory_dependencies WHERE scope_id=? AND parent_kind='artifact' AND parent_id=?`).all(scope, child.child_id).map((row) => ({ ...row })));
2413
+ continue;
2414
+ }
2427
2415
  db.prepare(`UPDATE memory_derivations SET state=?,reason=?,updated_at=?
2428
2416
  WHERE scope_id=? AND child_kind=? AND child_id=? AND state IN ('current','needs_revalidation') AND state<>?`).run(state, reason, (/* @__PURE__ */ new Date()).toISOString(), scope, child.child_kind, child.child_id, state);
2429
2417
  result.push(child.child_id);
@@ -2652,12 +2640,14 @@ var init_dependencies = __esm({
2652
2640
  return false;
2653
2641
  }
2654
2642
  }
2655
- dirty(scope) {
2643
+ /** excludeKinds:没有重验消费者的类别不计入(1203:foresight,1015 起不做周期重验,见 invalidateChildren)。 */
2644
+ dirty(scope, options = {}) {
2656
2645
  return this.readTransaction(() => {
2657
2646
  checkMemoryReadBudget();
2658
2647
  const memo = /* @__PURE__ */ new Map();
2659
2648
  return this.db.prepare("SELECT child_kind,child_id,version,state,updated_at FROM memory_derivations WHERE scope_id=? AND state IN ('current','needs_revalidation')").all(scopeId(scope)).filter((row) => {
2660
2649
  checkMemoryReadBudget();
2650
+ if (options.excludeKinds?.has(row.child_kind)) return false;
2661
2651
  return row.state === "needs_revalidation" || !this.artifactTimeCurrent(scope, row.child_kind, row.child_id, /* @__PURE__ */ new Set(), memo);
2662
2652
  }).map((row) => ({
2663
2653
  kind: row.child_kind,
@@ -2667,6 +2657,20 @@ var init_dependencies = __esm({
2667
2657
  }));
2668
2658
  });
2669
2659
  }
2660
+ /** needs_revalidation 的派生件按给定的现势状态归位(1203:foresight 一次性清标记——开窗的回 current、
2661
+ * 过期的 retire、行已不存在的记 deleted)。只动 needs_revalidation,不碰 current/invalid/deleted。 */
2662
+ settleRevalidation(scope, kind, verdicts) {
2663
+ return this.transaction(() => {
2664
+ const rows = this.db.prepare("SELECT child_id FROM memory_derivations WHERE scope_id=? AND child_kind=? AND state='needs_revalidation'").all(scopeId(scope), kind);
2665
+ let settled = 0;
2666
+ for (const row of rows) {
2667
+ const verdict = verdicts.get(row.child_id);
2668
+ if (!verdict) continue;
2669
+ settled += Number(this.db.prepare("UPDATE memory_derivations SET state=?,reason=?,updated_at=? WHERE scope_id=? AND child_kind=? AND child_id=? AND state='needs_revalidation'").run(verdict.state, verdict.reason, (/* @__PURE__ */ new Date()).toISOString(), scopeId(scope), kind, row.child_id).changes);
2670
+ }
2671
+ return settled;
2672
+ });
2673
+ }
2670
2674
  invalidate(scope, kind, id, expectedVersion, reason) {
2671
2675
  this.transaction(() => {
2672
2676
  this.db.prepare("UPDATE memory_derivations SET state='invalid',reason=?,updated_at=? WHERE scope_id=? AND child_kind=? AND child_id=? AND version=? AND state IN ('current','needs_revalidation')").run(reason, (/* @__PURE__ */ new Date()).toISOString(), scopeId(scope), kind, id, expectedVersion);
@@ -2922,6 +2926,18 @@ function loadArrow() {
2922
2926
  }
2923
2927
  return arrowPromise;
2924
2928
  }
2929
+ function plainRow(row) {
2930
+ const out = {};
2931
+ for (const [key4, value] of Object.entries(row)) {
2932
+ if (TIMESTAMP_COLUMNS.has(key4) && typeof value === "number") {
2933
+ out[key4] = new Date(value);
2934
+ continue;
2935
+ }
2936
+ const raw = value !== null && typeof value === "object" && typeof value.toArray === "function" ? value.toArray() : value;
2937
+ out[key4] = raw !== null && typeof raw === "object" && ArrayBuffer.isView(raw) ? Array.from(raw) : raw;
2938
+ }
2939
+ return out;
2940
+ }
2925
2941
  function buildSchemas(arrow) {
2926
2942
  const vecField = () => new arrow.Field("vector", new arrow.FixedSizeList(VECTOR_DIM, new arrow.Field("item", new arrow.Float32(), true)), true);
2927
2943
  const commonFields = () => [
@@ -3018,7 +3034,7 @@ function textColumnOf(kind) {
3018
3034
  return "fact";
3019
3035
  }
3020
3036
  }
3021
- var isIntelMac, lancePromise, mem7VectorWarning, arrowPromise, Mem7VectorUnavailableError, VECTOR_DIM, BM25_FIELDS, BM25_TEXT_FIELDS, sqlLiteral, RRF_K, warnedFts, warnedVecIdx, incompatibleIndexSegments, bootAt, schemasCache, Mem7VectorStore;
3037
+ var isIntelMac, lancePromise, mem7VectorWarning, arrowPromise, Mem7VectorUnavailableError, VECTOR_DIM, BM25_FIELDS, TOKEN_FIELDS, TIMESTAMP_COLUMNS, RRF_K, warnedFts, warnedVecIdx, incompatibleIndexSegments, bootAt, schemasCache, Mem7VectorStore;
3022
3038
  var init_vector_store = __esm({
3023
3039
  "src/mem7/core/vector-store.ts"() {
3024
3040
  "use strict";
@@ -3049,14 +3065,14 @@ var init_vector_store = __esm({
3049
3065
  agent_case: ["task_intent_tokens", "approach_tokens"],
3050
3066
  agent_skill: ["description_tokens", "content_tokens"]
3051
3067
  };
3052
- BM25_TEXT_FIELDS = {
3053
- foresight: ["foresight", "evidence"],
3054
- episode: ["episode"],
3055
- atomic_fact: ["fact"],
3056
- agent_case: ["task_intent", "approach"],
3057
- agent_skill: ["description", "content"]
3068
+ TOKEN_FIELDS = {
3069
+ foresight: [["foresight", "foresight_tokens"], ["evidence", "evidence_tokens"]],
3070
+ episode: [["episode", "episode_tokens"]],
3071
+ atomic_fact: [["fact", "fact_tokens"]],
3072
+ agent_case: [["task_intent", "task_intent_tokens"], ["approach", "approach_tokens"]],
3073
+ agent_skill: [["description", "description_tokens"], ["content", "content_tokens"]]
3058
3074
  };
3059
- sqlLiteral = (value) => value.replace(/'/g, "''");
3075
+ TIMESTAMP_COLUMNS = /* @__PURE__ */ new Set(["created_at", "updated_at", "timestamp", "start_time", "end_time"]);
3060
3076
  RRF_K = 60;
3061
3077
  warnedFts = /* @__PURE__ */ new Set();
3062
3078
  warnedVecIdx = /* @__PURE__ */ new Set();
@@ -3078,6 +3094,8 @@ var init_vector_store = __esm({
3078
3094
  vectorIndexChecks = /* @__PURE__ */ new Map();
3079
3095
  vectorIndexRechecks = /* @__PURE__ */ new Set();
3080
3096
  vectorIndexesReady = /* @__PURE__ */ new Set();
3097
+ /** 自上次 optimize 后有写入的表(bg-worker 每小时收一次,见 optimizePending) */
3098
+ unoptimized = /* @__PURE__ */ new Set();
3081
3099
  ledger = null;
3082
3100
  ledgerPath;
3083
3101
  withProofSnapshot = (operation) => {
@@ -3457,10 +3475,25 @@ var init_vector_store = __esm({
3457
3475
  assertRuntimeAuthority(this.stateDir, "WRITE");
3458
3476
  validate?.();
3459
3477
  await tbl.add(mapped);
3478
+ this.unoptimized.add(kind);
3460
3479
  assertRuntimeAuthority(this.stateDir, "WRITE");
3461
3480
  validate?.();
3462
3481
  void this.ensureVectorIndexes(kind, tbl, true);
3463
3482
  }
3483
+ /**
3484
+ * 有写入的表做一次 optimize。1203 实测:lancedb 新写入片段在 optimize 之前 FTS 匹配不到多字中文词
3485
+ * (MatchQuery('山径') 新行 0 命中 → optimize 后 3;ASCII 词不受影响),新对话的中文词 BM25 要等这一步才看得见。
3486
+ */
3487
+ async optimizePending() {
3488
+ const done = [];
3489
+ for (const kind of [...this.unoptimized]) {
3490
+ const tbl = await this.table(kind);
3491
+ await tbl.optimize();
3492
+ this.unoptimized.delete(kind);
3493
+ done.push(kind);
3494
+ }
3495
+ return done;
3496
+ }
3464
3497
  /**
3465
3498
  * 按 id upsert(everos repo.upsert 语义,1004 read 侧):digest 相同 → 跳过(不重嵌
3466
3499
  * 不重写,everos cascade 的 content_sha256 diff-skip);digest 变了 → 删旧行再插新。
@@ -3481,6 +3514,7 @@ var init_vector_store = __esm({
3481
3514
  assertRuntimeAuthority(this.stateDir, "WRITE");
3482
3515
  validate?.();
3483
3516
  await tbl.delete(`id = '${r.id.replace(/'/g, "''")}'`);
3517
+ this.unoptimized.add(kind);
3484
3518
  assertRuntimeAuthority(this.stateDir, "WRITE");
3485
3519
  validate?.();
3486
3520
  await this.insert(kind, [r], validate);
@@ -3500,6 +3534,49 @@ var init_vector_store = __esm({
3500
3534
  return null;
3501
3535
  }
3502
3536
  }
3537
+ /**
3538
+ * 分词器版本变了(TOKENIZER_VERSION)→ 存量行的 *_tokens 按当前 tokenize() 重切(1203:HMM 开回 everos 默认,
3539
+ * 人名要进索引)。向量不动:整行原样回写只改 tokens 列,按 id 分批 mergeInsert;有改动就 optimize 一次
3540
+ * (新片段不进 ANN/FTS 索引,重切完不 optimize 等于没切)。先取全量 id 再分批——回写会产生新片段,
3541
+ * 边写边按 offset 翻页会漏行/重行。
3542
+ */
3543
+ async retokenize(kind, options = {}) {
3544
+ if (this.options.readOnly) throw new Error("MEM7_VECTOR_READ_ONLY");
3545
+ if (!this.tables.has(kind) && !this.openingTables.has(kind) && !existsSync2(join5(this.dir, `${kind}.lance`))) return { rows: 0, changed: 0 };
3546
+ const tbl = await this.table(kind);
3547
+ const fields = TOKEN_FIELDS[kind];
3548
+ const batchSize = Math.max(1, options.batchSize ?? 500);
3549
+ const ids = [];
3550
+ for (let offset = 0; ; offset += 5e3) {
3551
+ const page = await tbl.query().select(["id"]).limit(5e3).offset(offset).toArray();
3552
+ for (const row of page) ids.push(String(row.id));
3553
+ if (page.length < 5e3) break;
3554
+ }
3555
+ let changed = 0;
3556
+ for (let start = 0; start < ids.length; start += batchSize) {
3557
+ assertRuntimeAuthority(this.stateDir, "WRITE");
3558
+ const slice = ids.slice(start, start + batchSize);
3559
+ const rows = await tbl.query().where(`id IN (${slice.map((id) => `'${id.replace(/'/g, "''")}'`).join(",")})`).toArray();
3560
+ const updates = [];
3561
+ for (const row of rows) {
3562
+ let diff = false;
3563
+ for (const [textCol, tokenCol] of fields) {
3564
+ const next = tokenizeToField(String(row[textCol] ?? ""));
3565
+ if (next !== String(row[tokenCol] ?? "")) {
3566
+ row[tokenCol] = next;
3567
+ diff = true;
3568
+ }
3569
+ }
3570
+ if (!diff) continue;
3571
+ updates.push(plainRow(row));
3572
+ }
3573
+ if (updates.length) await tbl.mergeInsert("id").whenMatchedUpdateAll().execute(updates);
3574
+ changed += updates.length;
3575
+ options.onProgress?.(Math.min(ids.length, start + batchSize), ids.length);
3576
+ }
3577
+ if (changed) await tbl.optimize();
3578
+ return { rows: ids.length, changed };
3579
+ }
3503
3580
  /** KNN(lancedb vectorSearch:cosine 距离,score=1-distance) */
3504
3581
  async readVisibleCandidates(kind, limit, query, method = "scan") {
3505
3582
  let count = Math.max(1, limit);
@@ -3654,47 +3731,6 @@ var init_vector_store = __esm({
3654
3731
  if (!cur || score > Number(cur._score ?? 0)) best.set(rid, r);
3655
3732
  }
3656
3733
  }
3657
- const textCols = BM25_TEXT_FIELDS[kind];
3658
- const scan = async (terms, op, limit) => {
3659
- 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 ");
3660
- const where2 = compileFilter(opts.filter);
3661
- return await tbl.query().where(where2 ? `(${where2}) AND (${expr})` : expr).limit(limit).toArray();
3662
- };
3663
- const maxScore = [...best.values()].reduce((max, r) => Math.max(max, Number(r._score ?? 0)), 0);
3664
- const scoreLiteral = (needles2, rows) => {
3665
- const terms = [.../* @__PURE__ */ new Set([...needles2, ...tokenizeToField(queryText).split(/\s+/).filter(Boolean)])];
3666
- const occurrences2 = (text2, term) => text2.split(term).length - 1;
3667
- for (const r of rows) {
3668
- const rid = String(r.id ?? "");
3669
- if (!rid) continue;
3670
- const text2 = textCols.map((col) => String(r[col] ?? "")).join(" ");
3671
- const matched = terms.filter((term) => text2.includes(term));
3672
- if (!matched.length || matched.every((term) => !needles2.includes(term))) continue;
3673
- const full = matched.length === terms.length;
3674
- const density = matched.reduce((sum, term) => sum + occurrences2(text2, term), 0) / Math.max(text2.length, 1) * 1e3;
3675
- 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;
3676
- const cur = best.get(rid);
3677
- if (cur) {
3678
- if (full) cur._score = Math.max(Number(cur._score ?? 0), score);
3679
- } else best.set(rid, { ...r, _score: score });
3680
- }
3681
- };
3682
- const needles = literalQueryNeedles(queryText);
3683
- if (needles) {
3684
- try {
3685
- const terms = [.../* @__PURE__ */ new Set([...needles, ...tokenizeToField(queryText).split(/\s+/).filter(Boolean)])];
3686
- const [all, any] = await Promise.all([
3687
- terms.length > 1 ? scan(terms, "AND", topK * 10) : Promise.resolve([]),
3688
- scan(needles, "OR", topK * 3)
3689
- ]);
3690
- scoreLiteral(needles, [...all, ...any]);
3691
- if (![...best.values()].some((r) => Number(r._score ?? 0) > maxScore)) {
3692
- const bigrams = [...new Set(needles.flatMap((name) => queryBigramNeedles(name) ?? []))].slice(0, 8);
3693
- if (bigrams.length && JSON.stringify(bigrams) !== JSON.stringify(needles)) scoreLiteral(bigrams, await scan(bigrams, "OR", topK * 3));
3694
- }
3695
- } catch {
3696
- }
3697
- }
3698
3734
  return this.visibleRows(kind, [...best.values()]).filter((r) => Number(r._score ?? 0) > 0).sort((a, b) => Number(b._score ?? 0) - Number(a._score ?? 0)).slice(0, topK).map((r) => ({ ...this.toHit(kind, r), distance: 0, score: Number(r._score ?? 0) }));
3699
3735
  } catch (err) {
3700
3736
  const msg = String(err?.message ?? err);
@@ -15664,7 +15700,7 @@ function buildMemoryContext(store, scope, request, clock = () => (/* @__PURE__ *
15664
15700
  historicalFacts: [],
15665
15701
  ...request.includeProjectionStatus === false ? {} : { projections: {
15666
15702
  pendingJobs: store.jobStatus(scope).filter((job) => ["pending", "running", "failed"].includes(job.state)).length,
15667
- dirtyArtifacts: store.dependencies.dirty(scope).length,
15703
+ dirtyArtifacts: store.dependencies.dirty(scope, { excludeKinds: NO_REVALIDATION_KINDS }).length,
15668
15704
  ...cutoff ? { asOf: "current" } : {}
15669
15705
  } },
15670
15706
  futureChanges: [],
@@ -15957,6 +15993,7 @@ function attachHistoricalEvidence(store, scope, context, request, episodes) {
15957
15993
  });
15958
15994
  return boundMemoryContext(context, request.maxTokens ?? 3e3);
15959
15995
  }
15996
+ var NO_REVALIDATION_KINDS;
15960
15997
  var init_context = __esm({
15961
15998
  "src/mem7/core/context.ts"() {
15962
15999
  "use strict";
@@ -15969,6 +16006,7 @@ var init_context = __esm({
15969
16006
  init_relationship_context();
15970
16007
  init_read_budget();
15971
16008
  init_fit_prefix();
16009
+ NO_REVALIDATION_KINDS = /* @__PURE__ */ new Set(["foresight"]);
15972
16010
  }
15973
16011
  });
15974
16012
 
@@ -20030,13 +20068,10 @@ var init_intent = __esm({
20030
20068
  }
20031
20069
  });
20032
20070
 
20033
- // src/memory/proactive/sweep.ts
20034
- var init_sweep = __esm({
20035
- "src/memory/proactive/sweep.ts"() {
20071
+ // src/memory/proactive/care-leads.ts
20072
+ var init_care_leads = __esm({
20073
+ "src/memory/proactive/care-leads.ts"() {
20036
20074
  "use strict";
20037
- init_calendar_bridge();
20038
- init_intent();
20039
- init_clock();
20040
20075
  }
20041
20076
  });
20042
20077
 
@@ -20065,7 +20100,8 @@ var init_opportunity = __esm({
20065
20100
  init_read_guard();
20066
20101
  init_scoped_opportunity();
20067
20102
  init_published_basis();
20068
- init_sweep();
20103
+ init_intent();
20104
+ init_care_leads();
20069
20105
  OPPORTUNITY_SCAN_INTERVAL_MS = 6 * 60 * 6e4;
20070
20106
  FORESIGHT_CACHE_TTL_MS = 30 * 6e4;
20071
20107
  OPPORTUNITY_DELAY_MS = 30 * 6e4;
@@ -20089,6 +20125,16 @@ var init_agent = __esm({
20089
20125
  }
20090
20126
  });
20091
20127
 
20128
+ // src/memory/proactive/sweep.ts
20129
+ var init_sweep = __esm({
20130
+ "src/memory/proactive/sweep.ts"() {
20131
+ "use strict";
20132
+ init_calendar_bridge();
20133
+ init_intent();
20134
+ init_clock();
20135
+ }
20136
+ });
20137
+
20092
20138
  // src/memory/proactive/planning-context.ts
20093
20139
  import { DatabaseSync as DatabaseSync13 } from "node:sqlite";
20094
20140
  var init_planning_context = __esm({
@@ -23590,27 +23636,8 @@ function mem7RelationshipContext(binding, args, hostBudget, options = {}) {
23590
23636
  });
23591
23637
  return result;
23592
23638
  }
23593
- function boundSearchResponse(context, episodes, maxTokens, historySearch) {
23594
- const result = { ...context, episodes, ...historySearch ? { historySearch } : {} };
23595
- const budget = maxTokens ?? Math.min(64e3, 3e3 + roughTokenCountEstimation(JSON.stringify(episodes)) + 100);
23596
- const exceeds = () => JSON.stringify(result).length > budget * 4 || roughTokenCountEstimation(JSON.stringify(result)) > budget;
23597
- if (exceeds()) {
23598
- const reserve = budget - 140 - roughTokenCountEstimation(JSON.stringify(result.episodes));
23599
- try {
23600
- const trimmed = boundMemoryContext(context, Math.max(1, reserve));
23601
- Object.assign(result, trimmed);
23602
- if (!trimmed.relationships) delete result.relationships;
23603
- result.truncated = true;
23604
- } catch {
23605
- for (const collection of ["pendingSources", "historicalEvidence", "historicalFacts", "hypotheses", "futureChanges", "people", "currentFacts", "conflicts", "ambiguity", "citations"]) {
23606
- result[collection] = [];
23607
- }
23608
- delete result.relationships;
23609
- result.truncated = true;
23610
- }
23611
- }
23612
- if (result.truncated && historySearch?.status === "complete") historySearch.status = "partial";
23613
- return JSON.stringify(result);
23639
+ function boundSearchResponse(context, episodes, historySearch) {
23640
+ return JSON.stringify({ ...context, episodes, ...historySearch ? { historySearch } : {} });
23614
23641
  }
23615
23642
  function searchResponse(service, request, episodes, historySearch) {
23616
23643
  const retained = episodes.filter((episode) => {
@@ -23654,7 +23681,7 @@ function searchResponse(service, request, episodes, historySearch) {
23654
23681
  ...episode
23655
23682
  }) => episode);
23656
23683
  if (historySearch.status === "complete") historySearch.status = retained.length < episodes.length ? "partial" : retained.length ? "complete" : "empty";
23657
- return boundSearchResponse(context, histories, request.maxTokens, historySearch);
23684
+ return boundSearchResponse(context, histories, historySearch);
23658
23685
  }
23659
23686
  function bindingMemoryService(binding, options = {}) {
23660
23687
  if (binding.backend !== "mem7" || !binding.stateDir) throw new Error("STORAGE_UNAVAILABLE: mem7 binding requires stateDir");
@@ -23744,7 +23771,7 @@ async function mem7Search(binding, args, options = {}) {
23744
23771
  else if (hits.length && ["unavailable", "timeout", "stale"].includes(result.historySearch.status)) result.historySearch.status = "partial";
23745
23772
  result.topicsHistory = { status: retained.some((ep) => ep.history_ref) ? "complete" : "empty", method: topicsImported(binding) ? "imported_native" : hasTopicsHistory(binding) ? "fts5" : "file_selection" };
23746
23773
  const { episodes: _episodes, ...context } = { ...fresh, topicsHistory: result.topicsHistory };
23747
- return boundSearchResponse(context, retained, args.max_tokens, result.historySearch);
23774
+ return boundSearchResponse(context, retained, result.historySearch);
23748
23775
  });
23749
23776
  }
23750
23777
  async function searchBoundMemory(binding, args, options) {
@@ -23786,7 +23813,6 @@ async function searchBoundMemory(binding, args, options) {
23786
23813
  version: evidence.version,
23787
23814
  publishedAt: evidence.publishedAt
23788
23815
  })),
23789
- request.maxTokens,
23790
23816
  { status: context.historicalEvidence.length ? "complete" : "empty", method: "keyword" }
23791
23817
  );
23792
23818
  });
@@ -1039,6 +1039,10 @@ function invalidateChildren(db, scope, pending, reason) {
1039
1039
  if (!referencedPlan.get(scope, child.child_id, scope, child.child_id)) continue;
1040
1040
  }
1041
1041
  const state = child.deleted ? "deleted" : "needs_revalidation";
1042
+ if (child.child_kind === "foresight" && !child.deleted) {
1043
+ pending.push(...db.prepare(`SELECT child_kind,child_id,role FROM memory_dependencies WHERE scope_id=? AND parent_kind='artifact' AND parent_id=?`).all(scope, child.child_id).map((row) => ({ ...row })));
1044
+ continue;
1045
+ }
1042
1046
  db.prepare(`UPDATE memory_derivations SET state=?,reason=?,updated_at=?
1043
1047
  WHERE scope_id=? AND child_kind=? AND child_id=? AND state IN ('current','needs_revalidation') AND state<>?`).run(state, reason, (/* @__PURE__ */ new Date()).toISOString(), scope, child.child_kind, child.child_id, state);
1044
1048
  result.push(child.child_id);