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.
@@ -1315,6 +1315,7 @@ var tokenizer_exports = {};
1315
1315
  __export(tokenizer_exports, {
1316
1316
  DEFAULT_STOPWORDS: () => DEFAULT_STOPWORDS,
1317
1317
  MIN_TOKEN_LENGTH: () => MIN_TOKEN_LENGTH,
1318
+ TOKENIZER_VERSION: () => TOKENIZER_VERSION,
1318
1319
  cjkBigrams: () => cjkBigrams,
1319
1320
  tokenize: () => tokenize,
1320
1321
  tokenizeCjk: () => tokenizeCjk,
@@ -1327,7 +1328,7 @@ function engine() {
1327
1328
  return jieba;
1328
1329
  }
1329
1330
  function tokenize(text2) {
1330
- const raw = engine().cutForSearch(String(text2 ?? ""));
1331
+ const raw = engine().cutForSearch(String(text2 ?? ""), true);
1331
1332
  const out = [];
1332
1333
  for (const t of raw) {
1333
1334
  const tok = t.trim().toLowerCase();
@@ -1350,7 +1351,7 @@ function cjkBigrams(text2) {
1350
1351
  function tokenizeCjk(text2) {
1351
1352
  return [...tokenize(text2), ...cjkBigrams(text2)];
1352
1353
  }
1353
- var DEFAULT_STOPWORDS, MIN_TOKEN_LENGTH, jieba;
1354
+ var DEFAULT_STOPWORDS, MIN_TOKEN_LENGTH, TOKENIZER_VERSION, jieba;
1354
1355
  var init_tokenizer = __esm({
1355
1356
  "src/mem7/core/tokenizer.ts"() {
1356
1357
  "use strict";
@@ -1422,6 +1423,7 @@ var init_tokenizer = __esm({
1422
1423
  "\u54E6"
1423
1424
  ]);
1424
1425
  MIN_TOKEN_LENGTH = 2;
1426
+ TOKENIZER_VERSION = 2;
1425
1427
  jieba = null;
1426
1428
  }
1427
1429
  });
@@ -2696,6 +2698,10 @@ function invalidateChildren(db2, scope, pending2, reason) {
2696
2698
  if (!referencedPlan.get(scope, child.child_id, scope, child.child_id)) continue;
2697
2699
  }
2698
2700
  const state = child.deleted ? "deleted" : "needs_revalidation";
2701
+ if (child.child_kind === "foresight" && !child.deleted) {
2702
+ pending2.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 })));
2703
+ continue;
2704
+ }
2699
2705
  db2.prepare(`UPDATE memory_derivations SET state=?,reason=?,updated_at=?
2700
2706
  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);
2701
2707
  result.push(child.child_id);
@@ -2924,12 +2930,14 @@ var init_dependencies = __esm({
2924
2930
  return false;
2925
2931
  }
2926
2932
  }
2927
- dirty(scope) {
2933
+ /** excludeKinds:没有重验消费者的类别不计入(1203:foresight,1015 起不做周期重验,见 invalidateChildren)。 */
2934
+ dirty(scope, options = {}) {
2928
2935
  return this.readTransaction(() => {
2929
2936
  checkMemoryReadBudget();
2930
2937
  const memo = /* @__PURE__ */ new Map();
2931
2938
  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) => {
2932
2939
  checkMemoryReadBudget();
2940
+ if (options.excludeKinds?.has(row.child_kind)) return false;
2933
2941
  return row.state === "needs_revalidation" || !this.artifactTimeCurrent(scope, row.child_kind, row.child_id, /* @__PURE__ */ new Set(), memo);
2934
2942
  }).map((row) => ({
2935
2943
  kind: row.child_kind,
@@ -2939,6 +2947,20 @@ var init_dependencies = __esm({
2939
2947
  }));
2940
2948
  });
2941
2949
  }
2950
+ /** needs_revalidation 的派生件按给定的现势状态归位(1203:foresight 一次性清标记——开窗的回 current、
2951
+ * 过期的 retire、行已不存在的记 deleted)。只动 needs_revalidation,不碰 current/invalid/deleted。 */
2952
+ settleRevalidation(scope, kind, verdicts) {
2953
+ return this.transaction(() => {
2954
+ 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);
2955
+ let settled = 0;
2956
+ for (const row of rows) {
2957
+ const verdict = verdicts.get(row.child_id);
2958
+ if (!verdict) continue;
2959
+ 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);
2960
+ }
2961
+ return settled;
2962
+ });
2963
+ }
2942
2964
  invalidate(scope, kind, id, expectedVersion, reason) {
2943
2965
  this.transaction(() => {
2944
2966
  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);
@@ -3247,11 +3269,17 @@ function loadArrow() {
3247
3269
  }
3248
3270
  return arrowPromise;
3249
3271
  }
3250
- function shortCjkQueryBigrams(text2) {
3251
- const chars = (String(text2 ?? "").match(/[\u4e00-\u9fff]/g) ?? []).length;
3252
- if (!chars || chars > 6) return null;
3253
- const grams = [...new Set(cjkBigrams(text2))].slice(0, 8);
3254
- return grams.length ? grams : null;
3272
+ function plainRow(row) {
3273
+ const out = {};
3274
+ for (const [key5, value] of Object.entries(row)) {
3275
+ if (TIMESTAMP_COLUMNS.has(key5) && typeof value === "number") {
3276
+ out[key5] = new Date(value);
3277
+ continue;
3278
+ }
3279
+ const raw = value !== null && typeof value === "object" && typeof value.toArray === "function" ? value.toArray() : value;
3280
+ out[key5] = raw !== null && typeof raw === "object" && ArrayBuffer.isView(raw) ? Array.from(raw) : raw;
3281
+ }
3282
+ return out;
3255
3283
  }
3256
3284
  function buildSchemas(arrow) {
3257
3285
  const vecField = () => new arrow.Field("vector", new arrow.FixedSizeList(VECTOR_DIM, new arrow.Field("item", new arrow.Float32(), true)), true);
@@ -3349,7 +3377,7 @@ function textColumnOf(kind) {
3349
3377
  return "fact";
3350
3378
  }
3351
3379
  }
3352
- var isIntelMac, lancePromise, mem7VectorWarning, arrowPromise, Mem7VectorUnavailableError, VECTOR_DIM, BM25_FIELDS, BM25_TEXT_FIELDS, sqlLiteral, RRF_K, warnedFts, warnedVecIdx, incompatibleIndexSegments, bootAt, schemasCache, Mem7VectorStore;
3380
+ var isIntelMac, lancePromise, mem7VectorWarning, arrowPromise, Mem7VectorUnavailableError, VECTOR_DIM, BM25_FIELDS, TOKEN_FIELDS, TIMESTAMP_COLUMNS, RRF_K, warnedFts, warnedVecIdx, incompatibleIndexSegments, bootAt, schemasCache, Mem7VectorStore;
3353
3381
  var init_vector_store = __esm({
3354
3382
  "src/mem7/core/vector-store.ts"() {
3355
3383
  "use strict";
@@ -3380,14 +3408,14 @@ var init_vector_store = __esm({
3380
3408
  agent_case: ["task_intent_tokens", "approach_tokens"],
3381
3409
  agent_skill: ["description_tokens", "content_tokens"]
3382
3410
  };
3383
- BM25_TEXT_FIELDS = {
3384
- foresight: ["foresight", "evidence"],
3385
- episode: ["episode"],
3386
- atomic_fact: ["fact"],
3387
- agent_case: ["task_intent", "approach"],
3388
- agent_skill: ["description", "content"]
3411
+ TOKEN_FIELDS = {
3412
+ foresight: [["foresight", "foresight_tokens"], ["evidence", "evidence_tokens"]],
3413
+ episode: [["episode", "episode_tokens"]],
3414
+ atomic_fact: [["fact", "fact_tokens"]],
3415
+ agent_case: [["task_intent", "task_intent_tokens"], ["approach", "approach_tokens"]],
3416
+ agent_skill: [["description", "description_tokens"], ["content", "content_tokens"]]
3389
3417
  };
3390
- sqlLiteral = (value) => value.replace(/'/g, "''");
3418
+ TIMESTAMP_COLUMNS = /* @__PURE__ */ new Set(["created_at", "updated_at", "timestamp", "start_time", "end_time"]);
3391
3419
  RRF_K = 60;
3392
3420
  warnedFts = /* @__PURE__ */ new Set();
3393
3421
  warnedVecIdx = /* @__PURE__ */ new Set();
@@ -3409,6 +3437,8 @@ var init_vector_store = __esm({
3409
3437
  vectorIndexChecks = /* @__PURE__ */ new Map();
3410
3438
  vectorIndexRechecks = /* @__PURE__ */ new Set();
3411
3439
  vectorIndexesReady = /* @__PURE__ */ new Set();
3440
+ /** 自上次 optimize 后有写入的表(bg-worker 每小时收一次,见 optimizePending) */
3441
+ unoptimized = /* @__PURE__ */ new Set();
3412
3442
  ledger = null;
3413
3443
  ledgerPath;
3414
3444
  withProofSnapshot = (operation) => {
@@ -3788,10 +3818,25 @@ var init_vector_store = __esm({
3788
3818
  assertRuntimeAuthority(this.stateDir, "WRITE");
3789
3819
  validate?.();
3790
3820
  await tbl.add(mapped);
3821
+ this.unoptimized.add(kind);
3791
3822
  assertRuntimeAuthority(this.stateDir, "WRITE");
3792
3823
  validate?.();
3793
3824
  void this.ensureVectorIndexes(kind, tbl, true);
3794
3825
  }
3826
+ /**
3827
+ * 有写入的表做一次 optimize。1203 实测:lancedb 新写入片段在 optimize 之前 FTS 匹配不到多字中文词
3828
+ * (MatchQuery('山径') 新行 0 命中 → optimize 后 3;ASCII 词不受影响),新对话的中文词 BM25 要等这一步才看得见。
3829
+ */
3830
+ async optimizePending() {
3831
+ const done = [];
3832
+ for (const kind of [...this.unoptimized]) {
3833
+ const tbl = await this.table(kind);
3834
+ await tbl.optimize();
3835
+ this.unoptimized.delete(kind);
3836
+ done.push(kind);
3837
+ }
3838
+ return done;
3839
+ }
3795
3840
  /**
3796
3841
  * 按 id upsert(everos repo.upsert 语义,1004 read 侧):digest 相同 → 跳过(不重嵌
3797
3842
  * 不重写,everos cascade 的 content_sha256 diff-skip);digest 变了 → 删旧行再插新。
@@ -3812,6 +3857,7 @@ var init_vector_store = __esm({
3812
3857
  assertRuntimeAuthority(this.stateDir, "WRITE");
3813
3858
  validate?.();
3814
3859
  await tbl.delete(`id = '${r.id.replace(/'/g, "''")}'`);
3860
+ this.unoptimized.add(kind);
3815
3861
  assertRuntimeAuthority(this.stateDir, "WRITE");
3816
3862
  validate?.();
3817
3863
  await this.insert(kind, [r], validate);
@@ -3831,6 +3877,49 @@ var init_vector_store = __esm({
3831
3877
  return null;
3832
3878
  }
3833
3879
  }
3880
+ /**
3881
+ * 分词器版本变了(TOKENIZER_VERSION)→ 存量行的 *_tokens 按当前 tokenize() 重切(1203:HMM 开回 everos 默认,
3882
+ * 人名要进索引)。向量不动:整行原样回写只改 tokens 列,按 id 分批 mergeInsert;有改动就 optimize 一次
3883
+ * (新片段不进 ANN/FTS 索引,重切完不 optimize 等于没切)。先取全量 id 再分批——回写会产生新片段,
3884
+ * 边写边按 offset 翻页会漏行/重行。
3885
+ */
3886
+ async retokenize(kind, options = {}) {
3887
+ if (this.options.readOnly) throw new Error("MEM7_VECTOR_READ_ONLY");
3888
+ if (!this.tables.has(kind) && !this.openingTables.has(kind) && !existsSync2(join5(this.dir, `${kind}.lance`))) return { rows: 0, changed: 0 };
3889
+ const tbl = await this.table(kind);
3890
+ const fields = TOKEN_FIELDS[kind];
3891
+ const batchSize = Math.max(1, options.batchSize ?? 500);
3892
+ const ids = [];
3893
+ for (let offset = 0; ; offset += 5e3) {
3894
+ const page = await tbl.query().select(["id"]).limit(5e3).offset(offset).toArray();
3895
+ for (const row of page) ids.push(String(row.id));
3896
+ if (page.length < 5e3) break;
3897
+ }
3898
+ let changed = 0;
3899
+ for (let start = 0; start < ids.length; start += batchSize) {
3900
+ assertRuntimeAuthority(this.stateDir, "WRITE");
3901
+ const slice = ids.slice(start, start + batchSize);
3902
+ const rows = await tbl.query().where(`id IN (${slice.map((id) => `'${id.replace(/'/g, "''")}'`).join(",")})`).toArray();
3903
+ const updates = [];
3904
+ for (const row of rows) {
3905
+ let diff = false;
3906
+ for (const [textCol, tokenCol] of fields) {
3907
+ const next = tokenizeToField(String(row[textCol] ?? ""));
3908
+ if (next !== String(row[tokenCol] ?? "")) {
3909
+ row[tokenCol] = next;
3910
+ diff = true;
3911
+ }
3912
+ }
3913
+ if (!diff) continue;
3914
+ updates.push(plainRow(row));
3915
+ }
3916
+ if (updates.length) await tbl.mergeInsert("id").whenMatchedUpdateAll().execute(updates);
3917
+ changed += updates.length;
3918
+ options.onProgress?.(Math.min(ids.length, start + batchSize), ids.length);
3919
+ }
3920
+ if (changed) await tbl.optimize();
3921
+ return { rows: ids.length, changed };
3922
+ }
3834
3923
  /** KNN(lancedb vectorSearch:cosine 距离,score=1-distance) */
3835
3924
  async readVisibleCandidates(kind, limit, query, method = "scan") {
3836
3925
  let count = Math.max(1, limit);
@@ -3985,28 +4074,6 @@ var init_vector_store = __esm({
3985
4074
  if (!cur || score > Number(cur._score ?? 0)) best.set(rid, r);
3986
4075
  }
3987
4076
  }
3988
- const grams = shortCjkQueryBigrams(queryText);
3989
- if (grams) {
3990
- try {
3991
- const textCols = BM25_TEXT_FIELDS[kind];
3992
- const expr = textCols.map((col) => `(${grams.map((g) => `contains(${col}, '${sqlLiteral(g)}')`).join(" OR ")})`).join(" OR ");
3993
- const where2 = compileFilter(opts.filter);
3994
- const extra = await tbl.query().where(where2 ? `(${where2}) AND (${expr})` : expr).limit(topK * 3).toArray();
3995
- const maxScore = [...best.values()].reduce((max, r) => Math.max(max, Number(r._score ?? 0)), 0);
3996
- for (const r of extra) {
3997
- const rid = String(r.id ?? "");
3998
- if (!rid) continue;
3999
- const text2 = textCols.map((col) => String(r[col] ?? "")).join(" ");
4000
- const matched = grams.filter((gram) => text2.includes(gram)).length;
4001
- if (!matched) continue;
4002
- const score = maxScore + matched / grams.length;
4003
- const cur = best.get(rid);
4004
- if (cur) cur._score = Math.max(Number(cur._score ?? 0), score);
4005
- else best.set(rid, { ...r, _score: score });
4006
- }
4007
- } catch {
4008
- }
4009
- }
4010
4077
  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) }));
4011
4078
  } catch (err) {
4012
4079
  const msg2 = String(err?.message ?? err);
@@ -16698,7 +16765,8 @@ function buildMemoryContext(store, scope, request, clock = () => (/* @__PURE__ *
16698
16765
  if (!resolved.has(id)) resolved.set(id, store.entities.resolve(scope, id, snapshot.entityRevision, cutoff ?? void 0));
16699
16766
  return resolved.get(id);
16700
16767
  };
16701
- const resolvedSelection = new Set((request.entityRef || matching.length ? matching : entities).map((entity) => resolve26(entity.entityId)?.entityId));
16768
+ const pool = request.entityRef || matching.length ? matching : request.matchedEntitiesOnly ? [] : entities;
16769
+ const resolvedSelection = new Set(pool.map((entity) => resolve26(entity.entityId)?.entityId));
16702
16770
  const selected = new Set(entities.filter((entity) => resolvedSelection.has(resolve26(entity.entityId)?.entityId)).map((entity) => entity.entityId));
16703
16771
  const context = {
16704
16772
  validAt,
@@ -16709,7 +16777,7 @@ function buildMemoryContext(store, scope, request, clock = () => (/* @__PURE__ *
16709
16777
  historicalFacts: [],
16710
16778
  ...request.includeProjectionStatus === false ? {} : { projections: {
16711
16779
  pendingJobs: store.jobStatus(scope).filter((job) => ["pending", "running", "failed"].includes(job.state)).length,
16712
- dirtyArtifacts: store.dependencies.dirty(scope).length,
16780
+ dirtyArtifacts: store.dependencies.dirty(scope, { excludeKinds: NO_REVALIDATION_KINDS }).length,
16713
16781
  ...cutoff ? { asOf: "current" } : {}
16714
16782
  } },
16715
16783
  futureChanges: [],
@@ -17002,6 +17070,7 @@ function attachHistoricalEvidence(store, scope, context, request, episodes) {
17002
17070
  });
17003
17071
  return boundMemoryContext(context, request.maxTokens ?? 3e3);
17004
17072
  }
17073
+ var NO_REVALIDATION_KINDS;
17005
17074
  var init_context = __esm({
17006
17075
  "src/mem7/core/context.ts"() {
17007
17076
  "use strict";
@@ -17014,6 +17083,7 @@ var init_context = __esm({
17014
17083
  init_relationship_context();
17015
17084
  init_read_budget();
17016
17085
  init_fit_prefix();
17086
+ NO_REVALIDATION_KINDS = /* @__PURE__ */ new Set(["foresight"]);
17017
17087
  }
17018
17088
  });
17019
17089
 
@@ -24580,7 +24650,7 @@ async function runProactiveCycle(deps, now2) {
24580
24650
  function normalizeTitle(title) {
24581
24651
  return title.replace(/Research: /g, "").replace(/Execute: /g, "").replace(/提醒|记得|跟进|确认一下|处理一下|去/g, "").replace(/[\s,。!?、,::;;()()\[\]]+/g, "").trim().toLowerCase();
24582
24652
  }
24583
- function titlesOverlap(a, b) {
24653
+ function titlesOverlap(a, b, minRatio = 0.6) {
24584
24654
  if (!a || !b) return false;
24585
24655
  if (a.length >= 4 && b.includes(a)) return true;
24586
24656
  if (b.length >= 4 && a.includes(b)) return true;
@@ -24588,9 +24658,10 @@ function titlesOverlap(a, b) {
24588
24658
  const ga = grams(a);
24589
24659
  const gb = grams(b);
24590
24660
  if (ga.size === 0 || gb.size === 0) return false;
24661
+ if (Math.min(ga.size, gb.size) <= 2) return false;
24591
24662
  let common = 0;
24592
24663
  for (const g of ga) if (gb.has(g)) common++;
24593
- return common / Math.min(ga.size, gb.size) >= 0.6;
24664
+ return common / Math.min(ga.size, gb.size) >= minRatio;
24594
24665
  }
24595
24666
  var PRIORITY_SCORES, IntentSelector, ActionAgent;
24596
24667
  var init_intent = __esm({
@@ -24786,351 +24857,58 @@ var init_intent = __esm({
24786
24857
  }
24787
24858
  });
24788
24859
 
24789
- // src/memory/proactive/sweep.ts
24790
- import { readFileSync as readFileSync24 } from "node:fs";
24791
- function sharesTerm(a, b) {
24792
- const x = normalizeTitle(a);
24793
- const y = normalizeTitle(b);
24794
- if (x.length < 2 || y.length < 2) return false;
24795
- const grams = new Set(Array.from({ length: x.length - 1 }, (_, i) => x.slice(i, i + 2)));
24796
- for (let i = 0; i < y.length - 1; i++) if (grams.has(y.slice(i, i + 2))) return true;
24797
- return false;
24860
+ // src/memory/proactive/care-leads.ts
24861
+ function userMentionLines(events, options = { since: "" }) {
24862
+ const limit = options.limit ?? 30;
24863
+ const skip = options.skip ?? WORK_EVENT;
24864
+ return events.filter((event2) => event2.createdAt >= options.since && !options.excludeIds?.has(event2.id) && !skip.test(`${event2.title} ${event2.evidence ?? ""}`)).sort((a, b) => b.createdAt.localeCompare(a.createdAt)).slice(0, limit).map((event2) => `- [${event2.id}] ${dayKey(event2.createdAt)} ${event2.title}${event2.evidence ? `
24865
+ ${event2.evidence.slice(0, options.evidenceChars ?? 160)}` : ""}`);
24798
24866
  }
24799
- function isSameCommitment(a, b) {
24800
- const x = normalizeTitle(a);
24801
- const y = normalizeTitle(b);
24802
- if (!x || !y) return false;
24803
- if (x === y) return true;
24804
- if (x.length >= 4 && y.includes(x)) return true;
24805
- if (y.length >= 4 && x.includes(y)) return true;
24806
- return false;
24807
- }
24808
- function guardVerdict(value) {
24809
- if (typeof value === "boolean") return { ok: value, reason: value ? "" : "GUARD_REJECTED" };
24810
- return { ok: value.ok, reason: value.reason ?? (value.ok ? "" : "GUARD_REJECTED") };
24867
+ function densePeriodLines(coverage, now2, parseDate, options = {}) {
24868
+ const days = options.days ?? 3;
24869
+ const from = now2.getTime() - days * 864e5;
24870
+ const items = coverage.filter((item) => !NON_EVENT_CALENDAR_TYPES.has(String(item.type ?? ""))).map((item) => ({ item, ms: parseDate(item.date, now2) })).filter((entry) => entry.ms !== null && entry.ms >= from && entry.ms <= now2.getTime() + 864e5).sort((a, b) => a.ms - b.ms);
24871
+ if (items.length < (options.minItems ?? 3)) return null;
24872
+ return items.map(({ item }) => `- [calendar #${item.id}] ${item.date} ${item.time} ${item.title}`);
24811
24873
  }
24812
- function actionPayload(a, now2, recentEvidence) {
24813
- let suggestedTask = null;
24814
- let scheduledLocal = null;
24815
- try {
24816
- const { dateStr, timeExact } = toCalendarWallParts(a.scheduledTime);
24817
- suggestedTask = { date: dateStr, time: timeExact };
24818
- scheduledLocal = formatForLlm(a.scheduledTime);
24819
- } catch {
24820
- }
24821
- let generatedLocal = null;
24822
- try {
24823
- generatedLocal = a.createdAt ? formatForLlm(a.createdAt) : null;
24824
- } catch {
24874
+ function stateSignalLines(facts, options = {}) {
24875
+ const lines = [];
24876
+ for (const fact of facts) {
24877
+ if (fact.claimKind !== "user_statement") continue;
24878
+ const value = fact.value ?? null;
24879
+ const text2 = String(value?.body ?? "").trim() || String(value?.label ?? "");
24880
+ if (!text2) continue;
24881
+ if (!STATE_KINDS.has(String(value?.contentKind ?? "")) && !STATE_PATTERN.test(text2)) continue;
24882
+ const at = value?.observedAsCurrentAt ? dayKey(value.observedAsCurrentAt) : "";
24883
+ lines.push(`${at ? `${at} ` : ""}${text2.replace(/\s+/g, " ").slice(0, 100)}`);
24884
+ if (lines.length >= (options.limit ?? 5)) break;
24825
24885
  }
24826
- const ageHours = (now2.getTime() - Date.parse(a.scheduledTime)) / 36e5;
24827
- const staleHint = ageHours > STALE_HINT_HOURS ? `\u8FD9\u6761\u5DF2\u8FC7\u6392\u671F ${Math.round(ageHours)} \u5C0F\u65F6\u2014\u2014\u6B63\u6587\u91CC\u7684"\u73B0\u5728/\u4ECA\u5929"\u6307\u7684\u662F**\u751F\u6210\u65F6\u523B**\uFF0C\u4E0D\u662F\u6B64\u523B\uFF0C\u5148\u6838\u5BF9\u518D\u5224` : void 0;
24828
- return {
24829
- action_id: a.id,
24830
- action_version: a.actionVersion,
24831
- intent_id: a.intentId,
24832
- title: a.title,
24833
- description: a.description,
24834
- scheduled_time: a.scheduledTime,
24835
- // UTC 绝对时刻(机器坐标)
24836
- scheduled_time_local: scheduledLocal,
24837
- // 本地可读 —— 与上一行是同一个时刻,别当两件事
24838
- suggested_task: suggestedTask,
24839
- // { date, time } 本地墙上时间,calendar add-task 参数
24840
- urgency: a.urgency,
24841
- duration_minutes: a.durationMinutes,
24842
- calendar_id: a.calendarId,
24843
- status: a.status,
24844
- generated_at_local: generatedLocal,
24845
- // 这条 action 是**几点生成的**(正文里的「现在」指这个点)
24846
- stale_hint: staleHint,
24847
- // 0906 anti-hindsight:近期关联证据(最新在前)——"后续对话已做完"的马后炮当场现形。
24848
- // 时间戳走 formatShort(本地);此前是 createdAt.slice(5,16) —— 那是 **UTC**,
24849
- // 混在 suggested_task(本地)旁边且无标注。
24850
- recent_evidence: recentEvidence && recentEvidence.length > 0 ? recentEvidence.map((e) => `[${formatShort(e.createdAt)}] ${e.title}${e.description ? `\uFF1A${e.description}` : ""}`) : void 0,
24851
- // 机械可判的过期事实标记(不靠 LLM):action 创建之后 graph 又来了新证据 →
24852
- // action 基于过期事实生成,先核对新证据再决定(生成侧 Time-Evidence Gate 的兜底)
24853
- stale_facts: recentEvidence && recentEvidence.length > 0 && recentEvidence.some((e) => Date.parse(e.createdAt) > Date.parse(a.createdAt)) ? "\u6B64 action \u751F\u6210\u540E\u53C8\u6709\u65B0\u8BC1\u636E\uFF08\u89C1 recent_evidence \u6700\u65B0\u4E00\u6761\uFF09\u2014\u2014\u5148\u6838\u5BF9\u518D\u51B3\u5B9A\uFF0C\u591A\u534A\u8BE5 cancelled" : void 0,
24854
- _received_at: now2.toISOString()
24855
- };
24886
+ return lines;
24856
24887
  }
24857
- var BACKLOG_ALERT_RUNS, STALE_HINT_HOURS, DEFAULT_PROMPT, TRANSIENT_GUARD_REASONS, DUE_PAGE_SIZE, DUE_MAX_PAGES, transientGuardLogged, Sweep;
24858
- var init_sweep = __esm({
24859
- "src/memory/proactive/sweep.ts"() {
24888
+ function prepLines(items) {
24889
+ return items.map((item) => [
24890
+ `- [calendar #${item.calendarId}] ${item.date} ${item.time} ${item.title}`,
24891
+ ...item.people.flatMap((person) => person.facts.length ? [` ${person.name}\uFF1A${person.facts.map((fact) => fact.replace(/\s+/g, " ").slice(0, 100)).join("\uFF1B")}`] : [])
24892
+ ].join("\n"));
24893
+ }
24894
+ var dayKey, WORK_EVENT, NON_EVENT_CALENDAR_TYPES, STATE_PATTERN, STATE_KINDS;
24895
+ var init_care_leads = __esm({
24896
+ "src/memory/proactive/care-leads.ts"() {
24860
24897
  "use strict";
24861
- init_calendar_bridge();
24862
- init_intent();
24863
- init_clock();
24864
- BACKLOG_ALERT_RUNS = 12;
24865
- STALE_HINT_HOURS = 8;
24866
- DEFAULT_PROMPT = `[proactive] \u6709 action \u5230\u671F\u4E86\u3002\u5904\u7406\u89C4\u5219\uFF1A
24867
-
24868
- 1. **\u5FC5\u987B\u8C03\u5DE5\u5177\u843D\u72B6\u6001**\uFF08\u786C\u8981\u6C42\uFF0C\u4E0D\u662F\u5EFA\u8BAE\uFF09\uFF1A
24869
- - \u5904\u7406\u5B8C \u2192 \`proactive_done\`\uFF08action_id\uFF0C\u843D\u8FDB\u65E5\u5386\u65F6\u5E26 calendar_id\uFF09
24870
- - \u8DF3\u8FC7 \u2192 \`proactive_cancel\`\uFF08action_id + reason\uFF09
24871
- \u26A0\uFE0F **\u5728\u56DE\u590D\u6B63\u6587\u91CC\u5199 \`act-xxx: cancelled\` \u4E0D\u7B97\u6807\u8BB0** \u2014\u2014 \u90A3\u662F\u7559\u75D5\uFF0C\u4E0D\u843D\u5E93\u3002
24872
- \u7CFB\u7EDF\u6709\u4E00\u9053\u515C\u5E95\u89E3\u6790\u4F1A\u635E\u6B63\u6587\uFF0C\u4F46\u5DE5\u5177\u8DEF\u5F84\u624D\u662F\u6B63\u8DEF\uFF08\u7406\u7531\u66F4\u6743\u5A01\u3001\u80FD\u56DE\u586B calendar\uFF09\u3002
24873
- 2. **\u6279\u91CF\u5904\u7406**\uFF1A\u5148\u5168\u90E8\u5224\u65AD\u5B8C\uFF0C\u518D\u7EDF\u4E00\u8C03\u5DE5\u5177\uFF08\u4E0D\u8981\u6BCF\u6761\u8C03\u4E00\u6B21\uFF09
24874
- 3. **status \u53EA\u6709**\uFF1Acompleted\uFF08\u5DF2\u5904\u7406\uFF0C\u542B\u5DF2\u544A\u8BC9 TA\uFF09/ cancelled\uFF08\u8DF3\u8FC7\uFF1A\u6280\u672F\u7C7B/\u5DF2\u8FC7\u65F6/\u91CD\u590D\uFF09/ failed\uFF08\u6267\u884C\u5931\u8D25\uFF09
24875
- \u26A0\uFE0F \u6CA1\u6709 notified\u3001\u6CA1\u6709 skipped
24876
- 4. **\u91CD\u590D\u68C0\u6D4B**\uFF1A\u591A\u6761 title \u9AD8\u5EA6\u76F8\u4F3C\u65F6\u53EA\u5904\u7406\u4E00\u6761\uFF0C\u5176\u4F59 cancelled
24877
- 5. **\u5148\u6838\u5BF9\u518D\u5224**\uFF1A\u6B63\u6587\u91CC\u7684"\u73B0\u5728/\u4ECA\u5929"\u662F**\u751F\u6210\u65F6\u523B**\u7684\uFF0C\u4E0D\u662F\u6B64\u523B\u2014\u2014
24878
- \u62FF \`generated_at_local\` \u8DDF \`_received_at\` \u5BF9\u4E00\u4E0B\uFF1B\u518D\u8DDF calendar/goal \u91CC\u5DF2\u6709\u7684\u5BF9\u4E00\u904D\u3002
24879
- 6. **urgency \u662F\u53C2\u8003**\uFF08urgent=\u51E0\u5C0F\u65F6/high=24h/medium=48h/low=\u4E00\u5468\uFF09\uFF0C\u6309\u5B9E\u9645\u60C5\u51B5\u5224\u65AD
24880
- 7. \u51B3\u5B9A\u544A\u8BC9 TA \u65F6\u7528\u4F60\u81EA\u5DF1\u7684\u8BED\u6C14\u2014\u2014\u8FD9\u662F\u4F60\u7684\u4E3B\u52A8\u5173\u6000\uFF0C\u4E0D\u662F\u7CFB\u7EDF\u901A\u77E5`;
24881
- TRANSIENT_GUARD_REASONS = /* @__PURE__ */ new Set(["MEMORY_GUARD_UNAVAILABLE", "ACTION_DELIVERY_UNKNOWN", "CALENDAR_DELIVERY_UNKNOWN", "MEMORY_SCHEMA_UNSUPPORTED", "EXECUTION_CONTEXT_INVALID"]);
24882
- DUE_PAGE_SIZE = 20;
24883
- DUE_MAX_PAGES = 5;
24884
- transientGuardLogged = /* @__PURE__ */ new Set();
24885
- Sweep = class {
24886
- constructor(deps, intervalMs = 3e5) {
24887
- this.deps = deps;
24888
- this.intervalMs = intervalMs;
24889
- }
24890
- timer = null;
24891
- /** executing 连续增长的轮数(对账告警用) */
24892
- backlogStreak = 0;
24893
- lastExecuting = 0;
24894
- start() {
24895
- if (this.timer) return;
24896
- this.runOnce(/* @__PURE__ */ new Date());
24897
- this.timer = setInterval(() => {
24898
- try {
24899
- this.runOnce(/* @__PURE__ */ new Date());
24900
- } catch (err) {
24901
- console.warn(`[proactive] sweep error: ${err.message}`);
24902
- }
24903
- }, this.intervalMs);
24904
- this.timer.unref?.();
24905
- }
24906
- stop() {
24907
- if (this.timer) {
24908
- clearInterval(this.timer);
24909
- this.timer = null;
24910
- }
24911
- }
24912
- isRunning() {
24913
- return this.timer !== null;
24914
- }
24915
- /** 单轮:收割超时 executing → due → 标记 → 合并注入一次。返回注入条数 */
24916
- runOnce(now2) {
24917
- const closed = this.deps.persist.settleBlockedHostActions(now2.toISOString());
24918
- if (closed) console.log(`[proactive] closed ${closed} blocked action(s) before dispatch`);
24919
- if (this.deps.durableSubmit) for (const item of this.deps.persist.hostDeliveries.pending()) {
24920
- try {
24921
- this.deps.durableSubmit(item.blocks, item.context, item.key);
24922
- } catch (error) {
24923
- console.warn(`[proactive] host delivery remains pending: ${error.message}`);
24924
- }
24925
- }
24926
- const reaped = this.deps.persist.reapStaleExecuting(now2.toISOString(), this.deps.staleHours ?? 36);
24927
- if (reaped > 0) console.log(`[proactive] reaped ${reaped} stale executing action(s)`);
24928
- const execNow = this.deps.persist.countByStatus("executing");
24929
- if (execNow > 0 && execNow >= this.lastExecuting) this.backlogStreak++;
24930
- else this.backlogStreak = 0;
24931
- this.lastExecuting = execNow;
24932
- if (this.backlogStreak >= BACKLOG_ALERT_RUNS) {
24933
- this.backlogStreak = 0;
24934
- try {
24935
- this.deps.onUnclosedBacklog?.(execNow);
24936
- } catch (err) {
24937
- console.warn(`[proactive] backlog alert failed: ${err.message}`);
24938
- }
24939
- }
24940
- const nowIso2 = now2.toISOString();
24941
- const gatedItems = [];
24942
- const gateOff = (a, reason) => {
24943
- gatedItems.push({ id: a.id, title: a.title, reason, version: a.actionVersion });
24944
- return false;
24945
- };
24946
- const seen = /* @__PURE__ */ new Set();
24947
- let due = [];
24948
- for (let page = 0; page < DUE_MAX_PAGES; page++) {
24949
- const batch = this.deps.persist.dueActions(nowIso2, DUE_PAGE_SIZE, [...seen]);
24950
- for (const action of batch) {
24951
- seen.add(action.id);
24952
- if (!this.deps.checkAction) {
24953
- due.push(action);
24954
- continue;
24955
- }
24956
- const verdict = guardVerdict(this.deps.checkAction(action));
24957
- if (verdict.ok) {
24958
- due.push(action);
24959
- continue;
24960
- }
24961
- if (TRANSIENT_GUARD_REASONS.has(verdict.reason)) {
24962
- const signature2 = `${action.id}:${verdict.reason}`;
24963
- if (!transientGuardLogged.has(signature2)) {
24964
- transientGuardLogged.add(signature2);
24965
- console.log(`[proactive] \u6295\u9012\u524D\u5B88\u536B\u6682\u6001\u62D2\u7EDD\uFF0C\u672C\u8F6E\u8DF3\u8FC7\uFF1A\u300C${action.title.slice(0, 24)}\u300D${verdict.reason}`);
24966
- }
24967
- continue;
24968
- }
24969
- gateOff(action, `\u6295\u9012\u524D\u5B88\u536B\uFF1A${verdict.reason}`);
24970
- }
24971
- if (batch.length < DUE_PAGE_SIZE || due.length >= DUE_PAGE_SIZE) break;
24972
- }
24973
- if (due.length === 0 && gatedItems.length === 0) return 0;
24974
- const opportunityGroups = [];
24975
- for (const action of due.filter((item) => item.scopeId && item.provenance?.decisionType === "opportunity")) {
24976
- const matches2 = opportunityGroups.filter((group) => group.some((item) => item.scopeId === action.scopeId && isSameCommitment(item.title, action.title)));
24977
- const joined = [action, ...matches2.flat()];
24978
- opportunityGroups.splice(0, opportunityGroups.length, ...opportunityGroups.filter((group) => !matches2.includes(group)), joined);
24979
- }
24980
- const duplicates = new Set(opportunityGroups.flatMap((group) => group.sort((a, b) => b.createdAt.localeCompare(a.createdAt) || b.id.localeCompare(a.id)).slice(1).map((action) => action.id)));
24981
- due = due.filter((action) => {
24982
- if (!duplicates.has(action.id)) return true;
24983
- this.deps.persist.updateActionStatus(action.id, "cancelled", {
24984
- completedAt: now2.toISOString(),
24985
- cancelReason: "duplicate_opportunity",
24986
- expectedActionVersion: action.actionVersion
24987
- });
24988
- return false;
24989
- });
24990
- const resolvedActions = [];
24991
- due = due.filter((a) => {
24992
- const intentStatus = this.deps.persist.getIntentStatus(a.intentId);
24993
- if (intentStatus === "resolved" || intentStatus === "rejected" || intentStatus === "deferred" || intentStatus === "expired") {
24994
- resolvedActions.push({ id: a.id, intentStatus, version: a.actionVersion });
24995
- return false;
24996
- }
24997
- return true;
24998
- });
24999
- if (resolvedActions.length > 0) {
25000
- for (const { id, intentStatus, version } of resolvedActions) {
25001
- this.deps.persist.updateActionStatus(id, "cancelled", {
25002
- completedAt: now2.toISOString(),
25003
- cancelReason: `intent ${intentStatus}\u2014\u2014R2 sweep \u518D\u9A8C\u8BC1`,
25004
- expectedActionVersion: version
25005
- });
25006
- }
25007
- console.log(`[proactive] R2: ${resolvedActions.length} due action(s) cancelled (intent resolved)`);
25008
- }
25009
- const coveredTitles = this.deps.coveredTitles ?? [];
25010
- const coveredEvents = this.deps.coveredEvents ?? [];
25011
- if (coveredTitles.length > 0 || coveredEvents.length > 0) {
25012
- due = due.filter((a) => {
25013
- if (coveredTitles.some((c) => isSameCommitment(a.title, c))) {
25014
- return gateOff(a, "calendar/goal \u91CC\u5DF2\u7ECF\u6709\u540C\u4E00\u4EF6\u4E8B\u2014\u2014\u4E0D\u91CD\u590D\u63D0\u9192");
25015
- }
25016
- const parts = toCalendarWallParts(a.scheduledTime);
25017
- const sameMoment = coveredEvents.some((ev) => ev.date === parts.dateStr && ev.time === parts.timeExact);
25018
- if (sameMoment && coveredEvents.some((ev) => ev.date === parts.dateStr && ev.time === parts.timeExact && sharesTerm(a.title, ev.title))) {
25019
- return gateOff(a, "\u540C\u4E00\u65F6\u523B calendar \u91CC\u5DF2\u6709\u540C\u4E00\u4EF6\u4E8B\uFF08\u65F6\u95F4\u951A\u70B9\u5224\u91CD\uFF09\u2014\u2014\u4E0D\u91CD\u590D\u63D0\u9192");
25020
- }
25021
- return true;
25022
- });
25023
- }
25024
- const minLeadDays = this.deps.minLeadDays ?? 0;
25025
- if (minLeadDays > 0) {
25026
- const repeatGapDays = this.deps.repeatGapDays ?? 0;
25027
- let injectedHistory = null;
25028
- const loadHistory = () => {
25029
- if (injectedHistory === null) injectedHistory = this.deps.persist.listInjectedTitlesSince(now2.getTime() - 30 * 864e5);
25030
- return injectedHistory;
25031
- };
25032
- due = due.filter((a) => {
25033
- if (a.provenance?.decisionType === "opportunity") return true;
25034
- const leadMs = Date.parse(a.scheduledTime) - Date.parse(a.createdAt);
25035
- if (leadMs >= minLeadDays * 864e5) return true;
25036
- if (repeatGapDays > 0) {
25037
- const lastSame = loadHistory().filter((h) => sharesTerm(a.title, h.title)).reduce((mx, h) => Math.max(mx, h.injectedAt), 0);
25038
- if (lastSame > 0 && now2.getTime() - lastSame >= repeatGapDays * 864e5) {
25039
- console.log(`[proactive] \u95F8\u4E8C\u65C1\u8DEF\u653E\u884C\uFF1A\u300C${a.title.slice(0, 24)}\u300D\u8DDD\u540C\u4E3B\u9898\u4E0A\u6B21\u9001\u8FBE ${Math.round((now2.getTime() - lastSame) / 864e5)} \u5929 \u2265 ${repeatGapDays} \u5929\uFF08\u5FAA\u73AF\u578B\u5173\u6000\uFF0C\u95F4\u9694\u5373\u8282\u6D41\uFF09`);
25040
- return true;
25041
- }
25042
- }
25043
- return gateOff(a, `\u63D0\u524D\u91CF\u4E0D\u8DB3 ${minLeadDays} \u5929\uFF08\u751F\u6210\u65F6\u79BB\u4E8B\u53D1\u592A\u8FD1\uFF09\u2014\u2014proactive \u53EA\u505A\u5468\u7EA7\u63D0\u524D\u91CF`);
25044
- });
25045
- }
25046
- for (const g of gatedItems) {
25047
- this.deps.persist.updateActionStatus(g.id, "cancelled", {
25048
- completedAt: now2.toISOString(),
25049
- cancelReason: g.reason,
25050
- expectedActionVersion: g.version
25051
- });
25052
- }
25053
- if (gatedItems.length > 0) {
25054
- console.log(`[proactive] gated ${gatedItems.length} action(s): ${gatedItems.map((g) => g.reason.slice(0, 12)).join(" / ")}`);
25055
- try {
25056
- this.deps.onGated?.(gatedItems);
25057
- } catch (err) {
25058
- console.warn(`[proactive] onGated failed: ${err.message}`);
25059
- }
25060
- }
25061
- if (due.length === 0) return 0;
25062
- due = due.flatMap((act) => this.deps.persist.transaction(() => {
25063
- if (!this.deps.persist.markActionReminded(act.id, now2.toISOString(), act.actionVersion)) return [];
25064
- const captured = this.deps.persist.getAction(act.id);
25065
- if (captured.scopeId && this.deps.durableSubmit) {
25066
- const context = this.executionContext([captured]);
25067
- this.deps.persist.hostDeliveries.enqueue(captured.id, captured.actionVersion, this.blocks([captured], now2), context);
25068
- }
25069
- return [captured];
25070
- }));
25071
- if (due.length === 0) return 0;
25072
- const groups = /* @__PURE__ */ new Map();
25073
- for (const action of due) {
25074
- const key5 = action.scopeId ? `${action.scopeId}:${action.id}` : "";
25075
- groups.set(key5, [...groups.get(key5) ?? [], action]);
25076
- }
25077
- let injected = 0;
25078
- for (const captured of groups.values()) {
25079
- const blocks = this.blocks(captured, now2);
25080
- const context = this.executionContext(captured);
25081
- let delivered = false;
25082
- const durable = Boolean(context && this.deps.durableSubmit);
25083
- try {
25084
- delivered = durable ? this.deps.durableSubmit(blocks, context, JSON.stringify(["proactive", captured[0].id, captured[0].actionVersion])) : this.deps.submit(blocks, context);
25085
- } catch (error) {
25086
- console.warn(`[proactive] injection failed: ${error.message}`);
25087
- }
25088
- if (delivered) injected += captured.length;
25089
- else if (!durable) {
25090
- const back = this.deps.persist.rollbackReminded(captured.map((a) => a.id));
25091
- console.warn(`[proactive] injection dropped \u2014 rolled back ${back} action(s) to queued`);
25092
- }
25093
- }
25094
- if (injected) console.log(`[proactive] injected ${injected} due action(s) to main session`);
25095
- return injected;
25096
- }
25097
- executionContext(actions) {
25098
- const scopeId2 = actions[0]?.scopeId;
25099
- return scopeId2 ? {
25100
- scopeId: scopeId2,
25101
- basisRefs: actions.flatMap((action) => action.basisRefs ?? []),
25102
- actionVersions: Object.fromEntries(actions.map((action) => [action.id, action.actionVersion]))
25103
- } : void 0;
25104
- }
25105
- blocks(actions, now2) {
25106
- const payload = actions.map((action) => actionPayload(action, now2, this.deps.persist.getIntentRecentEvents(action.intentId)));
25107
- return [
25108
- { type: "text", text: `## Actions (${payload.length} \u4E2A)
25109
-
25110
- \`\`\`json
25111
- ${JSON.stringify(payload)}
25112
- \`\`\`` },
25113
- { type: "text", text: this.loadPrompt() }
25114
- ];
25115
- }
25116
- /** 处理规则现读(改了不用重启);文件缺失/读失败用内置 */
25117
- loadPrompt() {
25118
- const file2 = this.deps.promptFile;
25119
- if (!file2) return DEFAULT_PROMPT;
25120
- try {
25121
- const text2 = readFileSync24(file2, "utf8").trim();
25122
- return text2 || DEFAULT_PROMPT;
25123
- } catch {
25124
- return DEFAULT_PROMPT;
25125
- }
25126
- }
24898
+ dayKey = (iso) => {
24899
+ const ms = Date.parse(iso);
24900
+ return Number.isFinite(ms) ? new Date(ms).toISOString().slice(5, 10) : "";
25127
24901
  };
24902
+ WORK_EVENT = /commit|分支|索引|召回|扫描|部署|发布|代码|修复|排查|日志|安装|重建|升级|配置|测试|方案|任务|清单|排障|接口|数据库|埋点|验收|review|merge|push|build|token|模型|提示词|prompt/i;
24903
+ NON_EVENT_CALENDAR_TYPES = /* @__PURE__ */ new Set(["task", "todo"]);
24904
+ STATE_PATTERN = /累|病|睡|吃|熬夜|不舒服|发烧|忙|加班|压力大|疲惫|失眠|胃|感冒|头疼|医院|药/;
24905
+ STATE_KINDS = /* @__PURE__ */ new Set(["feeling", "health", "physical_state", "mood", "condition"]);
25128
24906
  }
25129
24907
  });
25130
24908
 
25131
24909
  // src/memory/proactive/opportunity.ts
25132
24910
  import { setImmediate as yieldToEventLoop2 } from "node:timers/promises";
25133
- import { readdirSync as readdirSync6, readFileSync as readFileSync25, existsSync as existsSync11, realpathSync as realpathSync5 } from "node:fs";
24911
+ import { readdirSync as readdirSync6, readFileSync as readFileSync24, existsSync as existsSync11, realpathSync as realpathSync5 } from "node:fs";
25134
24912
  import { join as join29, relative as relative5 } from "node:path";
25135
24913
  import { DatabaseSync as DatabaseSync12 } from "node:sqlite";
25136
24914
  import { createHash as createHash32 } from "node:crypto";
@@ -25320,7 +25098,7 @@ function parseForesightEntries(everosRoot, now2, userId) {
25320
25098
  let content;
25321
25099
  let bytes2;
25322
25100
  try {
25323
- bytes2 = readFileSync25(file2);
25101
+ bytes2 = readFileSync24(file2);
25324
25102
  content = bytes2.toString("utf8");
25325
25103
  } catch {
25326
25104
  continue;
@@ -25328,7 +25106,7 @@ function parseForesightEntries(everosRoot, now2, userId) {
25328
25106
  const fileDigest = createHash32("sha256").update(bytes2).digest("hex");
25329
25107
  const assertCurrent = () => {
25330
25108
  try {
25331
- if (relative5(file2, realpathSync5(file2)) || createHash32("sha256").update(readFileSync25(file2)).digest("hex") !== fileDigest) throw new MemoryReadSupersededError();
25109
+ if (relative5(file2, realpathSync5(file2)) || createHash32("sha256").update(readFileSync24(file2)).digest("hex") !== fileDigest) throw new MemoryReadSupersededError();
25332
25110
  } catch {
25333
25111
  throw new MemoryReadSupersededError();
25334
25112
  }
@@ -25444,6 +25222,29 @@ async function runOpportunityScan(deps) {
25444
25222
  if (originals.length) actionEvidence.set(node.id, originals.join("\n"));
25445
25223
  }
25446
25224
  const context = buildMemoryContext(memory, scope, { query: "current facts and future changes", view: "current", validAt: now2.toISOString(), includeProjectionStatus: false });
25225
+ const mentionSince = new Date(now2.getTime() - 30 * 864e5).toISOString();
25226
+ const mentionEvents = graph.getNodesByType("event").filter((node) => actionEvidence.has(node.id) && node.createdAt >= mentionSince).map((node) => ({ id: node.id, title: String(node.data.title ?? ""), createdAt: node.createdAt, evidence: actionEvidence.get(node.id) }));
25227
+ const stateSignals = stateSignalLines(context.currentFacts);
25228
+ const prepItems = [];
25229
+ const upcoming = (deps.calendarCoverage ?? []).filter((item) => {
25230
+ const ms = parseCalendarDateMs(item.date, now2);
25231
+ return ms !== null && ms >= now2.getTime() - 864e5 && ms <= now2.getTime() + 3 * 864e5 && String(item.type ?? "") !== "task";
25232
+ }).slice(0, 10);
25233
+ for (const item of upcoming) {
25234
+ const people = memory.entities.matchQuery(scope, item.title).filter((entity) => ["person", "organization"].includes(entity.kind)).slice(0, 2).map((entity) => {
25235
+ const facts = buildMemoryContext(memory, scope, {
25236
+ query: item.title,
25237
+ entityRef: entity.entityId,
25238
+ view: "current",
25239
+ validAt: now2.toISOString(),
25240
+ includeProjectionStatus: false,
25241
+ maxTokens: 400
25242
+ }).currentFacts.filter((fact) => fact.claimKind === "user_statement").map((fact) => String(fact.value?.body ?? fact.value?.label ?? "")).filter(Boolean).slice(0, 4);
25243
+ return { name: entity.canonicalName, facts };
25244
+ }).filter((person) => person.facts.length);
25245
+ if (people.length) prepItems.push({ calendarId: item.id, date: item.date, time: item.time, title: item.title, people });
25246
+ if (prepItems.length >= 3) break;
25247
+ }
25447
25248
  const basis = { scope, dependencies: [] };
25448
25249
  includeContextBasis(memory, basis, context);
25449
25250
  for (const entry of entries) {
@@ -25462,6 +25263,9 @@ async function runOpportunityScan(deps) {
25462
25263
  actionEvidence,
25463
25264
  foresightEventIds,
25464
25265
  lines: entries.map((entry) => `[hypothesis ${entry.entryId}; window ${entry.start}~${entry.end}] ${entry.text}`),
25266
+ mentionEvents,
25267
+ stateSignals,
25268
+ prepLines: prepLines(prepItems),
25465
25269
  // Keep the model graph filtered; assertions and commit compare full incident edges for these readable nodes.
25466
25270
  // One query for all of them: per node it was two round trips, about 13,000 on a real graph.
25467
25271
  graphBasis: captureGraphBasis(
@@ -25487,12 +25291,15 @@ async function runOpportunityScan(deps) {
25487
25291
  return status !== "resolved" && status !== "rejected" && status !== "expired";
25488
25292
  }).slice(-20).map((n) => `- [${n.id}] ${String(n.data.title ?? "")}${captured ? `
25489
25293
  ${captured.actionEvidence.get(n.id) ?? "\u4EC5\u80CC\u666F\uFF0C\u4E0D\u80FD\u5355\u72EC\u4F5C\u4E3A\u884C\u52A8\u4F9D\u636E"}` : ""}`);
25490
- const recentEvents = store.getNodesByType("event").sort((a, b) => Number(captured?.foresightEventIds.has(b.id) ?? false) - Number(captured?.foresightEventIds.has(a.id) ?? false) || Number(captured?.actionEvidence.has(b.id) ?? false) - Number(captured?.actionEvidence.has(a.id) ?? false) || b.createdAt.localeCompare(a.createdAt)).slice(0, 15).map((n) => `- [${n.id}] ${String(n.data.title ?? "")}
25294
+ const recentEventNodes = store.getNodesByType("event").sort((a, b) => Number(captured?.foresightEventIds.has(b.id) ?? false) - Number(captured?.foresightEventIds.has(a.id) ?? false) || Number(captured?.actionEvidence.has(b.id) ?? false) - Number(captured?.actionEvidence.has(a.id) ?? false) || b.createdAt.localeCompare(a.createdAt)).slice(0, 15);
25295
+ const recentEvents = recentEventNodes.map((n) => `- [${n.id}] ${String(n.data.title ?? "")}
25491
25296
  ${captured ? captured.actionEvidence.get(n.id) ?? `\u4EC5\u80CC\u666F\uFF0C\u4E0D\u80FD\u5355\u72EC\u4F5C\u4E3A\u884C\u52A8\u4F9D\u636E\uFF1A${String(n.data.description ?? "").slice(0, 800)}` : String(n.data.description ?? "").slice(0, 800)}`);
25297
+ const mentionLines = userMentionLines(captured?.mentionEvents ?? [], { excludeIds: new Set(recentEventNodes.map((node) => node.id)), since: outcomeSince });
25492
25298
  const calendarLines = (deps.calendarCoverage ?? []).filter((c) => {
25493
25299
  const ms = parseCalendarDateMs(c.date, now2);
25494
25300
  return ms !== null && ms >= now2.getTime() - 864e5 && ms <= now2.getTime() + 31 * 864e5;
25495
25301
  }).sort((a, b) => (parseCalendarDateMs(a.date, now2) ?? 0) - (parseCalendarDateMs(b.date, now2) ?? 0)).slice(0, 30).map((c) => `- [calendar #${c.id}] ${c.date} ${c.time} ${c.title}`);
25302
+ const denseLines = captured ? densePeriodLines(deps.calendarCoverage ?? [], now2, parseCalendarDateMs) : null;
25496
25303
  const userPrompt = [
25497
25304
  // 这一行必须与上面的 calendar 行同坐标:calendar 的 date/time 是**配置时区**墙上时间,
25498
25305
  // 而这里此前给的是 UTC Z —— 同一个 prompt 两套坐标、且都没标注,模型无从判断"现在"。
@@ -25524,17 +25331,28 @@ ${captured ? captured.actionEvidence.get(n.id) ?? `\u4EC5\u80CC\u666F\uFF0C\u4E0
25524
25331
  "## \u8FD1\u671F\u4E8B\u4EF6\uFF08\u4F18\u5148\u63D0\u4F9B\u7528\u6237/\u5DE5\u5177\u4F9D\u636E\uFF0C\u6700\u591A 15 \u6761\uFF09",
25525
25332
  recentEvents.length > 0 ? recentEvents.join("\n") : "\uFF08\u65E0\uFF09",
25526
25333
  "",
25527
- '\u5224\u65AD\uFF1A\u4ECE\u65F6\u95F4\u89D2\u5EA6\uFF08\u4E0D\u662F\u65B0\u6D88\u606F\u89D2\u5EA6\uFF09\uFF0C\u73B0\u5728\u6709\u6CA1\u6709"\u6B63\u662F\u65F6\u673A"\u53EF\u4EE5\u4E3B\u52A8\u505A\u7684\u4E8B\uFF1F',
25528
- "\u7EBF\u7D22\u7EC4\u5408\u7740\u770B\uFF1A\u67D0\u4E2A\u9884\u6D4B\u7684\u7A97\u53E3\u6B63\u5728\u5F00\u542F\u6216\u4E34\u8FD1\u622A\u6B62\u2192\u73B0\u5728\u6B63\u662F\u63D0\u9192/\u51C6\u5907\u7684\u65F6\u5019\uFF1B",
25529
- "\u660E\u5929\u6709\u5B89\u6392\u2192\u4ECA\u665A\u63D0\u9192\u51C6\u5907\uFF1B\u67D0\u4E2A\u6302\u4E86\u5F88\u4E45\u7684 intent \u4E00\u76F4\u6CA1\u52A8\u9759\u2192\u81EA\u7136\u5730\u8DDF\u8FDB\u4E00\u53E5\uFF1B",
25530
- "\u7EA6\u5B9A\u5FEB\u5230\u671F\u2192\u63D0\u524D\u6253\u94A9\uFF1B\u5F88\u4E45\u6CA1\u8054\u7CFB/\u6CA1\u804A\u8FC7\u67D0\u4EF6 TA \u5728\u610F\u7684\u4E8B\u2192\u627E\u4E2A\u7531\u5934\u81EA\u7136\u63D0\u8D77\u3002",
25531
- "\u53EA\u5728\u65F6\u673A\u771F\u5BF9\u65F6\u8F93\u51FA\uFF1B\u6CA1\u6709\u5C31\u8F93\u51FA\u7A7A\u6570\u7EC4\u3002",
25532
- "\u5148\u68C0\u67E5\u540E\u7EED\u7ED3\u679C\uFF1A\u5DF2\u5B8C\u6210\u3001\u5DF2\u53D6\u6D88\u6216\u5DF2\u6709\u540C\u4E00\u4E8B\u9879\u7684 action \u5C31\u4E0D\u518D\u63D0\u9192\u3002\u4E0D\u8981\u628A\u65E9\u5148\u8BF7\u6C42\u518D\u6B21\u5F53\u6210\u5F85\u529E\uFF1B\u6539\u5199\u6807\u9898\u4E5F\u7B97\u91CD\u590D\u3002",
25334
+ // 1201 翀哥口径①:人向线索四段(用户提过的事 / 刚过去的密集时段 / 状态线索 / 前置备料)。
25335
+ "## \u4ED6\u63D0\u8FC7\u7684\u4E8B\uFF08\u8FD1 30 \u5929\u6709\u4ED6\u539F\u8BDD\u7684\u4E8B\u4EF6\uFF0C\u6309\u5929\u5012\u5E8F\uFF0CID \u53EF\u4F5C evidenceIds\uFF1B\u627E\u63D0\u8FC7\u4E0D\u6B62\u4E00\u6B21\u3001\u8FD8\u6CA1\u89C1\u505A\u6210\u7684\uFF09",
25336
+ mentionLines.length > 0 ? mentionLines.join("\n") : "\uFF08\u65E0\uFF09",
25337
+ ...denseLines ? ["", "## \u521A\u8FC7\u53BB\u7684\u51E0\u5929\uFF08\u5B89\u6392\u56DE\u770B\uFF0C\u521A\u7ECF\u5386\u4E00\u6BB5\u5BC6\u96C6\u65F6\u6BB5\u7684\u8BDD\uFF0C\u56DE\u6765\u7ED9\u4E2A\u5C0F\u7ED3\u662F\u4ED6\u4E0D\u7528\u81EA\u5DF1\u56DE\u60F3\u7684\uFF09", denseLines.join("\n")] : [],
25338
+ ...captured && captured.stateSignals.length ? ["", "## \u4ED6\u7684\u72B6\u6001\u7EBF\u7D22\uFF08\u4ED6\u81EA\u5DF1\u8BF4\u7684\u611F\u53D7/\u8EAB\u4F53/\u4F5C\u606F\uFF0C\u53EA\u4F5C\u80CC\u666F\uFF0C\u4E0D\u662F\u5F85\u529E\uFF09", captured.stateSignals.map((line) => `- ${line}`).join("\n")] : [],
25339
+ ...captured && captured.prepLines.length ? ["", "## \u8FD1 3 \u5929\u8981\u89C1\u7684\u4EBA/\u8981\u529E\u7684\u4E8B\uFF1A\u76F8\u5173\u8BB0\u5FC6\uFF08\u89C1\u4EBA\u524D\u5907\u6599\u7528\uFF09", captured.prepLines.join("\n")] : [],
25340
+ "",
25341
+ "\u5224\u65AD\uFF1A\u6709\u6CA1\u6709\u4E00\u4EF6\u4ED6\u6CA1\u60F3\u5230\u8981\u3001\u4F46\u505A\u4E86\u4ED6\u4F1A\u89C9\u5F97\u300C\u60F3\u5230\u6211\u5FC3\u574E\u4E0A\u4E86\u300D\u6216\u300C\u5E2E\u6211\u7701\u4E86\u4E8B\u300D\u7684\u4E8B\uFF1F",
25342
+ "\u4ECE\u4ED6\u63D0\u8FC7\u7684\u4E8B\u91CC\u627E\u53CD\u590D\u63D0\u8FC7\u6CA1\u505A\u7684\uFF1B\u4ECE\u521A\u8FC7\u53BB\u7684\u51E0\u5929\u627E\u8BE5\u6536\u6210\u5C0F\u7ED3\u7684\uFF1B\u4ECE\u8FD1 3 \u5929\u8981\u89C1\u7684\u4EBA\u627E\u8BE5\u63D0\u524D\u5907\u6599\u7684\uFF1B",
25343
+ "\u518D\u53E0\u4E0A\u65F6\u95F4\u7EBF\u7D22\uFF1A\u9884\u6D4B\u7A97\u53E3\u6B63\u5728\u5F00\u542F\u6216\u4E34\u8FD1\u622A\u6B62\u2192\u73B0\u5728\u6B63\u662F\u51C6\u5907\u7684\u65F6\u5019\uFF1B\u7EA6\u5B9A\u5FEB\u5230\u671F\u2192\u63D0\u524D\u6253\u94A9\uFF1B\u5F88\u4E45\u6CA1\u8054\u7CFB\u2192\u627E\u4E2A\u7531\u5934\u81EA\u7136\u63D0\u8D77\u3002",
25344
+ "\u6CDB\u6CDB\u7684\u95EE\u5019\uFF08\u300C\u4ECA\u5929\u7D2F\u4E0D\u7D2F\u300D\uFF09\u6CA1\u6709\u5177\u4F53\u4E8B\u5B9E\u652F\u6491\uFF0C\u4E0D\u5408\u683C\uFF1B\u6CDB\u6CDB\u7684\u63D0\u9192\u540C\u7406\u3002",
25345
+ "\u53EA\u5728\u8BF4\u5F97\u51FA\u300C\u4E3A\u4EC0\u4E48\u662F\u73B0\u5728\u3001\u4E3A\u4EC0\u4E48\u4ED6\u9700\u8981\u300D\u65F6\u8F93\u51FA\uFF1B\u6CA1\u6709\u5C31\u8F93\u51FA\u7A7A\u6570\u7EC4\u3002",
25346
+ "\u5148\u68C0\u67E5\u540E\u7EED\u7ED3\u679C\uFF1A\u5DF2\u5B8C\u6210\u3001\u5DF2\u53D6\u6D88\uFF08\u542B\u4ED6\u5426\u51B3\u8FC7\u7684\uFF09\u6216\u5DF2\u6709\u540C\u4E00\u4E8B\u9879\u7684 action/intent \u5C31\u4E0D\u518D\u63D0\u3002\u4E0D\u8981\u628A\u65E9\u5148\u8BF7\u6C42\u518D\u6B21\u5F53\u6210\u5F85\u529E\uFF1B\u6539\u5199\u6807\u9898\u4E5F\u7B97\u91CD\u590D\u3002",
25533
25347
  "",
25534
25348
  "\u8FD9\u662F\u6709\u9650\u7684\u8FD1\u671F\u8BB0\u5FC6\u7A97\u53E3\uFF0C\u4E0D\u4EE3\u8868\u5B8C\u6574\u5386\u53F2\u3002\u5EFA\u8BAE\u662F\u63A8\u65AD\uFF0C\u4E0D\u5F97\u5199\u6210\u5DF2\u7ECF\u786E\u8BA4\u7684\u4E8B\u5B9E\u6216\u627F\u8BFA\u3002",
25535
25349
  "\u6BCF\u6761\u5EFA\u8BAE\u5FC5\u987B\u7528 evidenceIds \u5F15\u7528\u4E0A\u9762\u5B9E\u9645\u7ED9\u51FA\u7684\u4E8B\u4EF6\u6216 intent ID\uFF1B\u65E0\u6CD5\u5F15\u7528\u5C31\u4E0D\u8981\u8F93\u51FA\u3002",
25536
- ...captured ? ["evidenceIds \u81F3\u5C11\u5F15\u7528\u4E00\u6761\u6807\u6709 user/tool \u539F\u6587\u7684\u4F9D\u636E\u3002\u52A9\u624B\u5EFA\u8BAE\u3001\u53CD\u601D\u548C\u9884\u6D4B\u53EA\u4F5C\u80CC\u666F\uFF0C\u4E0D\u80FD\u5F53\u6210\u7528\u6237\u7684\u610F\u613F\u3002"] : [],
25537
- '\u53EA\u56DE\u590D JSON\uFF1A{"opportunities": [{"title": "\u77ED\u6807\u9898", "description": "\u4E3A\u4EC0\u4E48\u73B0\u5728\u6B63\u662F\u65F6\u673A+\u5EFA\u8BAE\u505A\u4EC0\u4E48", "evidenceIds": ["\u5B9E\u9645\u7684\u4E8B\u4EF6ID"]}]}'
25350
+ ...captured ? [
25351
+ "evidenceIds \u81F3\u5C11\u5F15\u7528\u4E00\u6761\u6807\u6709 user/tool \u539F\u6587\u7684\u4F9D\u636E\u3002\u52A9\u624B\u5EFA\u8BAE\u3001\u53CD\u601D\u548C\u9884\u6D4B\u53EA\u4F5C\u80CC\u666F\uFF0C\u4E0D\u80FD\u5F53\u6210\u7528\u6237\u7684\u610F\u613F\u3002",
25352
+ // 1203 云机首轮:判定器想出了「把香港这趟办成一张收口单」,却没带 evidenceIds,只能落成候选送不出去。
25353
+ "\u5C0F\u7ED3/\u5907\u6599\u7C7B\u5EFA\u8BAE\u7684 evidenceIds \u5F15\u7528\u300C\u4ED6\u63D0\u8FC7\u7684\u4E8B\u300D\u6216\u300C\u8FD1\u671F\u4E8B\u4EF6\u300D\u91CC\u8FD9\u4E00\u8D9F\uFF08\u8FD9\u4E2A\u4EBA\uFF09\u7684\u51E0\u6761\u4E8B\u4EF6 ID\uFF0C\u81F3\u5C11\u4E00\u6761\u5E26 [user \u539F\u6587]\uFF1B\u7ED9\u4E0D\u51FA\u5C31\u4E0D\u8F93\u51FA\u8FD9\u6761\u3002"
25354
+ ] : [],
25355
+ '\u53EA\u56DE\u590D JSON\uFF1A{"opportunities": [{"title": "\u77ED\u6807\u9898", "description": "\u4E3A\u4EC0\u4E48\u662F\u73B0\u5728\u3001\u4E3A\u4EC0\u4E48\u4ED6\u9700\u8981+\u5EFA\u8BAE\u505A\u4EC0\u4E48", "evidenceIds": ["\u4E8B\u4EF6ID\uFF0C\u5982\u8FD1\u671F\u4E8B\u4EF6\u91CC\u7684 [evt-\u2026]"]}]}'
25538
25356
  ].join("\n");
25539
25357
  await yieldToEventLoop2();
25540
25358
  let active = true;
@@ -25572,14 +25390,20 @@ ${captured ? captured.actionEvidence.get(n.id) ?? `\u4EC5\u80CC\u666F\uFF0C\u4E0
25572
25390
  model: deps.model,
25573
25391
  messages: [{ role: "user", content: userPrompt }],
25574
25392
  systemPrompt: [
25575
- "\u4F60\u662F\u65F6\u673A\u5224\u5B9A\u5668\u3002Agent \u7684\u8BB0\u5FC6\u56FE\u548C\u65E5\u7A0B\u6446\u5728\u4F60\u9762\u524D\uFF0C\u4F60\u53EA\u5224\u4E00\u4EF6\u4E8B\uFF1A",
25576
- "\u4ECE\u65F6\u95F4\u6D41\u901D\u7684\u89D2\u5EA6\uFF0C\u73B0\u5728\u6709\u6CA1\u6709\u503C\u5F97 agent \u4E3B\u52A8\u53BB\u505A/\u63D0\u8D77/\u51C6\u5907\u7684\u4E8B\u3002",
25393
+ "\u4F60\u662F\u4E3B\u52A8\u5EFA\u8BAE\u5224\u5B9A\u5668\u3002\u4ED6\u7684\u8BB0\u5FC6\u56FE\u3001\u65E5\u7A0B\u548C\u521A\u53D1\u751F\u7684\u4E8B\u6446\u5728\u4F60\u9762\u524D\uFF0C\u4F60\u53EA\u5224\u4E00\u4EF6\u4E8B\uFF1A",
25394
+ "\u73B0\u5728\u6709\u6CA1\u6709\u4E00\u4EF6\u4ED6\u6CA1\u60F3\u5230\u8981\u3001\u4F46\u505A\u4E86\u4ED6\u4F1A\u89C9\u5F97\u300C\u60F3\u5230\u6211\u5FC3\u574E\u4E0A\u4E86\u300D\u6216\u300C\u5E2E\u6211\u7701\u4E86\u4E8B\u300D\u7684\u4E8B\u3002",
25577
25395
  "",
25578
- '\u9884\u6D4B\uFF08foresight\uFF09\u91CC\u6709\u4E00\u7C7B\u662F"\u884C\u4E3A/\u4E60\u60EF/\u5173\u7CFB\u503E\u5411"\uFF08\u5982\u4F1A\u66F4\u4F9D\u8D56\u67D0\u4EBA\u3001\u4F1A\u4FDD\u6301\u67D0\u4E60\u60EF\u3001',
25579
- "\u4ECA\u540E\u4F1A\u4F18\u5148\u600E\u6837\uFF09\u2014\u2014\u90A3\u662F\u80CC\u666F\u753B\u50CF\u4E0D\u662F\u673A\u4F1A\uFF0C\u9664\u975E\u5B83\u9644\u5E26\u5177\u4F53\u53EF\u884C\u52A8\u7684\u4E8B\u4EF6\u7A97\u53E3\uFF0C\u4E00\u5F8B\u5FFD\u7565\u3002",
25396
+ "\u5408\u683C\u7684\u56DB\u7C7B\uFF08\u5224\u65AD\u6807\u51C6\u53EA\u6709\u8FD9\u4E00\u6761\uFF1A\u4ED6\u770B\u5230\u4F1A\u4E0D\u4F1A\u89C9\u5F97\u503C\uFF09\uFF1A",
25397
+ "- \u4ED6\u4E0D\u7528\u81EA\u5DF1\u56DE\u60F3\uFF1A\u521A\u51FA\u5DEE/\u5F00\u5B8C\u4F1A\u56DE\u6765\uFF0C\u628A\u8FD9\u4E00\u8D9F\u529E\u7684\u4E8B\u6574\u7406\u6210\u4E00\u6BB5\uFF0C\u4ED6\u76F4\u63A5\u6709\u603B\u7ED3\u3002",
25398
+ "- \u4ED6\u6CA1\u5F00\u53E3\u4F46\u4F1A\u60F3\u8981\u7684\uFF1A\u5BB6\u957F\u4F1A 24 \u5F20 PPT \u91CC\u771F\u6B63\u8981\u4ED6\u6267\u884C\u7684\u4E5F\u5C31\u4E09\u56DB\u6761\uFF0C\u63D0\u524D\u62BD\u51FA\u6765\u3002",
25399
+ "- \u63D0\u8FC7\u51E0\u6B21\u6CA1\u505A\u7684\uFF1A\u300C\u5934\u53D1\u767D\u4E86\u5F97\u67D3\u4E86\u300D\u8BF4\u8FC7\u4E0D\u6B62\u4E00\u6B21\uFF0C\u54EA\u5929\u4E0B\u5348\u4ED6\u7A7A\u7740\u63D0\u9192\u4E00\u53E5\u3002",
25400
+ "- \u8981\u89C1\u4EBA\u4E4B\u524D\uFF1A\u660E\u5929\u89C1\u56FD\u660E\uFF0C\u628A\u8DDF\u56FD\u660E\u6709\u5173\u7684\u8BB0\u5FC6\u6574\u7406\u6210\u4E00\u9875\uFF0C\u89C1\u9762\u524D\u626B\u4E00\u773C\u3002",
25580
25401
  "",
25581
- "\u62FF\u4E0D\u51C6\u5C31\u4E0D\u8F93\u51FA\uFF08\u6C89\u9ED8\u662F\u9ED8\u8BA4\uFF09\uFF1B\u53EA\u8F93\u51FA\u65F6\u673A\u660E\u663E\u3001\u505A\u4E86\u4F1A\u6BD4\u4E0D\u505A\u66F4\u81EA\u7136\u66F4\u6709\u6E29\u5EA6\u7684\u4E8B\u3002",
25582
- "\u6700\u591A 2 \u6761\uFF0C\u5B81\u7F3A\u6BCB\u6EE5\u3002"
25402
+ "\u4E0D\u5408\u683C\uFF1A\u6CA1\u6709\u5177\u4F53\u4E8B\u5B9E\u652F\u6491\u7684\u6CDB\u6CDB\u95EE\u5019\uFF08\u300C\u4ECA\u5929\u7D2F\u4E0D\u7D2F\u300D\uFF09\uFF1B\u4ED6\u5DF2\u7ECF\u505A\u4E86\u6216\u5DF2\u6709\u5B89\u6392\u7684\u4E8B\uFF1B",
25403
+ '\u52A9\u624B\u5EFA\u8BAE\u3001\u53CD\u601D\u548C\u9884\u6D4B\u4E0D\u662F\u4ED6\u7684\u610F\u613F\u3002\u9884\u6D4B\uFF08foresight\uFF09\u91CC"\u884C\u4E3A/\u4E60\u60EF/\u5173\u7CFB\u503E\u5411"\u662F\u80CC\u666F\u753B\u50CF\uFF0C',
25404
+ "\u9664\u975E\u9644\u5E26\u5177\u4F53\u53EF\u884C\u52A8\u7684\u4E8B\u4EF6\u7A97\u53E3\uFF0C\u4E00\u5F8B\u5FFD\u7565\u3002",
25405
+ "",
25406
+ "\u62FF\u4E0D\u51C6\u5C31\u4E0D\u8F93\u51FA\uFF08\u6C89\u9ED8\u662F\u9ED8\u8BA4\uFF09\u3002\u6700\u591A 2 \u6761\uFF0C\u5B81\u7F3A\u6BCB\u6EE5\u2014\u2014\u9891\u7387\u4E0D\u662F\u95EE\u9898\uFF0C\u6BCF\u6761\u503C\u624D\u91CD\u8981\u3002"
25583
25407
  ].join("\n"),
25584
25408
  temperature: 0.3,
25585
25409
  disableThinking: true,
@@ -25618,17 +25442,20 @@ ${captured ? captured.actionEvidence.get(n.id) ?? `\u4EC5\u80CC\u666F\uFF0C\u4E0
25618
25442
  const memory = deps.memory;
25619
25443
  const previousTitles = new Set(persist.opportunityTitlesSince(scopeId(memory.scope), new Date(now2.getTime() - 30 * 864e5).toISOString()));
25620
25444
  const covered = (deps.coveredTitles ?? []).join(" ");
25621
- const opportunities = rawOpportunities.slice(0, 2).map(normalizeOpportunity).filter((item) => Boolean(item)).filter((item) => ![...previousTitles].some((title) => isSameCommitment(title, item.title)) && !(covered && item.title.length >= 4 && covered.includes(item.title.slice(0, 4)))).filter((item, index, items) => items.findIndex((other) => isSameCommitment(other.title, item.title)) === index).filter((item) => !captured.graph.getNodesByType("intent").some((node) => isSameCommitment(node.data.title ?? "", item.title)));
25445
+ const opportunities = rawOpportunities.slice(0, 2).map(normalizeOpportunity).filter((item) => Boolean(item)).filter((item) => ![...previousTitles].some((title) => titlesOverlap(title, item.title)) && !(covered && item.title.length >= 4 && covered.includes(item.title.slice(0, 4)))).filter((item, index, items) => items.findIndex((other) => titlesOverlap(other.title, item.title)) === index).filter((item) => !captured.graph.getNodesByType("intent").some((node) => node.data.status !== "deferred" && titlesOverlap(node.data.title ?? "", item.title)));
25622
25446
  if (!opportunities.length) return 0;
25623
25447
  try {
25624
25448
  const result = memory.store.transaction(() => {
25625
25449
  assertBasis();
25626
25450
  memory.store.dependencies.assertReferences(memory.scope, captured.basis.dependencies);
25627
25451
  const actions = [];
25452
+ let candidates = 0;
25628
25453
  deps.store.mutate((staged) => {
25629
25454
  for (const opportunity of opportunities) {
25630
25455
  const id = `opp-candidate-${newEventId()}`;
25631
25456
  const proof = scopedOpportunityBasis(memory.store, memory.scope, captured.graph, opportunity.evidenceIds);
25457
+ if (!proof && captured.graph.getNodesByType("intent").some((node) => node.data.status === "deferred" && titlesOverlap(node.data.title ?? "", opportunity.title, 0.3))) continue;
25458
+ candidates++;
25632
25459
  const dependencies = proof ? publishedGraphDependencies([...proof.dependencies, ...captured.concrete.filter((ref) => ref.parentKind === "scope" && ref.parentId.startsWith("valid-window:"))]) : publishedGraphDependencies(captured.concrete);
25633
25460
  staged.addNode({
25634
25461
  id,
@@ -25682,7 +25509,7 @@ ${captured ? captured.actionEvidence.get(n.id) ?? `\u4EC5\u80CC\u666F\uFF0C\u4E0
25682
25509
  }, (owner) => {
25683
25510
  for (const action of actions) owner.insertAction(action);
25684
25511
  }, captured.graphBasis);
25685
- return { candidates: opportunities.length, actionsScheduled: actions.length };
25512
+ return { candidates, actionsScheduled: actions.length };
25686
25513
  });
25687
25514
  console.log(`[proactive] scoped opportunity committed candidates=${result.candidates} actionsScheduled=${result.actionsScheduled} deferred=${result.candidates - result.actionsScheduled}`);
25688
25515
  return result.candidates;
@@ -25740,7 +25567,8 @@ var init_opportunity = __esm({
25740
25567
  init_read_guard();
25741
25568
  init_scoped_opportunity();
25742
25569
  init_published_basis();
25743
- init_sweep();
25570
+ init_intent();
25571
+ init_care_leads();
25744
25572
  OPPORTUNITY_SCAN_INTERVAL_MS = 6 * 60 * 6e4;
25745
25573
  PROFILE_RE = /今后|以后|将来|往后|再次遇到|下次遇到|会一直|会习惯|会继续|会优先|会避免|会主动|会定期|会倾向于|会按|会先|时会|倾向于|更愿意|养成了?.*习惯|将养成|将优先|将避免|习惯性地|will always|will prefer|will avoid|will continue|will keep|will strictly|tends? to|is likely to (?:always|keep|continue)/i;
25746
25574
  foresightCache = /* @__PURE__ */ new Map();
@@ -29444,6 +29272,348 @@ var init_config3 = __esm({
29444
29272
  }
29445
29273
  });
29446
29274
 
29275
+ // src/memory/proactive/sweep.ts
29276
+ import { readFileSync as readFileSync26 } from "node:fs";
29277
+ function sharesTerm(a, b) {
29278
+ const x = normalizeTitle(a);
29279
+ const y = normalizeTitle(b);
29280
+ if (x.length < 2 || y.length < 2) return false;
29281
+ const grams = new Set(Array.from({ length: x.length - 1 }, (_, i) => x.slice(i, i + 2)));
29282
+ for (let i = 0; i < y.length - 1; i++) if (grams.has(y.slice(i, i + 2))) return true;
29283
+ return false;
29284
+ }
29285
+ function isSameCommitment(a, b) {
29286
+ const x = normalizeTitle(a);
29287
+ const y = normalizeTitle(b);
29288
+ if (!x || !y) return false;
29289
+ if (x === y) return true;
29290
+ if (x.length >= 4 && y.includes(x)) return true;
29291
+ if (y.length >= 4 && x.includes(y)) return true;
29292
+ return false;
29293
+ }
29294
+ function guardVerdict(value) {
29295
+ if (typeof value === "boolean") return { ok: value, reason: value ? "" : "GUARD_REJECTED" };
29296
+ return { ok: value.ok, reason: value.reason ?? (value.ok ? "" : "GUARD_REJECTED") };
29297
+ }
29298
+ function actionPayload(a, now2, recentEvidence) {
29299
+ let suggestedTask = null;
29300
+ let scheduledLocal = null;
29301
+ try {
29302
+ const { dateStr, timeExact } = toCalendarWallParts(a.scheduledTime);
29303
+ suggestedTask = { date: dateStr, time: timeExact };
29304
+ scheduledLocal = formatForLlm(a.scheduledTime);
29305
+ } catch {
29306
+ }
29307
+ let generatedLocal = null;
29308
+ try {
29309
+ generatedLocal = a.createdAt ? formatForLlm(a.createdAt) : null;
29310
+ } catch {
29311
+ }
29312
+ const ageHours = (now2.getTime() - Date.parse(a.scheduledTime)) / 36e5;
29313
+ const staleHint = ageHours > STALE_HINT_HOURS ? `\u8FD9\u6761\u5DF2\u8FC7\u6392\u671F ${Math.round(ageHours)} \u5C0F\u65F6\u2014\u2014\u6B63\u6587\u91CC\u7684"\u73B0\u5728/\u4ECA\u5929"\u6307\u7684\u662F**\u751F\u6210\u65F6\u523B**\uFF0C\u4E0D\u662F\u6B64\u523B\uFF0C\u5148\u6838\u5BF9\u518D\u5224` : void 0;
29314
+ return {
29315
+ action_id: a.id,
29316
+ action_version: a.actionVersion,
29317
+ intent_id: a.intentId,
29318
+ title: a.title,
29319
+ description: a.description,
29320
+ scheduled_time: a.scheduledTime,
29321
+ // UTC 绝对时刻(机器坐标)
29322
+ scheduled_time_local: scheduledLocal,
29323
+ // 本地可读 —— 与上一行是同一个时刻,别当两件事
29324
+ suggested_task: suggestedTask,
29325
+ // { date, time } 本地墙上时间,calendar add-task 参数
29326
+ urgency: a.urgency,
29327
+ duration_minutes: a.durationMinutes,
29328
+ calendar_id: a.calendarId,
29329
+ status: a.status,
29330
+ generated_at_local: generatedLocal,
29331
+ // 这条 action 是**几点生成的**(正文里的「现在」指这个点)
29332
+ stale_hint: staleHint,
29333
+ // 0906 anti-hindsight:近期关联证据(最新在前)——"后续对话已做完"的马后炮当场现形。
29334
+ // 时间戳走 formatShort(本地);此前是 createdAt.slice(5,16) —— 那是 **UTC**,
29335
+ // 混在 suggested_task(本地)旁边且无标注。
29336
+ recent_evidence: recentEvidence && recentEvidence.length > 0 ? recentEvidence.map((e) => `[${formatShort(e.createdAt)}] ${e.title}${e.description ? `\uFF1A${e.description}` : ""}`) : void 0,
29337
+ // 机械可判的过期事实标记(不靠 LLM):action 创建之后 graph 又来了新证据 →
29338
+ // action 基于过期事实生成,先核对新证据再决定(生成侧 Time-Evidence Gate 的兜底)
29339
+ stale_facts: recentEvidence && recentEvidence.length > 0 && recentEvidence.some((e) => Date.parse(e.createdAt) > Date.parse(a.createdAt)) ? "\u6B64 action \u751F\u6210\u540E\u53C8\u6709\u65B0\u8BC1\u636E\uFF08\u89C1 recent_evidence \u6700\u65B0\u4E00\u6761\uFF09\u2014\u2014\u5148\u6838\u5BF9\u518D\u51B3\u5B9A\uFF0C\u591A\u534A\u8BE5 cancelled" : void 0,
29340
+ _received_at: now2.toISOString()
29341
+ };
29342
+ }
29343
+ var BACKLOG_ALERT_RUNS, STALE_HINT_HOURS, DEFAULT_PROMPT, TRANSIENT_GUARD_REASONS, DUE_PAGE_SIZE, DUE_MAX_PAGES, transientGuardLogged, Sweep;
29344
+ var init_sweep = __esm({
29345
+ "src/memory/proactive/sweep.ts"() {
29346
+ "use strict";
29347
+ init_calendar_bridge();
29348
+ init_intent();
29349
+ init_clock();
29350
+ BACKLOG_ALERT_RUNS = 12;
29351
+ STALE_HINT_HOURS = 8;
29352
+ DEFAULT_PROMPT = `[proactive] \u6709 action \u5230\u671F\u4E86\u3002\u5904\u7406\u89C4\u5219\uFF1A
29353
+
29354
+ 1. **\u5FC5\u987B\u8C03\u5DE5\u5177\u843D\u72B6\u6001**\uFF08\u786C\u8981\u6C42\uFF0C\u4E0D\u662F\u5EFA\u8BAE\uFF09\uFF1A
29355
+ - \u5904\u7406\u5B8C \u2192 \`proactive_done\`\uFF08action_id\uFF0C\u843D\u8FDB\u65E5\u5386\u65F6\u5E26 calendar_id\uFF09
29356
+ - \u8DF3\u8FC7 \u2192 \`proactive_cancel\`\uFF08action_id + reason\uFF09
29357
+ \u26A0\uFE0F **\u5728\u56DE\u590D\u6B63\u6587\u91CC\u5199 \`act-xxx: cancelled\` \u4E0D\u7B97\u6807\u8BB0** \u2014\u2014 \u90A3\u662F\u7559\u75D5\uFF0C\u4E0D\u843D\u5E93\u3002
29358
+ \u7CFB\u7EDF\u6709\u4E00\u9053\u515C\u5E95\u89E3\u6790\u4F1A\u635E\u6B63\u6587\uFF0C\u4F46\u5DE5\u5177\u8DEF\u5F84\u624D\u662F\u6B63\u8DEF\uFF08\u7406\u7531\u66F4\u6743\u5A01\u3001\u80FD\u56DE\u586B calendar\uFF09\u3002
29359
+ 2. **\u6279\u91CF\u5904\u7406**\uFF1A\u5148\u5168\u90E8\u5224\u65AD\u5B8C\uFF0C\u518D\u7EDF\u4E00\u8C03\u5DE5\u5177\uFF08\u4E0D\u8981\u6BCF\u6761\u8C03\u4E00\u6B21\uFF09
29360
+ 3. **status \u53EA\u6709**\uFF1Acompleted\uFF08\u5DF2\u5904\u7406\uFF0C\u542B\u5DF2\u544A\u8BC9 TA\uFF09/ cancelled\uFF08\u8DF3\u8FC7\uFF1A\u6280\u672F\u7C7B/\u5DF2\u8FC7\u65F6/\u91CD\u590D\uFF09/ failed\uFF08\u6267\u884C\u5931\u8D25\uFF09
29361
+ \u26A0\uFE0F \u6CA1\u6709 notified\u3001\u6CA1\u6709 skipped
29362
+ 4. **\u91CD\u590D\u68C0\u6D4B**\uFF1A\u591A\u6761 title \u9AD8\u5EA6\u76F8\u4F3C\u65F6\u53EA\u5904\u7406\u4E00\u6761\uFF0C\u5176\u4F59 cancelled
29363
+ 5. **\u5148\u6838\u5BF9\u518D\u5224**\uFF1A\u6B63\u6587\u91CC\u7684"\u73B0\u5728/\u4ECA\u5929"\u662F**\u751F\u6210\u65F6\u523B**\u7684\uFF0C\u4E0D\u662F\u6B64\u523B\u2014\u2014
29364
+ \u62FF \`generated_at_local\` \u8DDF \`_received_at\` \u5BF9\u4E00\u4E0B\uFF1B\u518D\u8DDF calendar/goal \u91CC\u5DF2\u6709\u7684\u5BF9\u4E00\u904D\u3002
29365
+ 6. **urgency \u662F\u53C2\u8003**\uFF08urgent=\u51E0\u5C0F\u65F6/high=24h/medium=48h/low=\u4E00\u5468\uFF09\uFF0C\u6309\u5B9E\u9645\u60C5\u51B5\u5224\u65AD
29366
+ 7. \u51B3\u5B9A\u544A\u8BC9 TA \u65F6\u7528\u4F60\u81EA\u5DF1\u7684\u8BED\u6C14\u2014\u2014\u8FD9\u662F\u4F60\u7684\u4E3B\u52A8\u5173\u6000\uFF0C\u4E0D\u662F\u7CFB\u7EDF\u901A\u77E5`;
29367
+ TRANSIENT_GUARD_REASONS = /* @__PURE__ */ new Set(["MEMORY_GUARD_UNAVAILABLE", "ACTION_DELIVERY_UNKNOWN", "CALENDAR_DELIVERY_UNKNOWN", "MEMORY_SCHEMA_UNSUPPORTED", "EXECUTION_CONTEXT_INVALID"]);
29368
+ DUE_PAGE_SIZE = 20;
29369
+ DUE_MAX_PAGES = 5;
29370
+ transientGuardLogged = /* @__PURE__ */ new Set();
29371
+ Sweep = class {
29372
+ constructor(deps, intervalMs = 3e5) {
29373
+ this.deps = deps;
29374
+ this.intervalMs = intervalMs;
29375
+ }
29376
+ timer = null;
29377
+ /** executing 连续增长的轮数(对账告警用) */
29378
+ backlogStreak = 0;
29379
+ lastExecuting = 0;
29380
+ start() {
29381
+ if (this.timer) return;
29382
+ this.runOnce(/* @__PURE__ */ new Date());
29383
+ this.timer = setInterval(() => {
29384
+ try {
29385
+ this.runOnce(/* @__PURE__ */ new Date());
29386
+ } catch (err) {
29387
+ console.warn(`[proactive] sweep error: ${err.message}`);
29388
+ }
29389
+ }, this.intervalMs);
29390
+ this.timer.unref?.();
29391
+ }
29392
+ stop() {
29393
+ if (this.timer) {
29394
+ clearInterval(this.timer);
29395
+ this.timer = null;
29396
+ }
29397
+ }
29398
+ isRunning() {
29399
+ return this.timer !== null;
29400
+ }
29401
+ /** 单轮:收割超时 executing → due → 标记 → 合并注入一次。返回注入条数 */
29402
+ runOnce(now2) {
29403
+ const closed = this.deps.persist.settleBlockedHostActions(now2.toISOString());
29404
+ if (closed) console.log(`[proactive] closed ${closed} blocked action(s) before dispatch`);
29405
+ if (this.deps.durableSubmit) for (const item of this.deps.persist.hostDeliveries.pending()) {
29406
+ try {
29407
+ this.deps.durableSubmit(item.blocks, item.context, item.key);
29408
+ } catch (error) {
29409
+ console.warn(`[proactive] host delivery remains pending: ${error.message}`);
29410
+ }
29411
+ }
29412
+ const reaped = this.deps.persist.reapStaleExecuting(now2.toISOString(), this.deps.staleHours ?? 36);
29413
+ if (reaped > 0) console.log(`[proactive] reaped ${reaped} stale executing action(s)`);
29414
+ const execNow = this.deps.persist.countByStatus("executing");
29415
+ if (execNow > 0 && execNow >= this.lastExecuting) this.backlogStreak++;
29416
+ else this.backlogStreak = 0;
29417
+ this.lastExecuting = execNow;
29418
+ if (this.backlogStreak >= BACKLOG_ALERT_RUNS) {
29419
+ this.backlogStreak = 0;
29420
+ try {
29421
+ this.deps.onUnclosedBacklog?.(execNow);
29422
+ } catch (err) {
29423
+ console.warn(`[proactive] backlog alert failed: ${err.message}`);
29424
+ }
29425
+ }
29426
+ const nowIso2 = now2.toISOString();
29427
+ const gatedItems = [];
29428
+ const gateOff = (a, reason) => {
29429
+ gatedItems.push({ id: a.id, title: a.title, reason, version: a.actionVersion });
29430
+ return false;
29431
+ };
29432
+ const seen = /* @__PURE__ */ new Set();
29433
+ let due = [];
29434
+ for (let page = 0; page < DUE_MAX_PAGES; page++) {
29435
+ const batch = this.deps.persist.dueActions(nowIso2, DUE_PAGE_SIZE, [...seen]);
29436
+ for (const action of batch) {
29437
+ seen.add(action.id);
29438
+ if (!this.deps.checkAction) {
29439
+ due.push(action);
29440
+ continue;
29441
+ }
29442
+ const verdict = guardVerdict(this.deps.checkAction(action));
29443
+ if (verdict.ok) {
29444
+ due.push(action);
29445
+ continue;
29446
+ }
29447
+ if (TRANSIENT_GUARD_REASONS.has(verdict.reason)) {
29448
+ const signature2 = `${action.id}:${verdict.reason}`;
29449
+ if (!transientGuardLogged.has(signature2)) {
29450
+ transientGuardLogged.add(signature2);
29451
+ console.log(`[proactive] \u6295\u9012\u524D\u5B88\u536B\u6682\u6001\u62D2\u7EDD\uFF0C\u672C\u8F6E\u8DF3\u8FC7\uFF1A\u300C${action.title.slice(0, 24)}\u300D${verdict.reason}`);
29452
+ }
29453
+ continue;
29454
+ }
29455
+ gateOff(action, `\u6295\u9012\u524D\u5B88\u536B\uFF1A${verdict.reason}`);
29456
+ }
29457
+ if (batch.length < DUE_PAGE_SIZE || due.length >= DUE_PAGE_SIZE) break;
29458
+ }
29459
+ if (due.length === 0 && gatedItems.length === 0) return 0;
29460
+ const opportunityGroups = [];
29461
+ for (const action of due.filter((item) => item.scopeId && item.provenance?.decisionType === "opportunity")) {
29462
+ const matches2 = opportunityGroups.filter((group) => group.some((item) => item.scopeId === action.scopeId && isSameCommitment(item.title, action.title)));
29463
+ const joined = [action, ...matches2.flat()];
29464
+ opportunityGroups.splice(0, opportunityGroups.length, ...opportunityGroups.filter((group) => !matches2.includes(group)), joined);
29465
+ }
29466
+ const duplicates = new Set(opportunityGroups.flatMap((group) => group.sort((a, b) => b.createdAt.localeCompare(a.createdAt) || b.id.localeCompare(a.id)).slice(1).map((action) => action.id)));
29467
+ due = due.filter((action) => {
29468
+ if (!duplicates.has(action.id)) return true;
29469
+ this.deps.persist.updateActionStatus(action.id, "cancelled", {
29470
+ completedAt: now2.toISOString(),
29471
+ cancelReason: "duplicate_opportunity",
29472
+ expectedActionVersion: action.actionVersion
29473
+ });
29474
+ return false;
29475
+ });
29476
+ const resolvedActions = [];
29477
+ due = due.filter((a) => {
29478
+ const intentStatus = this.deps.persist.getIntentStatus(a.intentId);
29479
+ if (intentStatus === "resolved" || intentStatus === "rejected" || intentStatus === "deferred" || intentStatus === "expired") {
29480
+ resolvedActions.push({ id: a.id, intentStatus, version: a.actionVersion });
29481
+ return false;
29482
+ }
29483
+ return true;
29484
+ });
29485
+ if (resolvedActions.length > 0) {
29486
+ for (const { id, intentStatus, version } of resolvedActions) {
29487
+ this.deps.persist.updateActionStatus(id, "cancelled", {
29488
+ completedAt: now2.toISOString(),
29489
+ cancelReason: `intent ${intentStatus}\u2014\u2014R2 sweep \u518D\u9A8C\u8BC1`,
29490
+ expectedActionVersion: version
29491
+ });
29492
+ }
29493
+ console.log(`[proactive] R2: ${resolvedActions.length} due action(s) cancelled (intent resolved)`);
29494
+ }
29495
+ const coveredTitles = this.deps.coveredTitles ?? [];
29496
+ const coveredEvents = this.deps.coveredEvents ?? [];
29497
+ if (coveredTitles.length > 0 || coveredEvents.length > 0) {
29498
+ due = due.filter((a) => {
29499
+ if (coveredTitles.some((c) => isSameCommitment(a.title, c))) {
29500
+ return gateOff(a, "calendar/goal \u91CC\u5DF2\u7ECF\u6709\u540C\u4E00\u4EF6\u4E8B\u2014\u2014\u4E0D\u91CD\u590D\u63D0\u9192");
29501
+ }
29502
+ const parts = toCalendarWallParts(a.scheduledTime);
29503
+ const sameMoment = coveredEvents.some((ev) => ev.date === parts.dateStr && ev.time === parts.timeExact);
29504
+ if (sameMoment && coveredEvents.some((ev) => ev.date === parts.dateStr && ev.time === parts.timeExact && sharesTerm(a.title, ev.title))) {
29505
+ return gateOff(a, "\u540C\u4E00\u65F6\u523B calendar \u91CC\u5DF2\u6709\u540C\u4E00\u4EF6\u4E8B\uFF08\u65F6\u95F4\u951A\u70B9\u5224\u91CD\uFF09\u2014\u2014\u4E0D\u91CD\u590D\u63D0\u9192");
29506
+ }
29507
+ return true;
29508
+ });
29509
+ }
29510
+ const minLeadDays = this.deps.minLeadDays ?? 0;
29511
+ if (minLeadDays > 0) {
29512
+ const repeatGapDays = this.deps.repeatGapDays ?? 0;
29513
+ let injectedHistory = null;
29514
+ const loadHistory = () => {
29515
+ if (injectedHistory === null) injectedHistory = this.deps.persist.listInjectedTitlesSince(now2.getTime() - 30 * 864e5);
29516
+ return injectedHistory;
29517
+ };
29518
+ due = due.filter((a) => {
29519
+ if (a.provenance?.decisionType === "opportunity") return true;
29520
+ const leadMs = Date.parse(a.scheduledTime) - Date.parse(a.createdAt);
29521
+ if (leadMs >= minLeadDays * 864e5) return true;
29522
+ if (repeatGapDays > 0) {
29523
+ const lastSame = loadHistory().filter((h) => sharesTerm(a.title, h.title)).reduce((mx, h) => Math.max(mx, h.injectedAt), 0);
29524
+ if (lastSame > 0 && now2.getTime() - lastSame >= repeatGapDays * 864e5) {
29525
+ console.log(`[proactive] \u95F8\u4E8C\u65C1\u8DEF\u653E\u884C\uFF1A\u300C${a.title.slice(0, 24)}\u300D\u8DDD\u540C\u4E3B\u9898\u4E0A\u6B21\u9001\u8FBE ${Math.round((now2.getTime() - lastSame) / 864e5)} \u5929 \u2265 ${repeatGapDays} \u5929\uFF08\u5FAA\u73AF\u578B\u5173\u6000\uFF0C\u95F4\u9694\u5373\u8282\u6D41\uFF09`);
29526
+ return true;
29527
+ }
29528
+ }
29529
+ return gateOff(a, `\u63D0\u524D\u91CF\u4E0D\u8DB3 ${minLeadDays} \u5929\uFF08\u751F\u6210\u65F6\u79BB\u4E8B\u53D1\u592A\u8FD1\uFF09\u2014\u2014proactive \u53EA\u505A\u5468\u7EA7\u63D0\u524D\u91CF`);
29530
+ });
29531
+ }
29532
+ for (const g of gatedItems) {
29533
+ this.deps.persist.updateActionStatus(g.id, "cancelled", {
29534
+ completedAt: now2.toISOString(),
29535
+ cancelReason: g.reason,
29536
+ expectedActionVersion: g.version
29537
+ });
29538
+ }
29539
+ if (gatedItems.length > 0) {
29540
+ console.log(`[proactive] gated ${gatedItems.length} action(s): ${gatedItems.map((g) => g.reason.slice(0, 12)).join(" / ")}`);
29541
+ try {
29542
+ this.deps.onGated?.(gatedItems);
29543
+ } catch (err) {
29544
+ console.warn(`[proactive] onGated failed: ${err.message}`);
29545
+ }
29546
+ }
29547
+ if (due.length === 0) return 0;
29548
+ due = due.flatMap((act) => this.deps.persist.transaction(() => {
29549
+ if (!this.deps.persist.markActionReminded(act.id, now2.toISOString(), act.actionVersion)) return [];
29550
+ const captured = this.deps.persist.getAction(act.id);
29551
+ if (captured.scopeId && this.deps.durableSubmit) {
29552
+ const context = this.executionContext([captured]);
29553
+ this.deps.persist.hostDeliveries.enqueue(captured.id, captured.actionVersion, this.blocks([captured], now2), context);
29554
+ }
29555
+ return [captured];
29556
+ }));
29557
+ if (due.length === 0) return 0;
29558
+ const groups = /* @__PURE__ */ new Map();
29559
+ for (const action of due) {
29560
+ const key5 = action.scopeId ? `${action.scopeId}:${action.id}` : "";
29561
+ groups.set(key5, [...groups.get(key5) ?? [], action]);
29562
+ }
29563
+ let injected = 0;
29564
+ for (const captured of groups.values()) {
29565
+ const blocks = this.blocks(captured, now2);
29566
+ const context = this.executionContext(captured);
29567
+ let delivered = false;
29568
+ const durable = Boolean(context && this.deps.durableSubmit);
29569
+ try {
29570
+ delivered = durable ? this.deps.durableSubmit(blocks, context, JSON.stringify(["proactive", captured[0].id, captured[0].actionVersion])) : this.deps.submit(blocks, context);
29571
+ } catch (error) {
29572
+ console.warn(`[proactive] injection failed: ${error.message}`);
29573
+ }
29574
+ if (delivered) injected += captured.length;
29575
+ else if (!durable) {
29576
+ const back = this.deps.persist.rollbackReminded(captured.map((a) => a.id));
29577
+ console.warn(`[proactive] injection dropped \u2014 rolled back ${back} action(s) to queued`);
29578
+ }
29579
+ }
29580
+ if (injected) console.log(`[proactive] injected ${injected} due action(s) to main session`);
29581
+ return injected;
29582
+ }
29583
+ executionContext(actions) {
29584
+ const scopeId2 = actions[0]?.scopeId;
29585
+ return scopeId2 ? {
29586
+ scopeId: scopeId2,
29587
+ basisRefs: actions.flatMap((action) => action.basisRefs ?? []),
29588
+ actionVersions: Object.fromEntries(actions.map((action) => [action.id, action.actionVersion]))
29589
+ } : void 0;
29590
+ }
29591
+ blocks(actions, now2) {
29592
+ const payload = actions.map((action) => actionPayload(action, now2, this.deps.persist.getIntentRecentEvents(action.intentId)));
29593
+ return [
29594
+ { type: "text", text: `## Actions (${payload.length} \u4E2A)
29595
+
29596
+ \`\`\`json
29597
+ ${JSON.stringify(payload)}
29598
+ \`\`\`` },
29599
+ { type: "text", text: this.loadPrompt() }
29600
+ ];
29601
+ }
29602
+ /** 处理规则现读(改了不用重启);文件缺失/读失败用内置 */
29603
+ loadPrompt() {
29604
+ const file2 = this.deps.promptFile;
29605
+ if (!file2) return DEFAULT_PROMPT;
29606
+ try {
29607
+ const text2 = readFileSync26(file2, "utf8").trim();
29608
+ return text2 || DEFAULT_PROMPT;
29609
+ } catch {
29610
+ return DEFAULT_PROMPT;
29611
+ }
29612
+ }
29613
+ };
29614
+ }
29615
+ });
29616
+
29447
29617
  // src/memory/proactive/planning-context.ts
29448
29618
  import { existsSync as existsSync13, readFileSync as readFileSync27 } from "node:fs";
29449
29619
  import { join as join32 } from "node:path";
@@ -33248,6 +33418,13 @@ function withStore(fn) {
33248
33418
  store.close();
33249
33419
  }
33250
33420
  }
33421
+ function rejectIntentOnCancel(store, intentId, userRejected) {
33422
+ if (!userRejected) return null;
33423
+ const data = store.getIntentData(intentId);
33424
+ if (!data || terminalIntentStatuses.has(String(data.status))) return null;
33425
+ if (!store.setIntentData(intentId, { ...data, status: "rejected", reasonCode: "user_rejected", deferredReason: null, waitingFor: null }, stateVersion(data))) return null;
33426
+ return "user_rejected";
33427
+ }
33251
33428
  function fmtRow2(a) {
33252
33429
  const when = a.scheduledTime ? formatForLlm(a.scheduledTime) : "(\u65E0)";
33253
33430
  return `#${a.id} [${a.status}, version=${a.actionVersion}] ${a.title} (urgency=${a.urgency}, scheduled=${when}${a.calendarId ? `, cal=#${a.calendarId}` : ""})`;
@@ -33291,13 +33468,14 @@ function registerProactiveTools() {
33291
33468
  });
33292
33469
  registry.register({
33293
33470
  name: "proactive_cancel",
33294
- description: "\u53D6\u6D88\u4E00\u4E2A proactive action\uFF08\u5224\u5B9A\u4E3A\u4E0D\u8BE5\u505A/\u5DF2\u8FC7\u671F/\u9A6C\u540E\u70AE\u65F6\u8C03\u7528\uFF09\u3002",
33471
+ description: "\u53D6\u6D88\u4E00\u4E2A proactive action\uFF08\u5224\u5B9A\u4E3A\u4E0D\u8BE5\u505A/\u5DF2\u8FC7\u671F/\u9A6C\u540E\u70AE\u65F6\u8C03\u7528\uFF09\u3002\u7528\u6237\u660E\u786E\u8BF4\u4E0D\u8981\u8FD9\u6761\u65F6\u5E26 user_rejected=true\uFF1A\u610F\u56FE\u76F4\u63A5 rejected\uFF0C\u4E0D\u518D\u751F\u6210\u540C\u7C7B\u3002",
33295
33472
  schema: {
33296
33473
  type: "object",
33297
33474
  properties: {
33298
33475
  action_id: { type: "string", description: "action id" },
33299
33476
  reason: { type: "string", description: "\u53D6\u6D88\u7406\u7531\uFF08\u4F1A\u8BB0\u8FDB cancel_reason\uFF09" },
33300
- expected_action_version: { type: "integer", description: "\u6CE8\u5165\u6216 proactive_status \u63D0\u4F9B\u7684 action version" }
33477
+ expected_action_version: { type: "integer", description: "\u6CE8\u5165\u6216 proactive_status \u63D0\u4F9B\u7684 action version" },
33478
+ user_rejected: { type: "boolean", description: "\u7528\u6237\u660E\u786E\u5426\u51B3\u8FD9\u6761\u5EFA\u8BAE\uFF08\u610F\u56FE\u76F4\u63A5 rejected\uFF09" }
33301
33479
  },
33302
33480
  required: ["action_id"]
33303
33481
  },
@@ -33313,7 +33491,9 @@ function registerProactiveTools() {
33313
33491
  expectedActionVersion: args2.expected_action_version ?? a.actionVersion
33314
33492
  });
33315
33493
  if (!changed) return { content: "\u9519\u8BEF: action \u7684\u7248\u672C\u6216\u72B6\u6001\u5DF2\u7ECF\u53D8\u5316\uFF0C\u8BF7\u91CD\u65B0\u8BFB\u53D6 proactive_status\u3002", isError: true };
33316
- return { content: `\u2713 action ${a.id} \u6807\u8BB0\u4E3A cancelled\uFF08${String(args2.reason || "\u672A\u6CE8\u660E")}\uFF09` };
33494
+ const rejected = rejectIntentOnCancel(store, a.intentId, args2.user_rejected === true);
33495
+ if (rejected) toolStore?.refreshNode(a.intentId);
33496
+ return { content: `\u2713 action ${a.id} \u6807\u8BB0\u4E3A cancelled\uFF08${String(args2.reason || "\u672A\u6CE8\u660E")}\uFF09` + (rejected ? `\uFF1B\u610F\u56FE ${a.intentId} \u5DF2 rejected\uFF08${rejected}\uFF09` : "") };
33317
33497
  });
33318
33498
  return out ?? { content: "proactive \u672A\u542F\u7528", isError: true };
33319
33499
  }
@@ -34981,11 +35161,11 @@ async function expireBackups(state, roots, now2, maxAgeMs, max, allowed) {
34981
35161
  for (const entry of await readdir(unlinked(histories), { withFileTypes: true })) {
34982
35162
  if (removed >= max || !allowed()) break;
34983
35163
  if (!entry.isDirectory() || entry.isSymbolicLink() || !/^[a-f0-9]{64}$/.test(entry.name)) continue;
34984
- const history = unlinked(join44(histories, entry.name)), markerPath = join44(history, "topics-import.json");
35164
+ const history = unlinked(join44(histories, entry.name)), markerPath3 = join44(history, "topics-import.json");
34985
35165
  if (importerActive(history) || existsSync21(join44(history, pointerName))) continue;
34986
35166
  let marker;
34987
35167
  try {
34988
- marker = readJson(markerPath);
35168
+ marker = readJson(markerPath3);
34989
35169
  } catch {
34990
35170
  continue;
34991
35171
  }
@@ -35012,7 +35192,7 @@ async function expireBackups(state, roots, now2, maxAgeMs, max, allowed) {
35012
35192
  if (!candidates.length) continue;
35013
35193
  try {
35014
35194
  await withTopicsImportLock(history, async () => {
35015
- if (!allowed() || existsSync21(join44(history, pointerName)) || digest3(canonical(readJson(markerPath))) !== completionHash) return;
35195
+ if (!allowed() || existsSync21(join44(history, pointerName)) || digest3(canonical(readJson(markerPath3))) !== completionHash) return;
35016
35196
  const result = await validateInHelper(["--validate-topics-import-live", state, history], allowed);
35017
35197
  if (!result.verified) {
35018
35198
  console.log(`[bg-worker] topics backup expiry deferred: ${result.reason}`);
@@ -35020,7 +35200,7 @@ async function expireBackups(state, roots, now2, maxAgeMs, max, allowed) {
35020
35200
  }
35021
35201
  for (const candidate of candidates.sort((a, b) => a.createdAt - b.createdAt)) {
35022
35202
  if (removed >= max || !allowed() || existsSync21(join44(history, pointerName))) break;
35023
- if (digest3(canonical(readJson(markerPath))) !== completionHash) break;
35203
+ if (digest3(canonical(readJson(markerPath3))) !== completionHash) break;
35024
35204
  const root = unlinked(candidate.root), target = unlinked(join44(root, candidate.name));
35025
35205
  if (dirname24(target) !== root || basename8(target) !== candidate.name) throw new Error("BACKUP_PATH_ESCAPE");
35026
35206
  disjoint(join44(state, "mem7", "index"), join44(state, "mem7", "users"), target);
@@ -35353,16 +35533,130 @@ var init_validate_import_live = __esm({
35353
35533
  }
35354
35534
  });
35355
35535
 
35536
+ // src/memory/mem7-retokenize.ts
35537
+ var mem7_retokenize_exports = {};
35538
+ __export(mem7_retokenize_exports, {
35539
+ retokenizeIfNeeded: () => retokenizeIfNeeded,
35540
+ tokenizerMarkerCurrent: () => tokenizerMarkerCurrent
35541
+ });
35542
+ import { existsSync as existsSync24, mkdirSync as mkdirSync21, readFileSync as readFileSync37, renameSync as renameSync12, writeFileSync as writeFileSync16 } from "node:fs";
35543
+ import { dirname as dirname27, join as join50 } from "node:path";
35544
+ function tokenizerMarkerCurrent(stateDir2) {
35545
+ const path23 = markerPath(stateDir2);
35546
+ if (!existsSync24(path23)) return false;
35547
+ try {
35548
+ return JSON.parse(readFileSync37(path23, "utf8")).version === TOKENIZER_VERSION;
35549
+ } catch {
35550
+ return false;
35551
+ }
35552
+ }
35553
+ async function retokenizeIfNeeded(options) {
35554
+ if (tokenizerMarkerCurrent(options.stateDir)) return { ran: false, rows: 0, changed: 0, ms: 0 };
35555
+ const started = Date.now();
35556
+ let rows = 0, changed = 0;
35557
+ for (const kind of KINDS) {
35558
+ const report = await options.vectorStore.retokenize(kind);
35559
+ rows += report.rows;
35560
+ changed += report.changed;
35561
+ if (report.rows) options.log?.(`[bg-worker] mem7 retokenize ${kind} rows=${report.rows} changed=${report.changed}`);
35562
+ }
35563
+ const path23 = markerPath(options.stateDir);
35564
+ mkdirSync21(dirname27(path23), { recursive: true });
35565
+ writeFileSync16(`${path23}.${process.pid}.tmp`, JSON.stringify({ version: TOKENIZER_VERSION, at: (/* @__PURE__ */ new Date()).toISOString(), rows, changed }));
35566
+ renameSync12(`${path23}.${process.pid}.tmp`, path23);
35567
+ const ms = Date.now() - started;
35568
+ options.log?.(`[bg-worker] mem7 retokenize done rows=${rows} changed=${changed} ms=${ms}`);
35569
+ return { ran: true, rows, changed, ms };
35570
+ }
35571
+ var KINDS, markerPath;
35572
+ var init_mem7_retokenize = __esm({
35573
+ "src/memory/mem7-retokenize.ts"() {
35574
+ "use strict";
35575
+ init_tokenizer();
35576
+ init_store();
35577
+ KINDS = ["episode", "atomic_fact", "foresight", "agent_case", "agent_skill"];
35578
+ markerPath = (stateDir2) => join50(mem7Root(stateDir2), "tokenizer.json");
35579
+ }
35580
+ });
35581
+
35582
+ // src/memory/mem7-foresight-settle.ts
35583
+ var mem7_foresight_settle_exports = {};
35584
+ __export(mem7_foresight_settle_exports, {
35585
+ foresightSettleDone: () => foresightSettleDone,
35586
+ settleForesightRevalidation: () => settleForesightRevalidation
35587
+ });
35588
+ import { existsSync as existsSync25, mkdirSync as mkdirSync22, readFileSync as readFileSync38, renameSync as renameSync13, writeFileSync as writeFileSync17 } from "node:fs";
35589
+ import { dirname as dirname28, join as join51 } from "node:path";
35590
+ function foresightSettleDone(stateDir2) {
35591
+ const path23 = markerPath2(stateDir2);
35592
+ if (!existsSync25(path23)) return false;
35593
+ try {
35594
+ return JSON.parse(readFileSync38(path23, "utf8")).version === MARKER_VERSION;
35595
+ } catch {
35596
+ return false;
35597
+ }
35598
+ }
35599
+ async function settleForesightRevalidation(options) {
35600
+ if (foresightSettleDone(options.stateDir)) return { ran: false, settled: 0 };
35601
+ const path23 = markerPath2(options.stateDir);
35602
+ const now2 = (options.now ?? Date.now)();
35603
+ const windows = /* @__PURE__ */ new Map();
35604
+ try {
35605
+ const tbl = await options.vectorStore.table("foresight");
35606
+ for (const row of await tbl.query().select(["id", "entry_id", "end_time"]).toArray()) {
35607
+ const end = row.end_time ? new Date(row.end_time).getTime() : null;
35608
+ windows.set(String(row.id), end);
35609
+ if (row.entry_id) windows.set(String(row.entry_id), end);
35610
+ }
35611
+ } catch {
35612
+ }
35613
+ let settled = 0;
35614
+ const tally = { current: 0, invalid: 0, deleted: 0 };
35615
+ for (const scope of options.store.sources.scopes()) {
35616
+ const verdicts = /* @__PURE__ */ new Map();
35617
+ for (const artifact of options.store.dependencies.dirty(scope)) {
35618
+ if (artifact.kind !== "foresight") continue;
35619
+ const end = windows.get(artifact.id);
35620
+ if (end === void 0) {
35621
+ verdicts.set(artifact.id, { state: "deleted", reason: "foresight row missing (1203 settle)" });
35622
+ tally.deleted++;
35623
+ } else if (end !== null && end < now2) {
35624
+ verdicts.set(artifact.id, { state: "invalid", reason: "retired_expired_foresight_1203" });
35625
+ tally.invalid++;
35626
+ } else {
35627
+ verdicts.set(artifact.id, { state: "current", reason: "foresight_revalidation_off_1015" });
35628
+ tally.current++;
35629
+ }
35630
+ }
35631
+ settled += options.store.dependencies.settleRevalidation(scope, "foresight", verdicts);
35632
+ }
35633
+ mkdirSync22(dirname28(path23), { recursive: true });
35634
+ writeFileSync17(`${path23}.${process.pid}.tmp`, JSON.stringify({ version: MARKER_VERSION, at: (/* @__PURE__ */ new Date()).toISOString(), settled, ...tally }));
35635
+ renameSync13(`${path23}.${process.pid}.tmp`, path23);
35636
+ options.log?.(`[bg-worker] foresight revalidation flags settled=${settled} current=${tally.current} expired=${tally.invalid} missing=${tally.deleted}`);
35637
+ return { ran: true, settled };
35638
+ }
35639
+ var MARKER_VERSION, markerPath2;
35640
+ var init_mem7_foresight_settle = __esm({
35641
+ "src/memory/mem7-foresight-settle.ts"() {
35642
+ "use strict";
35643
+ init_store();
35644
+ MARKER_VERSION = 1;
35645
+ markerPath2 = (stateDir2) => join51(mem7Root(stateDir2), "foresight-settle.json");
35646
+ }
35647
+ });
35648
+
35356
35649
  // src/memory/topics-chunks.ts
35357
35650
  var topics_chunks_exports = {};
35358
35651
  __export(topics_chunks_exports, {
35359
35652
  TOPICS_CHUNK_SESSION: () => TOPICS_CHUNK_SESSION,
35653
+ chunkTimestamp: () => chunkTimestamp,
35360
35654
  chunkTopicsText: () => chunkTopicsText,
35361
35655
  importTopicChunks: () => importTopicChunks
35362
35656
  });
35363
35657
  import { createHash as createHash36 } from "node:crypto";
35364
- import { readdirSync as readdirSync7, readFileSync as readFileSync37, mkdirSync as mkdirSync21, writeFileSync as writeFileSync16, renameSync as renameSync12, existsSync as existsSync24 } from "node:fs";
35365
- import { join as join50, relative as relative8 } from "node:path";
35658
+ import { readdirSync as readdirSync7, readFileSync as readFileSync39, mkdirSync as mkdirSync23, writeFileSync as writeFileSync18, renameSync as renameSync14, existsSync as existsSync26 } from "node:fs";
35659
+ import { join as join52, relative as relative8 } from "node:path";
35366
35660
  function parseMd(text2) {
35367
35661
  const m = /^---\r?\n([\s\S]*?)\r?\n---/.exec(text2);
35368
35662
  const meta = {};
@@ -35411,7 +35705,7 @@ function walk(root) {
35411
35705
  const visit = (dir) => {
35412
35706
  for (const entry of readdirSync7(dir, { withFileTypes: true })) {
35413
35707
  if (entry.isSymbolicLink()) continue;
35414
- const path23 = join50(dir, entry.name);
35708
+ const path23 = join52(dir, entry.name);
35415
35709
  if (entry.isDirectory()) visit(path23);
35416
35710
  else if (entry.isFile() && /\.md$/i.test(entry.name) && entry.name.toUpperCase() !== "MEMORY.MD") out.push(path23);
35417
35711
  }
@@ -35419,13 +35713,17 @@ function walk(root) {
35419
35713
  visit(root);
35420
35714
  return out.sort();
35421
35715
  }
35716
+ function chunkTimestamp(meta) {
35717
+ const ms = Date.parse(String(meta.date ?? ""));
35718
+ return new Date(Number.isFinite(ms) ? ms : Date.now());
35719
+ }
35422
35720
  async function importTopicChunks(options) {
35423
35721
  const { stateDir: stateDir2, topicsDir, userId, embed } = options;
35424
- const manifestPath = join50(stateDir2, "mem7", "topics-chunks.json");
35425
- mkdirSync21(join50(stateDir2, "mem7"), { recursive: true });
35722
+ const manifestPath = join52(stateDir2, "mem7", "topics-chunks.json");
35723
+ mkdirSync23(join52(stateDir2, "mem7"), { recursive: true });
35426
35724
  let manifest = {};
35427
35725
  try {
35428
- if (existsSync24(manifestPath)) manifest = JSON.parse(readFileSync37(manifestPath, "utf8"));
35726
+ if (existsSync26(manifestPath)) manifest = JSON.parse(readFileSync39(manifestPath, "utf8"));
35429
35727
  } catch {
35430
35728
  manifest = {};
35431
35729
  }
@@ -35434,8 +35732,8 @@ async function importTopicChunks(options) {
35434
35732
  const report = { files: 0, chunks: 0, embedded: 0, deleted: 0, failed: 0, errors: [] };
35435
35733
  const save = () => {
35436
35734
  const tmp = `${manifestPath}.${process.pid}.tmp`;
35437
- writeFileSync16(tmp, JSON.stringify(manifest));
35438
- renameSync12(tmp, manifestPath);
35735
+ writeFileSync18(tmp, JSON.stringify(manifest));
35736
+ renameSync14(tmp, manifestPath);
35439
35737
  };
35440
35738
  const files = walk(topicsDir);
35441
35739
  const seen = /* @__PURE__ */ new Set();
@@ -35443,13 +35741,13 @@ async function importTopicChunks(options) {
35443
35741
  for (const file2 of files) {
35444
35742
  const rel = relative8(topicsDir, file2);
35445
35743
  seen.add(rel);
35446
- const bytes2 = readFileSync37(file2);
35744
+ const bytes2 = readFileSync39(file2);
35447
35745
  const hash8 = sha(bytes2);
35448
35746
  const previous = manifest[rel];
35449
35747
  if (previous?.hash === hash8) continue;
35450
35748
  try {
35451
35749
  const parentId = `topic_chunk:${rel}`;
35452
- await table.delete(`parent_id = '${sqlLiteral2(parentId)}'`);
35750
+ await table.delete(`parent_id = '${sqlLiteral(parentId)}'`);
35453
35751
  const text2 = bytes2.toString("utf8");
35454
35752
  const parsed = parseMd(text2);
35455
35753
  const title = parsed.meta.name || rel.split("/").pop().replace(/\.md$/i, "");
@@ -35477,7 +35775,7 @@ async function importTopicChunks(options) {
35477
35775
  appId: options.appId ?? "default",
35478
35776
  projectId: options.projectId ?? "default",
35479
35777
  sessionId: TOPICS_CHUNK_SESSION,
35480
- timestamp: new Date(parsed.meta.date || Date.now()),
35778
+ timestamp: chunkTimestamp(parsed.meta),
35481
35779
  parentId,
35482
35780
  text: chunk.text,
35483
35781
  subject: title,
@@ -35498,10 +35796,10 @@ async function importTopicChunks(options) {
35498
35796
  report.errors.push(`${rel}: ${error instanceof Error ? error.message : String(error)}`);
35499
35797
  }
35500
35798
  }
35501
- for (const rel of Object.keys(manifest)) {
35799
+ if (options.prune !== false) for (const rel of Object.keys(manifest)) {
35502
35800
  if (seen.has(rel)) continue;
35503
35801
  try {
35504
- await table.delete(`parent_id = '${sqlLiteral2(`topic_chunk:${rel}`)}'`);
35802
+ await table.delete(`parent_id = '${sqlLiteral(`topic_chunk:${rel}`)}'`);
35505
35803
  delete manifest[rel];
35506
35804
  report.deleted++;
35507
35805
  } catch (error) {
@@ -35518,7 +35816,7 @@ async function importTopicChunks(options) {
35518
35816
  }
35519
35817
  return report;
35520
35818
  }
35521
- var TOPICS_CHUNK_SESSION, CHUNK_MIN, CHUNK_MAX, MAX_CHUNKS_PER_FILE, sha, sqlLiteral2;
35819
+ var TOPICS_CHUNK_SESSION, CHUNK_MIN, CHUNK_MAX, MAX_CHUNKS_PER_FILE, sha, sqlLiteral;
35522
35820
  var init_topics_chunks = __esm({
35523
35821
  "src/memory/topics-chunks.ts"() {
35524
35822
  "use strict";
@@ -35528,7 +35826,7 @@ var init_topics_chunks = __esm({
35528
35826
  CHUNK_MAX = 800;
35529
35827
  MAX_CHUNKS_PER_FILE = 200;
35530
35828
  sha = (input) => createHash36("sha256").update(input).digest("hex");
35531
- sqlLiteral2 = (value) => value.replace(/'/g, "''");
35829
+ sqlLiteral = (value) => value.replace(/'/g, "''");
35532
35830
  }
35533
35831
  });
35534
35832
 
@@ -35757,7 +36055,7 @@ var init_memoryTypes = __esm({
35757
36055
  // src/memory/memdir/memoryScan.ts
35758
36056
  import fs11 from "node:fs/promises";
35759
36057
  import { StringDecoder } from "node:string_decoder";
35760
- import { basename as basename12, join as join51, sep as sep6 } from "node:path";
36058
+ import { basename as basename12, join as join53, sep as sep6 } from "node:path";
35761
36059
  function isArchivedPath(relativePath) {
35762
36060
  return relativePath.split(sep6).includes("archive");
35763
36061
  }
@@ -35832,7 +36130,7 @@ async function scanMemoryFiles(memoryDir, signal, maxFiles) {
35832
36130
  const entries = await fs11.readdir(memoryDir, { recursive: true });
35833
36131
  const files = entries.filter((f) => typeof f === "string" && f.endsWith(".md") && basename12(f) !== "MEMORY.md" && !isArchivedPath(f));
35834
36132
  const candidates = await mapFiles(files, 16, signal, async (filename) => {
35835
- const filePath = join51(memoryDir, filename);
36133
+ const filePath = join53(memoryDir, filename);
35836
36134
  return { filename, filePath, mtimeMs: (await fs11.stat(filePath)).mtimeMs };
35837
36135
  });
35838
36136
  const selected = candidates.sort((a, b) => b.mtimeMs - a.mtimeMs).slice(0, limit);
@@ -36037,11 +36335,11 @@ var init_reader = __esm({
36037
36335
 
36038
36336
  // src/memory/topics-history/import-mem7.ts
36039
36337
  import { DatabaseSync as DatabaseSync21 } from "node:sqlite";
36040
- import { existsSync as existsSync25, readFileSync as readFileSync38, renameSync as renameSync13, statSync as statSync7, writeFileSync as writeFileSync17 } from "node:fs";
36041
- import { join as join52 } from "node:path";
36338
+ import { existsSync as existsSync27, readFileSync as readFileSync40, renameSync as renameSync15, statSync as statSync7, writeFileSync as writeFileSync19 } from "node:fs";
36339
+ import { join as join54 } from "node:path";
36042
36340
  function topicsImported(binding) {
36043
36341
  if (!binding.stateDir) return false;
36044
- const marker = join52(topicsHistoryRoot(binding), "topics-import.json");
36342
+ const marker = join54(topicsHistoryRoot(binding), "topics-import.json");
36045
36343
  let size2 = 0, mtimeMs = 0, ino = 0;
36046
36344
  try {
36047
36345
  const s = statSync7(marker);
@@ -36058,19 +36356,19 @@ function topicsImported(binding) {
36058
36356
  try {
36059
36357
  const done = readJson(marker);
36060
36358
  if (typeof done.rulesVersion === "number" && done.rulesVersion !== TOPIC_DATE_RULES_VERSION) {
36061
- const retired = join52(topicsHistoryRoot(binding), `topics-import.stale-rules-${(/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-")}.json`);
36062
- renameSync13(marker, retired);
36359
+ const retired = join54(topicsHistoryRoot(binding), `topics-import.stale-rules-${(/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-")}.json`);
36360
+ renameSync15(marker, retired);
36063
36361
  console.warn(`[topics-import] \u65E5\u671F\u89C4\u5219 v${done.rulesVersion}\u2192v${TOPIC_DATE_RULES_VERSION}\uFF0C\u65E7\u6E05\u5355\u4F5C\u5E9F\u91CD\u5F00 \u2192 ${retired}`);
36064
36362
  } else if ((done.report?.total ?? 0) > 0) imported = true;
36065
36363
  else {
36066
- const retired = join52(topicsHistoryRoot(binding), `topics-import.degenerate-${(/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-")}.json`);
36067
- renameSync13(marker, retired);
36364
+ const retired = join54(topicsHistoryRoot(binding), `topics-import.degenerate-${(/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-")}.json`);
36365
+ renameSync15(marker, retired);
36068
36366
  console.warn(`[topics-import] total=0 \u5B8C\u6210\u6E05\u5355\u4F5C\u5E9F\uFF08\u6E05\u6D17\u9000\u5316\u5047\u5B8C\u6210\uFF0C\u95F8\u95E8\u91CD\u5F00\uFF09\u2192 ${retired}`);
36069
36367
  }
36070
36368
  } catch {
36071
- const retired = join52(topicsHistoryRoot(binding), `topics-import.degenerate-${(/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-")}.json`);
36369
+ const retired = join54(topicsHistoryRoot(binding), `topics-import.degenerate-${(/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-")}.json`);
36072
36370
  try {
36073
- renameSync13(marker, retired);
36371
+ renameSync15(marker, retired);
36074
36372
  console.warn(`[topics-import] \u6E05\u5355\u635F\u574F\u4F5C\u5E9F\uFF08\u4E0B\u8F6E\u5BFC\u5165\u91CD\u5199\u81EA\u6108\uFF09\u2192 ${retired}`);
36075
36373
  } catch {
36076
36374
  }
@@ -38521,7 +38819,7 @@ var init_on_demand_recall = __esm({
38521
38819
  async search(binding, args2, run, signal) {
38522
38820
  const status = (value, reason) => JSON.stringify({ historySearch: { status: value, reason } });
38523
38821
  if (signal?.aborted) return status("aborted", "\u672C\u8F6E\u5DF2\u53D6\u6D88\u3002");
38524
- if (args2.mode === "agentic") return status("unavailable", "\u60C5\u611F\u8F6E\u8BF7\u7528 keyword \u6216 hybrid \u6709\u754C\u8865\u67E5\u3002");
38822
+ if (args2.mode === "agentic") return status("unavailable", "\u60C5\u611F\u8F6E\u8BF7\u7528 hybrid\uFF08\u4E0D\u586B mode\uFF09\u6709\u754C\u8865\u67E5\u3002");
38525
38823
  const bounded = {
38526
38824
  query: String(args2.query ?? "").trim(),
38527
38825
  view: args2.view ?? "mixed",
@@ -40345,8 +40643,8 @@ __export(memdir_exports, {
40345
40643
  loadMemoryPrompt: () => loadMemoryPrompt,
40346
40644
  truncateEntrypointContent: () => truncateEntrypointContent
40347
40645
  });
40348
- import { readFileSync as readFileSync41 } from "node:fs";
40349
- import { join as join58 } from "node:path";
40646
+ import { readFileSync as readFileSync43 } from "node:fs";
40647
+ import { join as join60 } from "node:path";
40350
40648
  function truncateEntrypointContent(raw) {
40351
40649
  const trimmed = raw.trim();
40352
40650
  const contentLines = trimmed.split("\n");
@@ -40439,11 +40737,11 @@ function buildMemoryLines(displayName, memoryDir, extraGuidelines, skipIndex = f
40439
40737
  }
40440
40738
  function buildMemoryPrompt(params) {
40441
40739
  const { displayName, memoryDir, extraGuidelines } = params;
40442
- const entrypoint = join58(memoryDir, ENTRYPOINT_NAME);
40740
+ const entrypoint = join60(memoryDir, ENTRYPOINT_NAME);
40443
40741
  let entrypointContent = params.entrypointContent ?? "";
40444
40742
  if (params.entrypointContent === void 0) {
40445
40743
  try {
40446
- entrypointContent = readFileSync41(entrypoint, "utf-8");
40744
+ entrypointContent = readFileSync43(entrypoint, "utf-8");
40447
40745
  } catch {
40448
40746
  }
40449
40747
  }
@@ -42736,11 +43034,11 @@ var init_providers = __esm({
42736
43034
 
42737
43035
  // src/task-sessions/extraction.ts
42738
43036
  import { mkdir as mkdir2, readFile as readFile2, readdir as readdir4, rename, rm as rm2, writeFile } from "node:fs/promises";
42739
- import { basename as basename13, dirname as dirname31, join as join61, resolve as resolve22 } from "node:path";
43037
+ import { basename as basename13, dirname as dirname33, join as join63, resolve as resolve22 } from "node:path";
42740
43038
  function validTaskTopicNotice(stateDir2, notice) {
42741
43039
  if (!notice.topicsDir || !notice.sessionId || !notice.transcriptPath.endsWith(".jsonl")) return false;
42742
- const project = dirname31(resolve22(notice.topicsDir));
42743
- return dirname31(project) === resolve22(stateDir2, "agents", "main", "projects") && resolve22(notice.topicsDir) === join61(project, "topics") && dirname31(resolve22(notice.transcriptPath)) === join61(project, "sessions");
43040
+ const project = dirname33(resolve22(notice.topicsDir));
43041
+ return dirname33(project) === resolve22(stateDir2, "agents", "main", "projects") && resolve22(notice.topicsDir) === join63(project, "topics") && dirname33(resolve22(notice.transcriptPath)) === join63(project, "sessions");
42744
43042
  }
42745
43043
  async function readPendingTaskTopics(stateDir2) {
42746
43044
  const dir = queueDir(stateDir2);
@@ -42754,7 +43052,7 @@ async function readPendingTaskTopics(stateDir2) {
42754
43052
  const items = [];
42755
43053
  for (const name of names) {
42756
43054
  if (!/^[a-f0-9]{64}-[a-f0-9-]{36}\.json$/.test(name)) continue;
42757
- const file2 = join61(dir, name);
43055
+ const file2 = join63(dir, name);
42758
43056
  try {
42759
43057
  const notice = JSON.parse(await readFile2(file2, "utf8"));
42760
43058
  if (validTaskTopicNotice(stateDir2, notice)) items.push({ file: file2, notice });
@@ -42768,8 +43066,8 @@ function acknowledgeTaskTopics(item) {
42768
43066
  return rm2(item.file, { force: true });
42769
43067
  }
42770
43068
  async function markTaskTopicsWorker(stateDir2) {
42771
- const marker = join61(queueDir(stateDir2), "worker.pid");
42772
- await mkdir2(dirname31(marker), { recursive: true });
43069
+ const marker = join63(queueDir(stateDir2), "worker.pid");
43070
+ await mkdir2(dirname33(marker), { recursive: true });
42773
43071
  await writeFile(marker, String(process.pid));
42774
43072
  return async () => {
42775
43073
  if (await readFile2(marker, "utf8").catch(() => "") === String(process.pid)) await rm2(marker, { force: true });
@@ -42783,7 +43081,7 @@ var init_extraction = __esm({
42783
43081
  init_extractMemories();
42784
43082
  init_reader2();
42785
43083
  init_providers();
42786
- queueDir = (stateDir2) => join61(stateDir2, "task-topics-queue");
43084
+ queueDir = (stateDir2) => join63(stateDir2, "task-topics-queue");
42787
43085
  }
42788
43086
  });
42789
43087
 
@@ -43847,7 +44145,7 @@ __export(topic_extraction_exports, {
43847
44145
  startTopicExtraction: () => startTopicExtraction
43848
44146
  });
43849
44147
  import { readFile as readFile3, stat as stat2 } from "node:fs/promises";
43850
- import { basename as basename16, join as join64, resolve as resolve24 } from "node:path";
44148
+ import { basename as basename16, join as join66, resolve as resolve24 } from "node:path";
43851
44149
  function startTopicExtraction(config, workspace2, stateDir2, isBusy) {
43852
44150
  const toolConfig = { stateDir: stateDir2, workspace: workspace2 };
43853
44151
  liveConfig.init(toolConfig);
@@ -43973,12 +44271,12 @@ function startTopicExtraction(config, workspace2, stateDir2, isBusy) {
43973
44271
  const recover = async () => {
43974
44272
  if (!enabled()) return;
43975
44273
  try {
43976
- const dir = join64(stateDir2, "agents", "main", "sessions");
43977
- const [platform, index] = await Promise.all(["platform-map.json", "session-index.json"].map((file3) => readFile3(join64(dir, file3), "utf8").then(JSON.parse)));
44274
+ const dir = join66(stateDir2, "agents", "main", "sessions");
44275
+ const [platform, index] = await Promise.all(["platform-map.json", "session-index.json"].map((file3) => readFile3(join66(dir, file3), "utf8").then(JSON.parse)));
43978
44276
  const sessionId = platform["scope:main"], file2 = index[sessionId]?.file;
43979
44277
  if (typeof sessionId === "string" && typeof file2 === "string") {
43980
44278
  const localName = basename16(file2.replace(/\\/g, "/"));
43981
- notify({ sessionId, transcriptPath: join64(dir, localName) });
44279
+ notify({ sessionId, transcriptPath: join66(dir, localName) });
43982
44280
  }
43983
44281
  } catch (error) {
43984
44282
  if (error?.code !== "ENOENT") console.warn(`[bg-worker] topics recovery: ${error?.message ?? error}`);
@@ -44038,7 +44336,7 @@ var init_topic_extraction = __esm({
44038
44336
  });
44039
44337
 
44040
44338
  // src/bg/bg-worker.ts
44041
- import { existsSync as existsSync34 } from "node:fs";
44339
+ import { existsSync as existsSync36 } from "node:fs";
44042
44340
  import { resolve as resolve25 } from "node:path";
44043
44341
 
44044
44342
  // src/bg/host.ts
@@ -44051,8 +44349,8 @@ init_pipeline();
44051
44349
  init_job_runner();
44052
44350
  init_projection_driver();
44053
44351
  import { execFile as execFile2, fork as fork2 } from "node:child_process";
44054
- import { dirname as dirname27, join as join53 } from "node:path";
44055
- import { existsSync as existsSync26 } from "node:fs";
44352
+ import { dirname as dirname29, join as join55 } from "node:path";
44353
+ import { existsSync as existsSync28 } from "node:fs";
44056
44354
  import { fileURLToPath as fileURLToPath14 } from "node:url";
44057
44355
 
44058
44356
  // src/mem7/worker-projection.ts
@@ -45107,6 +45405,8 @@ function startMem7Worker(config, fallback, options = {}) {
45107
45405
  let lastCheckpointMs = 0;
45108
45406
  let lastBackupCleanupMs = 0;
45109
45407
  let lastTopicChunksMs = Date.now() - 36e5 + 5 * 6e4;
45408
+ let lastOptimizeMs = Date.now() - 36e5 + 10 * 6e4;
45409
+ let retokenizeInFlight = false;
45110
45410
  const scanSchedule = createOpportunityScanSchedule(now2());
45111
45411
  const completedScanScopes = /* @__PURE__ */ new Set();
45112
45412
  const scan = async (store, busy = false) => {
@@ -45149,10 +45449,10 @@ function startMem7Worker(config, fallback, options = {}) {
45149
45449
  }
45150
45450
  if (!options.isBusy?.() && Date.now() - lastCheckpointMs >= 6e5) {
45151
45451
  lastCheckpointMs = Date.now();
45152
- const dbPath = join53(mem7Root(stateDir2), "index", "mem7.db");
45452
+ const dbPath = join55(mem7Root(stateDir2), "index", "mem7.db");
45153
45453
  const built = fileURLToPath14(new URL("./sqlite-maintenance-worker.mjs", import.meta.url));
45154
45454
  const source = fileURLToPath14(new URL("../mem7/sqlite-maintenance-worker.ts", import.meta.url));
45155
- const entry = existsSync26(built) ? built : source;
45455
+ const entry = existsSync28(built) ? built : source;
45156
45456
  execFile2(process.execPath, [...entry.endsWith(".ts") ? ["--import", "tsx"] : [], entry, "--sqlite-checkpoint", dbPath, stateDir2], { timeout: 18e4, windowsHide: true }, (error, stdout) => {
45157
45457
  if (error) console.warn(`[bg-worker] wal checkpoint \u8F85\u52A9\u8FDB\u7A0B\u5931\u8D25: ${error.message}`);
45158
45458
  else console.log(`[bg-worker] ${(stdout || "").trim()}`);
@@ -45166,12 +45466,12 @@ function startMem7Worker(config, fallback, options = {}) {
45166
45466
  const recoveredTurns = store.hostTurns.recoverInterrupted();
45167
45467
  if (recoveredTurns) console.log(`[bg-worker] abandoned host turns reconciled=${recoveredTurns}`);
45168
45468
  try {
45169
- const retention = await store.pruneTerminalJobData({ shouldRun: () => !stopping && !options.isBusy?.() && !intakePendingForDatabase(join53(mem7Root(stateDir2), "index", "mem7.db")) && !store.sources.scopes().some((scope) => store.sources.interpretationBatch(scope, 1).length > 0) });
45469
+ const retention = await store.pruneTerminalJobData({ shouldRun: () => !stopping && !options.isBusy?.() && !intakePendingForDatabase(join55(mem7Root(stateDir2), "index", "mem7.db")) && !store.sources.scopes().some((scope) => store.sources.interpretationBatch(scope, 1).length > 0) });
45170
45470
  if (retention.results || retention.payloads) console.log(`[bg-worker] job retention results=${retention.results} inputs=${retention.payloads} archived=${retention.archivedInputs} logicalBytes=${retention.bytesReclaimed}`);
45171
45471
  } catch (error) {
45172
45472
  console.warn(`[bg-worker] job retention deferred: ${error?.message ?? error}`);
45173
45473
  }
45174
- const backupCleanupAllowed = () => !stopping && !options.isBusy?.() && !intakePendingForDatabase(join53(mem7Root(stateDir2), "index", "mem7.db")) && !store.sources.scopes().some((scope) => store.sources.interpretationBatch(scope, 1).length > 0);
45474
+ const backupCleanupAllowed = () => !stopping && !options.isBusy?.() && !intakePendingForDatabase(join55(mem7Root(stateDir2), "index", "mem7.db")) && !store.sources.scopes().some((scope) => store.sources.interpretationBatch(scope, 1).length > 0);
45175
45475
  if (Date.now() - lastBackupCleanupMs >= 36e5 && backupCleanupAllowed()) {
45176
45476
  lastBackupCleanupMs = Date.now();
45177
45477
  try {
@@ -45182,6 +45482,26 @@ function startMem7Worker(config, fallback, options = {}) {
45182
45482
  }
45183
45483
  }
45184
45484
  if (Date.now() - lastTopicChunksMs >= 36e5 && backupCleanupAllowed()) {
45485
+ const { tokenizerMarkerCurrent: tokenizerMarkerCurrent2 } = await Promise.resolve().then(() => (init_mem7_retokenize(), mem7_retokenize_exports));
45486
+ const { foresightSettleDone: foresightSettleDone2 } = await Promise.resolve().then(() => (init_mem7_foresight_settle(), mem7_foresight_settle_exports));
45487
+ if ((!tokenizerMarkerCurrent2(stateDir2) || !foresightSettleDone2(stateDir2)) && !retokenizeInFlight) {
45488
+ retokenizeInFlight = true;
45489
+ lastTopicChunksMs = Date.now();
45490
+ void (async () => {
45491
+ try {
45492
+ const { retokenizeIfNeeded: retokenizeIfNeeded2 } = await Promise.resolve().then(() => (init_mem7_retokenize(), mem7_retokenize_exports));
45493
+ await retokenizeIfNeeded2({ stateDir: stateDir2, vectorStore: store.vectorStore(), log: (message) => console.log(message) });
45494
+ const { settleForesightRevalidation: settleForesightRevalidation2 } = await Promise.resolve().then(() => (init_mem7_foresight_settle(), mem7_foresight_settle_exports));
45495
+ await settleForesightRevalidation2({ stateDir: stateDir2, store, vectorStore: store.vectorStore(), log: (message) => console.log(message) });
45496
+ } catch (error) {
45497
+ console.warn(`[bg-worker] mem7 maintenance deferred: ${error?.message ?? error}`);
45498
+ } finally {
45499
+ retokenizeInFlight = false;
45500
+ }
45501
+ })();
45502
+ }
45503
+ }
45504
+ if (Date.now() - lastTopicChunksMs >= 36e5 && backupCleanupAllowed() && !retokenizeInFlight) {
45185
45505
  lastTopicChunksMs = Date.now();
45186
45506
  const workspace2 = String(config.get("workspace") ?? "");
45187
45507
  const topicsDir = workspace2 ? getAutoMemPath(workspace2) : "";
@@ -45203,6 +45523,15 @@ function startMem7Worker(config, fallback, options = {}) {
45203
45523
  }
45204
45524
  })();
45205
45525
  }
45526
+ if (Date.now() - lastOptimizeMs >= 36e5 && backupCleanupAllowed() && !retokenizeInFlight) {
45527
+ lastOptimizeMs = Date.now();
45528
+ try {
45529
+ const optimized = await store.vectorStore().optimizePending();
45530
+ if (optimized.length) console.log(`[bg-worker] mem7 optimized ${optimized.join(",")}`);
45531
+ } catch (error) {
45532
+ console.warn(`[bg-worker] mem7 optimize deferred: ${error?.message ?? error}`);
45533
+ }
45534
+ }
45206
45535
  const cleanupMs = Math.round(performance.now() - started);
45207
45536
  if (cleanupMs >= 1e3) console.log(`[bg-worker] cleanup ${cleanupMs}ms`);
45208
45537
  const agentName = mem7AgentName((key5) => config.get(key5));
@@ -45210,7 +45539,7 @@ function startMem7Worker(config, fallback, options = {}) {
45210
45539
  let relationshipGraph;
45211
45540
  if (config.get("mem7.relationshipCognition") !== false) {
45212
45541
  if (options.relationshipGraphPath) {
45213
- if (existsSync26(options.relationshipGraphPath)) {
45542
+ if (existsSync28(options.relationshipGraphPath)) {
45214
45543
  try {
45215
45544
  relationshipGraph = workerGraph(options.relationshipGraphPath, store).graph;
45216
45545
  relationshipGraph.ensureFresh();
@@ -45298,7 +45627,7 @@ function startMem7Worker(config, fallback, options = {}) {
45298
45627
  if (!store || !stateDir2 || config.get("mem7.enabled") !== true) return;
45299
45628
  try {
45300
45629
  if (physicalMaintenance?.running()) {
45301
- if (!intakePendingForDatabase(join53(mem7Root(stateDir2), "index", "mem7.db"))) return;
45630
+ if (!intakePendingForDatabase(join55(mem7Root(stateDir2), "index", "mem7.db"))) return;
45302
45631
  await physicalMaintenance.interrupt();
45303
45632
  }
45304
45633
  const applied = drainIntakeSpool(stateDir2, store, 50);
@@ -45306,10 +45635,10 @@ function startMem7Worker(config, fallback, options = {}) {
45306
45635
  await physicalMaintenance?.interrupt();
45307
45636
  void pipeline.tick();
45308
45637
  }
45309
- if (!activeStore && !options.isBusy?.() && !intakePendingForDatabase(join53(mem7Root(stateDir2), "index", "mem7.db"))) {
45638
+ if (!activeStore && !options.isBusy?.() && !intakePendingForDatabase(join55(mem7Root(stateDir2), "index", "mem7.db"))) {
45310
45639
  const retired = store.retireGraphPlanAuditsBatch();
45311
45640
  if (retired.plans) console.log(`[bg-worker] unused graph audits retired=${retired.plans}`);
45312
- await store.pruneTerminalJobData({ shouldRun: () => !stopping && !options.isBusy?.() && !activeStore && !intakePendingForDatabase(join53(mem7Root(stateDir2), "index", "mem7.db")) });
45641
+ await store.pruneTerminalJobData({ shouldRun: () => !stopping && !options.isBusy?.() && !activeStore && !intakePendingForDatabase(join55(mem7Root(stateDir2), "index", "mem7.db")) });
45313
45642
  }
45314
45643
  } catch (error) {
45315
45644
  console.warn(`[bg-worker] intake service failed: ${error?.message ?? error}`);
@@ -45463,7 +45792,7 @@ async function runWorkerOpportunityScan(config, store, graphPath, fallback, comp
45463
45792
  const { provider, model } = resolveWorkerModel(config, config.get("proactive.model")) ?? fallback();
45464
45793
  const { persist, graph } = workerGraph(graphPath, store);
45465
45794
  graph.ensureFresh();
45466
- const workspace2 = dirname27(dirname27(graphPath));
45795
+ const workspace2 = dirname29(dirname29(graphPath));
45467
45796
  if (!store) {
45468
45797
  if (completedScopes.has("legacy")) return 0;
45469
45798
  const count = await runOpportunityScan({
@@ -45705,7 +46034,7 @@ var relationshipGraphPath = graphFlag >= 0 ? resolve25(args[graphFlag + 1]) : vo
45705
46034
  var mainFlag = args.indexOf("--main-model");
45706
46035
  var mainModelRef = mainFlag >= 0 ? args[mainFlag + 1] : void 0;
45707
46036
  var workspaceFlag = args.indexOf("--workspace");
45708
- if (!configPath || !existsSync34(configPath)) {
46037
+ if (!configPath || !existsSync36(configPath)) {
45709
46038
  console.error("[bg-worker] usage: node dist/bg-worker.mjs --engine-config <path>");
45710
46039
  process.exit(1);
45711
46040
  }