@modusensus/dsh-mneme 0.8.10 → 0.8.12

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.
Files changed (45) hide show
  1. package/README.md +5 -5
  2. package/assets/icon.svg +3 -0
  3. package/lib/client.js +190 -58
  4. package/lib/config.js +47 -1
  5. package/lib/dream/decisions.js +16 -0
  6. package/lib/dream/sleep.js +3 -0
  7. package/lib/dream.js +57 -9
  8. package/lib/entities/extractor.js +4 -1
  9. package/lib/graph/anchoring.js +180 -0
  10. package/lib/index.js +5 -0
  11. package/lib/inject.js +15 -3
  12. package/lib/lang.js +10 -0
  13. package/lib/service.js +164 -23
  14. package/lib/settings.js +24 -2
  15. package/lib/store.js +155 -11
  16. package/lib/summarize.js +104 -7
  17. package/locale/en.json +6 -0
  18. package/locale/zh.json +6 -0
  19. package/package.json +12 -7
  20. package/scripts/sync-test-badge.mjs +9 -7
  21. package/scripts/test-count-sync.mjs +44 -0
  22. package/src/config.js +47 -1
  23. package/src/dream/decisions.js +16 -0
  24. package/src/dream/sleep.js +3 -0
  25. package/src/dream.js +57 -9
  26. package/src/entities/extractor.js +4 -1
  27. package/src/graph/anchoring.js +180 -0
  28. package/src/index.js +5 -0
  29. package/src/inject.js +15 -3
  30. package/src/lang.js +10 -0
  31. package/src/service.js +164 -23
  32. package/src/settings.js +24 -2
  33. package/src/store.js +155 -11
  34. package/src/summarize.js +104 -7
  35. package/test/api.test.js +7 -2
  36. package/test/baseline-persist.test.js +248 -0
  37. package/test/client.test.js +245 -45
  38. package/test/dream.test.js +75 -0
  39. package/test/graph-anchoring.test.js +185 -0
  40. package/test/graph-inject-budget.test.js +104 -0
  41. package/test/graph-passive-confirm.test.js +92 -0
  42. package/test/graph-weight-evolution.test.js +105 -0
  43. package/test/scope-inject-soft.test.js +106 -0
  44. package/test/summarize.test.js +177 -0
  45. package/test/test-count-sync.test.js +60 -0
package/lib/service.js CHANGED
@@ -11,6 +11,7 @@ import { createDocumentRegistrar } from "./document.js";
11
11
  import { createOrganizer } from "./organize.js";
12
12
  import { createBM25Index } from "./search/bm25.js";
13
13
  import { adaptiveThreshold } from "./search/adaptive.js";
14
+ import { anchorSeeds, normalizePath, cascadeDepths, HOP_QUOTA } from "./graph/anchoring.js";
14
15
 
15
16
  const INJECT_TYPES = new Set(["preference", "project", "decision", "summary", "rejected_solution", "pitfall", "constraint"]);
16
17
 
@@ -448,30 +449,92 @@ export function createService({ store, mirror, config, onWrite, logger, document
448
449
  }
449
450
 
450
451
  /**
451
- * Graph fourth recall path (issue #219). When the query text mentions a
452
- * known entity name, memories linked to that entity (attrs + relations)
453
- * join the fusion pool as a confirm/backfill signal — same standing as
454
- * BM25, never dominating the semantic ranking. Tier scores: attr-linked
455
- * 1.0 (direct evidence, same source searchByEntity trusts) > relation
456
- * edge 0.9. Archived/forgotten rows never participate. Failures degrade
457
- * to [] — a recall booster, never a correctness gate (same contract as
458
- * bm25Recall).
452
+ * Graph fourth recall path (issue #219 → #24 块1 锚定层). When the query text
453
+ * mentions a known entity name, memories linked to that entity (attrs +
454
+ * relations) join the fusion pool as a confirm/backfill signal — same standing
455
+ * as BM25, never dominating the semantic ranking. Tier scores: attr-linked
456
+ * 1.0 (direct evidence, same source searchByEntity trusts) > relation edge
457
+ * 0.9. Archived/forgotten rows never participate. Failures degrade to [] —
458
+ * a recall booster, never a correctness gate (same contract as bm25Recall).
459
+ *
460
+ * #24 升级(graphAnchoringEnabled):命中实体作为锚定种子,沿 entity_relations
461
+ * 级联扩散邻居(默认深度 2),邻居挂联的记忆以 hop 配额权重参与——把「关系是
462
+ * 用出来的」延伸成检索信号:查询命中的不只有直接挂联,还有跳跃可达的活跃子图。
463
+ * 邻居权重 = HOP_QUOTA[hop] × linked tier(attr 1.0 / relation 0.9),仍低于
464
+ * 直达种子的满权,绝不喧宾夺主。
459
465
  */
460
466
  function entityRecall(q, limit) {
461
467
  if (config?.entityRecallEnabled !== true) return [];
462
468
  try {
463
469
  const entities = store.findEntitiesMentionedIn(q);
464
470
  if (!entities.length) return [];
465
- const linked = store.getLinkedMemoryIds(entities.map((e) => e.id));
466
- if (!linked.size) return [];
467
- const hits = [];
468
- for (const [id, tier] of linked) {
469
- const row = store.getById(id);
470
- if (!row || row.archived || row.forgotten) continue;
471
- hits.push({ ...row, score: tier === "attr" ? 1.0 : 0.9, source: "entity" });
472
- if (hits.length >= limit * 2) break;
471
+ // 关闭锚定级联=逐字节复用 #219 单跳轴:种子裁剪/重排/截断全是 #24 新增的
472
+ // 行为,默认关时一条都不许漏进旧路径(graphSeedCap 也只在开启后生效——
473
+ // 无论 cap 调多小,关档时命中实体仍全量挂联)。
474
+ if (config?.graphAnchoringEnabled !== true) {
475
+ const linked = store.getLinkedMemoryIds(entities.map((e) => e.id));
476
+ if (!linked.size) return [];
477
+ const hits = [];
478
+ for (const [id, tier] of linked) {
479
+ const row = store.getById(id);
480
+ if (!row || row.archived || row.forgotten) continue;
481
+ hits.push({ ...row, score: tier === "attr" ? 1.0 : 0.9, source: "entity" });
482
+ if (hits.length >= limit * 2) break;
483
+ }
484
+ return hits;
485
+ }
486
+ // 锚定种子(精确名布尔通路——命名实体逻辑上是离散匹配,不参与 min-max)。
487
+ const exact = normalizePath(entities.map((e) => e.id), { path: "exact" });
488
+ const seeds = anchorSeeds({ paths: [exact], cap: config?.graphSeedCap ?? 12 });
489
+ if (!seeds.length) return [];
490
+ // 0-hop 直达:挂联记忆按 tier 定分(attr 1.0 / relation 0.9)——与 #219
491
+ // 单跳轴同分。MAX 语义:同一条记忆被多实体挂联时保留最高分。
492
+ const scored = new Map();
493
+ const push = (memId, score) => {
494
+ if (scored.has(memId) && scored.get(memId) >= score) return;
495
+ const row = store.getById(memId);
496
+ if (!row || row.archived || row.forgotten) return;
497
+ scored.set(memId, score);
498
+ };
499
+ const seedLinked = store.getLinkedMemoryIds(seeds.map((s) => s.id));
500
+ for (const [memId, tier] of seedLinked) {
501
+ push(memId, tier === "attr" ? 1.0 : 0.9);
502
+ }
503
+ // 级联:沿 entity_relations 走 BFS,邻居挂联的记忆以 hop 配额权重补位——
504
+ // 不覆盖种子直达分(MAX 语义保证),只填「种子里没有但邻居可达」的槽。
505
+ const seedIds = seeds.map((s) => s.id);
506
+ const adjacency = store.getEntityNeighbors(seedIds);
507
+ const depths = cascadeDepths({
508
+ seeds,
509
+ // 逐节点懒取邻居:初次查询只带种子那一层的邻接,BFS 走到 1-hop 节点时
510
+ // 必须按需再拉一层,否则 >1 跳永远拿到空邻居、graphCascadeDepth≥2 形同
511
+ // 虚设。节点数随图度数增长,热路径上以 graphCascadeDepth≤3 为天然上界,
512
+ // 真遇到大图再考虑查询配额。
513
+ adjacencyOf: (id) => {
514
+ if (!adjacency.has(id)) adjacency.set(id, store.getEntityNeighbors([id]).get(id) ?? []);
515
+ return adjacency.get(id);
516
+ },
517
+ maxDepth: config?.graphCascadeDepth ?? 2
518
+ });
519
+ let neighborsSeen = 0;
520
+ const neighborCap = (config?.graphSeedCap ?? 12) * HOP_QUOTA[1]; // 1-hop 配额即为邻居总量上界
521
+ for (const [nid, hop] of depths) {
522
+ if (hop < 1) continue;
523
+ if (neighborsSeen >= Math.max(1, Math.floor(neighborCap))) break;
524
+ neighborsSeen++;
525
+ const neighborLinked = store.getLinkedMemoryIds([nid]);
526
+ for (const [memId, tier] of neighborLinked) {
527
+ const tierW = tier === "attr" ? 1.0 : 0.9;
528
+ push(memId, HOP_QUOTA[Math.min(hop, 3)] * tierW);
529
+ }
473
530
  }
474
- return hits;
531
+ const hits = [...scored.entries()]
532
+ .map(([id, score]) => {
533
+ const row = store.getById(id);
534
+ return { ...row, score, source: "entity" };
535
+ })
536
+ .sort((a, b) => b.score - a.score || (a.id < b.id ? -1 : a.id > b.id ? 1 : 0));
537
+ return hits.slice(0, limit * 2);
475
538
  } catch {
476
539
  return [];
477
540
  }
@@ -530,11 +593,28 @@ export function createService({ store, mirror, config, onWrite, logger, document
530
593
  * on the hot recall path). A touch failure must never break search/inject.
531
594
  */
532
595
  function touchRecalled(memories) {
533
- if (config?.heatEnabled === false || !Array.isArray(memories) || memories.length === 0) return;
596
+ if (!Array.isArray(memories) || memories.length === 0) return;
597
+ // heatEnabled=false 只关 touchLastAccess 的热度消费(既有语义),但 #24
598
+ // 块4 被动确认独立于 heat——graphPassiveConfirm 开时照常 bump 关联边。
599
+ // graphWeightEnabled 是块2 立的演化总闸:它关着时任何触达都不该改边权,被动
600
+ // 确认只是它底下的一个通道(后续块还会接别的确认通道),两键同开才 bump,
601
+ // 否则单开通道键就等于绕过「演化默认关」的承诺。
602
+ // 两条路径都 best-effort,失败绝不阻断检索/注入。
603
+ const heatOn = config?.heatEnabled !== false;
604
+ const passive = config?.graphPassiveConfirm === true && config?.graphWeightEnabled === true;
605
+ const delta = config?.graphWeightDelta ?? 0.1;
534
606
  for (const m of memories) {
535
607
  if (!m?.id) continue;
536
608
  try {
537
- store.touchLastAccess(m.id);
609
+ if (heatOn) store.touchLastAccess(m.id);
610
+ if (passive) {
611
+ // 正常触达=对该记忆挂联关系边的被动确认;bump 只加不减封顶 1.0,
612
+ // 自激回路由封顶天然遏制。「仅异常路径暴露给用户复核」的确认记录
613
+ // 侧在此落地,复核 UI 留后续块。
614
+ for (const rel of store.getRelationsByMemory(m.id)) {
615
+ store.bumpRelationWeight(rel.id, delta);
616
+ }
617
+ }
538
618
  } catch { /* touch is best effort */ }
539
619
  }
540
620
  }
@@ -1427,6 +1507,14 @@ export function createService({ store, mirror, config, onWrite, logger, document
1427
1507
  ? new Map(filtered.map((m) => [m.id, computeHeat(m, Date.now(), config)]))
1428
1508
  : null;
1429
1509
  const heatOf = (m) => (heatMap ? heatMap.get(m.id) ?? 1 : 1);
1510
+ // v0.8.x(issue #339 / E7 实测):A2 软加权补齐到注入通道。此前 ×0.5/×1.25
1511
+ // 只作用于 searchMemories——E7 考卷里「explicit 标注 + 软档」的注入集与无标注
1512
+ // 逐条相同(80/80),主泄露面上软档形同虚设。门控与检索侧同款:scopeEnabled
1513
+ // 且当前会话至少一维可解析;strictScope 硬过滤在下方先行,硬墙开启时被滤行
1514
+ // 不会到这里被二次降权。未激活时乘 1,排序与改动前逐字节一致。
1515
+ const softScopeActive = config?.scopeEnabled === true && scope != null &&
1516
+ Boolean(scope.agent_scope || scope.workspace_scope);
1517
+ const scopeMultOf = (m) => (softScopeActive ? scopeMultiplier(m, scope) : 1);
1430
1518
  const items = filtered.sort((a, b) => {
1431
1519
  // 编码记忆在编码任务时优先于普通 decision(与 preference 同级),
1432
1520
  // importance 乘 codingBoostFactor 加权(封顶 5,保持 importance 语义)。
@@ -1447,8 +1535,11 @@ export function createService({ store, mirror, config, onWrite, logger, document
1447
1535
  : m.importance;
1448
1536
  const pa = priority(a);
1449
1537
  const pb = priority(b);
1538
+ // 软加权乘在层内数值积上(priority 档位不动):foreign ×0.5 后压不过
1539
+ // 同档自己行——E7 的同 importance 档设计正是这个场景。
1450
1540
  return pa - pb ||
1451
- (effImportance(b) * qualityWeight(b) * heatOf(b)) - (effImportance(a) * qualityWeight(a) * heatOf(a));
1541
+ (effImportance(b) * qualityWeight(b) * heatOf(b) * scopeMultOf(b)) -
1542
+ (effImportance(a) * qualityWeight(a) * heatOf(a) * scopeMultOf(a));
1452
1543
  });
1453
1544
  let candidates = items;
1454
1545
  if (config.hybridInject !== false && q) {
@@ -1493,6 +1584,13 @@ export function createService({ store, mirror, config, onWrite, logger, document
1493
1584
  semanticItems.push(hit);
1494
1585
  }
1495
1586
  }
1587
+ // issue #339(CodeRabbit review on #350):首轮 BM25 兜底领跑合并池,
1588
+ // 而 selectiveInject 相似度重排要等查询向量就绪才执行——软加权必须
1589
+ // 在这里就位,否则 foreign 命中绕过降权直接占注入位。
1590
+ if (softScopeActive) {
1591
+ semanticItems.sort((a, b) =>
1592
+ (b.score ?? 0) * scopeMultOf(b) - (a.score ?? 0) * scopeMultOf(a));
1593
+ }
1496
1594
  }
1497
1595
  if (semanticItems.length) {
1498
1596
  const seen = new Set();
@@ -1523,7 +1621,13 @@ export function createService({ store, mirror, config, onWrite, logger, document
1523
1621
  const hits = vectorIndex.search(queryVector, { limit: 200, threshold: 0 });
1524
1622
  const sim = new Map(hits.map((m) => [m.id, m.score ?? 0]));
1525
1623
  if (sim.size) {
1526
- candidates = [...candidates].sort((a, b) => (sim.get(b.id) ?? -1) - (sim.get(a.id) ?? -1));
1624
+ // 软加权作用在真实 sim 上;未命中的规则候选保持 -1 沉底(缺失项
1625
+ // 乘乘数会让 foreign 缺失项反而排到自己的缺失项之上,故不乘)。
1626
+ const scopedSim = (m) => {
1627
+ const s = sim.get(m.id);
1628
+ return s === undefined ? -1 : s * scopeMultOf(m);
1629
+ };
1630
+ candidates = [...candidates].sort((a, b) => scopedSim(b) - scopedSim(a));
1527
1631
  }
1528
1632
  } catch { /* topic re-rank unavailable: keep rule-based order */ }
1529
1633
  }
@@ -1532,6 +1636,26 @@ export function createService({ store, mirror, config, onWrite, logger, document
1532
1636
  if (config?.strictScope === true && scope) {
1533
1637
  candidates = candidates.filter((m) => isVisibleInScope(m, scope));
1534
1638
  }
1639
+ // #24 块3:图召回候选打标。entityRecall 只在 entityRecallEnabled 开启时
1640
+ // 有产出,这里为命中者贴 graphHint 标签——注入侧据此(a)graphInjectHint
1641
+ // 开=标成 [检索线索] 前缀的线索行(独立预算),(b)关=线索行只参与排序
1642
+ // 不改变注入块(保守档)。与检索侧共用同一图闸:块1 #341 把 entityRecall
1643
+ // 升级成级联后,注入侧自动吃到同样的扩散信号,无需再改。只在语义/规则候选
1644
+ // 为空时兜底检索,避免注入路径双倍候选成本。
1645
+ if (config?.entityRecallEnabled === true && q) {
1646
+ try {
1647
+ const graphHits = entityRecall(q, maxItems * 2);
1648
+ if (graphHits.length) {
1649
+ const graphIds = new Set(graphHits.map((m) => m.id));
1650
+ candidates = [
1651
+ ...candidates.map((m) => graphIds.has(m.id) ? { ...m, graphHint: true } : m),
1652
+ ...graphHits
1653
+ .filter((m) => !candidates.some((c) => c.id === m.id))
1654
+ .map((m) => ({ ...m, graphHint: true }))
1655
+ ];
1656
+ }
1657
+ } catch { /* graph hint is best-effort */ }
1658
+ }
1535
1659
  // #249 第一批:B1 pin 池。取在相关性排序之后、轮换之前——取谁按此刻的候选
1536
1660
  // 次序(即相关性次序),取到后从候选中摘除,于是下面的轮换重排碰不到它们
1537
1661
  // (验收:pin 不参与跨轮轮换)。独立预算的两层意义:pin 既不占 maxItems
@@ -1539,7 +1663,10 @@ export function createService({ store, mirror, config, onWrite, logger, document
1539
1663
  // 超预算的条数回报给调用方,在块内如实标注(绝不静默省略)。
1540
1664
  const pinnedBudget = Math.max(0, Math.min(5, Math.floor(config?.pinnedInjectBudget ?? 0)));
1541
1665
  // eligible 留到块外:未展示条数要等 general 槽选完才算得准(见 selected 之后)。
1542
- const eligible = pinnedBudget > 0 ? candidates.filter((m) => PINNED_MEMORY_TYPES.has(m.type)) : [];
1666
+ // graphHint 行不进 pin 池:pin 是「每轮必进的约束/偏好」,而线索行按定义是
1667
+ // 「链路信息、非事实断言」,且 pin 长在候选池遍历之前——不排除的话,保守档
1668
+ // (graphInjectHint 关)也能从 pin 侧把它放回注入块,线索开关就被绕过去了。
1669
+ const eligible = pinnedBudget > 0 ? candidates.filter((m) => PINNED_MEMORY_TYPES.has(m.type) && m.graphHint !== true) : [];
1543
1670
  let pinned = [];
1544
1671
  if (pinnedBudget > 0 && eligible.length > 0) {
1545
1672
  pinned = eligible.slice(0, pinnedBudget);
@@ -1560,9 +1687,23 @@ export function createService({ store, mirror, config, onWrite, logger, document
1560
1687
  // 注入块变成文档目录(#164 失败判据:批量把历史塞进上下文)。
1561
1688
  const documentBudget = config?.documentInjectBudget ?? 2;
1562
1689
  let documentSeen = 0;
1690
+ // #24 块3:图线索行(graphHint)按独立预算 graphInjectBudget 进块;所谓
1691
+ // 独立=既不受 document 预算约束、也不挤占 maxItems 槽位。graphInjectHint
1692
+ // 关(默认保守档)时线索行**不进注入块**——它们只参与候选池排序(对融合无
1693
+ // 影响,因为候选池生成的唯一用途就是注入),桥接信号不污染常驻文本;开时
1694
+ // 才作为 [检索线索] 前缀行进入。与 document/pin 同构:预算只约束注入。
1695
+ const hintOpen = config?.graphInjectHint === true;
1696
+ let graphSeen = 0;
1697
+ const graphBudget = hintOpen ? Math.max(0, Math.floor(config?.graphInjectBudget ?? 1)) : 0;
1563
1698
  const general = [];
1564
1699
  for (const m of candidates) {
1565
- if (general.length >= maxItems) break;
1700
+ if (m.graphHint === true) {
1701
+ if (!hintOpen) continue; // 保守档:线索只排序不进块
1702
+ if (graphSeen >= graphBudget) continue; // 独立预算内放行
1703
+ graphSeen++;
1704
+ } else if (general.length >= maxItems) {
1705
+ break; // 普通候选受 maxItems 槽位上界
1706
+ }
1566
1707
  if (m.type === "document") {
1567
1708
  if (documentSeen >= documentBudget) continue;
1568
1709
  documentSeen++;
package/lib/settings.js CHANGED
@@ -58,6 +58,18 @@ const FEATURE_FLAG_BOOLEANS = [
58
58
  // Issue #219:图召回轴——查询命中实体名时把挂联记忆并入检索融合池
59
59
  // (默认关;依赖实体抽取产出,lightMode 强制关闭)。
60
60
  "entityRecallEnabled",
61
+ // Issue #24 块1:图谱锚定层级联——命中实体作种子、沿关系表向邻居扩散
62
+ // (默认关;依赖实体抽取产出,lightMode 强制关闭)。
63
+ "graphAnchoringEnabled",
64
+ // Issue #24 块2:边权重演化总闸——关着时任何触达都不改边权(默认关;
65
+ // 依赖实体抽取产出,lightMode 强制关闭)。块4 的被动确认是它底下的一个通道。
66
+ "graphWeightEnabled",
67
+ // Issue #24 块3:关联提示防幻觉——图召回线索行以「[检索线索]」标注进注入
68
+ // (默认关=线索只参与排序不进块;依赖实体抽取产出,lightMode 强制关闭)。
69
+ "graphInjectHint",
70
+ // Issue #24 块4:被动确认通道——正常触达即对该记忆挂联的边 bump 一格
71
+ // (默认关;需总闸 graphWeightEnabled 同开)。
72
+ "graphPassiveConfirm",
61
73
  // Issue #164:叙述条——dream 期间按 tag 主题簇合成叙述落库(source=
62
74
  // narrative,evidence 回链簇内记忆;按需检索不常驻注入;默认关)。
63
75
  "dreamNarrativeEnabled",
@@ -88,6 +100,9 @@ const FEATURE_FLAG_BOOLEANS = [
88
100
  // Issue #89:宽容校验回归(默认开)+ 跨类型合并显式放宽(默认关)。
89
101
  "dreamSkipInvalid",
90
102
  "allowCrossTypeMerge",
103
+ // Issue #339 / E8:guarded 类型 merge 护栏(默认关)——合并对象命中
104
+ // 长保留类型的 merge 决策整条跳过。
105
+ "dreamMergeGuard",
91
106
  // Issue #17(v0.8.0 A1):scope 隔离存储层总开关。开启后写入标注
92
107
  // agent_scope/workspace_scope、去重键扩展(含 sensitivity);检索侧过滤在
93
108
  // A2/A3。默认关=行为与 A1 前逐字节一致。
@@ -143,7 +158,12 @@ const FEATURE_FLAG_INT_RANGES = {
143
158
  // Issue #257:sleep 冲突/模式阶段的 LLM 输出预算(原硬编码 2048,实测不足)。
144
159
  sleepMaxTokens: [256, 131072],
145
160
  // Issue #258:总览(dream_summarize)输入条数硬上限(0 = 不设上限)。
146
- dreamSummaryMaxInputs: [0, 100000]
161
+ dreamSummaryMaxInputs: [0, 100000],
162
+ // Issue #24 块1:锚定种子上限与级联深度(闭区间与 config.js 的 z.natural() 对齐)。
163
+ graphSeedCap: [1, 30],
164
+ graphCascadeDepth: [1, 3],
165
+ // Issue #24 块3:图线索行的独立注入预算(0 = 线索不进块)。
166
+ graphInjectBudget: [0, 5]
147
167
  };
148
168
  // 浮点开关的闭区间(与 config.js 的 z.number().min().max() 对齐)。与整数开关
149
169
  // 分开:面板的整数控件要求 Number.isInteger,而余弦相似度阈值必须允许小数。
@@ -151,7 +171,9 @@ const FEATURE_FLAG_NUMBER_RANGES = {
151
171
  // Issue #127:vector 去重档的并入阈值。
152
172
  summarizeDedupeMinSim: [0.5, 0.99],
153
173
  // Issue #125:hybrid 判"高相似"的阈值。
154
- dreamCandidateMinSim: [0.5, 0.99]
174
+ dreamCandidateMinSim: [0.5, 0.99],
175
+ // Issue #24 块2:单次有效触达的边权抬升幅度(与 config.js 的闭区间对齐)。
176
+ graphWeightDelta: [0, 1]
155
177
  };
156
178
  // 自由字符串开关(与 config.js 的 z.string() 同名同型):trim 后 ≤200 字符,
157
179
  // 空串合法(= 跟随主对话模型/默认路径,面板显示 placeholder)。
package/lib/store.js CHANGED
@@ -52,7 +52,13 @@ CREATE TABLE IF NOT EXISTS dream_runs (
52
52
  receipt TEXT NOT NULL,
53
53
  policy_epoch INTEGER NOT NULL DEFAULT 0, -- 裁决规则版本:规则升级后旧裁决降级为历史证据
54
54
  run_type TEXT NOT NULL DEFAULT 'auto', -- auto | sleep | organize:周期审计的类别区分
55
- skipped TEXT -- JSON: degraded 轮被跳过的逐条明细(index/action/ids/error)
55
+ skipped TEXT, -- JSON: degraded 轮被跳过的逐条明细(index/action/ids/error)
56
+ -- Issue #89(基线半边):本轮成功刷新后的活跃记忆「条数 / 正文字符数」——阈值判定的
57
+ -- 基线原本只活在调度器闭包内存里,进程重启归零 → 库里记忆多于阈值时,重启后第一条
58
+ -- 写入就绕过阈值开跑整轮(#291 只持久化了 lastRunAt 那半边)。成功轮才落这两列,
59
+ -- 失败/降级不推进基线的既有语义不变;两列同时有值或同时为 NULL。
60
+ store_count INTEGER,
61
+ store_chars INTEGER
56
62
  );
57
63
  CREATE INDEX IF NOT EXISTS idx_dream_runs_created ON dream_runs(created_at);
58
64
 
@@ -249,7 +255,12 @@ CREATE TABLE IF NOT EXISTS entity_relations (
249
255
  relation_type TEXT NOT NULL,
250
256
  memory_id TEXT,
251
257
  created_at TEXT NOT NULL,
252
- metadata TEXT
258
+ metadata TEXT,
259
+ -- issue #24 块2(权重演化):边权重 + 建边来源。初值按 source 映射
260
+ -- (manual 1.0 / confirmed 保持 / tag 0.3 / llm 0.4),演化只经
261
+ -- bumpRelationWeight(只加不减、封顶),触达侧由 touch 门控驱动。
262
+ weight REAL NOT NULL DEFAULT 1.0,
263
+ source TEXT NOT NULL DEFAULT 'manual'
253
264
  );
254
265
  CREATE INDEX IF NOT EXISTS idx_relations_from ON entity_relations(from_entity);
255
266
  CREATE INDEX IF NOT EXISTS idx_relations_to ON entity_relations(to_entity);
@@ -482,7 +493,10 @@ function toDreamRun(row) {
482
493
  policy_epoch: row.policy_epoch ?? 0,
483
494
  run_type: row.run_type ?? "auto",
484
495
  // Issue #104:degraded 轮的逐条跳过明细(JSON 列,NULL = 该轮无跳过项)。
485
- skipped: row.skipped ? JSON.parse(row.skipped) : undefined
496
+ skipped: row.skipped ? JSON.parse(row.skipped) : undefined,
497
+ // Issue #89(基线半边):成功轮落下的阈值基线(NULL = 该轮没有推进基线)。
498
+ store_count: row.store_count ?? undefined,
499
+ store_chars: row.store_chars ?? undefined
486
500
  };
487
501
  }
488
502
 
@@ -549,6 +563,15 @@ function toRecallRun(row) {
549
563
  };
550
564
  }
551
565
 
566
+ // issue #24 块2:建边来源 → 初值权重映射。tag 延续 LLM 偏差取低起步,
567
+ // llm 抽取自动建边取中低,manual 全权(1.0 是满权,不含演化余量的上限)。
568
+ export const RELATION_SOURCE_DEFAULTS = Object.freeze({
569
+ manual: 1.0,
570
+ confirmed: 1.0, // manual_confirmed:已人工确认,维持满权
571
+ tag: 0.3,
572
+ llm: 0.4
573
+ });
574
+
552
575
  function toRecallEval(row) {
553
576
  if (!row) return undefined;
554
577
  let metrics;
@@ -612,6 +635,8 @@ function toRelation(row) {
612
635
  relation_type: row.relation_type,
613
636
  memory_id: row.memory_id ?? undefined,
614
637
  created_at: row.created_at,
638
+ weight: row.weight ?? 1.0,
639
+ source: row.source ?? "manual",
615
640
  metadata
616
641
  };
617
642
  }
@@ -751,6 +776,10 @@ export function createStore(path) {
751
776
  // 老库打开时 SCHEMA 的 CREATE TABLE 对既有表不生效,列还不存在,把索引写进 SCHEMA
752
777
  // 会直接报 no such column(与下方 llm_audit_logs.session_key 同理)。
753
778
  addColumn("memories", "content_hash", "ALTER TABLE memories ADD COLUMN content_hash TEXT");
779
+ // issue #24 块2(权重演化):entity_relations 加 weight + source。存量关系
780
+ // 行缺列 → 默认 manual 1.0(最保守:既有语义不因迁移而变弱)。
781
+ addColumn("entity_relations", "weight", "ALTER TABLE entity_relations ADD COLUMN weight REAL NOT NULL DEFAULT 1.0");
782
+ addColumn("entity_relations", "source", "ALTER TABLE entity_relations ADD COLUMN source TEXT NOT NULL DEFAULT 'manual'");
754
783
  // 列序是 content_hash 打头:哈希几乎唯一,等值 seek 就已收窄到候选行,type 只当同
755
784
  // 一次 seek 里的第二列过滤;反过来(type 打头)下面的存量回填就得全表扫——每次打开
756
785
  // 都要把全部正文读一遍。
@@ -780,6 +809,11 @@ export function createStore(path) {
780
809
  // Issue #104:degraded(合法子集已应用)轮被跳过的决策明细。此前只进 logger.warn,
781
810
  // 离线回放 dream_runs 无法定位 degraded 成因(跨类型 merge / update 保护期 / unknown id)。
782
811
  addColumn("dream_runs", "skipped", "ALTER TABLE dream_runs ADD COLUMN skipped TEXT");
812
+ // Issue #89(基线半边):阈值基线跨重启持久化。存量行两列皆 NULL——历史行反推不出
813
+ // 「那轮结束时库有多大」(input_count 是窗口条数,不是库规模),所以升级后第一次
814
+ // 成功轮之前播种端拿不到基线,行为与升级前一致;跑过一轮之后闸门即跨重启生效。
815
+ addColumn("dream_runs", "store_count", "ALTER TABLE dream_runs ADD COLUMN store_count INTEGER");
816
+ addColumn("dream_runs", "store_chars", "ALTER TABLE dream_runs ADD COLUMN store_chars INTEGER");
783
817
 
784
818
  // Legacy mirror_state without v0.3.6 generation columns → add each missing
785
819
  // column idempotently (old DBs open cleanly, no data loss).
@@ -1605,17 +1639,26 @@ export function createStore(path) {
1605
1639
  // Issue #104:degraded 轮的跳过明细(JSON)。与 decisions/outcome 同为可选
1606
1640
  // 载荷,未提供时落 NULL(而不是 "[]"),审计行只记真实发生过的跳过。
1607
1641
  const skipped = run.skipped !== undefined ? JSON.stringify(run.skipped) : null;
1642
+ // Issue #89(基线半边):只有成功刷新过基线的 run 才带这两个值。非法/缺失一律落
1643
+ // NULL——播种端以「两列同时有值」为唯一认账条件,半个基线(只有条数没有字符数)
1644
+ // 会让阈值按 0 字符起算,比不认还糟。
1645
+ const baselineKnown =
1646
+ Number.isInteger(run.store_count) && run.store_count >= 0 &&
1647
+ Number.isInteger(run.store_chars) && run.store_chars >= 0;
1648
+ const storeCount = baselineKnown ? run.store_count : null;
1649
+ const storeChars = baselineKnown ? run.store_chars : null;
1608
1650
  db.prepare(
1609
1651
  `INSERT INTO dream_runs (id, created_at, status, error, provider, model, snapshot_hash,
1610
- input_count, input, decisions, outcome, applied, summary_stored, receipt, policy_epoch, run_type, skipped)
1611
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
1652
+ input_count, input, decisions, outcome, applied, summary_stored, receipt, policy_epoch, run_type, skipped,
1653
+ store_count, store_chars)
1654
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
1612
1655
  ON CONFLICT(id) DO UPDATE SET
1613
1656
  created_at=excluded.created_at, status=excluded.status, error=excluded.error,
1614
1657
  provider=excluded.provider, model=excluded.model, snapshot_hash=excluded.snapshot_hash,
1615
1658
  input_count=excluded.input_count, input=excluded.input, decisions=excluded.decisions,
1616
1659
  outcome=excluded.outcome, applied=excluded.applied, summary_stored=excluded.summary_stored,
1617
1660
  receipt=excluded.receipt, policy_epoch=excluded.policy_epoch, run_type=excluded.run_type,
1618
- skipped=excluded.skipped`
1661
+ skipped=excluded.skipped, store_count=excluded.store_count, store_chars=excluded.store_chars`
1619
1662
  ).run(
1620
1663
  id,
1621
1664
  run.created_at ?? now,
@@ -1633,7 +1676,9 @@ export function createStore(path) {
1633
1676
  run.receipt,
1634
1677
  policyEpoch,
1635
1678
  runType,
1636
- skipped
1679
+ skipped,
1680
+ storeCount,
1681
+ storeChars
1637
1682
  );
1638
1683
  return getDreamRun(id);
1639
1684
  }
@@ -1667,6 +1712,27 @@ export function createStore(path) {
1667
1712
  return Number.isFinite(ms) ? ms : 0;
1668
1713
  }
1669
1714
 
1715
+ // Issue #89(基线半边):上次成功刷新后的阈值基线(活跃条数 / 正文字符数)。与
1716
+ // lastDreamRunAt 同源——审计表就是事实源,不另开一份状态;差别只在只认「推进过
1717
+ // 基线」的行(两列同时非 NULL = 那一轮是 ok)。按 run_type 隔离:sleep/organize
1718
+ // 的轮次不参与 auto 的阈值判定,混用会让其余模块的库规模假扮成巩固基线。
1719
+ // 认不出行时返回 null,调用方退回零基线(= 升级前行为),绝不假装知道基线。
1720
+ function lastDreamBaseline(runType = null) {
1721
+ const where = "store_count IS NOT NULL AND store_chars IS NOT NULL";
1722
+ const row = runType
1723
+ ? db.prepare(
1724
+ `SELECT store_count, store_chars FROM dream_runs
1725
+ WHERE run_type = ? AND ${where}
1726
+ ORDER BY created_at DESC, id LIMIT 1`
1727
+ ).get(runType)
1728
+ : db.prepare(
1729
+ `SELECT store_count, store_chars FROM dream_runs
1730
+ WHERE ${where} ORDER BY created_at DESC, id LIMIT 1`
1731
+ ).get();
1732
+ if (!row) return null;
1733
+ return { count: row.store_count, chars: row.store_chars };
1734
+ }
1735
+
1670
1736
  /**
1671
1737
  * Latest ruling-rule version seen on the audit trail. policy_epoch is a config
1672
1738
  * value stamped onto each run by the caller; reading the newest row's epoch
@@ -2402,8 +2468,13 @@ export function createStore(path) {
2402
2468
  /**
2403
2469
  * Record a typed relation between two entities. metadata (optional) is a
2404
2470
  * free-form JSON blob describing the relation. Relations are append-only.
2471
+ *
2472
+ * issue #24 块2(权重演化):source 决定边初值——manual 1.0 / confirmed
2473
+ * 保持 / tag 0.3 / llm 0.4;显式传入 weight 时优先于 source 映射(manual
2474
+ * 建边可自带权重)。哲学「关系是用出来的,不是建出来的」:初值只反映来源
2475
+ * 偏见,真正的抬升留给 bumpRelationWeight(touch 门控驱动)。
2405
2476
  */
2406
- function saveRelation({ from_entity, to_entity, relation_type, memory_id, metadata }) {
2477
+ function saveRelation({ from_entity, to_entity, relation_type, memory_id, metadata, weight, source }) {
2407
2478
  const id = randomUUID();
2408
2479
  const now = nowIso();
2409
2480
  const metaStr = metadata === undefined
@@ -2411,13 +2482,36 @@ export function createStore(path) {
2411
2482
  : typeof metadata === "string"
2412
2483
  ? metadata
2413
2484
  : JSON.stringify(metadata);
2485
+ const src = source ?? "manual";
2486
+ // 只认映射表的自有键:src="constructor"/"toString" 会命中原型链上的函数,直接查表
2487
+ // 拿到的是函数而非权重(绑进 SQL 就是整条写入抛错),必须回退默认 1.0。
2488
+ const w = weight ?? (Object.hasOwn(RELATION_SOURCE_DEFAULTS, src) ? RELATION_SOURCE_DEFAULTS[src] : 1.0);
2414
2489
  db.prepare(
2415
- `INSERT INTO entity_relations (id, from_entity, to_entity, relation_type, memory_id, created_at, metadata)
2416
- VALUES (?, ?, ?, ?, ?, ?, ?)`
2417
- ).run(id, from_entity, to_entity, relation_type, memory_id ?? null, now, metaStr);
2490
+ `INSERT INTO entity_relations (id, from_entity, to_entity, relation_type, memory_id, created_at, metadata, weight, source)
2491
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`
2492
+ ).run(id, from_entity, to_entity, relation_type, memory_id ?? null, now, metaStr, w, src);
2418
2493
  return toRelation(db.prepare("SELECT * FROM entity_relations WHERE id = ?").get(id));
2419
2494
  }
2420
2495
 
2496
+ /**
2497
+ * 边权重演化(issue #24 块2)。只加不减、封顶 1.0——权重只能靠「被用」抬升、
2498
+ * 不能靠被人为敲低,封顶防触达过频把边吹到无意义大。
2499
+ * 下界守在这里而不是调用方:增量为负/非有限数一律拒绝(返回 false)。限幅只留
2500
+ * 上界、把「只加不减」托付给配置范围,等于把存储接口的契约挂在调用方自觉上。
2501
+ * 读改写合并成单条 UPDATE(MIN(1.0, weight + ?)):memoryDir 可被多进程共用,
2502
+ * 先 SELECT 再 UPDATE 会丢并发增量,还会拿旧值把别人已抬升的权重压回去。
2503
+ * 幂等(缺行 changes=0 → false);delta 默认 0.1,由调用方(touch 门控)决定
2504
+ * 何时算一次有效触达。**作用在关系行**,与 memories 的 last_accessed_at 是两码
2505
+ * 事:这条是针对「这条边被激活了」的演化。
2506
+ */
2507
+ function bumpRelationWeight(id, delta = 0.1) {
2508
+ if (!Number.isFinite(delta) || delta < 0) return false;
2509
+ const result = db.prepare(
2510
+ "UPDATE entity_relations SET weight = MIN(1.0, weight + ?) WHERE id = ?"
2511
+ ).run(delta, id);
2512
+ return result.changes > 0;
2513
+ }
2514
+
2421
2515
  /**
2422
2516
  * Re-point every attr row whose memory_id is fromMemoryId to toMemoryId
2423
2517
  * (autoDream merge migration, v0.3.0 Phase 4 / 4.3.2). When the keeper
@@ -2459,6 +2553,52 @@ export function createStore(path) {
2459
2553
  ).all(entityId, entityId).map(toRelation);
2460
2554
  }
2461
2555
 
2556
+ /**
2557
+ /**
2558
+ * 批量邻接(issue #24 · 块1 锚定层级联):给定多条实体 id,一并取全部关系行
2559
+ * 并归并成「每个实体 → 相邻实体 id 去重列表」的邻接表。供 anchoring.js 的
2560
+ * cascadeDepths 使用——多实体一族只需要一次 SQL(IN 查询),比逐实体调
2561
+ * getRelations 的 N 次往返省。邻接是无向的(from/to 双向),往返不重复。
2562
+ * 返回 Map<entityId, Array<entityId>>;未命中的实体缺省为 absent(级联视为
2563
+ * 无邻居,Map 里不放键同行,null 同等对待)。
2564
+ */
2565
+ function getEntityNeighbors(entityIds) {
2566
+ const out = new Map();
2567
+ const ids = Array.isArray(entityIds) ? entityIds.filter(Boolean) : [];
2568
+ if (!ids.length) return out;
2569
+ const placeholders = ids.map(() => "?").join(",");
2570
+ const rows = db.prepare(
2571
+ `SELECT from_entity, to_entity FROM entity_relations
2572
+ WHERE from_entity IN (${placeholders}) OR to_entity IN (${placeholders})`
2573
+ ).all(...ids, ...ids);
2574
+ for (const r of rows) {
2575
+ addNeighbor(out, r.from_entity, r.to_entity, ids);
2576
+ addNeighbor(out, r.to_entity, r.from_entity, ids);
2577
+ }
2578
+ return out;
2579
+ }
2580
+
2581
+ function addNeighbor(out, anchor, neighbor, queryIds) {
2582
+ if (!queryIds.includes(anchor)) return; // 只以查询过的实体为锚
2583
+ if (neighbor === anchor) return; // 自环不构成扩散边
2584
+ if (!out.has(anchor)) out.set(anchor, []);
2585
+ const list = out.get(anchor);
2586
+ if (!list.includes(neighbor)) list.push(neighbor);
2587
+ }
2588
+
2589
+ /**
2590
+ * 按记忆反查关联边(issue #24 块4 被动确认):一条记忆被召回/注入(触达)
2591
+ * 时,挂在同一记忆上的关系行即「这条关系被用过了」的证据——正常触达视为
2592
+ * 被动确认,调用方据此 bumpRelationWeight。返回 toRelation 行(含 weight/
2593
+ * source)。索引 idx_relations_memory 已建(#219)。
2594
+ */
2595
+ function getRelationsByMemory(memoryId) {
2596
+ if (!memoryId) return [];
2597
+ return db.prepare(
2598
+ "SELECT * FROM entity_relations WHERE memory_id = ?"
2599
+ ).all(memoryId).map(toRelation);
2600
+ }
2601
+
2462
2602
  /** All entities (optionally name-filtered, newest first). Used by sleep phase 4
2463
2603
  * orphan detection: an entity with zero relations is a candidate for relation
2464
2604
  * completion. */
@@ -2788,6 +2928,7 @@ export function createStore(path) {
2788
2928
  searchVector,
2789
2929
  saveDreamRun,
2790
2930
  lastDreamRunAt,
2931
+ lastDreamBaseline,
2791
2932
  getDreamRun,
2792
2933
  listDreamRuns,
2793
2934
  getLatestPolicyEpoch,
@@ -2840,8 +2981,11 @@ export function createStore(path) {
2840
2981
  findEntitiesMentionedIn,
2841
2982
  getLinkedMemoryIds,
2842
2983
  saveRelation,
2984
+ bumpRelationWeight,
2843
2985
  migrateAttrsToMemory,
2844
2986
  getRelations,
2987
+ getEntityNeighbors,
2988
+ getRelationsByMemory,
2845
2989
  setMirrorState,
2846
2990
  getMirrorState,
2847
2991
  markMirrorDirty,