dsh-layers-hippocampus 1.6.9 → 1.7.0

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.
package/CHANGELOG.md CHANGED
@@ -4,6 +4,66 @@ All notable changes to `dsh-layers-hippocampus` are documented here.
4
4
  The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
5
5
  and the project adheres to [Semantic Versioning](https://semver.org/).
6
6
 
7
+ ## [1.7.0] — 2026-11-24
8
+
9
+ **全链路记忆的第二半:写入侧去重(实体)、检索侧联想(1 跳)、语义侧分层(六维人格)、
10
+ 隐私侧闸门(secret)、以及“模型不知道自己有哪些工具”的可观测性。**
11
+
12
+ - **Added — 实体归并(M1 本地半,零 Token)**。新增 `src/entityAlias.js`:
13
+ `entity:` 标签在**写入前**折向已有规范词——先查 `state/entity_alias.json` 字典,
14
+ 再判子串包含(已有 `entity:红薯` 时 `entity:烤红薯` 直接折向短词),最后是编辑距离
15
+ (相似度 ≥0.8 且长度差 ≤2,专治拼写错误)。折名结果改写的是**写入形状**,raw 日志照旧
16
+ append-only;同一批写入里连续出现的实体也互通(`_recentEntityWords` 兜住索引未跟上的窗口)。
17
+ 折名发生在 `stage()` 内、`_resolveTags()` 之前;早先传原始 tags 会让合并结果被整体覆盖。
18
+ - **Added — 别名字典落盘**。`state/entity_alias.json`(schema 1,`writeJsonAtomic`),
19
+ 词表可由 Dream 自动扩充,也可人工编辑。
20
+ - **Added — 离线同义词学习**。`DreamEngine.learnAliases()`:取过去 24h 新增 `entity:` 词
21
+ (<2 个词直接 skip),走与蒸馏**同一套** fetch 超时/鉴权/熔断设施发一次小请求
22
+ (`maxTokens = max(128, 词数×8+64)`),只接受 `{"aliases":{variant:canonical}}`;
23
+ `sanitiseAliasPairs(..., {known})` 要求 canonical **必须已存在**,否则等于凭空造节点。
24
+ 学到新词后 `markDirty()` + `invalidateAdjacency()`,索引重建时旧事件自动折到新节点
25
+ (日志不动,删空节点只是派生视图的事)。
26
+ - **Added — 1 跳联想召回(M2)**。新增 `src/tagGraph.js`:`buildAdjacency()` 把共现边编成
27
+ `Map<tag, [{tag,weight}]>`(对称、去重、权重降序、每节点最多 8 个邻居),
28
+ `expandOneHop()` 每条种子只做**一次** `Map.get`——没有队列、没有 visited 集,因此不存在图遍历。
29
+ `recall()` 新增 `adjacency` / `maxAssociativeHops`(默认 1)/ `associativeLimit`(默认 2):
30
+ >1 直接抛 `MEM_E_INVALID_INPUT: maxAssociativeHops must be <= 1: associative recall is a single
31
+ O(1) lookup, not a graph walk`(空索引也照样抛,参数错误不该被数据量掩盖);
32
+ 0 则完全关闭联想。命中的邻居以 `ASSOCIATION_PENALTY`(0.5)参与打分,
33
+ 最相似的 1–2 条 L3 摘要以半权重返回,并在 `associative` 里说明“经由哪个标签、几跳”。
34
+ 种子来自三处:显式查询标签、文本分词命中的标签、以及**在查询文本里被点名的实体**
35
+ (`entitySeedsMentioned()`,硬上限 200 次扫描)——所以“红薯怎么做”也能顺着图谱摸到 `topic:吃饭`。
36
+ - **Added — 时间窗加成**。`recall()` 的 `recentWindow`(`retrieval.recentWindowTurns`,默认 50 轮):
37
+ 窗口内事件按“离窗口末尾多近”给 1.2×–1.5× 加成。因为上限从 1.3 抬到 1.5,
38
+ 剪枝硬上界同步从 `salience × 3.9` 改为 **`salience × 4.5`**(剪枝仍是精确的,测试逐位比对)。
39
+ - **Added — 自动指针注入(M3)**。`context.autoInjectIndex`(默认 `{enabled:true, everyNTurns:3,
40
+ maxPointers:3, maxChars:300}`,也接受 `true`/`false` 简写):每 N 个 user turn 在
41
+ `[Memory Hints]` 之后追加 `[Memory Index]`,格式 `- [memory <eventId>] <tag> · <title>`,
42
+ **绝不注入正文**;单次硬限 300 字符;注入过的 eventId 进入同一个 `injectedIds` 去重池;
43
+ 活跃标签签名没变就保持沉默(不重复刷同一批指针);新会话 / 插件重启后立刻重新布防一次
44
+ ——这正是“重启后上下文空白”那个缺口的补丁。`/memory status` 会报 `[Memory Index]` 状态。
45
+ - **Added — L3 六维人格(M2)**。新增 `src/semantic/dimensions.js`:persona / preferences /
46
+ facts-rules / relationships / skills-patterns / boundaries;`upsert()` 接受 `dimension`
47
+ 并落 `dim:<dim>` 标签(**标签不变量仍按调用方原始 tags 校验**,`dim:` 不能当免标签后门);
48
+ 未指定时按 tag → 标题 → 关键词推断。`personaTraitsText()` 按维度排序并**逐行剥离生理状态**
49
+ (`PHYSIOLOGY_TERMS`:疲劳/心率/体温/激素…)——“不是人体,是人格”。
50
+ - **Added — 隐私闸门(M3)**。新增 `src/privacy.js`:带 `privacy:secret` 标签或
51
+ `meta.privacy='secret'` 的记录,`recall` **默认过滤**并在 `notes` 记 `privacy-withheld:<n>`;
52
+ 只有显式 `includeSecret`(工具参数 `include_secret`)才返回;secret 既不进
53
+ `[Memory Index]` 指针,也不做联想种子(不然隐私会从邻边漏出来)。
54
+ 判定与打标由调用方(情感插件)负责,本插件只提供接口与过滤。
55
+ - **Added — Dream 事实来源(M4)**。蒸馏输出契约扩展为
56
+ `{"summary","confidence","facts":[{"text","source"}],"dimension"}`;`source` 只认
57
+ `user`/`self`,**无主或非法的条目直接丢弃**(绝不默认成“用户说”),机械兜底
58
+ `localDistillation()` 也按事件 role 标注。facts 与 dimension 落进该 L3 记录的 `meta`。
59
+ - **Added — 交接摘要结构化(M1)**。`getLatestHandoffSummary()` 在保留 `text` 的同时新增
60
+ `activeTask` / `recentFacts` / `personaTraits` / `lastRawTurns`;`lastRawTurns` 条数由
61
+ `context.handoffSummaryTurns`(默认 4,范围 3–5)控制,**每条都带 role**——不接受无主纯文本。
62
+ - **Added — 工具使用证据(M5)**。`runtime.toolUsage` 统计每个工具的真实调用次数,
63
+ `/memory status` 新增「工具使用(本进程)」段;`remember/recall/capture/deep_raw`
64
+ 长期 0 次时直接建议 `/memory tools disable`。不新增任何模型请求。
65
+ - **Tests**:新增 `test/v170.dimensions.test.js`(7 例)。全量 **548/548**(86 个测试文件)。
66
+
7
67
  ## [1.6.9] — 2026-11-22
8
68
 
9
69
  **全链路记忆机制:写入时归并、检索时联想、装配时只给指针。**
package/README.md CHANGED
@@ -7,7 +7,7 @@
7
7
 
8
8
  | | |
9
9
  | --- | --- |
10
- | 版本 | **1.6.9** |
10
+ | 版本 | **1.7.0** |
11
11
  | 包名 | `dsh-layers-hippocampus` |
12
12
  | 仓库 | <https://github.com/382quaii/dsh-Layers-Hippocampus> |
13
13
  | 许可证 | MIT |
@@ -232,7 +232,7 @@ raw 层提供三档,覆盖从“只留关键”到“全留”:
232
232
  pnpm add dsh-layers-hippocampus
233
233
 
234
234
  # 或从 GitHub 指定 tag
235
- pnpm add "github:382quaii/dsh-Layers-Hippocampus#v1.6.9"
235
+ pnpm add "github:382quaii/dsh-Layers-Hippocampus#v1.7.0"
236
236
  ```
237
237
 
238
238
  ### 2. 挂到 profile
@@ -303,7 +303,7 @@ node scripts/wait-for-routes.mjs
303
303
  ### 6. 验证
304
304
 
305
305
  ```bash
306
- npm test # 进程内全量用例(541 个)
306
+ npm test # 进程内全量用例(548 个)
307
307
  npm run check # 语法检查 + 全量测试
308
308
  ```
309
309
 
@@ -1,6 +1,6 @@
1
1
  # @local/dsh-memory — 分层长期记忆 Host 插件
2
2
 
3
- > 版本:**1.6.9** | 全量用例:**541/541** | 运行时依赖:**零**
3
+ > 版本:**1.7.0** | 全量用例:**548/548** | 运行时依赖:**零**
4
4
 
5
5
  给 DSH 智能体一份"活得比会话久"的记忆:**追加式原始日志是唯一真相源**,标签索引、日记、活跃集合全部是可丢弃、可重建的读模型,语义摘要独立于原始日志生死。
6
6
 
@@ -681,7 +681,7 @@ window.__ModuleLoader__.load({
681
681
 
682
682
  运行器带**看门狗**:默认 **60s**(`MEM_TEST_TIMEOUT_MS` 可调)仍未退出,就打印**卡住时正在导入/执行的文件、最后完成的测试名与完成数、活动资源、尚未触发的定时器**,然后 `process.exit(1)`。它不会用 `process.exit(0)` 掩盖超时——挂起即失败。`MEM_TEST_TRACE=1` 可看文件级进度,`MEM_TEST_ONLY=<子串>` 只跑一组。
683
683
 
684
- 535 个用例(85 个文件)覆盖:
684
+ 548 个用例(86 个文件)覆盖:
685
685
 
686
686
  - 索引与标签:重建 digest 一致、行号漂移防护(eventId 不变、行号变)、同义合并、活跃集 cap 挤出、规则变更不改清单、空活跃集降级、top-k 有界有序去重。
687
687
  - 衰减与删除:30 天半衰期、reinforce 移动锚点(不存字段)、仅文本粗筛、标签过滤、维护代切换且旧代可读、boot 检查、压缩不丢记录、并发维护串行化、四阶段删除、archive 可回滚 vs purge 不可、strict 巩固暂停与恢复、任务重放幂等、错误 id 零变更。
package/index.js CHANGED
@@ -43,6 +43,8 @@ import { DreamTimer } from './src/dreamTimer.js';
43
43
  import { probeCompression, resolveEngine } from './src/compression.js';
44
44
  import { LIVE_COMPACT_DEFAULTS, liveCompactSession } from './src/context/liveCompact.js';
45
45
  import { snippet } from './src/util.js';
46
+ import { dimensionOf, groupByDimension, stripPhysiology, containsPhysiology } from './src/semantic/dimensions.js';
47
+ import { isSecretRecord } from './src/privacy.js';
46
48
  import { MEMORY_API, registerMemoryRoutes } from './src/webRoutes.js';
47
49
 
48
50
  export const name = 'memory';
@@ -63,7 +65,7 @@ export { resolveConfig, DEFAULT_CONFIG };
63
65
  * of letting a raw 404 reach the user.
64
66
  */
65
67
  export const CAPABILITIES = Object.freeze({
66
- version: '1.6.9',
68
+ version: '1.7.0',
67
69
  spaces: true,
68
70
  memories: true,
69
71
  transferConsent: true,
@@ -386,6 +388,12 @@ export function createRuntime({ ctx = null, config, options, clock, raw = null,
386
388
  };
387
389
 
388
390
  /** Called by every tool: keeps the dream idle clock honest. */
391
+ /**
392
+ * v1.7.0 (M5): per-tool call counts for THIS process (no model request, no file).
393
+ * The point is evidence: a tool that never gets called is prompt budget spent for
394
+ * nothing, and `/memory status` can say so.
395
+ */
396
+ runtime.toolUsage = { counts: new Map(), since: null };
389
397
  runtime.recordToolCall = ({ landed = false } = {}) => {
390
398
  runtime.syncAgentPreset();
391
399
  runtime.touch();
@@ -503,18 +511,42 @@ export function createRuntime({ ctx = null, config, options, clock, raw = null,
503
511
  .sort()
504
512
  .join(',')}`;
505
513
  if (runtime._personaCache?.signature === signature) return runtime._personaCache.text;
506
- const ranked = [...summaries]
514
+ const byConfidence = (left, right) =>
515
+ (Number(right.confidence) || 0) - (Number(left.confidence) || 0) ||
516
+ String(right.summaryId ?? '').localeCompare(String(left.summaryId ?? ''));
517
+ const oneLine = (value) => String(value ?? '').replace(/\s+/g, ' ').trim().slice(0, 240);
518
+ // v1.7.0 (M2): six dimensions, and NOTHING physiological. This plugin models a
519
+ // persona, not a body: a summary line that talks about fatigue/mood/heart-rate is
520
+ // dropped line-by-line (the rest of the same summary may still be persona), and a
521
+ // summary left with nothing is not rendered at all.
522
+ const cleaned = [];
523
+ for (const summary of [...summaries].sort(byConfidence)) {
524
+ const text = stripPhysiology(summary.text ?? '');
525
+ if (!text) continue;
526
+ cleaned.push({ ...summary, text });
527
+ if (cleaned.length >= 18) break;
528
+ }
529
+ if (cleaned.length === 0) return '';
530
+ // The dimension is a PREFIX, not a section header: one line per trait keeps the
531
+ // block the same size it was, and the order is grouped by dimension so a reader
532
+ // (human or model) can still scan it by category.
533
+ const dimensionOrder = new Map(
534
+ ['persona', 'preferences', 'facts-rules', 'relationships', 'skills-patterns', 'boundaries'].map((id, index) => [id, index]),
535
+ );
536
+ const ordered = cleaned
537
+ .map((summary) => ({ ...summary, dimension: dimensionOf(summary) }))
507
538
  .sort(
508
539
  (left, right) =>
509
- (Number(right.confidence) || 0) - (Number(left.confidence) || 0) ||
510
- String(right.summaryId ?? '').localeCompare(String(left.summaryId ?? '')),
540
+ (dimensionOrder.get(left.dimension) ?? 99) - (dimensionOrder.get(right.dimension) ?? 99) ||
541
+ byConfidence(left, right),
511
542
  )
512
543
  .slice(0, 10);
513
- if (ranked.length === 0) return '';
514
- const oneLine = (value) => String(value ?? '').replace(/\s+/g, ' ').trim().slice(0, 240);
544
+ if (ordered.length === 0) return '';
515
545
  const text = [
516
546
  '[Persona & Traits]',
517
- ...ranked.map((summary) => `- ${oneLine(summary.title) || 'trait'}: ${oneLine(summary.text)}`),
547
+ ...ordered.map(
548
+ (summary) => `- [${summary.dimension}] ${oneLine(summary.title) || summary.dimension}: ${oneLine(summary.text)}`,
549
+ ),
518
550
  ].join('\n');
519
551
  runtime._personaCache = { signature, text };
520
552
  return text;
@@ -646,6 +678,9 @@ export function createRuntime({ ctx = null, config, options, clock, raw = null,
646
678
  const best = postings.find((posting) => byId.has(posting.eventId));
647
679
  if (!best) continue;
648
680
  const event = byId.get(best.eventId);
681
+ // v1.7.0 (M3): a secret memory is never advertised as a pointer — the index
682
+ // would otherwise leak its existence into every prompt.
683
+ if (isSecretRecord(event)) continue;
649
684
  // A pointer already delivered in this session is never repeated.
650
685
  if (runtime.injection.ids.has(event.eventId)) continue;
651
686
  const title = snippet(String(event.content ?? ''), 60);
@@ -1468,15 +1503,67 @@ export function createRuntime({ ctx = null, config, options, clock, raw = null,
1468
1503
  tailTurns: Array.isArray(handoff?.tailTurns) ? handoff.tailTurns.map((turn) => ({ ...turn })) : [],
1469
1504
  text: null,
1470
1505
  found: false,
1506
+ // v1.7.0 (M1): a router plugin needs FIELDS, not a wall of prose. Every raw
1507
+ // turn below carries a role, so nothing here is unattributed text.
1508
+ activeTask: null,
1509
+ recentFacts: [],
1510
+ personaTraits: [],
1511
+ lastRawTurns: [],
1512
+ };
1513
+ const structured = () => {
1514
+ const turns = Math.max(3, Math.min(5, Number(runtime.config?.context?.handoffSummaryTurns) || 4));
1515
+ const tail = Array.isArray(base.tailTurns)
1516
+ ? base.tailTurns.filter((turn) => turn && typeof turn.text === 'string' && turn.text.length > 0)
1517
+ : [];
1518
+ const lastRawTurns = tail
1519
+ .slice(-turns)
1520
+ .map((turn) => ({ role: turn.role === 'assistant' ? 'assistant' : 'user', text: String(turn.text).slice(0, 600) }));
1521
+ let activeTask = null;
1522
+ try {
1523
+ const task = memory.promptActiveTask?.();
1524
+ if (task?.text) {
1525
+ activeTask = {
1526
+ eventId: task.eventId ?? null,
1527
+ text: String(task.text).replace(/\s+/g, ' ').trim().slice(0, 600),
1528
+ };
1529
+ }
1530
+ } catch {
1531
+ activeTask = null;
1532
+ }
1533
+ let summaries = [];
1534
+ try {
1535
+ summaries = typeof memory.semanticStore?.list === 'function' ? memory.semanticStore.list() : [];
1536
+ } catch {
1537
+ summaries = [];
1538
+ }
1539
+ const buckets = groupByDimension(summaries.filter((summary) => !containsPhysiology(summary.text ?? '')));
1540
+ const slim = (list, dimension, limit) =>
1541
+ (list ?? [])
1542
+ .slice()
1543
+ .sort((left, right) => (Number(right.confidence) || 0) - (Number(left.confidence) || 0))
1544
+ .slice(0, limit)
1545
+ .map((summary) => ({
1546
+ dimension,
1547
+ summaryId: summary.summaryId ?? null,
1548
+ text: String(stripPhysiology(summary.text ?? '') || '').replace(/\s+/g, ' ').trim().slice(0, 300),
1549
+ }))
1550
+ .filter((entry) => entry.text.length > 0);
1551
+ return {
1552
+ ...base,
1553
+ activeTask,
1554
+ recentFacts: slim(buckets.get('facts-rules'), 'facts-rules', 5),
1555
+ personaTraits: slim(buckets.get('persona'), 'persona', 5),
1556
+ lastRawTurns,
1557
+ };
1471
1558
  };
1472
- if (!handoff?.summaryEventId) return base;
1559
+ if (!handoff?.summaryEventId) return { ...base, ...structured() };
1473
1560
  try {
1474
1561
  const events = memory.indexManager.snapshot()?.events ?? [];
1475
1562
  const event = events.find((entry) => entry?.eventId === handoff.summaryEventId);
1476
- if (!event?.content) return base;
1477
- return { ...base, text: String(event.content).slice(0, 4000), found: true };
1563
+ if (!event?.content) return { ...base, ...structured() };
1564
+ return { ...base, ...structured(), text: String(event.content).slice(0, 4000), found: true };
1478
1565
  } catch {
1479
- return base;
1566
+ return { ...base, ...structured() };
1480
1567
  }
1481
1568
  };
1482
1569
 
@@ -2196,7 +2283,18 @@ export async function apply(ctx, rawConfig = {}) {
2196
2283
  ctx.logger?.info?.(`hippocampus: tool ${definition.name} skipped by disabled feature flags`);
2197
2284
  return;
2198
2285
  }
2199
- disposers.push(ctx.tools.register(definition));
2286
+ // v1.7.0 (M5): count calls per tool so `/memory status` can show real usage
2287
+ // evidence instead of guessing. Wrapping here (one place) keeps the 10 tool
2288
+ // definitions untouched and costs no model tokens.
2289
+ const counted = {
2290
+ ...definition,
2291
+ execute: (args, context) => {
2292
+ const name = String(definition.name ?? '').replace(`${config.toolPrefix}_`, '');
2293
+ if (name) runtime.toolUsage.counts.set(name, (runtime.toolUsage.counts.get(name) ?? 0) + 1);
2294
+ return definition.execute(args, context);
2295
+ },
2296
+ };
2297
+ disposers.push(ctx.tools.register(counted));
2200
2298
  };
2201
2299
  const toolLine = (suffix, text) =>
2202
2300
  disabledToolSuffixes.has(suffix) || featureDisabledSuffix(suffix) ? null : `- ${config.toolPrefix}_${suffix}: ${text}`;
@@ -2408,6 +2506,12 @@ export async function apply(ctx, rawConfig = {}) {
2408
2506
  max_tokens: { type: 'number', description: 'deep_raw only: result token budget, default from raw.maxResultTokens' },
2409
2507
  hash: { type: 'string', description: 'deep_raw only: restore one raw turn verbatim by sha256 (from [Slimmed] hash_…)' },
2410
2508
  regex: { type: 'boolean', description: 'deep_raw only: treat text as a restricted regular expression' },
2509
+ include_secret: {
2510
+ type: 'boolean',
2511
+ description:
2512
+ 'Include memories tagged privacy:secret. Omitted by default: secret records are filtered out and only ' +
2513
+ 'a count appears in notes (privacy-withheld:N).',
2514
+ },
2411
2515
  },
2412
2516
  output: { schema: { type: 'string' }, render: (_args, value) => toolResult(value) },
2413
2517
  execute: async (args = {}) =>
@@ -2439,6 +2543,7 @@ export async function apply(ctx, rawConfig = {}) {
2439
2543
  tags: args.tags ?? [],
2440
2544
  topK: Math.min(args.top_k ?? config.retrieval.topK, config.maxRecallTopK),
2441
2545
  targetSpaceId: args.target_space_id,
2546
+ includeSecret: args.include_secret === true,
2442
2547
  });
2443
2548
  runtime.recordToolCall({
2444
2549
  landed: (result.hits ?? []).length > 0 || (result.ghostHints ?? []).length > 0,
@@ -3030,6 +3135,15 @@ export async function apply(ctx, rawConfig = {}) {
3030
3135
  return ok(parts.length > 0 ? `维护完成:${parts.join(';')}。` : '维护完成:本轮无变更。');
3031
3136
  }
3032
3137
 
3138
+ const toolUsageLine = () => {
3139
+ const counts = [...runtime.toolUsage.counts.entries()].sort((left, right) => right[1] - left[1]);
3140
+ if (counts.length === 0) return '本进程尚无工具调用(重启会清零)';
3141
+ const shown = counts.slice(0, 6).map(([name, count]) => `${name} ${count}`);
3142
+ const idle = ['remember', 'recall', 'capture', 'deep_raw'].filter((name) => !runtime.toolUsage.counts.get(name));
3143
+ const advice = idle.length > 0 ? `;长时间 0 次:${idle.join('/')}(可考虑 /memory tools disable)` : '';
3144
+ return `${shown.join(' · ')}${advice}`;
3145
+ };
3146
+
3033
3147
  if (verb === 'status') {
3034
3148
  if (runtime.phase !== 'ready') return fail(`记忆引擎状态:${runtime.phase}${runtime.phaseError ? `(${asMemoryError(runtime.phaseError).code})` : ''}`);
3035
3149
  const payload = await runtime.uiPayload();
@@ -3054,6 +3168,8 @@ export async function apply(ctx, rawConfig = {}) {
3054
3168
  `交接标记:${session.handoffActive ? `active(${session.handoffAt ?? '?'})` : '无'} · 冷启动待注入 ${runtime.coldStart.pending.size} 条 / 已注入 ${runtime.coldStart.injected.size} 次`,
3055
3169
  tagList.length ? `活跃标签 Top:${tagList.join('、')}` : '活跃标签:无',
3056
3170
  `[Memory Hints]:${runtime.hintsMuted ? '已静默(/memory unmute 恢复)' : '开启'}`,
3171
+ // v1.7.0 (M5): usage EVIDENCE, computed from in-process counters only.
3172
+ `工具使用(本进程):${toolUsageLine()}`,
3057
3173
  ].join('\n'),
3058
3174
  );
3059
3175
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-layers-hippocampus",
3
- "version": "1.6.9",
3
+ "version": "1.7.0",
4
4
  "private": false,
5
5
  "description": "Layered long-term memory for DeepSeek Harness: append-only event log, rebuildable tag index, day diaries, independent semantic layer, L2.5 trend quarantine, offline knowledge graph and a Web UI panel.",
6
6
  "type": "module",
package/src/config.js CHANGED
@@ -218,6 +218,9 @@ export const DEFAULT_CONFIG = Object.freeze({
218
218
  // - recentTurns: inject the last few turns of the handed-off conversation
219
219
  // (v1.6.3 default ON: a new conversation must not start "blind")
220
220
  coldStartInjectSummary: true,
221
+ // v1.7.0 (M1): how many raw tail turns `getLatestHandoffSummary()` carries.
222
+ // Bounded 3..5: fewer loses the thread, more is a second transcript.
223
+ handoffSummaryTurns: 4,
221
224
  coldStartInjectRecentTurns: true,
222
225
  // REMOVED in v1.5.3: `minInjectConfidence`. It never demonstrably saved tokens
223
226
  // (0.6 vs 0 produced byte-identical payloads) and every hit-shaping pass is a
@@ -832,6 +835,11 @@ function buildResolvedConfig(raw = {}, { env = process.env } = {}) {
832
835
  : contextIn.coldStartInjectSummary,
833
836
  'context.coldStartInjectSummary',
834
837
  );
838
+ const contextHandoffSummaryTurns = requireInteger(
839
+ contextIn.handoffSummaryTurns === undefined ? defaults.context.handoffSummaryTurns : contextIn.handoffSummaryTurns,
840
+ 'context.handoffSummaryTurns',
841
+ { min: 3, max: 5 },
842
+ );
835
843
  const contextColdStartInjectRecentTurns = requireBoolean(
836
844
  contextIn.coldStartInjectRecentTurns === undefined
837
845
  ? defaults.context.coldStartInjectRecentTurns
@@ -1468,6 +1476,7 @@ function buildResolvedConfig(raw = {}, { env = process.env } = {}) {
1468
1476
  },
1469
1477
  // v1.6.3 cold-start injection switches (independent booleans).
1470
1478
  coldStartInjectSummary: contextColdStartInjectSummary,
1479
+ handoffSummaryTurns: contextHandoffSummaryTurns,
1471
1480
  coldStartInjectRecentTurns: contextColdStartInjectRecentTurns,
1472
1481
  // v1.5.0 routing knobs below; v1.5.3 removed minInjectConfidence entirely.
1473
1482
  autoSpaceFollow: contextAutoSpaceFollow,
package/src/dream.js CHANGED
@@ -155,7 +155,34 @@ export function parseDistillation(text, { maxSummaryChars = 200 } = {}) {
155
155
  got: parsed.confidence ?? null,
156
156
  });
157
157
  }
158
- return { summary, confidence };
158
+ return { summary, confidence, facts: parseFacts(parsed.facts), dimension: parseDimension(parsed.dimension) };
159
+ }
160
+
161
+ const FACT_SOURCES = Object.freeze(['user', 'self']);
162
+
163
+ /**
164
+ * v1.7.0 (M4): validate the fact list. A fact without a valid `source` is DROPPED,
165
+ * not assumed to be the user's — "unattributed" is exactly the failure this fixes.
166
+ */
167
+ export function parseFacts(value, { limit = 5, maxChars = 200 } = {}) {
168
+ if (!Array.isArray(value)) return [];
169
+ const out = [];
170
+ for (const entry of value) {
171
+ const text = typeof entry?.text === 'string' ? entry.text.trim() : '';
172
+ const source = typeof entry?.source === 'string' ? entry.source.trim().toLowerCase() : '';
173
+ if (!text || !FACT_SOURCES.includes(source)) continue;
174
+ out.push({ text: text.slice(0, maxChars), source });
175
+ if (out.length >= limit) break;
176
+ }
177
+ return out;
178
+ }
179
+
180
+ /** v1.7.0 (M2): the model may name the dimension; anything else falls back to null. */
181
+ export function parseDimension(value) {
182
+ if (typeof value !== 'string') return null;
183
+ const key = value.trim().toLowerCase();
184
+ const allowed = ['persona', 'preferences', 'facts-rules', 'relationships', 'skills-patterns', 'boundaries'];
185
+ return allowed.includes(key) ? key : null;
159
186
  }
160
187
 
161
188
  /**
@@ -183,16 +210,33 @@ export function localDistillation(tag, events = [], { maxSummaryChars = 200 } =
183
210
  }
184
211
  let text = `经验·${tag}(${ordered.length} 条 / ${first}~${last}):${cores.join(';') || '(无可用文本)'}`;
185
212
  if (text.length > maxSummaryChars) text = `${text.slice(0, Math.max(1, maxSummaryChars - 1))}…`;
186
- return { summary: text, confidence: 0.5, mode: 'local' };
213
+ // v1.7.0 (M4): the mechanical fallback still attributes provenance from the
214
+ // recorded role, so a local merge never produces an unattributed fact either.
215
+ const facts = [];
216
+ for (const event of ordered) {
217
+ const role = event.role === 'assistant' ? 'self' : event.role === 'user' ? 'user' : null;
218
+ if (!role) continue;
219
+ const text = cleanText(snippet(event.content, 120));
220
+ if (!text) continue;
221
+ if (facts.some((fact) => fact.text === text && fact.source === role)) continue;
222
+ facts.push({ text, source: role });
223
+ if (facts.length >= 3) break;
224
+ }
225
+ return { summary: text, confidence: 0.5, mode: 'local', facts };
187
226
  }
188
227
 
189
228
  function systemPrompt(config) {
190
229
  return [
191
230
  '你是长期记忆蒸馏器。只输出一个 JSON 对象,不要 Markdown 代码块,不要任何解释。',
192
- '输出格式:{"summary":"...","confidence":0.0}',
231
+ '输出格式:{"summary":"...","confidence":0.0,"facts":[{"text":"...","source":"user"}],"dimension":"facts-rules"}',
232
+ // v1.7.0 (M4): provenance is a first-class field. "用户说过" and "我说过" are not
233
+ // the same knowledge: one is a preference to honour, the other is a claim to keep.
234
+ '3) facts 最多 5 条,每条必须写 source:"user"(用户说过的事实/偏好)或 "self"(我自己的结论/习惯),禁止无主陈述;',
235
+ '4) dimension 必须取 persona / preferences / facts-rules / relationships / skills-patterns / boundaries 之一;',
236
+ '5) 严禁输出生理或身体状态(疲劳、情绪、体温、心率等)——这里记录的是人格,不是人体;',
193
237
  `规则:1) summary 必须是 <= ${config.maxSummaryChars} 个字符的中文经验结论,只压缩可复用的根因/做法/教训,严禁编造;`,
194
238
  '2) confidence 是 0..1 的数字,表示结论的可信度;',
195
- '3) 不要输出事件 id、时间戳或来源信息;4) 信息不足时仍输出 JSON,summary 写“经验不足,待补充”。',
239
+ '6) 不要输出事件 id、时间戳或来源信息;7) 信息不足时仍输出 JSON,summary 写“经验不足,待补充”。',
196
240
  ].join('\n');
197
241
  }
198
242
 
@@ -456,12 +500,19 @@ export class DreamEngine {
456
500
  let distilledBy = 'local';
457
501
  let fallbackReason = null;
458
502
  let failure = null;
503
+ // v1.7.0 (M4): provenance travels with the summary. `facts` is only ever filled
504
+ // from a source that names its owner (parseFacts drops the rest); `dimension` may
505
+ // stay null and is then inferred by the L3 store from the text.
506
+ let facts = [];
507
+ let dimension = null;
459
508
 
460
509
  if (config.useLlm && isLlmConfigured(config.llm) && this._circuitAllows(now)) {
461
510
  try {
462
511
  const result = await this._callLlm({ tag, sources, config, now });
463
512
  summary = result.summary;
464
513
  confidence = result.confidence;
514
+ facts = result.facts ?? [];
515
+ dimension = result.dimension ?? null;
465
516
  distilledBy = 'llm';
466
517
  this._recordLlmSuccess();
467
518
  } catch (error) {
@@ -482,6 +533,7 @@ export class DreamEngine {
482
533
  const local = localDistillation(tag, sources, { maxSummaryChars: config.maxSummaryChars });
483
534
  summary = local.summary;
484
535
  confidence = local.confidence;
536
+ facts = local.facts ?? [];
485
537
  distilledBy = 'local';
486
538
  }
487
539
 
@@ -496,6 +548,8 @@ export class DreamEngine {
496
548
  distilled_by: distilledBy,
497
549
  source_event_ids: sourceEventIds,
498
550
  confidence,
551
+ ...(facts.length > 0 ? { facts } : {}),
552
+ ...(dimension ? { dimension } : {}),
499
553
  },
500
554
  });
501
555
  const eventId = result?.eventId ?? null;
package/src/memory.js CHANGED
@@ -115,6 +115,7 @@ function validateRoutedNewSpaceId(value) {
115
115
  }
116
116
  import { ensureDir, dayKey, genNumber, sha256, readJson, writeJsonAtomic, snippet } from './util.js';
117
117
  import { detectCiphertext } from './entropy.js';
118
+ import { filterSecret, isSecretRecord, privacyMetaFor } from './privacy.js';
118
119
 
119
120
  /** Recursive byte size of a directory tree (symlinks count as their target size). */
120
121
  function diskUsage(dir) {
@@ -805,6 +806,13 @@ export class Memory {
805
806
  if (entityMerged) {
806
807
  payloadMeta = { ...(payloadMeta && typeof payloadMeta === 'object' ? payloadMeta : {}), entity_merged: entityMerged };
807
808
  }
809
+ // v1.7.0 (M3): the engine does not DECIDE what is secret — the emotion plugin
810
+ // does, by tagging the write. Here we only make the interface honest: store it
811
+ // verbatim, record the fact in meta, and filter it out of every ordinary read.
812
+ const secretMeta = privacyMetaFor(tagInfo.tags);
813
+ if (secretMeta) {
814
+ payloadMeta = { ...(payloadMeta && typeof payloadMeta === 'object' ? payloadMeta : {}), ...secretMeta };
815
+ }
808
816
  const payload = {
809
817
  content,
810
818
  tags: tagInfo.tags,
@@ -1319,7 +1327,7 @@ export class Memory {
1319
1327
  }
1320
1328
 
1321
1329
  /** The space-local read path. */
1322
- async _recallLocal({ text = '', tags = [], topK, maxAssociativeHops } = {}, { mergeRecall = true } = {}) {
1330
+ async _recallLocal({ text = '', tags = [], topK, maxAssociativeHops, includeSecret = false } = {}, { mergeRecall = true } = {}) {
1323
1331
  this.assertOpen();
1324
1332
  const now = this.clock.now();
1325
1333
  // v1.6.9: validated BEFORE any work (and before the empty-index shortcut) so an
@@ -1354,7 +1362,8 @@ export class Memory {
1354
1362
  canonicalTags.length > 0 &&
1355
1363
  canonicalTags.every((tag) => this._oversizedHintTags.has(tag)) &&
1356
1364
  this._oversizedHintTags.size > 0;
1357
- const semantic = this.semanticSummaries();
1365
+ // v1.7.0 (M3): secret summaries are not candidates unless explicitly requested.
1366
+ const semantic = filterSecret(this.semanticSummaries(), { includeSecret }).list;
1358
1367
  const tempSemantic = this.tempStore.list({ status: 'temp', now });
1359
1368
  const associations = this.graphAssociations({ tags, text });
1360
1369
  // v1.6.9 (module 2): the O(1) neighbour table + the recent-turn window. Both are
@@ -1388,9 +1397,12 @@ export class Memory {
1388
1397
  // recalled, the memo wins and duplicates collapse. Only when the Orchestrator
1389
1398
  // dedupe service is present; the pure core keeps its previous payload shape.
1390
1399
  const merged = mergeRecall ? this.mergeRecallHits(ghostPass.hits) : { hits: ghostPass.hits, stats: null };
1400
+ // v1.7.0 (M3): the last gate before a hit can reach the model. `withheld` is a
1401
+ // COUNT only — a caller may learn that something was withheld, never what it was.
1402
+ const visible = filterSecret(merged.hits, { includeSecret });
1391
1403
  const payload = {
1392
1404
  ...result,
1393
- hits: merged.hits,
1405
+ hits: visible.list,
1394
1406
  ...(merged.stats ? { merge: merged.stats } : {}),
1395
1407
  ghostHints: ghostPass.ghostHints,
1396
1408
  oversizedTagHints: result.oversizedTagHints ?? [],
@@ -1404,6 +1416,7 @@ export class Memory {
1404
1416
  ...ghostPass.notes,
1405
1417
  ...(associations.length > 0 ? [`graph-associations:${associations.length}`] : []),
1406
1418
  ...(merged.stats ? [`read-merge:${merged.stats.total}`] : []),
1419
+ ...(visible.withheld > 0 ? [`privacy-withheld:${visible.withheld}`] : []),
1407
1420
  ...(this._boot && this._boot.status !== 'ok' ? [`boot-check:${this._boot.status}`] : []),
1408
1421
  ],
1409
1422
  };
package/src/privacy.js ADDED
@@ -0,0 +1,63 @@
1
+ /**
2
+ * `privacy:secret` (v1.7.0, roadmap item M3).
3
+ *
4
+ * Boundary decision (2026-11-24): the MEMORY plugin owns the INTERFACE and the
5
+ * FILTERING; it does NOT decide what is secret. Deciding "this is private" is
6
+ * semantic understanding, and that belongs to the emotion plugin, which calls
7
+ * `remember({ tags: ['privacy:secret'] })` after it has decided.
8
+ *
9
+ * What the memory side guarantees here:
10
+ * - the write is stored verbatim (no redaction, no dropping) with `meta.privacy`;
11
+ * - ordinary retrieval NEVER returns it: recall/associative/hints/pointers all skip
12
+ * it unless the caller explicitly asks with `includeSecret: true`;
13
+ * - it is not federated to other spaces and not turned into a hint tag.
14
+ */
15
+
16
+ export const PRIVACY_SECRET_TAG = 'privacy:secret';
17
+ export const PRIVACY_META_KEY = 'privacy';
18
+ export const PRIVACY_SECRET_VALUE = 'secret';
19
+
20
+ /** True when this tag list declares the record secret. */
21
+ export function isSecretTags(tags) {
22
+ for (const entry of Array.isArray(tags) ? tags : []) {
23
+ const tag = typeof entry === 'string' ? entry : entry?.tag;
24
+ if (tag === PRIVACY_SECRET_TAG) return true;
25
+ }
26
+ return false;
27
+ }
28
+
29
+ /**
30
+ * True when a stored episode/summary/hit is secret. Checks the tag list AND the
31
+ * recorded meta, because a record written before the tag was understood may only
32
+ * carry `meta.privacy`.
33
+ */
34
+ export function isSecretRecord(record) {
35
+ if (!record || typeof record !== 'object') return false;
36
+ if (isSecretTags(record.tags)) return true;
37
+ const meta = record.meta;
38
+ return Boolean(meta && typeof meta === 'object' && meta[PRIVACY_META_KEY] === PRIVACY_SECRET_VALUE);
39
+ }
40
+
41
+ /**
42
+ * Filter a list of records/hits for ordinary retrieval.
43
+ *
44
+ * `includeSecret === true` returns everything; otherwise secret records are removed
45
+ * and counted, so a caller can report "there is more, ask explicitly" without
46
+ * leaking a single character of the content.
47
+ */
48
+ export function filterSecret(records, { includeSecret = false } = {}) {
49
+ const list = Array.isArray(records) ? records : [];
50
+ if (includeSecret === true) return { list, withheld: 0 };
51
+ const kept = [];
52
+ let withheld = 0;
53
+ for (const record of list) {
54
+ if (isSecretRecord(record)) withheld += 1;
55
+ else kept.push(record);
56
+ }
57
+ return { list: kept, withheld };
58
+ }
59
+
60
+ /** The meta patch to merge into a write that declares the secret tag. */
61
+ export function privacyMetaFor(tags) {
62
+ return isSecretTags(tags) ? { [PRIVACY_META_KEY]: PRIVACY_SECRET_VALUE } : null;
63
+ }
package/src/retrieval.js CHANGED
@@ -21,6 +21,7 @@ import { ErrorCodes, MemoryError } from './errors.js';
21
21
  import { normaliseTagToken } from './policy.js';
22
22
  import { classifyHit, parseTagPath, DAY_MS } from './tagTreeRebuild.js';
23
23
  import { assertAssociativeHops } from './tagGraph.js';
24
+ import { PRIVACY_SECRET_TAG } from './privacy.js';
24
25
  import { clamp, round, snippet } from './util.js';
25
26
 
26
27
  const TOKEN_RE = /[a-z0-9]{2,}|[\u4e00-\u9fff]{1,}/gi;
@@ -277,6 +278,9 @@ function entitySeedsMentioned({ index, text }) {
277
278
  const seeds = [];
278
279
  let scanned = 0;
279
280
  for (const tag of tags) {
281
+ // v1.7.0 (M3): a secret tag never becomes a seed, so its neighbours cannot be
282
+ // used to reach the secret sideways through graph association.
283
+ if (tag === PRIVACY_SECRET_TAG) continue;
280
284
  if (!tag.startsWith('entity:')) continue;
281
285
  if (scanned >= ASSOCIATIVE_SEED_SCAN_CAP) break;
282
286
  scanned += 1;
@@ -0,0 +1,169 @@
1
+ /**
2
+ * L3 six dimensions (v1.7.0, roadmap item M2).
3
+ *
4
+ * The semantic layer used to be a flat pile of free-text summaries ranked only by
5
+ * confidence. That is unusable as a persona: the model cannot tell a PREFERENCE from
6
+ * a FACT, and nothing stopped physiological state ("fatigue", "mood") from being
7
+ * written as personality.
8
+ *
9
+ * Contract:
10
+ * - every L3 record carries exactly ONE `dimension` out of `L3_DIMENSIONS`;
11
+ * - the dimension is also written as a `dim:<dimension>` tag, so tag-driven
12
+ * retrieval can reach it with no new index structure;
13
+ * - physiological / body-state vocabulary is REFUSED at the boundary: this plugin
14
+ * models a persona, not a body (user decision 2026-11-24).
15
+ */
16
+
17
+ /** The six dimensions, in the order they are rendered into the prompt. */
18
+ export const L3_DIMENSIONS = Object.freeze([
19
+ 'persona',
20
+ 'preferences',
21
+ 'facts-rules',
22
+ 'relationships',
23
+ 'skills-patterns',
24
+ 'boundaries',
25
+ ]);
26
+
27
+ export const DIMENSION_TAG_PREFIX = 'dim:';
28
+
29
+ /** Default when nothing can be inferred: a durable statement is a fact or a rule. */
30
+ export const DEFAULT_DIMENSION = 'facts-rules';
31
+
32
+ /**
33
+ * Physiological / body-state vocabulary. A summary that carries any of these is NOT
34
+ * a persona trait — the emotion plugin owns the body; the memory plugin refuses it
35
+ * so "fatigue 0.31" can never be inherited as a personality.
36
+ */
37
+ export const PHYSIOLOGY_TERMS = Object.freeze([
38
+ 'bodystate',
39
+ 'body_state',
40
+ 'fatigue',
41
+ 'mood',
42
+ 'hormone',
43
+ 'heart-rate',
44
+ 'heartrate',
45
+ '体温',
46
+ '心率',
47
+ '心跳',
48
+ '疲劳',
49
+ '体力',
50
+ '精力值',
51
+ '激素',
52
+ '生理状态',
53
+ '情动值',
54
+ '血糖',
55
+ '血压',
56
+ '困倦',
57
+ ]);
58
+
59
+ /** Aliases accepted from callers/LLMs, mapped onto the enumeration. */
60
+ const DIMENSION_ALIASES = Object.freeze({
61
+ persona: 'persona',
62
+ personality: 'persona',
63
+ identity: 'persona',
64
+ preference: 'preferences',
65
+ preferences: 'preferences',
66
+ habit: 'preferences',
67
+ 偏好: 'preferences',
68
+ fact: 'facts-rules',
69
+ facts: 'facts-rules',
70
+ rule: 'facts-rules',
71
+ rules: 'facts-rules',
72
+ 'facts-rules': 'facts-rules',
73
+ factsrules: 'facts-rules',
74
+ relationship: 'relationships',
75
+ relationships: 'relationships',
76
+ relation: 'relationships',
77
+ skill: 'skills-patterns',
78
+ skills: 'skills-patterns',
79
+ patterns: 'skills-patterns',
80
+ 'skills-patterns': 'skills-patterns',
81
+ boundary: 'boundaries',
82
+ boundaries: 'boundaries',
83
+ limit: 'boundaries',
84
+ limits: 'boundaries',
85
+ });
86
+
87
+ const DIMENSION_PATTERNS = [
88
+ [/^(?:pref|偏好|喜欢|习惯)/, 'preferences'],
89
+ [/^(?:rel|关系|人际)/, 'relationships'],
90
+ [/^(?:skill|pattern|技能|模式|做法)/, 'skills-patterns'],
91
+ [/^(?:bound|boundary|边界|红线|底线)/, 'boundaries'],
92
+ [/^(?:persona|人格|性格|身份)/, 'persona'],
93
+ [/^(?:fact|rule|事实|规则|结论)/, 'facts-rules'],
94
+ ];
95
+
96
+ /**
97
+ * Normalise anything the caller/LLM sends into one of the six dimensions.
98
+ * @returns {string|null} `null` when the value is not a recognisable dimension.
99
+ */
100
+ export function normaliseDimension(value) {
101
+ if (typeof value !== 'string') return null;
102
+ const key = value.trim().toLowerCase();
103
+ if (key.length === 0) return null;
104
+ if (DIMENSION_ALIASES[key]) return DIMENSION_ALIASES[key];
105
+ for (const [pattern, dimension] of DIMENSION_PATTERNS) {
106
+ if (pattern.test(key)) return dimension;
107
+ }
108
+ return null;
109
+ }
110
+
111
+ export function dimensionTag(dimension) {
112
+ return `${DIMENSION_TAG_PREFIX}${dimension}`;
113
+ }
114
+
115
+ /** True when the text names a physiological state (never persona material). */
116
+ export function containsPhysiology(text) {
117
+ const haystack = String(text ?? '').toLowerCase();
118
+ if (haystack.length === 0) return false;
119
+ return PHYSIOLOGY_TERMS.some((term) => haystack.includes(term));
120
+ }
121
+
122
+ /** Drop the offending lines instead of the whole record: the rest may be persona. */
123
+ export function stripPhysiology(text) {
124
+ const lines = String(text ?? '').split(/\r?\n/);
125
+ const kept = lines.filter((line) => !containsPhysiology(line));
126
+ return kept.join('\n').trim();
127
+ }
128
+
129
+ /**
130
+ * Deterministic dimension inference: tags win, then title/text keywords, then the
131
+ * default. Mechanical on purpose — it must work with no model call, offline, inside
132
+ * the delete pipeline.
133
+ */
134
+ export function inferDimension({ title = '', text = '', tags = [] } = {}) {
135
+ for (const entry of Array.isArray(tags) ? tags : []) {
136
+ const tag = typeof entry === 'string' ? entry : entry?.tag;
137
+ if (typeof tag !== 'string') continue;
138
+ if (!tag.startsWith(DIMENSION_TAG_PREFIX)) continue;
139
+ const normalised = normaliseDimension(tag.slice(DIMENSION_TAG_PREFIX.length));
140
+ if (normalised) return normalised;
141
+ }
142
+ const titleDimension = normaliseDimension(title);
143
+ if (titleDimension) return titleDimension;
144
+ const haystack = `${title} ${text}`.toLowerCase();
145
+ if (/偏好|喜欢|更喜欢|习惯用|prefer/.test(haystack)) return 'preferences';
146
+ if (/关系|称呼|对我|朋友|队友|relationship/.test(haystack)) return 'relationships';
147
+ if (/技能|做法|套路|模式|流程|skill|pattern/.test(haystack)) return 'skills-patterns';
148
+ if (/边界|红线|底线|禁止|不得|boundary|never/.test(haystack)) return 'boundaries';
149
+ if (/人格|性格|身份|persona|personality/.test(haystack)) return 'persona';
150
+ return DEFAULT_DIMENSION;
151
+ }
152
+
153
+ /** The dimension recorded on one L3 record (`dim:` tag first, then the field). */
154
+ export function dimensionOf(summary = {}) {
155
+ const explicit = normaliseDimension(summary?.dimension);
156
+ if (explicit) return explicit;
157
+ return inferDimension({ title: summary?.title ?? '', text: summary?.text ?? '', tags: summary?.tags ?? [] });
158
+ }
159
+
160
+ /** Group summaries by dimension, preserving the canonical dimension order. */
161
+ export function groupByDimension(summaries = []) {
162
+ const buckets = new Map(L3_DIMENSIONS.map((dimension) => [dimension, []]));
163
+ for (const summary of Array.isArray(summaries) ? summaries : []) {
164
+ const dimension = dimensionOf(summary);
165
+ if (!buckets.has(dimension)) buckets.set(dimension, []);
166
+ buckets.get(dimension).push(summary);
167
+ }
168
+ return buckets;
169
+ }
@@ -24,6 +24,7 @@ import {
24
24
  import { normaliseTagToken } from '../policy.js';
25
25
  import { extractTags } from '../tagging.js';
26
26
  import { controlIdFor } from '../identity.js';
27
+ import { dimensionTag, inferDimension, normaliseDimension } from './dimensions.js';
27
28
 
28
29
  export const SUMMARY_TYPES = Object.freeze({ UPSERT: 'semantic_upsert', RETIRE: 'semantic_retire' });
29
30
 
@@ -81,6 +82,10 @@ export class SemanticStore {
81
82
  text: record.text,
82
83
  confidence: record.confidence,
83
84
  tags,
85
+ // v1.7.0 (M2): every L3 record belongs to exactly one of six dimensions.
86
+ // Records written before this existed get a deterministic inference here
87
+ // instead of a rewrite of the append-only log.
88
+ dimension: normaliseDimension(record.dimension) ?? inferDimension({ title: record.title, text: record.text, tags }),
84
89
  sourceEvents: record.source_events ?? [],
85
90
  firstSeenAt: record.first_seen_at ?? record.log_time,
86
91
  updatedAt: record.log_time,
@@ -102,7 +107,7 @@ export class SemanticStore {
102
107
  * @param {Function} input.nextId id factory
103
108
  * @param {object} input.clock
104
109
  */
105
- upsert({ clock, title, text, confidence, tags = [], sourceEvents = [] }) {
110
+ upsert({ clock, title, text, confidence, tags = [], sourceEvents = [], dimension = null }) {
106
111
  if (!title || !text) throw new MemoryError(ErrorCodes.INVALID_INPUT, 'summary needs title and text');
107
112
  const mergedTags = [...new Set(tags.map(normaliseTagToken).filter(Boolean))].sort();
108
113
  // v1.5.6 invariant: an L3 summary without an anchor is dead knowledge — tag-driven
@@ -115,6 +120,12 @@ export class SemanticStore {
115
120
  hint: '提供 tags,或让写作路径从内容提取(extractTags);离线路径会写 origin:unlabelled-* 兜底锚点',
116
121
  });
117
122
  }
123
+ // v1.7.0 (M2): the dimension is recorded as BOTH a field and a `dim:` tag, so
124
+ // tag-driven retrieval reaches it without any new index structure. The tag
125
+ // invariant above still uses the caller's tags: adding `dim:` must not be a way
126
+ // to smuggle in a tagless summary.
127
+ const resolvedDimension = normaliseDimension(dimension) ?? inferDimension({ title, text, tags: mergedTags });
128
+ const dimensionedTags = [...new Set([...mergedTags, dimensionTag(resolvedDimension)])].sort();
118
129
  const summaryId = summaryIdFor({ title, sourceEvents });
119
130
  const existing = this.list().find((summary) => summary.summaryId === summaryId);
120
131
  const record = {
@@ -124,7 +135,8 @@ export class SemanticStore {
124
135
  title,
125
136
  text,
126
137
  confidence: Number.isFinite(confidence) ? Math.max(0, Math.min(1, confidence)) : 0.5,
127
- tags: mergedTags,
138
+ tags: dimensionedTags,
139
+ dimension: resolvedDimension,
128
140
  source_events: [...sourceEvents].sort(),
129
141
  first_seen_at: existing?.firstSeenAt ?? clock.now(),
130
142
  event_time: clock.now(),
@@ -176,6 +188,7 @@ export class SemanticStore {
176
188
  text,
177
189
  confidence,
178
190
  tags: finalTags,
191
+ dimension: inferDimension({ title, text, tags: finalTags }),
179
192
  sourceEvents: [event.event_id],
180
193
  });
181
194
  }
@@ -227,6 +240,9 @@ export class SemanticStore {
227
240
  text: record.text,
228
241
  confidence: record.confidence,
229
242
  tags: record.tags,
243
+ dimension:
244
+ normaliseDimension(record.dimension) ??
245
+ inferDimension({ title: record.title, text: record.text, tags: record.tags ?? [] }),
230
246
  sourceEvents: record.source_events,
231
247
  firstSeenAt: record.first_seen_at,
232
248
  updatedAt: record.log_time,
package/src/webRoutes.js CHANGED
@@ -97,6 +97,7 @@ export const EDITABLE_CONFIG_KEYS = Object.freeze([
97
97
  'context.autoInjectIndex.maxPointers',
98
98
  'context.autoInjectIndex.maxChars',
99
99
  // v1.6.0 cold-start injection switches (independent; both default on since 1.6.3).
100
+ 'context.handoffSummaryTurns',
100
101
  'context.coldStartInjectSummary',
101
102
  'context.coldStartInjectRecentTurns',
102
103
  // v1.5.6 L2 multi-merge tunables (offline maintain phase).