engine7 7.1.153 → 7.1.154

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1315,9 +1315,8 @@ 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
- literalQueryNeedles: () => literalQueryNeedles,
1320
- queryBigramNeedles: () => queryBigramNeedles,
1321
1320
  tokenize: () => tokenize,
1322
1321
  tokenizeCjk: () => tokenizeCjk,
1323
1322
  tokenizeToField: () => tokenizeToField
@@ -1329,7 +1328,7 @@ function engine() {
1329
1328
  return jieba;
1330
1329
  }
1331
1330
  function tokenize(text2) {
1332
- const raw = engine().cutForSearch(String(text2 ?? ""));
1331
+ const raw = engine().cutForSearch(String(text2 ?? ""), true);
1333
1332
  const out = [];
1334
1333
  for (const t of raw) {
1335
1334
  const tok = t.trim().toLowerCase();
@@ -1352,22 +1351,7 @@ function cjkBigrams(text2) {
1352
1351
  function tokenizeCjk(text2) {
1353
1352
  return [...tokenize(text2), ...cjkBigrams(text2)];
1354
1353
  }
1355
- function invisibleCjkNeedles(candidates) {
1356
- return [...new Set(candidates.map((token) => token.trim()))].filter((token) => /^[\u4e00-\u9fff]{2,}$/.test(token) && tokenize(token).length === 0).slice(0, 8);
1357
- }
1358
- function literalQueryNeedles(text2) {
1359
- const chars = shortCjkCharCount(text2);
1360
- if (!chars || chars > 6) return null;
1361
- const names = invisibleCjkNeedles(engine().cut(String(text2 ?? ""), true));
1362
- return names.length ? names : queryBigramNeedles(text2);
1363
- }
1364
- function queryBigramNeedles(text2) {
1365
- const chars = shortCjkCharCount(text2);
1366
- if (!chars || chars > 6) return null;
1367
- const grams = [...new Set(cjkBigrams(text2))].slice(0, 8);
1368
- return grams.length ? grams : null;
1369
- }
1370
- var DEFAULT_STOPWORDS, MIN_TOKEN_LENGTH, jieba, shortCjkCharCount;
1354
+ var DEFAULT_STOPWORDS, MIN_TOKEN_LENGTH, TOKENIZER_VERSION, jieba;
1371
1355
  var init_tokenizer = __esm({
1372
1356
  "src/mem7/core/tokenizer.ts"() {
1373
1357
  "use strict";
@@ -1439,8 +1423,8 @@ var init_tokenizer = __esm({
1439
1423
  "\u54E6"
1440
1424
  ]);
1441
1425
  MIN_TOKEN_LENGTH = 2;
1426
+ TOKENIZER_VERSION = 2;
1442
1427
  jieba = null;
1443
- shortCjkCharCount = (text2) => (String(text2 ?? "").match(/[\u4e00-\u9fff]/g) ?? []).length;
1444
1428
  }
1445
1429
  });
1446
1430
 
@@ -2714,6 +2698,10 @@ function invalidateChildren(db2, scope, pending2, reason) {
2714
2698
  if (!referencedPlan.get(scope, child.child_id, scope, child.child_id)) continue;
2715
2699
  }
2716
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
+ }
2717
2705
  db2.prepare(`UPDATE memory_derivations SET state=?,reason=?,updated_at=?
2718
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);
2719
2707
  result.push(child.child_id);
@@ -2942,12 +2930,14 @@ var init_dependencies = __esm({
2942
2930
  return false;
2943
2931
  }
2944
2932
  }
2945
- dirty(scope) {
2933
+ /** excludeKinds:没有重验消费者的类别不计入(1203:foresight,1015 起不做周期重验,见 invalidateChildren)。 */
2934
+ dirty(scope, options = {}) {
2946
2935
  return this.readTransaction(() => {
2947
2936
  checkMemoryReadBudget();
2948
2937
  const memo = /* @__PURE__ */ new Map();
2949
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) => {
2950
2939
  checkMemoryReadBudget();
2940
+ if (options.excludeKinds?.has(row.child_kind)) return false;
2951
2941
  return row.state === "needs_revalidation" || !this.artifactTimeCurrent(scope, row.child_kind, row.child_id, /* @__PURE__ */ new Set(), memo);
2952
2942
  }).map((row) => ({
2953
2943
  kind: row.child_kind,
@@ -2957,6 +2947,20 @@ var init_dependencies = __esm({
2957
2947
  }));
2958
2948
  });
2959
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
+ }
2960
2964
  invalidate(scope, kind, id, expectedVersion, reason) {
2961
2965
  this.transaction(() => {
2962
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);
@@ -3265,6 +3269,18 @@ function loadArrow() {
3265
3269
  }
3266
3270
  return arrowPromise;
3267
3271
  }
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;
3283
+ }
3268
3284
  function buildSchemas(arrow) {
3269
3285
  const vecField = () => new arrow.Field("vector", new arrow.FixedSizeList(VECTOR_DIM, new arrow.Field("item", new arrow.Float32(), true)), true);
3270
3286
  const commonFields = () => [
@@ -3361,7 +3377,7 @@ function textColumnOf(kind) {
3361
3377
  return "fact";
3362
3378
  }
3363
3379
  }
3364
- 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;
3365
3381
  var init_vector_store = __esm({
3366
3382
  "src/mem7/core/vector-store.ts"() {
3367
3383
  "use strict";
@@ -3392,14 +3408,14 @@ var init_vector_store = __esm({
3392
3408
  agent_case: ["task_intent_tokens", "approach_tokens"],
3393
3409
  agent_skill: ["description_tokens", "content_tokens"]
3394
3410
  };
3395
- BM25_TEXT_FIELDS = {
3396
- foresight: ["foresight", "evidence"],
3397
- episode: ["episode"],
3398
- atomic_fact: ["fact"],
3399
- agent_case: ["task_intent", "approach"],
3400
- 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"]]
3401
3417
  };
3402
- sqlLiteral = (value) => value.replace(/'/g, "''");
3418
+ TIMESTAMP_COLUMNS = /* @__PURE__ */ new Set(["created_at", "updated_at", "timestamp", "start_time", "end_time"]);
3403
3419
  RRF_K = 60;
3404
3420
  warnedFts = /* @__PURE__ */ new Set();
3405
3421
  warnedVecIdx = /* @__PURE__ */ new Set();
@@ -3421,6 +3437,8 @@ var init_vector_store = __esm({
3421
3437
  vectorIndexChecks = /* @__PURE__ */ new Map();
3422
3438
  vectorIndexRechecks = /* @__PURE__ */ new Set();
3423
3439
  vectorIndexesReady = /* @__PURE__ */ new Set();
3440
+ /** 自上次 optimize 后有写入的表(bg-worker 每小时收一次,见 optimizePending) */
3441
+ unoptimized = /* @__PURE__ */ new Set();
3424
3442
  ledger = null;
3425
3443
  ledgerPath;
3426
3444
  withProofSnapshot = (operation) => {
@@ -3800,10 +3818,25 @@ var init_vector_store = __esm({
3800
3818
  assertRuntimeAuthority(this.stateDir, "WRITE");
3801
3819
  validate?.();
3802
3820
  await tbl.add(mapped);
3821
+ this.unoptimized.add(kind);
3803
3822
  assertRuntimeAuthority(this.stateDir, "WRITE");
3804
3823
  validate?.();
3805
3824
  void this.ensureVectorIndexes(kind, tbl, true);
3806
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
+ }
3807
3840
  /**
3808
3841
  * 按 id upsert(everos repo.upsert 语义,1004 read 侧):digest 相同 → 跳过(不重嵌
3809
3842
  * 不重写,everos cascade 的 content_sha256 diff-skip);digest 变了 → 删旧行再插新。
@@ -3824,6 +3857,7 @@ var init_vector_store = __esm({
3824
3857
  assertRuntimeAuthority(this.stateDir, "WRITE");
3825
3858
  validate?.();
3826
3859
  await tbl.delete(`id = '${r.id.replace(/'/g, "''")}'`);
3860
+ this.unoptimized.add(kind);
3827
3861
  assertRuntimeAuthority(this.stateDir, "WRITE");
3828
3862
  validate?.();
3829
3863
  await this.insert(kind, [r], validate);
@@ -3843,6 +3877,49 @@ var init_vector_store = __esm({
3843
3877
  return null;
3844
3878
  }
3845
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
+ }
3846
3923
  /** KNN(lancedb vectorSearch:cosine 距离,score=1-distance) */
3847
3924
  async readVisibleCandidates(kind, limit, query, method = "scan") {
3848
3925
  let count = Math.max(1, limit);
@@ -3997,47 +4074,6 @@ var init_vector_store = __esm({
3997
4074
  if (!cur || score > Number(cur._score ?? 0)) best.set(rid, r);
3998
4075
  }
3999
4076
  }
4000
- const textCols = BM25_TEXT_FIELDS[kind];
4001
- const scan = async (terms, op, limit) => {
4002
- const expr = op === "AND" ? terms.map((g) => `(${textCols.map((col) => `contains(${col}, '${sqlLiteral(g)}')`).join(" OR ")})`).join(" AND ") : textCols.map((col) => `(${terms.map((g) => `contains(${col}, '${sqlLiteral(g)}')`).join(" OR ")})`).join(" OR ");
4003
- const where2 = compileFilter(opts.filter);
4004
- return await tbl.query().where(where2 ? `(${where2}) AND (${expr})` : expr).limit(limit).toArray();
4005
- };
4006
- const maxScore = [...best.values()].reduce((max, r) => Math.max(max, Number(r._score ?? 0)), 0);
4007
- const scoreLiteral = (needles2, rows) => {
4008
- const terms = [.../* @__PURE__ */ new Set([...needles2, ...tokenizeToField(queryText).split(/\s+/).filter(Boolean)])];
4009
- const occurrences2 = (text2, term) => text2.split(term).length - 1;
4010
- for (const r of rows) {
4011
- const rid = String(r.id ?? "");
4012
- if (!rid) continue;
4013
- const text2 = textCols.map((col) => String(r[col] ?? "")).join(" ");
4014
- const matched = terms.filter((term) => text2.includes(term));
4015
- if (!matched.length || matched.every((term) => !needles2.includes(term))) continue;
4016
- const full = matched.length === terms.length;
4017
- const density = matched.reduce((sum, term) => sum + occurrences2(text2, term), 0) / Math.max(text2.length, 1) * 1e3;
4018
- const score = full ? maxScore + 1 + Math.min(0.99, density / 10) : maxScore > 0 ? maxScore * (0.5 + 0.5 * matched.length / terms.length) : matched.length / terms.length;
4019
- const cur = best.get(rid);
4020
- if (cur) {
4021
- if (full) cur._score = Math.max(Number(cur._score ?? 0), score);
4022
- } else best.set(rid, { ...r, _score: score });
4023
- }
4024
- };
4025
- const needles = literalQueryNeedles(queryText);
4026
- if (needles) {
4027
- try {
4028
- const terms = [.../* @__PURE__ */ new Set([...needles, ...tokenizeToField(queryText).split(/\s+/).filter(Boolean)])];
4029
- const [all, any] = await Promise.all([
4030
- terms.length > 1 ? scan(terms, "AND", topK * 10) : Promise.resolve([]),
4031
- scan(needles, "OR", topK * 3)
4032
- ]);
4033
- scoreLiteral(needles, [...all, ...any]);
4034
- if (![...best.values()].some((r) => Number(r._score ?? 0) > maxScore)) {
4035
- const bigrams = [...new Set(needles.flatMap((name) => queryBigramNeedles(name) ?? []))].slice(0, 8);
4036
- if (bigrams.length && JSON.stringify(bigrams) !== JSON.stringify(needles)) scoreLiteral(bigrams, await scan(bigrams, "OR", topK * 3));
4037
- }
4038
- } catch {
4039
- }
4040
- }
4041
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) }));
4042
4078
  } catch (err) {
4043
4079
  const msg2 = String(err?.message ?? err);
@@ -16741,7 +16777,7 @@ function buildMemoryContext(store, scope, request, clock = () => (/* @__PURE__ *
16741
16777
  historicalFacts: [],
16742
16778
  ...request.includeProjectionStatus === false ? {} : { projections: {
16743
16779
  pendingJobs: store.jobStatus(scope).filter((job) => ["pending", "running", "failed"].includes(job.state)).length,
16744
- dirtyArtifacts: store.dependencies.dirty(scope).length,
16780
+ dirtyArtifacts: store.dependencies.dirty(scope, { excludeKinds: NO_REVALIDATION_KINDS }).length,
16745
16781
  ...cutoff ? { asOf: "current" } : {}
16746
16782
  } },
16747
16783
  futureChanges: [],
@@ -17034,6 +17070,7 @@ function attachHistoricalEvidence(store, scope, context, request, episodes) {
17034
17070
  });
17035
17071
  return boundMemoryContext(context, request.maxTokens ?? 3e3);
17036
17072
  }
17073
+ var NO_REVALIDATION_KINDS;
17037
17074
  var init_context = __esm({
17038
17075
  "src/mem7/core/context.ts"() {
17039
17076
  "use strict";
@@ -17046,6 +17083,7 @@ var init_context = __esm({
17046
17083
  init_relationship_context();
17047
17084
  init_read_budget();
17048
17085
  init_fit_prefix();
17086
+ NO_REVALIDATION_KINDS = /* @__PURE__ */ new Set(["foresight"]);
17049
17087
  }
17050
17088
  });
17051
17089
 
@@ -24612,7 +24650,7 @@ async function runProactiveCycle(deps, now2) {
24612
24650
  function normalizeTitle(title) {
24613
24651
  return title.replace(/Research: /g, "").replace(/Execute: /g, "").replace(/提醒|记得|跟进|确认一下|处理一下|去/g, "").replace(/[\s,。!?、,::;;()()\[\]]+/g, "").trim().toLowerCase();
24614
24652
  }
24615
- function titlesOverlap(a, b) {
24653
+ function titlesOverlap(a, b, minRatio = 0.6) {
24616
24654
  if (!a || !b) return false;
24617
24655
  if (a.length >= 4 && b.includes(a)) return true;
24618
24656
  if (b.length >= 4 && a.includes(b)) return true;
@@ -24620,9 +24658,10 @@ function titlesOverlap(a, b) {
24620
24658
  const ga = grams(a);
24621
24659
  const gb = grams(b);
24622
24660
  if (ga.size === 0 || gb.size === 0) return false;
24661
+ if (Math.min(ga.size, gb.size) <= 2) return false;
24623
24662
  let common = 0;
24624
24663
  for (const g of ga) if (gb.has(g)) common++;
24625
- return common / Math.min(ga.size, gb.size) >= 0.6;
24664
+ return common / Math.min(ga.size, gb.size) >= minRatio;
24626
24665
  }
24627
24666
  var PRIORITY_SCORES, IntentSelector, ActionAgent;
24628
24667
  var init_intent = __esm({
@@ -24818,351 +24857,58 @@ var init_intent = __esm({
24818
24857
  }
24819
24858
  });
24820
24859
 
24821
- // src/memory/proactive/sweep.ts
24822
- import { readFileSync as readFileSync24 } from "node:fs";
24823
- function sharesTerm(a, b) {
24824
- const x = normalizeTitle(a);
24825
- const y = normalizeTitle(b);
24826
- if (x.length < 2 || y.length < 2) return false;
24827
- const grams = new Set(Array.from({ length: x.length - 1 }, (_, i) => x.slice(i, i + 2)));
24828
- for (let i = 0; i < y.length - 1; i++) if (grams.has(y.slice(i, i + 2))) return true;
24829
- return false;
24830
- }
24831
- function isSameCommitment(a, b) {
24832
- const x = normalizeTitle(a);
24833
- const y = normalizeTitle(b);
24834
- if (!x || !y) return false;
24835
- if (x === y) return true;
24836
- if (x.length >= 4 && y.includes(x)) return true;
24837
- if (y.length >= 4 && x.includes(y)) return true;
24838
- 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)}` : ""}`);
24839
24866
  }
24840
- function guardVerdict(value) {
24841
- if (typeof value === "boolean") return { ok: value, reason: value ? "" : "GUARD_REJECTED" };
24842
- 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}`);
24843
24873
  }
24844
- function actionPayload(a, now2, recentEvidence) {
24845
- let suggestedTask = null;
24846
- let scheduledLocal = null;
24847
- try {
24848
- const { dateStr, timeExact } = toCalendarWallParts(a.scheduledTime);
24849
- suggestedTask = { date: dateStr, time: timeExact };
24850
- scheduledLocal = formatForLlm(a.scheduledTime);
24851
- } catch {
24852
- }
24853
- let generatedLocal = null;
24854
- try {
24855
- generatedLocal = a.createdAt ? formatForLlm(a.createdAt) : null;
24856
- } 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;
24857
24885
  }
24858
- const ageHours = (now2.getTime() - Date.parse(a.scheduledTime)) / 36e5;
24859
- 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;
24860
- return {
24861
- action_id: a.id,
24862
- action_version: a.actionVersion,
24863
- intent_id: a.intentId,
24864
- title: a.title,
24865
- description: a.description,
24866
- scheduled_time: a.scheduledTime,
24867
- // UTC 绝对时刻(机器坐标)
24868
- scheduled_time_local: scheduledLocal,
24869
- // 本地可读 —— 与上一行是同一个时刻,别当两件事
24870
- suggested_task: suggestedTask,
24871
- // { date, time } 本地墙上时间,calendar add-task 参数
24872
- urgency: a.urgency,
24873
- duration_minutes: a.durationMinutes,
24874
- calendar_id: a.calendarId,
24875
- status: a.status,
24876
- generated_at_local: generatedLocal,
24877
- // 这条 action 是**几点生成的**(正文里的「现在」指这个点)
24878
- stale_hint: staleHint,
24879
- // 0906 anti-hindsight:近期关联证据(最新在前)——"后续对话已做完"的马后炮当场现形。
24880
- // 时间戳走 formatShort(本地);此前是 createdAt.slice(5,16) —— 那是 **UTC**,
24881
- // 混在 suggested_task(本地)旁边且无标注。
24882
- recent_evidence: recentEvidence && recentEvidence.length > 0 ? recentEvidence.map((e) => `[${formatShort(e.createdAt)}] ${e.title}${e.description ? `\uFF1A${e.description}` : ""}`) : void 0,
24883
- // 机械可判的过期事实标记(不靠 LLM):action 创建之后 graph 又来了新证据 →
24884
- // action 基于过期事实生成,先核对新证据再决定(生成侧 Time-Evidence Gate 的兜底)
24885
- 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,
24886
- _received_at: now2.toISOString()
24887
- };
24886
+ return lines;
24888
24887
  }
24889
- var BACKLOG_ALERT_RUNS, STALE_HINT_HOURS, DEFAULT_PROMPT, TRANSIENT_GUARD_REASONS, DUE_PAGE_SIZE, DUE_MAX_PAGES, transientGuardLogged, Sweep;
24890
- var init_sweep = __esm({
24891
- "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"() {
24892
24897
  "use strict";
24893
- init_calendar_bridge();
24894
- init_intent();
24895
- init_clock();
24896
- BACKLOG_ALERT_RUNS = 12;
24897
- STALE_HINT_HOURS = 8;
24898
- DEFAULT_PROMPT = `[proactive] \u6709 action \u5230\u671F\u4E86\u3002\u5904\u7406\u89C4\u5219\uFF1A
24899
-
24900
- 1. **\u5FC5\u987B\u8C03\u5DE5\u5177\u843D\u72B6\u6001**\uFF08\u786C\u8981\u6C42\uFF0C\u4E0D\u662F\u5EFA\u8BAE\uFF09\uFF1A
24901
- - \u5904\u7406\u5B8C \u2192 \`proactive_done\`\uFF08action_id\uFF0C\u843D\u8FDB\u65E5\u5386\u65F6\u5E26 calendar_id\uFF09
24902
- - \u8DF3\u8FC7 \u2192 \`proactive_cancel\`\uFF08action_id + reason\uFF09
24903
- \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
24904
- \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
24905
- 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
24906
- 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
24907
- \u26A0\uFE0F \u6CA1\u6709 notified\u3001\u6CA1\u6709 skipped
24908
- 4. **\u91CD\u590D\u68C0\u6D4B**\uFF1A\u591A\u6761 title \u9AD8\u5EA6\u76F8\u4F3C\u65F6\u53EA\u5904\u7406\u4E00\u6761\uFF0C\u5176\u4F59 cancelled
24909
- 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
24910
- \u62FF \`generated_at_local\` \u8DDF \`_received_at\` \u5BF9\u4E00\u4E0B\uFF1B\u518D\u8DDF calendar/goal \u91CC\u5DF2\u6709\u7684\u5BF9\u4E00\u904D\u3002
24911
- 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
24912
- 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`;
24913
- TRANSIENT_GUARD_REASONS = /* @__PURE__ */ new Set(["MEMORY_GUARD_UNAVAILABLE", "ACTION_DELIVERY_UNKNOWN", "CALENDAR_DELIVERY_UNKNOWN", "MEMORY_SCHEMA_UNSUPPORTED", "EXECUTION_CONTEXT_INVALID"]);
24914
- DUE_PAGE_SIZE = 20;
24915
- DUE_MAX_PAGES = 5;
24916
- transientGuardLogged = /* @__PURE__ */ new Set();
24917
- Sweep = class {
24918
- constructor(deps, intervalMs = 3e5) {
24919
- this.deps = deps;
24920
- this.intervalMs = intervalMs;
24921
- }
24922
- timer = null;
24923
- /** executing 连续增长的轮数(对账告警用) */
24924
- backlogStreak = 0;
24925
- lastExecuting = 0;
24926
- start() {
24927
- if (this.timer) return;
24928
- this.runOnce(/* @__PURE__ */ new Date());
24929
- this.timer = setInterval(() => {
24930
- try {
24931
- this.runOnce(/* @__PURE__ */ new Date());
24932
- } catch (err) {
24933
- console.warn(`[proactive] sweep error: ${err.message}`);
24934
- }
24935
- }, this.intervalMs);
24936
- this.timer.unref?.();
24937
- }
24938
- stop() {
24939
- if (this.timer) {
24940
- clearInterval(this.timer);
24941
- this.timer = null;
24942
- }
24943
- }
24944
- isRunning() {
24945
- return this.timer !== null;
24946
- }
24947
- /** 单轮:收割超时 executing → due → 标记 → 合并注入一次。返回注入条数 */
24948
- runOnce(now2) {
24949
- const closed = this.deps.persist.settleBlockedHostActions(now2.toISOString());
24950
- if (closed) console.log(`[proactive] closed ${closed} blocked action(s) before dispatch`);
24951
- if (this.deps.durableSubmit) for (const item of this.deps.persist.hostDeliveries.pending()) {
24952
- try {
24953
- this.deps.durableSubmit(item.blocks, item.context, item.key);
24954
- } catch (error) {
24955
- console.warn(`[proactive] host delivery remains pending: ${error.message}`);
24956
- }
24957
- }
24958
- const reaped = this.deps.persist.reapStaleExecuting(now2.toISOString(), this.deps.staleHours ?? 36);
24959
- if (reaped > 0) console.log(`[proactive] reaped ${reaped} stale executing action(s)`);
24960
- const execNow = this.deps.persist.countByStatus("executing");
24961
- if (execNow > 0 && execNow >= this.lastExecuting) this.backlogStreak++;
24962
- else this.backlogStreak = 0;
24963
- this.lastExecuting = execNow;
24964
- if (this.backlogStreak >= BACKLOG_ALERT_RUNS) {
24965
- this.backlogStreak = 0;
24966
- try {
24967
- this.deps.onUnclosedBacklog?.(execNow);
24968
- } catch (err) {
24969
- console.warn(`[proactive] backlog alert failed: ${err.message}`);
24970
- }
24971
- }
24972
- const nowIso2 = now2.toISOString();
24973
- const gatedItems = [];
24974
- const gateOff = (a, reason) => {
24975
- gatedItems.push({ id: a.id, title: a.title, reason, version: a.actionVersion });
24976
- return false;
24977
- };
24978
- const seen = /* @__PURE__ */ new Set();
24979
- let due = [];
24980
- for (let page = 0; page < DUE_MAX_PAGES; page++) {
24981
- const batch = this.deps.persist.dueActions(nowIso2, DUE_PAGE_SIZE, [...seen]);
24982
- for (const action of batch) {
24983
- seen.add(action.id);
24984
- if (!this.deps.checkAction) {
24985
- due.push(action);
24986
- continue;
24987
- }
24988
- const verdict = guardVerdict(this.deps.checkAction(action));
24989
- if (verdict.ok) {
24990
- due.push(action);
24991
- continue;
24992
- }
24993
- if (TRANSIENT_GUARD_REASONS.has(verdict.reason)) {
24994
- const signature2 = `${action.id}:${verdict.reason}`;
24995
- if (!transientGuardLogged.has(signature2)) {
24996
- transientGuardLogged.add(signature2);
24997
- 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}`);
24998
- }
24999
- continue;
25000
- }
25001
- gateOff(action, `\u6295\u9012\u524D\u5B88\u536B\uFF1A${verdict.reason}`);
25002
- }
25003
- if (batch.length < DUE_PAGE_SIZE || due.length >= DUE_PAGE_SIZE) break;
25004
- }
25005
- if (due.length === 0 && gatedItems.length === 0) return 0;
25006
- const opportunityGroups = [];
25007
- for (const action of due.filter((item) => item.scopeId && item.provenance?.decisionType === "opportunity")) {
25008
- const matches2 = opportunityGroups.filter((group) => group.some((item) => item.scopeId === action.scopeId && isSameCommitment(item.title, action.title)));
25009
- const joined = [action, ...matches2.flat()];
25010
- opportunityGroups.splice(0, opportunityGroups.length, ...opportunityGroups.filter((group) => !matches2.includes(group)), joined);
25011
- }
25012
- 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)));
25013
- due = due.filter((action) => {
25014
- if (!duplicates.has(action.id)) return true;
25015
- this.deps.persist.updateActionStatus(action.id, "cancelled", {
25016
- completedAt: now2.toISOString(),
25017
- cancelReason: "duplicate_opportunity",
25018
- expectedActionVersion: action.actionVersion
25019
- });
25020
- return false;
25021
- });
25022
- const resolvedActions = [];
25023
- due = due.filter((a) => {
25024
- const intentStatus = this.deps.persist.getIntentStatus(a.intentId);
25025
- if (intentStatus === "resolved" || intentStatus === "rejected" || intentStatus === "deferred" || intentStatus === "expired") {
25026
- resolvedActions.push({ id: a.id, intentStatus, version: a.actionVersion });
25027
- return false;
25028
- }
25029
- return true;
25030
- });
25031
- if (resolvedActions.length > 0) {
25032
- for (const { id, intentStatus, version } of resolvedActions) {
25033
- this.deps.persist.updateActionStatus(id, "cancelled", {
25034
- completedAt: now2.toISOString(),
25035
- cancelReason: `intent ${intentStatus}\u2014\u2014R2 sweep \u518D\u9A8C\u8BC1`,
25036
- expectedActionVersion: version
25037
- });
25038
- }
25039
- console.log(`[proactive] R2: ${resolvedActions.length} due action(s) cancelled (intent resolved)`);
25040
- }
25041
- const coveredTitles = this.deps.coveredTitles ?? [];
25042
- const coveredEvents = this.deps.coveredEvents ?? [];
25043
- if (coveredTitles.length > 0 || coveredEvents.length > 0) {
25044
- due = due.filter((a) => {
25045
- if (coveredTitles.some((c) => isSameCommitment(a.title, c))) {
25046
- return gateOff(a, "calendar/goal \u91CC\u5DF2\u7ECF\u6709\u540C\u4E00\u4EF6\u4E8B\u2014\u2014\u4E0D\u91CD\u590D\u63D0\u9192");
25047
- }
25048
- const parts = toCalendarWallParts(a.scheduledTime);
25049
- const sameMoment = coveredEvents.some((ev) => ev.date === parts.dateStr && ev.time === parts.timeExact);
25050
- if (sameMoment && coveredEvents.some((ev) => ev.date === parts.dateStr && ev.time === parts.timeExact && sharesTerm(a.title, ev.title))) {
25051
- 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");
25052
- }
25053
- return true;
25054
- });
25055
- }
25056
- const minLeadDays = this.deps.minLeadDays ?? 0;
25057
- if (minLeadDays > 0) {
25058
- const repeatGapDays = this.deps.repeatGapDays ?? 0;
25059
- let injectedHistory = null;
25060
- const loadHistory = () => {
25061
- if (injectedHistory === null) injectedHistory = this.deps.persist.listInjectedTitlesSince(now2.getTime() - 30 * 864e5);
25062
- return injectedHistory;
25063
- };
25064
- due = due.filter((a) => {
25065
- if (a.provenance?.decisionType === "opportunity") return true;
25066
- const leadMs = Date.parse(a.scheduledTime) - Date.parse(a.createdAt);
25067
- if (leadMs >= minLeadDays * 864e5) return true;
25068
- if (repeatGapDays > 0) {
25069
- const lastSame = loadHistory().filter((h) => sharesTerm(a.title, h.title)).reduce((mx, h) => Math.max(mx, h.injectedAt), 0);
25070
- if (lastSame > 0 && now2.getTime() - lastSame >= repeatGapDays * 864e5) {
25071
- 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`);
25072
- return true;
25073
- }
25074
- }
25075
- 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`);
25076
- });
25077
- }
25078
- for (const g of gatedItems) {
25079
- this.deps.persist.updateActionStatus(g.id, "cancelled", {
25080
- completedAt: now2.toISOString(),
25081
- cancelReason: g.reason,
25082
- expectedActionVersion: g.version
25083
- });
25084
- }
25085
- if (gatedItems.length > 0) {
25086
- console.log(`[proactive] gated ${gatedItems.length} action(s): ${gatedItems.map((g) => g.reason.slice(0, 12)).join(" / ")}`);
25087
- try {
25088
- this.deps.onGated?.(gatedItems);
25089
- } catch (err) {
25090
- console.warn(`[proactive] onGated failed: ${err.message}`);
25091
- }
25092
- }
25093
- if (due.length === 0) return 0;
25094
- due = due.flatMap((act) => this.deps.persist.transaction(() => {
25095
- if (!this.deps.persist.markActionReminded(act.id, now2.toISOString(), act.actionVersion)) return [];
25096
- const captured = this.deps.persist.getAction(act.id);
25097
- if (captured.scopeId && this.deps.durableSubmit) {
25098
- const context = this.executionContext([captured]);
25099
- this.deps.persist.hostDeliveries.enqueue(captured.id, captured.actionVersion, this.blocks([captured], now2), context);
25100
- }
25101
- return [captured];
25102
- }));
25103
- if (due.length === 0) return 0;
25104
- const groups = /* @__PURE__ */ new Map();
25105
- for (const action of due) {
25106
- const key5 = action.scopeId ? `${action.scopeId}:${action.id}` : "";
25107
- groups.set(key5, [...groups.get(key5) ?? [], action]);
25108
- }
25109
- let injected = 0;
25110
- for (const captured of groups.values()) {
25111
- const blocks = this.blocks(captured, now2);
25112
- const context = this.executionContext(captured);
25113
- let delivered = false;
25114
- const durable = Boolean(context && this.deps.durableSubmit);
25115
- try {
25116
- delivered = durable ? this.deps.durableSubmit(blocks, context, JSON.stringify(["proactive", captured[0].id, captured[0].actionVersion])) : this.deps.submit(blocks, context);
25117
- } catch (error) {
25118
- console.warn(`[proactive] injection failed: ${error.message}`);
25119
- }
25120
- if (delivered) injected += captured.length;
25121
- else if (!durable) {
25122
- const back = this.deps.persist.rollbackReminded(captured.map((a) => a.id));
25123
- console.warn(`[proactive] injection dropped \u2014 rolled back ${back} action(s) to queued`);
25124
- }
25125
- }
25126
- if (injected) console.log(`[proactive] injected ${injected} due action(s) to main session`);
25127
- return injected;
25128
- }
25129
- executionContext(actions) {
25130
- const scopeId2 = actions[0]?.scopeId;
25131
- return scopeId2 ? {
25132
- scopeId: scopeId2,
25133
- basisRefs: actions.flatMap((action) => action.basisRefs ?? []),
25134
- actionVersions: Object.fromEntries(actions.map((action) => [action.id, action.actionVersion]))
25135
- } : void 0;
25136
- }
25137
- blocks(actions, now2) {
25138
- const payload = actions.map((action) => actionPayload(action, now2, this.deps.persist.getIntentRecentEvents(action.intentId)));
25139
- return [
25140
- { type: "text", text: `## Actions (${payload.length} \u4E2A)
25141
-
25142
- \`\`\`json
25143
- ${JSON.stringify(payload)}
25144
- \`\`\`` },
25145
- { type: "text", text: this.loadPrompt() }
25146
- ];
25147
- }
25148
- /** 处理规则现读(改了不用重启);文件缺失/读失败用内置 */
25149
- loadPrompt() {
25150
- const file2 = this.deps.promptFile;
25151
- if (!file2) return DEFAULT_PROMPT;
25152
- try {
25153
- const text2 = readFileSync24(file2, "utf8").trim();
25154
- return text2 || DEFAULT_PROMPT;
25155
- } catch {
25156
- return DEFAULT_PROMPT;
25157
- }
25158
- }
24898
+ dayKey = (iso) => {
24899
+ const ms = Date.parse(iso);
24900
+ return Number.isFinite(ms) ? new Date(ms).toISOString().slice(5, 10) : "";
25159
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"]);
25160
24906
  }
25161
24907
  });
25162
24908
 
25163
24909
  // src/memory/proactive/opportunity.ts
25164
24910
  import { setImmediate as yieldToEventLoop2 } from "node:timers/promises";
25165
- 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";
25166
24912
  import { join as join29, relative as relative5 } from "node:path";
25167
24913
  import { DatabaseSync as DatabaseSync12 } from "node:sqlite";
25168
24914
  import { createHash as createHash32 } from "node:crypto";
@@ -25352,7 +25098,7 @@ function parseForesightEntries(everosRoot, now2, userId) {
25352
25098
  let content;
25353
25099
  let bytes2;
25354
25100
  try {
25355
- bytes2 = readFileSync25(file2);
25101
+ bytes2 = readFileSync24(file2);
25356
25102
  content = bytes2.toString("utf8");
25357
25103
  } catch {
25358
25104
  continue;
@@ -25360,7 +25106,7 @@ function parseForesightEntries(everosRoot, now2, userId) {
25360
25106
  const fileDigest = createHash32("sha256").update(bytes2).digest("hex");
25361
25107
  const assertCurrent = () => {
25362
25108
  try {
25363
- 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();
25364
25110
  } catch {
25365
25111
  throw new MemoryReadSupersededError();
25366
25112
  }
@@ -25476,6 +25222,29 @@ async function runOpportunityScan(deps) {
25476
25222
  if (originals.length) actionEvidence.set(node.id, originals.join("\n"));
25477
25223
  }
25478
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
+ }
25479
25248
  const basis = { scope, dependencies: [] };
25480
25249
  includeContextBasis(memory, basis, context);
25481
25250
  for (const entry of entries) {
@@ -25494,6 +25263,9 @@ async function runOpportunityScan(deps) {
25494
25263
  actionEvidence,
25495
25264
  foresightEventIds,
25496
25265
  lines: entries.map((entry) => `[hypothesis ${entry.entryId}; window ${entry.start}~${entry.end}] ${entry.text}`),
25266
+ mentionEvents,
25267
+ stateSignals,
25268
+ prepLines: prepLines(prepItems),
25497
25269
  // Keep the model graph filtered; assertions and commit compare full incident edges for these readable nodes.
25498
25270
  // One query for all of them: per node it was two round trips, about 13,000 on a real graph.
25499
25271
  graphBasis: captureGraphBasis(
@@ -25519,12 +25291,15 @@ async function runOpportunityScan(deps) {
25519
25291
  return status !== "resolved" && status !== "rejected" && status !== "expired";
25520
25292
  }).slice(-20).map((n) => `- [${n.id}] ${String(n.data.title ?? "")}${captured ? `
25521
25293
  ${captured.actionEvidence.get(n.id) ?? "\u4EC5\u80CC\u666F\uFF0C\u4E0D\u80FD\u5355\u72EC\u4F5C\u4E3A\u884C\u52A8\u4F9D\u636E"}` : ""}`);
25522
- 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 ?? "")}
25523
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 });
25524
25298
  const calendarLines = (deps.calendarCoverage ?? []).filter((c) => {
25525
25299
  const ms = parseCalendarDateMs(c.date, now2);
25526
25300
  return ms !== null && ms >= now2.getTime() - 864e5 && ms <= now2.getTime() + 31 * 864e5;
25527
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;
25528
25303
  const userPrompt = [
25529
25304
  // 这一行必须与上面的 calendar 行同坐标:calendar 的 date/time 是**配置时区**墙上时间,
25530
25305
  // 而这里此前给的是 UTC Z —— 同一个 prompt 两套坐标、且都没标注,模型无从判断"现在"。
@@ -25556,17 +25331,28 @@ ${captured ? captured.actionEvidence.get(n.id) ?? `\u4EC5\u80CC\u666F\uFF0C\u4E0
25556
25331
  "## \u8FD1\u671F\u4E8B\u4EF6\uFF08\u4F18\u5148\u63D0\u4F9B\u7528\u6237/\u5DE5\u5177\u4F9D\u636E\uFF0C\u6700\u591A 15 \u6761\uFF09",
25557
25332
  recentEvents.length > 0 ? recentEvents.join("\n") : "\uFF08\u65E0\uFF09",
25558
25333
  "",
25559
- '\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',
25560
- "\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",
25561
- "\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",
25562
- "\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",
25563
- "\u53EA\u5728\u65F6\u673A\u771F\u5BF9\u65F6\u8F93\u51FA\uFF1B\u6CA1\u6709\u5C31\u8F93\u51FA\u7A7A\u6570\u7EC4\u3002",
25564
- "\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",
25565
25347
  "",
25566
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",
25567
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",
25568
- ...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"] : [],
25569
- '\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]"]}]}'
25570
25356
  ].join("\n");
25571
25357
  await yieldToEventLoop2();
25572
25358
  let active = true;
@@ -25604,14 +25390,20 @@ ${captured ? captured.actionEvidence.get(n.id) ?? `\u4EC5\u80CC\u666F\uFF0C\u4E0
25604
25390
  model: deps.model,
25605
25391
  messages: [{ role: "user", content: userPrompt }],
25606
25392
  systemPrompt: [
25607
- "\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",
25608
- "\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",
25609
25395
  "",
25610
- '\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',
25611
- "\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",
25612
25401
  "",
25613
- "\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",
25614
- "\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"
25615
25407
  ].join("\n"),
25616
25408
  temperature: 0.3,
25617
25409
  disableThinking: true,
@@ -25650,17 +25442,20 @@ ${captured ? captured.actionEvidence.get(n.id) ?? `\u4EC5\u80CC\u666F\uFF0C\u4E0
25650
25442
  const memory = deps.memory;
25651
25443
  const previousTitles = new Set(persist.opportunityTitlesSince(scopeId(memory.scope), new Date(now2.getTime() - 30 * 864e5).toISOString()));
25652
25444
  const covered = (deps.coveredTitles ?? []).join(" ");
25653
- 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)));
25654
25446
  if (!opportunities.length) return 0;
25655
25447
  try {
25656
25448
  const result = memory.store.transaction(() => {
25657
25449
  assertBasis();
25658
25450
  memory.store.dependencies.assertReferences(memory.scope, captured.basis.dependencies);
25659
25451
  const actions = [];
25452
+ let candidates = 0;
25660
25453
  deps.store.mutate((staged) => {
25661
25454
  for (const opportunity of opportunities) {
25662
25455
  const id = `opp-candidate-${newEventId()}`;
25663
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++;
25664
25459
  const dependencies = proof ? publishedGraphDependencies([...proof.dependencies, ...captured.concrete.filter((ref) => ref.parentKind === "scope" && ref.parentId.startsWith("valid-window:"))]) : publishedGraphDependencies(captured.concrete);
25665
25460
  staged.addNode({
25666
25461
  id,
@@ -25714,7 +25509,7 @@ ${captured ? captured.actionEvidence.get(n.id) ?? `\u4EC5\u80CC\u666F\uFF0C\u4E0
25714
25509
  }, (owner) => {
25715
25510
  for (const action of actions) owner.insertAction(action);
25716
25511
  }, captured.graphBasis);
25717
- return { candidates: opportunities.length, actionsScheduled: actions.length };
25512
+ return { candidates, actionsScheduled: actions.length };
25718
25513
  });
25719
25514
  console.log(`[proactive] scoped opportunity committed candidates=${result.candidates} actionsScheduled=${result.actionsScheduled} deferred=${result.candidates - result.actionsScheduled}`);
25720
25515
  return result.candidates;
@@ -25772,7 +25567,8 @@ var init_opportunity = __esm({
25772
25567
  init_read_guard();
25773
25568
  init_scoped_opportunity();
25774
25569
  init_published_basis();
25775
- init_sweep();
25570
+ init_intent();
25571
+ init_care_leads();
25776
25572
  OPPORTUNITY_SCAN_INTERVAL_MS = 6 * 60 * 6e4;
25777
25573
  PROFILE_RE = /今后|以后|将来|往后|再次遇到|下次遇到|会一直|会习惯|会继续|会优先|会避免|会主动|会定期|会倾向于|会按|会先|时会|倾向于|更愿意|养成了?.*习惯|将养成|将优先|将避免|习惯性地|will always|will prefer|will avoid|will continue|will keep|will strictly|tends? to|is likely to (?:always|keep|continue)/i;
25778
25574
  foresightCache = /* @__PURE__ */ new Map();
@@ -29476,6 +29272,348 @@ var init_config3 = __esm({
29476
29272
  }
29477
29273
  });
29478
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
+
29479
29617
  // src/memory/proactive/planning-context.ts
29480
29618
  import { existsSync as existsSync13, readFileSync as readFileSync27 } from "node:fs";
29481
29619
  import { join as join32 } from "node:path";
@@ -33280,6 +33418,13 @@ function withStore(fn) {
33280
33418
  store.close();
33281
33419
  }
33282
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
+ }
33283
33428
  function fmtRow2(a) {
33284
33429
  const when = a.scheduledTime ? formatForLlm(a.scheduledTime) : "(\u65E0)";
33285
33430
  return `#${a.id} [${a.status}, version=${a.actionVersion}] ${a.title} (urgency=${a.urgency}, scheduled=${when}${a.calendarId ? `, cal=#${a.calendarId}` : ""})`;
@@ -33323,13 +33468,14 @@ function registerProactiveTools() {
33323
33468
  });
33324
33469
  registry.register({
33325
33470
  name: "proactive_cancel",
33326
- 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",
33327
33472
  schema: {
33328
33473
  type: "object",
33329
33474
  properties: {
33330
33475
  action_id: { type: "string", description: "action id" },
33331
33476
  reason: { type: "string", description: "\u53D6\u6D88\u7406\u7531\uFF08\u4F1A\u8BB0\u8FDB cancel_reason\uFF09" },
33332
- 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" }
33333
33479
  },
33334
33480
  required: ["action_id"]
33335
33481
  },
@@ -33345,7 +33491,9 @@ function registerProactiveTools() {
33345
33491
  expectedActionVersion: args2.expected_action_version ?? a.actionVersion
33346
33492
  });
33347
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 };
33348
- 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` : "") };
33349
33497
  });
33350
33498
  return out ?? { content: "proactive \u672A\u542F\u7528", isError: true };
33351
33499
  }
@@ -35013,11 +35161,11 @@ async function expireBackups(state, roots, now2, maxAgeMs, max, allowed) {
35013
35161
  for (const entry of await readdir(unlinked(histories), { withFileTypes: true })) {
35014
35162
  if (removed >= max || !allowed()) break;
35015
35163
  if (!entry.isDirectory() || entry.isSymbolicLink() || !/^[a-f0-9]{64}$/.test(entry.name)) continue;
35016
- 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");
35017
35165
  if (importerActive(history) || existsSync21(join44(history, pointerName))) continue;
35018
35166
  let marker;
35019
35167
  try {
35020
- marker = readJson(markerPath);
35168
+ marker = readJson(markerPath3);
35021
35169
  } catch {
35022
35170
  continue;
35023
35171
  }
@@ -35044,7 +35192,7 @@ async function expireBackups(state, roots, now2, maxAgeMs, max, allowed) {
35044
35192
  if (!candidates.length) continue;
35045
35193
  try {
35046
35194
  await withTopicsImportLock(history, async () => {
35047
- 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;
35048
35196
  const result = await validateInHelper(["--validate-topics-import-live", state, history], allowed);
35049
35197
  if (!result.verified) {
35050
35198
  console.log(`[bg-worker] topics backup expiry deferred: ${result.reason}`);
@@ -35052,7 +35200,7 @@ async function expireBackups(state, roots, now2, maxAgeMs, max, allowed) {
35052
35200
  }
35053
35201
  for (const candidate of candidates.sort((a, b) => a.createdAt - b.createdAt)) {
35054
35202
  if (removed >= max || !allowed() || existsSync21(join44(history, pointerName))) break;
35055
- if (digest3(canonical(readJson(markerPath))) !== completionHash) break;
35203
+ if (digest3(canonical(readJson(markerPath3))) !== completionHash) break;
35056
35204
  const root = unlinked(candidate.root), target = unlinked(join44(root, candidate.name));
35057
35205
  if (dirname24(target) !== root || basename8(target) !== candidate.name) throw new Error("BACKUP_PATH_ESCAPE");
35058
35206
  disjoint(join44(state, "mem7", "index"), join44(state, "mem7", "users"), target);
@@ -35385,6 +35533,119 @@ var init_validate_import_live = __esm({
35385
35533
  }
35386
35534
  });
35387
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
+
35388
35649
  // src/memory/topics-chunks.ts
35389
35650
  var topics_chunks_exports = {};
35390
35651
  __export(topics_chunks_exports, {
@@ -35394,8 +35655,8 @@ __export(topics_chunks_exports, {
35394
35655
  importTopicChunks: () => importTopicChunks
35395
35656
  });
35396
35657
  import { createHash as createHash36 } from "node:crypto";
35397
- import { readdirSync as readdirSync7, readFileSync as readFileSync37, mkdirSync as mkdirSync21, writeFileSync as writeFileSync16, renameSync as renameSync12, existsSync as existsSync24 } from "node:fs";
35398
- 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";
35399
35660
  function parseMd(text2) {
35400
35661
  const m = /^---\r?\n([\s\S]*?)\r?\n---/.exec(text2);
35401
35662
  const meta = {};
@@ -35444,7 +35705,7 @@ function walk(root) {
35444
35705
  const visit = (dir) => {
35445
35706
  for (const entry of readdirSync7(dir, { withFileTypes: true })) {
35446
35707
  if (entry.isSymbolicLink()) continue;
35447
- const path23 = join50(dir, entry.name);
35708
+ const path23 = join52(dir, entry.name);
35448
35709
  if (entry.isDirectory()) visit(path23);
35449
35710
  else if (entry.isFile() && /\.md$/i.test(entry.name) && entry.name.toUpperCase() !== "MEMORY.MD") out.push(path23);
35450
35711
  }
@@ -35458,11 +35719,11 @@ function chunkTimestamp(meta) {
35458
35719
  }
35459
35720
  async function importTopicChunks(options) {
35460
35721
  const { stateDir: stateDir2, topicsDir, userId, embed } = options;
35461
- const manifestPath = join50(stateDir2, "mem7", "topics-chunks.json");
35462
- mkdirSync21(join50(stateDir2, "mem7"), { recursive: true });
35722
+ const manifestPath = join52(stateDir2, "mem7", "topics-chunks.json");
35723
+ mkdirSync23(join52(stateDir2, "mem7"), { recursive: true });
35463
35724
  let manifest = {};
35464
35725
  try {
35465
- if (existsSync24(manifestPath)) manifest = JSON.parse(readFileSync37(manifestPath, "utf8"));
35726
+ if (existsSync26(manifestPath)) manifest = JSON.parse(readFileSync39(manifestPath, "utf8"));
35466
35727
  } catch {
35467
35728
  manifest = {};
35468
35729
  }
@@ -35471,8 +35732,8 @@ async function importTopicChunks(options) {
35471
35732
  const report = { files: 0, chunks: 0, embedded: 0, deleted: 0, failed: 0, errors: [] };
35472
35733
  const save = () => {
35473
35734
  const tmp = `${manifestPath}.${process.pid}.tmp`;
35474
- writeFileSync16(tmp, JSON.stringify(manifest));
35475
- renameSync12(tmp, manifestPath);
35735
+ writeFileSync18(tmp, JSON.stringify(manifest));
35736
+ renameSync14(tmp, manifestPath);
35476
35737
  };
35477
35738
  const files = walk(topicsDir);
35478
35739
  const seen = /* @__PURE__ */ new Set();
@@ -35480,13 +35741,13 @@ async function importTopicChunks(options) {
35480
35741
  for (const file2 of files) {
35481
35742
  const rel = relative8(topicsDir, file2);
35482
35743
  seen.add(rel);
35483
- const bytes2 = readFileSync37(file2);
35744
+ const bytes2 = readFileSync39(file2);
35484
35745
  const hash8 = sha(bytes2);
35485
35746
  const previous = manifest[rel];
35486
35747
  if (previous?.hash === hash8) continue;
35487
35748
  try {
35488
35749
  const parentId = `topic_chunk:${rel}`;
35489
- await table.delete(`parent_id = '${sqlLiteral2(parentId)}'`);
35750
+ await table.delete(`parent_id = '${sqlLiteral(parentId)}'`);
35490
35751
  const text2 = bytes2.toString("utf8");
35491
35752
  const parsed = parseMd(text2);
35492
35753
  const title = parsed.meta.name || rel.split("/").pop().replace(/\.md$/i, "");
@@ -35538,7 +35799,7 @@ async function importTopicChunks(options) {
35538
35799
  if (options.prune !== false) for (const rel of Object.keys(manifest)) {
35539
35800
  if (seen.has(rel)) continue;
35540
35801
  try {
35541
- await table.delete(`parent_id = '${sqlLiteral2(`topic_chunk:${rel}`)}'`);
35802
+ await table.delete(`parent_id = '${sqlLiteral(`topic_chunk:${rel}`)}'`);
35542
35803
  delete manifest[rel];
35543
35804
  report.deleted++;
35544
35805
  } catch (error) {
@@ -35555,7 +35816,7 @@ async function importTopicChunks(options) {
35555
35816
  }
35556
35817
  return report;
35557
35818
  }
35558
- 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;
35559
35820
  var init_topics_chunks = __esm({
35560
35821
  "src/memory/topics-chunks.ts"() {
35561
35822
  "use strict";
@@ -35565,7 +35826,7 @@ var init_topics_chunks = __esm({
35565
35826
  CHUNK_MAX = 800;
35566
35827
  MAX_CHUNKS_PER_FILE = 200;
35567
35828
  sha = (input) => createHash36("sha256").update(input).digest("hex");
35568
- sqlLiteral2 = (value) => value.replace(/'/g, "''");
35829
+ sqlLiteral = (value) => value.replace(/'/g, "''");
35569
35830
  }
35570
35831
  });
35571
35832
 
@@ -35794,7 +36055,7 @@ var init_memoryTypes = __esm({
35794
36055
  // src/memory/memdir/memoryScan.ts
35795
36056
  import fs11 from "node:fs/promises";
35796
36057
  import { StringDecoder } from "node:string_decoder";
35797
- 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";
35798
36059
  function isArchivedPath(relativePath) {
35799
36060
  return relativePath.split(sep6).includes("archive");
35800
36061
  }
@@ -35869,7 +36130,7 @@ async function scanMemoryFiles(memoryDir, signal, maxFiles) {
35869
36130
  const entries = await fs11.readdir(memoryDir, { recursive: true });
35870
36131
  const files = entries.filter((f) => typeof f === "string" && f.endsWith(".md") && basename12(f) !== "MEMORY.md" && !isArchivedPath(f));
35871
36132
  const candidates = await mapFiles(files, 16, signal, async (filename) => {
35872
- const filePath = join51(memoryDir, filename);
36133
+ const filePath = join53(memoryDir, filename);
35873
36134
  return { filename, filePath, mtimeMs: (await fs11.stat(filePath)).mtimeMs };
35874
36135
  });
35875
36136
  const selected = candidates.sort((a, b) => b.mtimeMs - a.mtimeMs).slice(0, limit);
@@ -36074,11 +36335,11 @@ var init_reader = __esm({
36074
36335
 
36075
36336
  // src/memory/topics-history/import-mem7.ts
36076
36337
  import { DatabaseSync as DatabaseSync21 } from "node:sqlite";
36077
- import { existsSync as existsSync25, readFileSync as readFileSync38, renameSync as renameSync13, statSync as statSync7, writeFileSync as writeFileSync17 } from "node:fs";
36078
- 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";
36079
36340
  function topicsImported(binding) {
36080
36341
  if (!binding.stateDir) return false;
36081
- const marker = join52(topicsHistoryRoot(binding), "topics-import.json");
36342
+ const marker = join54(topicsHistoryRoot(binding), "topics-import.json");
36082
36343
  let size2 = 0, mtimeMs = 0, ino = 0;
36083
36344
  try {
36084
36345
  const s = statSync7(marker);
@@ -36095,19 +36356,19 @@ function topicsImported(binding) {
36095
36356
  try {
36096
36357
  const done = readJson(marker);
36097
36358
  if (typeof done.rulesVersion === "number" && done.rulesVersion !== TOPIC_DATE_RULES_VERSION) {
36098
- const retired = join52(topicsHistoryRoot(binding), `topics-import.stale-rules-${(/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-")}.json`);
36099
- renameSync13(marker, retired);
36359
+ const retired = join54(topicsHistoryRoot(binding), `topics-import.stale-rules-${(/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-")}.json`);
36360
+ renameSync15(marker, retired);
36100
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}`);
36101
36362
  } else if ((done.report?.total ?? 0) > 0) imported = true;
36102
36363
  else {
36103
- const retired = join52(topicsHistoryRoot(binding), `topics-import.degenerate-${(/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-")}.json`);
36104
- renameSync13(marker, retired);
36364
+ const retired = join54(topicsHistoryRoot(binding), `topics-import.degenerate-${(/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-")}.json`);
36365
+ renameSync15(marker, retired);
36105
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}`);
36106
36367
  }
36107
36368
  } catch {
36108
- 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`);
36109
36370
  try {
36110
- renameSync13(marker, retired);
36371
+ renameSync15(marker, retired);
36111
36372
  console.warn(`[topics-import] \u6E05\u5355\u635F\u574F\u4F5C\u5E9F\uFF08\u4E0B\u8F6E\u5BFC\u5165\u91CD\u5199\u81EA\u6108\uFF09\u2192 ${retired}`);
36112
36373
  } catch {
36113
36374
  }
@@ -38558,7 +38819,7 @@ var init_on_demand_recall = __esm({
38558
38819
  async search(binding, args2, run, signal) {
38559
38820
  const status = (value, reason) => JSON.stringify({ historySearch: { status: value, reason } });
38560
38821
  if (signal?.aborted) return status("aborted", "\u672C\u8F6E\u5DF2\u53D6\u6D88\u3002");
38561
- 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");
38562
38823
  const bounded = {
38563
38824
  query: String(args2.query ?? "").trim(),
38564
38825
  view: args2.view ?? "mixed",
@@ -40382,8 +40643,8 @@ __export(memdir_exports, {
40382
40643
  loadMemoryPrompt: () => loadMemoryPrompt,
40383
40644
  truncateEntrypointContent: () => truncateEntrypointContent
40384
40645
  });
40385
- import { readFileSync as readFileSync41 } from "node:fs";
40386
- import { join as join58 } from "node:path";
40646
+ import { readFileSync as readFileSync43 } from "node:fs";
40647
+ import { join as join60 } from "node:path";
40387
40648
  function truncateEntrypointContent(raw) {
40388
40649
  const trimmed = raw.trim();
40389
40650
  const contentLines = trimmed.split("\n");
@@ -40476,11 +40737,11 @@ function buildMemoryLines(displayName, memoryDir, extraGuidelines, skipIndex = f
40476
40737
  }
40477
40738
  function buildMemoryPrompt(params) {
40478
40739
  const { displayName, memoryDir, extraGuidelines } = params;
40479
- const entrypoint = join58(memoryDir, ENTRYPOINT_NAME);
40740
+ const entrypoint = join60(memoryDir, ENTRYPOINT_NAME);
40480
40741
  let entrypointContent = params.entrypointContent ?? "";
40481
40742
  if (params.entrypointContent === void 0) {
40482
40743
  try {
40483
- entrypointContent = readFileSync41(entrypoint, "utf-8");
40744
+ entrypointContent = readFileSync43(entrypoint, "utf-8");
40484
40745
  } catch {
40485
40746
  }
40486
40747
  }
@@ -42773,11 +43034,11 @@ var init_providers = __esm({
42773
43034
 
42774
43035
  // src/task-sessions/extraction.ts
42775
43036
  import { mkdir as mkdir2, readFile as readFile2, readdir as readdir4, rename, rm as rm2, writeFile } from "node:fs/promises";
42776
- 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";
42777
43038
  function validTaskTopicNotice(stateDir2, notice) {
42778
43039
  if (!notice.topicsDir || !notice.sessionId || !notice.transcriptPath.endsWith(".jsonl")) return false;
42779
- const project = dirname31(resolve22(notice.topicsDir));
42780
- 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");
42781
43042
  }
42782
43043
  async function readPendingTaskTopics(stateDir2) {
42783
43044
  const dir = queueDir(stateDir2);
@@ -42791,7 +43052,7 @@ async function readPendingTaskTopics(stateDir2) {
42791
43052
  const items = [];
42792
43053
  for (const name of names) {
42793
43054
  if (!/^[a-f0-9]{64}-[a-f0-9-]{36}\.json$/.test(name)) continue;
42794
- const file2 = join61(dir, name);
43055
+ const file2 = join63(dir, name);
42795
43056
  try {
42796
43057
  const notice = JSON.parse(await readFile2(file2, "utf8"));
42797
43058
  if (validTaskTopicNotice(stateDir2, notice)) items.push({ file: file2, notice });
@@ -42805,8 +43066,8 @@ function acknowledgeTaskTopics(item) {
42805
43066
  return rm2(item.file, { force: true });
42806
43067
  }
42807
43068
  async function markTaskTopicsWorker(stateDir2) {
42808
- const marker = join61(queueDir(stateDir2), "worker.pid");
42809
- await mkdir2(dirname31(marker), { recursive: true });
43069
+ const marker = join63(queueDir(stateDir2), "worker.pid");
43070
+ await mkdir2(dirname33(marker), { recursive: true });
42810
43071
  await writeFile(marker, String(process.pid));
42811
43072
  return async () => {
42812
43073
  if (await readFile2(marker, "utf8").catch(() => "") === String(process.pid)) await rm2(marker, { force: true });
@@ -42820,7 +43081,7 @@ var init_extraction = __esm({
42820
43081
  init_extractMemories();
42821
43082
  init_reader2();
42822
43083
  init_providers();
42823
- queueDir = (stateDir2) => join61(stateDir2, "task-topics-queue");
43084
+ queueDir = (stateDir2) => join63(stateDir2, "task-topics-queue");
42824
43085
  }
42825
43086
  });
42826
43087
 
@@ -43884,7 +44145,7 @@ __export(topic_extraction_exports, {
43884
44145
  startTopicExtraction: () => startTopicExtraction
43885
44146
  });
43886
44147
  import { readFile as readFile3, stat as stat2 } from "node:fs/promises";
43887
- 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";
43888
44149
  function startTopicExtraction(config, workspace2, stateDir2, isBusy) {
43889
44150
  const toolConfig = { stateDir: stateDir2, workspace: workspace2 };
43890
44151
  liveConfig.init(toolConfig);
@@ -44010,12 +44271,12 @@ function startTopicExtraction(config, workspace2, stateDir2, isBusy) {
44010
44271
  const recover = async () => {
44011
44272
  if (!enabled()) return;
44012
44273
  try {
44013
- const dir = join64(stateDir2, "agents", "main", "sessions");
44014
- 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)));
44015
44276
  const sessionId = platform["scope:main"], file2 = index[sessionId]?.file;
44016
44277
  if (typeof sessionId === "string" && typeof file2 === "string") {
44017
44278
  const localName = basename16(file2.replace(/\\/g, "/"));
44018
- notify({ sessionId, transcriptPath: join64(dir, localName) });
44279
+ notify({ sessionId, transcriptPath: join66(dir, localName) });
44019
44280
  }
44020
44281
  } catch (error) {
44021
44282
  if (error?.code !== "ENOENT") console.warn(`[bg-worker] topics recovery: ${error?.message ?? error}`);
@@ -44075,7 +44336,7 @@ var init_topic_extraction = __esm({
44075
44336
  });
44076
44337
 
44077
44338
  // src/bg/bg-worker.ts
44078
- import { existsSync as existsSync34 } from "node:fs";
44339
+ import { existsSync as existsSync36 } from "node:fs";
44079
44340
  import { resolve as resolve25 } from "node:path";
44080
44341
 
44081
44342
  // src/bg/host.ts
@@ -44088,8 +44349,8 @@ init_pipeline();
44088
44349
  init_job_runner();
44089
44350
  init_projection_driver();
44090
44351
  import { execFile as execFile2, fork as fork2 } from "node:child_process";
44091
- import { dirname as dirname27, join as join53 } from "node:path";
44092
- 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";
44093
44354
  import { fileURLToPath as fileURLToPath14 } from "node:url";
44094
44355
 
44095
44356
  // src/mem7/worker-projection.ts
@@ -45144,6 +45405,8 @@ function startMem7Worker(config, fallback, options = {}) {
45144
45405
  let lastCheckpointMs = 0;
45145
45406
  let lastBackupCleanupMs = 0;
45146
45407
  let lastTopicChunksMs = Date.now() - 36e5 + 5 * 6e4;
45408
+ let lastOptimizeMs = Date.now() - 36e5 + 10 * 6e4;
45409
+ let retokenizeInFlight = false;
45147
45410
  const scanSchedule = createOpportunityScanSchedule(now2());
45148
45411
  const completedScanScopes = /* @__PURE__ */ new Set();
45149
45412
  const scan = async (store, busy = false) => {
@@ -45186,10 +45449,10 @@ function startMem7Worker(config, fallback, options = {}) {
45186
45449
  }
45187
45450
  if (!options.isBusy?.() && Date.now() - lastCheckpointMs >= 6e5) {
45188
45451
  lastCheckpointMs = Date.now();
45189
- const dbPath = join53(mem7Root(stateDir2), "index", "mem7.db");
45452
+ const dbPath = join55(mem7Root(stateDir2), "index", "mem7.db");
45190
45453
  const built = fileURLToPath14(new URL("./sqlite-maintenance-worker.mjs", import.meta.url));
45191
45454
  const source = fileURLToPath14(new URL("../mem7/sqlite-maintenance-worker.ts", import.meta.url));
45192
- const entry = existsSync26(built) ? built : source;
45455
+ const entry = existsSync28(built) ? built : source;
45193
45456
  execFile2(process.execPath, [...entry.endsWith(".ts") ? ["--import", "tsx"] : [], entry, "--sqlite-checkpoint", dbPath, stateDir2], { timeout: 18e4, windowsHide: true }, (error, stdout) => {
45194
45457
  if (error) console.warn(`[bg-worker] wal checkpoint \u8F85\u52A9\u8FDB\u7A0B\u5931\u8D25: ${error.message}`);
45195
45458
  else console.log(`[bg-worker] ${(stdout || "").trim()}`);
@@ -45203,12 +45466,12 @@ function startMem7Worker(config, fallback, options = {}) {
45203
45466
  const recoveredTurns = store.hostTurns.recoverInterrupted();
45204
45467
  if (recoveredTurns) console.log(`[bg-worker] abandoned host turns reconciled=${recoveredTurns}`);
45205
45468
  try {
45206
- 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) });
45207
45470
  if (retention.results || retention.payloads) console.log(`[bg-worker] job retention results=${retention.results} inputs=${retention.payloads} archived=${retention.archivedInputs} logicalBytes=${retention.bytesReclaimed}`);
45208
45471
  } catch (error) {
45209
45472
  console.warn(`[bg-worker] job retention deferred: ${error?.message ?? error}`);
45210
45473
  }
45211
- 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);
45212
45475
  if (Date.now() - lastBackupCleanupMs >= 36e5 && backupCleanupAllowed()) {
45213
45476
  lastBackupCleanupMs = Date.now();
45214
45477
  try {
@@ -45219,6 +45482,26 @@ function startMem7Worker(config, fallback, options = {}) {
45219
45482
  }
45220
45483
  }
45221
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) {
45222
45505
  lastTopicChunksMs = Date.now();
45223
45506
  const workspace2 = String(config.get("workspace") ?? "");
45224
45507
  const topicsDir = workspace2 ? getAutoMemPath(workspace2) : "";
@@ -45240,6 +45523,15 @@ function startMem7Worker(config, fallback, options = {}) {
45240
45523
  }
45241
45524
  })();
45242
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
+ }
45243
45535
  const cleanupMs = Math.round(performance.now() - started);
45244
45536
  if (cleanupMs >= 1e3) console.log(`[bg-worker] cleanup ${cleanupMs}ms`);
45245
45537
  const agentName = mem7AgentName((key5) => config.get(key5));
@@ -45247,7 +45539,7 @@ function startMem7Worker(config, fallback, options = {}) {
45247
45539
  let relationshipGraph;
45248
45540
  if (config.get("mem7.relationshipCognition") !== false) {
45249
45541
  if (options.relationshipGraphPath) {
45250
- if (existsSync26(options.relationshipGraphPath)) {
45542
+ if (existsSync28(options.relationshipGraphPath)) {
45251
45543
  try {
45252
45544
  relationshipGraph = workerGraph(options.relationshipGraphPath, store).graph;
45253
45545
  relationshipGraph.ensureFresh();
@@ -45335,7 +45627,7 @@ function startMem7Worker(config, fallback, options = {}) {
45335
45627
  if (!store || !stateDir2 || config.get("mem7.enabled") !== true) return;
45336
45628
  try {
45337
45629
  if (physicalMaintenance?.running()) {
45338
- if (!intakePendingForDatabase(join53(mem7Root(stateDir2), "index", "mem7.db"))) return;
45630
+ if (!intakePendingForDatabase(join55(mem7Root(stateDir2), "index", "mem7.db"))) return;
45339
45631
  await physicalMaintenance.interrupt();
45340
45632
  }
45341
45633
  const applied = drainIntakeSpool(stateDir2, store, 50);
@@ -45343,10 +45635,10 @@ function startMem7Worker(config, fallback, options = {}) {
45343
45635
  await physicalMaintenance?.interrupt();
45344
45636
  void pipeline.tick();
45345
45637
  }
45346
- if (!activeStore && !options.isBusy?.() && !intakePendingForDatabase(join53(mem7Root(stateDir2), "index", "mem7.db"))) {
45638
+ if (!activeStore && !options.isBusy?.() && !intakePendingForDatabase(join55(mem7Root(stateDir2), "index", "mem7.db"))) {
45347
45639
  const retired = store.retireGraphPlanAuditsBatch();
45348
45640
  if (retired.plans) console.log(`[bg-worker] unused graph audits retired=${retired.plans}`);
45349
- 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")) });
45350
45642
  }
45351
45643
  } catch (error) {
45352
45644
  console.warn(`[bg-worker] intake service failed: ${error?.message ?? error}`);
@@ -45500,7 +45792,7 @@ async function runWorkerOpportunityScan(config, store, graphPath, fallback, comp
45500
45792
  const { provider, model } = resolveWorkerModel(config, config.get("proactive.model")) ?? fallback();
45501
45793
  const { persist, graph } = workerGraph(graphPath, store);
45502
45794
  graph.ensureFresh();
45503
- const workspace2 = dirname27(dirname27(graphPath));
45795
+ const workspace2 = dirname29(dirname29(graphPath));
45504
45796
  if (!store) {
45505
45797
  if (completedScopes.has("legacy")) return 0;
45506
45798
  const count = await runOpportunityScan({
@@ -45742,7 +46034,7 @@ var relationshipGraphPath = graphFlag >= 0 ? resolve25(args[graphFlag + 1]) : vo
45742
46034
  var mainFlag = args.indexOf("--main-model");
45743
46035
  var mainModelRef = mainFlag >= 0 ? args[mainFlag + 1] : void 0;
45744
46036
  var workspaceFlag = args.indexOf("--workspace");
45745
- if (!configPath || !existsSync34(configPath)) {
46037
+ if (!configPath || !existsSync36(configPath)) {
45746
46038
  console.error("[bg-worker] usage: node dist/bg-worker.mjs --engine-config <path>");
45747
46039
  process.exit(1);
45748
46040
  }