dsh-layers-hippocampus 1.6.4 → 1.6.6

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,62 @@ 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.6.5] — 2026-11-15
8
+
9
+ **回归微内核:引擎只负责存储、检索与蒸馏,绝不驱动对话;蒸馏只有一个总调度器;
10
+ 面板的全部能力收进 `/memory` 指令集,且不花一分模型 Token。**
11
+
12
+ - **Added — `/memory` 指令集(0 Token)**。四条子命令通过宿主的 `commands` 服务注册,
13
+ `commands.execute()` 的语义是「parse and execute a known command **without sending it
14
+ to the model**」,因此不产生任何模型请求(测试用 `fetch` 计数断言为 0):
15
+ - `/memory resume`:拉取上一次交接摘要并**强制重新注入**当前上下文。它绕过「每会话
16
+ 每交接批次只注入一次」的去重(`armColdStartNow()` 先删掉该 `session|epoch` 的投递
17
+ 记录再布防),所以用户可以随时把摘要拉回来;没有交接时明确回「没有可恢复的交接摘要」。
18
+ - `/memory maintain`:立即触发一次后台维护(索引重建 / 月记 / L2 合并 / Dream / 冷归档),
19
+ 回报各阶段计数;已在运行时直接拒绝而不是排队。
20
+ - `/memory status`:事件数、L3 摘要数、活跃标签列表、会话 token 与窗口来源
21
+ (`host`/`config`/`default`)、静默状态、冷启动队列长度。
22
+ 这些数字全部取自面板同一份契约(`panel.global.*` + 索引快照的活跃集合),
23
+ 不再各自拼字段——早期实现读错了契约,导致整行显示成 `?`。
24
+ - `/memory mute` / `/memory unmute`:紧急静默 `[Memory Hints]`。静音时**不消费标签**,
25
+ 所以解除后提示会原样回来,而不是被会话级去重池吃掉。
26
+ - **Fixed — 月记与 Dream 重复咀嚼同一批日记**。L2.5 月记原本挂在 `maintain()` 上,与
27
+ Dream 各走各的调度,同一条 L2 日记可能先被压进月记、再被按标签蒸馏一次。
28
+ 现在 **`executeDream()` 是唯一的蒸馏总调度器**:先跑月记(只处理已结束的自然月),
29
+ 再让 Dream 处理剩下的材料。被月记吸收的事件 id 记入 `state/months.json` 的
30
+ `promoted` 映射(即 `promoted_to_monthly`),`DreamEngine.collectGroups()` 直接跳过,
31
+ 并在报告里给出 `skippedPromoted` 计数。
32
+ **为什么不写进事件本身**:raw 日志是 append-only 的唯一真相源,永不改写;标记放在
33
+ 派生状态里,语义等价且可重建。
34
+ - **Added — 原子服务接口 `getLatestHandoffSummary()`**。`ctx.get('hippocampus')
35
+ .getLatestHandoffSummary()` 返回 `{ active, state, at, sessionId, summaryEventId,
36
+ agentPreset, tailTurns, text, found }`,纯读:不装配 prompt、不消费 marker、不产生副作用。
37
+ 外部路由插件想自己决定「什么时候续上、怎么展示」时用它,而不是去解析提示词。
38
+ - **Changed — 微内核边界**。引擎半侧(`index.js` + `src/**`)不含任何宿主 UI 或追加模式
39
+ 监听:`autoNewSession` 整链已在 1.6.3 删除,本次用测试把这条边界**锁死**——源码扫描
40
+ 禁止出现 `uiWorkspace` / `startSession(` / `sessionStorage` / `appendMode` /
41
+ `onSlot(` / `slots.register(` / `ctx.slots =`。会话控制交给外部路由插件。
42
+ - **Fixed — 上下文在每轮请求里被悄悄缩水(“从 10% 直接掉到 7%”)**。1.6.4 的
43
+ `guardRequest` 在**每一次** `agent/request` 上都把宿主 `toolResultPruner.pruneSession()`
44
+ 委托执行了一遍。两处都错:
45
+ - 宿主用的预算是 **预设自己的**(ptc: `thresholdChars 8192` → 留 4k 头 + 1k 尾),
46
+ 于是一次普通的 20 KB 文件读取在下一次请求就被腰斩;
47
+ - 宿主自己只在 compaction-basic 的 `context-overflow` 分支里调它
48
+ (`this.ctx.get('toolResultPruner')?.pruneSession(agent.session)`),
49
+ 「溢出时裁剪」被我们变成了「每一轮都裁剪」。实测一次 pass 可掉 **~80k tokens**。
50
+ 现在 Live Compact **只跑我们自己的保守裁剪**:单条 `tool/result` 超过
51
+ `context.liveCompact.thresholdChars`(默认 200,000 字符)才指针化,头部 4k / 尾部 2k
52
+ 原样保留、中间换成 `deep_raw` 可取回的指针行。健康的对话**永远不会被改写**——
53
+ 宿主压缩链路的裁剪仍由宿主在真溢出时负责。
54
+ 新增回归用例锁定:请求里即使注入了假 `toolResultPruner`,`pruneSession` 的调用次数也必须为 0,
55
+ 且一条 20k 字符的正常结果不产生任何 surface 改写。
56
+ - **Tests**:新增 `test/v165.micokernel.test.js`(8 例):`/memory` 注册与全部子命令返回
57
+ 纯文本、**网络调用数为 0**、静默真的不注入提示、`resume` 在无交接时明确报错且服务接口
58
+ 与它同源、`executeDream()` 先跑月记并把日记标进 `promoted`、`maintain()` 不再产出月记、
59
+ 已晋升日记在下一轮仍被排除、以及上面那条「无 UI/追加模式监听」的源码扫描。
60
+ `test/flow.test.js` 与 `test/v156.federation.test.js` 的月记断言随调度器迁移改为
61
+ `executeDream()`。全量 **502/502**(80 个测试文件)。
62
+
7
63
  ## [1.6.4] — 2026-11-14
8
64
 
9
65
  **修复 1M 上下文溢出(`CONTEXT_WINDOW_EXCEEDED`):交接判定的分母、分子与状态机三处
package/README.md CHANGED
@@ -7,7 +7,7 @@
7
7
 
8
8
  | | |
9
9
  | --- | --- |
10
- | 版本 | **1.6.4** |
10
+ | 版本 | **1.6.5** |
11
11
  | 包名 | `dsh-layers-hippocampus` |
12
12
  | 仓库 | <https://github.com/382quaii/dsh-Layers-Hippocampus> |
13
13
  | 许可证 | MIT |
@@ -98,6 +98,28 @@
98
98
  中间压成一行指向 raw 日志的指针(带 `seq` / `call` / `tool` 坐标),原文仍可用
99
99
  `deep_raw` 取回。宿主自带 `toolResultPruner` 时优先交给它。
100
100
 
101
+ ### `/memory` 指令集(0 Token)
102
+
103
+ 引擎半侧不驱动对话:它只提供存储、检索、蒸馏和纯文本指令。四条子命令通过宿主的
104
+ `commands` 服务注册,`commands.execute()` 的语义是「执行已知命令、**不发给模型**」,
105
+ 所以它们**不消耗任何模型 Token**(测试用 `fetch` 调用计数断言为 0)。
106
+
107
+ | 指令 | 作用 |
108
+ |---|---|
109
+ | `/memory resume` | 拉取上一次交接摘要并**强制重新注入**当前上下文(绕过“每会话只注入一次”的去重) |
110
+ | `/memory maintain` | 立即触发一次后台维护:索引重建 / 月记 / L2 合并 / Dream / 冷归档,并回报各阶段计数 |
111
+ | `/memory status` | 事件数、L3 摘要数、活跃标签、会话 token 与窗口来源、静默状态、冷启动队列 |
112
+ | `/memory mute` / `unmute` | 紧急静默 / 恢复 `[Memory Hints]`;静音期间不消费标签,解除后提示原样回来 |
113
+
114
+ 外部插件要自己决定「什么时候续上」时,用原子服务接口而不是解析提示词:
115
+
116
+ ```js
117
+ const summary = ctx.get('hippocampus').getLatestHandoffSummary();
118
+ // { active, state, at, sessionId, summaryEventId, agentPreset, tailTurns, text, found }
119
+ ```
120
+
121
+ 该接口纯读:不装配 prompt、不消费交接标记、无副作用。
122
+
101
123
  ### 打破线性增长:压缩 / 编码 / 语义三层
102
124
 
103
125
  append-only 日志天然是 O(n),只压不改斜率。三层各自掰弯一段曲线:
@@ -164,7 +186,7 @@ raw 层提供三档,覆盖从“只留关键”到“全留”:
164
186
  pnpm add dsh-layers-hippocampus
165
187
 
166
188
  # 或从 GitHub 指定 tag
167
- pnpm add "github:382quaii/dsh-Layers-Hippocampus#v1.6.4"
189
+ pnpm add "github:382quaii/dsh-Layers-Hippocampus#v1.6.5"
168
190
  ```
169
191
 
170
192
  ### 2. 挂到 profile
@@ -235,7 +257,7 @@ node scripts/wait-for-routes.mjs
235
257
  ### 6. 验证
236
258
 
237
259
  ```bash
238
- npm test # 进程内全量用例(494 个)
260
+ npm test # 进程内全量用例(502 个)
239
261
  npm run check # 语法检查 + 全量测试
240
262
  ```
241
263
 
@@ -1,6 +1,6 @@
1
1
  # @local/dsh-memory — 分层长期记忆 Host 插件
2
2
 
3
- > 版本:**1.6.4** | 全量用例:**494/494** | 运行时依赖:**零**
3
+ > 版本:**1.6.5** | 全量用例:**502/502** | 运行时依赖:**零**
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
- 494 个用例(79 个文件)覆盖:
684
+ 502 个用例(80 个文件)覆盖:
685
685
 
686
686
  - 索引与标签:重建 digest 一致、行号漂移防护(eventId 不变、行号变)、同义合并、活跃集 cap 挤出、规则变更不改清单、空活跃集降级、top-k 有界有序去重。
687
687
  - 衰减与删除:30 天半衰期、reinforce 移动锚点(不存字段)、仅文本粗筛、标签过滤、维护代切换且旧代可读、boot 检查、压缩不丢记录、并发维护串行化、四阶段删除、archive 可回滚 vs purge 不可、strict 巩固暂停与恢复、任务重放幂等、错误 id 零变更。
package/index.js CHANGED
@@ -62,7 +62,7 @@ export { resolveConfig, DEFAULT_CONFIG };
62
62
  * of letting a raw 404 reach the user.
63
63
  */
64
64
  export const CAPABILITIES = Object.freeze({
65
- version: '1.6.4',
65
+ version: '1.6.5',
66
66
  spaces: true,
67
67
  memories: true,
68
68
  transferConsent: true,
@@ -439,6 +439,8 @@ export function createRuntime({ ctx = null, config, options, clock, raw = null,
439
439
  * conversation arms its own pending entry on its first captured turn.
440
440
  */
441
441
  runtime.coldStart = { pending: new Map(), injected: new Set(), lastSessionId: null };
442
+ /** v1.6.5 `/memory mute`: emergency switch that silences [Memory Hints] only. */
443
+ runtime.hintsMuted = false;
442
444
  const COLD_START_INJECTED_LIMIT = 64;
443
445
  const COLD_START_PENDING_LIMIT = 8;
444
446
  const COLD_START_PENDING_TTL_MS = 5 * 60_000;
@@ -549,9 +551,28 @@ export function createRuntime({ ctx = null, config, options, clock, raw = null,
549
551
  return entry;
550
552
  };
551
553
 
554
+ /**
555
+ * v1.6.5 `/memory resume`: force ONE more cold-start injection for this conversation.
556
+ *
557
+ * The automatic path deliberately injects at most once per `session|handoff-epoch`
558
+ * (a re-injection on every turn would be pure prompt noise). An explicit user
559
+ * command overrules that: the recorded delivery is forgotten, then the entry is
560
+ * re-armed with reason `command-resume`, so the NEXT prompt assembly replays the
561
+ * summary + tail exactly once more.
562
+ */
563
+ runtime.armColdStartNow = ({ sessionId = null, agentId = null, source = 'command-resume' } = {}) => {
564
+ const handoff = memory.handoffState();
565
+ if (!handoff?.summaryEventId) return null;
566
+ const epoch = `${handoff.at ?? 0}:${handoff.summaryEventId}`;
567
+ const key = `${sessionId ?? agentId ?? 'unknown'}|${epoch}`;
568
+ runtime.coldStart.injected.delete(key);
569
+ const armed = runtime.noteColdStart({ sessionId, agentId, source });
570
+ if (armed) armed.at = memory.clock.now();
571
+ return armed ?? null;
572
+ };
573
+
552
574
  /** Drop pendings that were never consumed (a conversation that never assembled). */
553
- runtime.pruneColdStartPendings = () => {
554
- const pendings = runtime.coldStart.pending;
575
+ runtime.pruneColdStartPendings = () => { const pendings = runtime.coldStart.pending;
555
576
  if (pendings.size === 0) return 0;
556
577
  const now = memory.clock.now();
557
578
  let dropped = 0;
@@ -687,17 +708,23 @@ export function createRuntime({ ctx = null, config, options, clock, raw = null,
687
708
  const view = memory.indexManager.snapshot();
688
709
  const entries = view?.activeSet?.entries ?? [];
689
710
  const activeTags = entries.map((entry) => ({ tag: entry.tag, count: entry.eventCount ?? 0 }));
711
+ // v1.6.5 `/memory mute`: emergency silence for [Memory Hints]. Tags are NOT
712
+ // consumed while muted, so unmuting restores the same hints instead of losing
713
+ // them to the session-level dedup pool.
714
+ const hintsMuted = runtime.hintsMuted === true;
690
715
  // v1.5.6: relevance-first hints; short inputs ("继续"/"在吗") fall back to the
691
716
  // previous turn's matched tags so the model still gets a thread to pull.
692
- const selected = selectRelevantTags({
693
- text: runtime.lastUserText,
694
- activeTags,
695
- fallbackTags: runtime.lastHintTags,
696
- });
717
+ const selected = hintsMuted
718
+ ? []
719
+ : selectRelevantTags({
720
+ text: runtime.lastUserText,
721
+ activeTags,
722
+ fallbackTags: runtime.lastHintTags,
723
+ });
697
724
  const freshTags = selected.filter((tag) => !runtime.injection.tags.has(tag));
698
725
  for (const tag of freshTags) runtime.injection.tags.add(tag);
699
726
  if (selected.length > 0) runtime.lastHintTags = selected;
700
- const hints = renderMemoryHints(freshTags, { toolName: `${config.toolPrefix}_recall` });
727
+ const hints = hintsMuted ? '' : renderMemoryHints(freshTags, { toolName: `${config.toolPrefix}_recall` });
701
728
 
702
729
  // v1.5.6: [Active Task] is unconditional when a handoff summary or a `task:`
703
730
  // event exists — injected once per session.
@@ -769,26 +796,23 @@ export function createRuntime({ ctx = null, config, options, clock, raw = null,
769
796
  runtime.guardRequest = async ({ agent = null, config: requestConfig = null, signal = null } = {}) => {
770
797
  const session = agent?.session ?? null;
771
798
  // ---- 1. Live Compact ---------------------------------------------------
799
+ // ONLY our own conservative pass, on OUR threshold (200k chars by default).
800
+ //
801
+ // v1.6.5: this used to delegate to the host's `toolResultPruner` on EVERY
802
+ // request, which was wrong twice over:
803
+ // - the host prunes with the PRESET's budget (ptc: 8192 chars -> 4k head +
804
+ // 1k tail), so an ordinary 20 KB file read was silently cut down on the
805
+ // very next request;
806
+ // - the host itself only calls `pruneSession` on the `context-overflow`
807
+ // trigger inside compaction-basic. Calling it per request turned "prune at
808
+ // overflow" into "shrink every single turn" — exactly the reported
809
+ // "context drops from 10% to 7% over and over".
810
+ // Our pointerization keeps head/tail plus a `deep_raw` recoverable pointer and
811
+ // only fires on a genuinely oversized single result, so a healthy conversation
812
+ // is never rewritten.
772
813
  const liveConfig = runtime.config?.context?.liveCompact ?? {};
773
814
  if (liveConfig.enabled !== false && session) {
774
- // The HOST owns the canonical pruner (`tool-result-pruner`, replay-safe, wired
775
- // into the ptc preset). Delegate when present; only fall back to our own
776
- // surface surgery when the host has no pruner at all.
777
- const hostPruner = (() => {
778
- try {
779
- return ctx?.get?.('toolResultPruner') ?? null;
780
- } catch {
781
- return null;
782
- }
783
- })();
784
- if (hostPruner && typeof hostPruner.pruneSession === 'function') {
785
- try {
786
- await hostPruner.pruneSession(session);
787
- runtime.lastLiveCompact = { source: 'host', at: memory.clock.now() };
788
- } catch (error) {
789
- runtime.logger?.warn?.(`hippocampus: host live-compact failed: ${asMemoryError(error).code}`);
790
- }
791
- } else {
815
+ try {
792
816
  runtime.lastLiveCompact = {
793
817
  source: 'hippocampus',
794
818
  at: memory.clock.now(),
@@ -800,6 +824,8 @@ export function createRuntime({ ctx = null, config, options, clock, raw = null,
800
824
  logger: runtime.logger,
801
825
  }),
802
826
  };
827
+ } catch (error) {
828
+ runtime.logger?.warn?.(`hippocampus: live compact failed: ${asMemoryError(error).code}`);
803
829
  }
804
830
  }
805
831
 
@@ -1280,6 +1306,39 @@ export function createRuntime({ ctx = null, config, options, clock, raw = null,
1280
1306
  };
1281
1307
  };
1282
1308
 
1309
+ /**
1310
+ * v1.6.5: the ATOMIC read model an outside router plugin needs — no prompt
1311
+ * assembly, no session bookkeeping, no side effects.
1312
+ *
1313
+ * `text` is the distilled handoff summary itself (not the marker), so a caller can
1314
+ * paste it into its own UI or prompt; `tailTurns` carries the last few verbatim
1315
+ * turns when the marker has them. A marker that exists but whose summary event is
1316
+ * not in the index yet returns `text: null` instead of pretending there is one.
1317
+ */
1318
+ runtime.latestHandoffSummary = () => {
1319
+ const handoff = memory.handoffState();
1320
+ const base = {
1321
+ active: handoff?.active === true,
1322
+ state: handoff?.state ?? null,
1323
+ at: handoff?.at ?? null,
1324
+ sessionId: handoff?.sessionId ?? null,
1325
+ summaryEventId: handoff?.summaryEventId ?? null,
1326
+ agentPreset: handoff?.agentPreset ?? runtime.agentPreset ?? null,
1327
+ tailTurns: Array.isArray(handoff?.tailTurns) ? handoff.tailTurns.map((turn) => ({ ...turn })) : [],
1328
+ text: null,
1329
+ found: false,
1330
+ };
1331
+ if (!handoff?.summaryEventId) return base;
1332
+ try {
1333
+ const events = memory.indexManager.snapshot()?.events ?? [];
1334
+ const event = events.find((entry) => entry?.eventId === handoff.summaryEventId);
1335
+ if (!event?.content) return base;
1336
+ return { ...base, text: String(event.content).slice(0, 4000), found: true };
1337
+ } catch {
1338
+ return base;
1339
+ }
1340
+ };
1341
+
1283
1342
  /** "+ 新建空间": creates the child store lazily, then returns the updated list. */
1284
1343
  runtime.ensureSpace = async (spaceId) => {
1285
1344
  if (runtime.phase !== 'ready') throw runtime.notReady('spaces');
@@ -2596,7 +2655,7 @@ export async function apply(ctx, rawConfig = {}) {
2596
2655
  /** false after this plugin fiber is disposed; callers must re-resolve the service. */
2597
2656
  available: !serviceDisposed,
2598
2657
  l3Traits: 10,
2599
- service: { remember: true, recall: true, maintenance: true, handoff: true, promptState: true, stats: true },
2658
+ service: { remember: true, recall: true, maintenance: true, handoff: true, promptState: true, stats: true, latestHandoffSummary: true },
2600
2659
  }),
2601
2660
  async remember(input = {}) {
2602
2661
  if (serviceDisposed) throw new MemoryError(ErrorCodes.SERVICE_DISPOSED, 'hippocampus service is disposed');
@@ -2675,6 +2734,11 @@ export async function apply(ctx, rawConfig = {}) {
2675
2734
  return runtime.uiPayload();
2676
2735
  },
2677
2736
  handoffView: () => (serviceDisposed ? null : runtime.handoffView()),
2737
+ /**
2738
+ * v1.6.5: atomic accessor for external router plugins. Read-only, no prompt
2739
+ * assembly and no handoff consumption — the caller decides what to do with it.
2740
+ */
2741
+ getLatestHandoffSummary: () => (serviceDisposed ? null : runtime.latestHandoffSummary()),
2678
2742
  promptState: () => (serviceDisposed ? null : runtime.promptState()),
2679
2743
  onDispose(callback) {
2680
2744
  if (typeof callback !== 'function') return () => {};
@@ -2688,6 +2752,122 @@ export async function apply(ctx, rawConfig = {}) {
2688
2752
  if (typeof ctx.provide === 'function') {
2689
2753
  disposers.push(ctx.provide('hippocampus', hippocampusService));
2690
2754
  }
2755
+
2756
+ /**
2757
+ * v1.6.5 — `/memory` command set.
2758
+ *
2759
+ * The host executes a registered command WITHOUT sending it to the model
2760
+ * (`commands.execute()` is documented as "parse and execute a known command
2761
+ * without sending it to the model"), so every sub-command below costs **zero
2762
+ * model tokens**. They only return plain text to the UI.
2763
+ *
2764
+ * The registration is OPTIONAL on purpose: `ctx.get('commands')` is probed, so a
2765
+ * host without the command service still loads this plugin (the memory core does
2766
+ * not depend on the UI half).
2767
+ */
2768
+ const MEMORY_COMMAND_HELP = [
2769
+ '用法:/memory <resume|maintain|status|mute|unmute>',
2770
+ ' resume 拉取上一次交接摘要并注入当前上下文(不计入模型 Token)',
2771
+ ' maintain 立即触发一次后台维护(索引重建 / 冷热归档 / 蒸馏)',
2772
+ ' status 查看当前记忆规模、活跃标签与会话压力',
2773
+ ' mute 静默 [Memory Hints] 注入(紧急降噪)',
2774
+ ' unmute 恢复 [Memory Hints] 注入',
2775
+ ].join('\n');
2776
+
2777
+ runtime.memoryCommand = async (invocation) => {
2778
+ const raw = String(invocation?.rawInput ?? '').trim();
2779
+ const [verbRaw, ...rest] = raw.split(/\s+/);
2780
+ const verb = (verbRaw ?? '').toLowerCase();
2781
+ const sessionId = runtime.memory?.sessionUsage?.()?.sessionId ?? null;
2782
+ const agentId = invocation?.agent?.id ?? null;
2783
+ const ok = (text) => ({ kind: 'success', text });
2784
+ const fail = (text) => ({ kind: 'error', text });
2785
+
2786
+ if (verb === '' || verb === 'help') return ok(MEMORY_COMMAND_HELP);
2787
+
2788
+ if (verb === 'resume') {
2789
+ const summary = runtime.latestHandoffSummary();
2790
+ if (!summary?.summaryEventId) return fail('没有可恢复的交接摘要:尚未发生过交接。');
2791
+ // Re-arm the cold-start injection for THIS conversation even if it was already
2792
+ // delivered once — an explicit command outranks the once-per-epoch dedupe.
2793
+ runtime.armColdStartNow({ sessionId, agentId, source: 'command-resume' });
2794
+ const head = summary.found
2795
+ ? `已注入上一次交接摘要(${summary.summaryEventId}${summary.active ? ',交接标记仍 active' : ''})。`
2796
+ : `交接摘要事件 ${summary.summaryEventId} 暂不在索引中(可能尚未重建),已请求重新注入。`;
2797
+ const tail = summary.tailTurns?.length ? `\n附带上一次对话最后 ${summary.tailTurns.length} 轮原话。` : '';
2798
+ return ok(head + tail);
2799
+ }
2800
+
2801
+ if (verb === 'maintain') {
2802
+ if (rest.length > 0 && rest[0] !== 'now') return fail('用法:/memory maintain');
2803
+ if (runtime.phase !== 'ready') return fail(`记忆引擎尚未就绪(${runtime.phase}),稍后再试。`);
2804
+ if (runtime.maintenanceInFlight) return fail('维护已在运行中,本次请求被忽略。');
2805
+ const result = await runtime.runMaintenance('manual');
2806
+ const report = result?.report ?? {};
2807
+ const parts = ['维护完成:'];
2808
+ if (report.logGen) parts.push(`日志代 ${report.logGen} / 索引代 ${report.indexGen}`);
2809
+ if (report.monthly) parts.push(`月记 ${report.monthly.generated} 条`);
2810
+ if (report.l2Merge) parts.push(`L2 合并 ${report.l2Merge.merged ?? 0} 组`);
2811
+ if (report.dream) parts.push(`Dream ${report.dream.merged ?? 0} 条`);
2812
+ if (report.rawArchive) parts.push(`冷归档 ${report.rawArchive.archived ?? 0} 个`);
2813
+ return ok(parts.join(';'));
2814
+ }
2815
+
2816
+ if (verb === 'status') {
2817
+ if (runtime.phase !== 'ready') return fail(`记忆引擎状态:${runtime.phase}${runtime.phaseError ? `(${asMemoryError(runtime.phaseError).code})` : ''}`);
2818
+ const payload = await runtime.uiPayload();
2819
+ const panel = payload?.panel ?? {};
2820
+ // `/memory status` must read the SAME contract the panel does. `panel.global`
2821
+ // holds the counters; `activeTags` there is a NUMBER, and the tag NAMES live in
2822
+ // the index snapshot's active set.
2823
+ const global = panel.global ?? {};
2824
+ const session = panel.session ?? {};
2825
+ const snapshot = runtime.memory?.indexManager?.snapshot?.();
2826
+ const tagList = (snapshot?.activeSet?.entries ?? [])
2827
+ .slice()
2828
+ .sort((left, right) => (right.eventCount ?? 0) - (left.eventCount ?? 0))
2829
+ .slice(0, 8)
2830
+ .map((entry) => entry.tag)
2831
+ .filter(Boolean);
2832
+ return ok(
2833
+ [
2834
+ `记忆引擎:ready(v${CAPABILITIES.version})`,
2835
+ `事件 ${global.events ?? '?'} 条 · L3 摘要 ${global.semanticSummaries ?? '?'} 条 · 活跃标签 ${global.activeTags ?? '?'} 个(上限 ${runtime.config?.activeSet?.cap ?? '?'})`,
2836
+ `会话 ${session.sessionId ?? '未知'} · 已用 ${session.tokens ?? 0} + 预留 ${session.reservedTokens ?? 0} = ${session.projectedTokens ?? 0} / 窗口 ${session.nativeTokenLimit ?? '?'}(来源 ${session.windowSource ?? 'config'})`,
2837
+ `交接标记:${session.handoffActive ? `active(${session.handoffAt ?? '?'})` : '无'} · 冷启动待注入 ${runtime.coldStart.pending.size} 条 / 已注入 ${runtime.coldStart.injected.size} 次`,
2838
+ tagList.length ? `活跃标签 Top:${tagList.join('、')}` : '活跃标签:无',
2839
+ `[Memory Hints]:${runtime.hintsMuted ? '已静默(/memory unmute 恢复)' : '开启'}`,
2840
+ ].join('\n'),
2841
+ );
2842
+ }
2843
+
2844
+ if (verb === 'mute' || verb === 'unmute') {
2845
+ const next = verb === 'mute';
2846
+ if (runtime.hintsMuted === next) return ok(next ? '已经是静默状态。' : '当前并未静默。');
2847
+ runtime.hintsMuted = next;
2848
+ if (next) runtime.injection.tags.clear();
2849
+ return ok(next ? '已静默 [Memory Hints](记忆写入与召回不受影响,/memory unmute 恢复)。' : '已恢复 [Memory Hints] 注入。');
2850
+ }
2851
+
2852
+ return fail(`未知子命令 "${verbRaw}"。\n${MEMORY_COMMAND_HELP}`);
2853
+ };
2854
+
2855
+ try {
2856
+ const commands = typeof ctx.get === 'function' ? ctx.get('commands') : null;
2857
+ if (commands && typeof commands.register === 'function') {
2858
+ disposers.push(
2859
+ commands.register({
2860
+ name: 'memory',
2861
+ description: '海马体:恢复交接摘要 / 触发维护 / 查看状态 / 静默提示',
2862
+ input: { hint: 'resume | maintain | status | mute | unmute' },
2863
+ handler: (invocation) => runtime.memoryCommand(invocation),
2864
+ }),
2865
+ );
2866
+ }
2867
+ } catch (error) {
2868
+ // A host without a command service is a valid host; the memory core is unaffected.
2869
+ ctx?.logger?.debug?.(`hippocampus: /memory command not registered: ${asMemoryError(error).code}`);
2870
+ }
2691
2871
  disposers.push(() => {
2692
2872
  serviceDisposed = true;
2693
2873
  for (const callback of serviceDisposers.splice(0)) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-layers-hippocampus",
3
- "version": "1.6.4",
3
+ "version": "1.6.6",
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/dream.js CHANGED
@@ -330,9 +330,19 @@ export class DreamEngine {
330
330
  const rawEvents = view?.events;
331
331
  const events = rawEvents instanceof Map ? [...rawEvents.values()] : Array.isArray(rawEvents) ? rawEvents : [];
332
332
  const merged = new Set(this._load().mergedEventIds);
333
+ // v1.6.5: monthly memos are condensed FIRST by `executeDream()`, so anything they
334
+ // already absorbed is off-limits here — otherwise the same L2 diaries would be
335
+ // paid for twice (one memo write plus one per-tag LLM distillation).
336
+ const promotedMonthly =
337
+ typeof this.memory.promotedToMonthly === 'function' ? this.memory.promotedToMonthly() : new Set();
333
338
  const byTag = new Map();
339
+ let skippedPromoted = 0;
334
340
  for (const event of events) {
335
341
  if (!event || typeof event.eventId !== 'string' || merged.has(event.eventId)) continue;
342
+ if (promotedMonthly.has(event.eventId)) {
343
+ skippedPromoted += 1;
344
+ continue;
345
+ }
336
346
  const names = (event.tags ?? []).map(tagName).filter(Boolean);
337
347
  if (names.includes(DREAM_TAG) || names.some(isInternalTag)) continue;
338
348
  for (const tag of new Set(names)) {
@@ -340,10 +350,14 @@ export class DreamEngine {
340
350
  byTag.get(tag).push(event);
341
351
  }
342
352
  }
343
- return [...byTag.entries()]
353
+ // `skippedPromoted` rides along on the array so `run()` can report it without a
354
+ // second pass over the whole event set.
355
+ const groups = [...byTag.entries()]
344
356
  .filter(([, list]) => list.length >= config.minGroupSize)
345
357
  .map(([tag, list]) => ({ tag, events: list }))
346
358
  .sort((a, b) => b.events.length - a.events.length || a.tag.localeCompare(b.tag));
359
+ Object.defineProperty(groups, 'skippedPromoted', { value: skippedPromoted, enumerable: false });
360
+ return groups;
347
361
  }
348
362
 
349
363
  async _callLlm({ tag, sources, config, now }) {
@@ -515,6 +529,10 @@ export class DreamEngine {
515
529
  status: 'ok',
516
530
  now,
517
531
  groups: groups.length,
532
+ // v1.6.5: how many events the monthly memo already absorbed (they are NOT in
533
+ // any group here). Non-zero is healthy: it means the scheduler ran monthly
534
+ // first and Dream was spared a second pass over the same material.
535
+ skippedPromoted: groups.skippedPromoted ?? 0,
518
536
  merged: 0,
519
537
  llmSuccess: 0,
520
538
  llmFallback: 0,
package/src/memory.js CHANGED
@@ -2176,13 +2176,10 @@ export class Memory {
2176
2176
  this.assertOpen();
2177
2177
  const report = await this.maintenance.run({ reason });
2178
2178
  this._boot = { status: 'ok', logGen: report.logGen, indexGen: report.indexGen };
2179
- // Monthly memos are part of maintenance: a completed natural month becomes
2180
- // one durable memo before the graph is rebuilt from the same index.
2181
- try {
2182
- report.monthly = await this.generateMonthlyMemos();
2183
- } catch (error) {
2184
- report.monthlyError = error instanceof Error ? error.message : String(error);
2185
- }
2179
+ // v1.6.5: monthly memos (L2.5) are NOT generated here any more. They used to run
2180
+ // from maintenance AND the Dream leg could then distill the very same diaries per
2181
+ // tag — two condensations of one material. `executeDream()` now schedules them
2182
+ // first and marks what they absorbed as `promoted_to_monthly`.
2186
2183
  // v1.5.6: L2 multi-merge runs offline, after the read model converged. A failure
2187
2184
  // must never fail maintenance (duplicates are cosmetic, the log is the truth).
2188
2185
  try {
@@ -2329,11 +2326,27 @@ export class Memory {
2329
2326
  * deterministic local merge and records `MEM_E_DREAM_LLM_FALLBACK`; the returned
2330
2327
  * record always carries `meta.source_event_ids`.
2331
2328
  *
2329
+ * v1.6.5: this is the ONE distillation scheduler. Monthly memos (L2.5) used to run
2330
+ * from `maintain()` on their own schedule, which meant an event could be condensed
2331
+ * into a monthly memo and then distilled AGAIN per tag by Dream in the same night —
2332
+ * two network/storage passes over the same material. Ordering now lives here:
2333
+ * monthly aggregation FIRST (it only touches COMPLETED months), then tag-level
2334
+ * distillation over what is left. `generateMonthlyMemos()` marks every event it
2335
+ * absorbed as `promoted_to_monthly`, and Dream's `collectGroups()` skips those.
2336
+ *
2332
2337
  * @param {{now?: number, fetchImpl?: Function, logger?: object}} [options]
2333
2338
  */
2334
2339
  async executeDream(options = {}) {
2335
2340
  this.assertOpen();
2336
- return this.dream.run(options);
2341
+ const run = { monthly: null, monthlyError: null };
2342
+ try {
2343
+ run.monthly = await this.generateMonthlyMemos({ now: options.now ?? this.clock.now() });
2344
+ } catch (error) {
2345
+ // A memo failure must never cancel the tag distillation that follows.
2346
+ run.monthlyError = error instanceof Error ? error.message : String(error);
2347
+ }
2348
+ const report = await this.dream.run(options);
2349
+ return { ...report, monthly: run.monthly, monthlyError: run.monthlyError };
2337
2350
  }
2338
2351
 
2339
2352
  /** Circuit + last-run snapshot for the panel / admin surface. */
@@ -2548,18 +2561,39 @@ export class Memory {
2548
2561
  return path.join(this.paths.state, 'months.json');
2549
2562
  }
2550
2563
 
2564
+ /**
2565
+ * v1.6.5: ids that a monthly memo already absorbed, i.e. "promoted to monthly".
2566
+ *
2567
+ * The append-only log never gets rewritten (charter: the log is the truth source),
2568
+ * so the flag lives in `state/months.json` under `promoted` and is exposed as a set
2569
+ * here. Dream reads it through `collectGroups()` so an event is distilled at most
2570
+ * once — monthly aggregation happens first and owns those ids from then on.
2571
+ */
2572
+ promotedToMonthly() {
2573
+ const state = readJson(this.monthlyStatePath(), null);
2574
+ const promoted = state && typeof state === 'object' ? state.promoted : null;
2575
+ if (!promoted || typeof promoted !== 'object') return new Set();
2576
+ return new Set(Object.keys(promoted));
2577
+ }
2578
+
2551
2579
  /**
2552
2580
  * Multi-level time aggregation: once a natural month is over, its diaries are
2553
2581
  * condensed into one monthly memo (tag `status:monthly`). Memos are written as
2554
2582
  * ordinary episodes, so they are durable; retrieval gives them no decay and a
2555
2583
  * boost when the query is about a fuzzy historical period.
2584
+ *
2585
+ * v1.6.5: every absorbed event id is recorded as `promoted_to_monthly` in
2586
+ * `state/months.json`, and `executeDream()` — not `maintain()` — drives this step,
2587
+ * so Dream never re-distills what the monthly memo already condensed.
2556
2588
  */
2557
2589
  async generateMonthlyMemos({ now = this.clock.now() } = {}) {
2558
2590
  const view = this.indexManager.snapshot();
2559
2591
  const events = view?.events ?? [];
2592
+ const promoted = new Set(this.promotedToMonthly());
2560
2593
  const byMonth = new Map();
2561
2594
  for (const event of events) {
2562
2595
  if (!event.day) continue;
2596
+ if (promoted.has(event.eventId)) continue;
2563
2597
  if ((event.tags ?? []).some((tag) => (tag.tag ?? tag) === MONTHLY_TAG)) continue;
2564
2598
  const month = String(event.day).slice(0, 7);
2565
2599
  if (!/^\d{4}-\d{2}$/.test(month)) continue;
@@ -2568,6 +2602,9 @@ export class Memory {
2568
2602
  }
2569
2603
  const state = readJson(this.monthlyStatePath(), null);
2570
2604
  const done = new Set(Array.isArray(state?.months) ? state.months : []);
2605
+ // Carry previous promotions forward: a memo written by an older version has no
2606
+ // record of what it absorbed, and dropping the map would re-distill its events.
2607
+ const promotedMap = state && typeof state.promoted === 'object' && state.promoted !== null ? { ...state.promoted } : {};
2571
2608
  const generated = [];
2572
2609
  const skipped = [];
2573
2610
  for (const [month, list] of [...byMonth].sort(([a], [b]) => a.localeCompare(b))) {
@@ -2618,13 +2655,22 @@ export class Memory {
2618
2655
  meta: { source_event_ids: list.map((event) => event.eventId).sort() },
2619
2656
  });
2620
2657
  done.add(month);
2658
+ // v1.6.5: the memo now owns these events; Dream must not chew them again.
2659
+ for (const event of list) promotedMap[event.eventId] = month;
2621
2660
  generated.push({ month, eventId: result.eventId, status: result.status, events: list.length });
2622
2661
  }
2623
2662
  if (generated.length > 0) {
2624
2663
  ensureDir(this.paths.state);
2625
- writeJsonAtomic(this.monthlyStatePath(), { schema: 1, months: [...done].sort(), updatedAt: now });
2664
+ writeJsonAtomic(this.monthlyStatePath(), { schema: 1, months: [...done].sort(), promoted: promotedMap, updatedAt: now });
2626
2665
  }
2627
- return { generated: generated.length, months: generated.map((entry) => entry.month), entries: generated, skipped: skipped.length, skippedEntries: skipped };
2666
+ return {
2667
+ generated: generated.length,
2668
+ months: generated.map((entry) => entry.month),
2669
+ entries: generated,
2670
+ skipped: skipped.length,
2671
+ skippedEntries: skipped,
2672
+ promoted: Object.keys(promotedMap).length,
2673
+ };
2628
2674
  }
2629
2675
 
2630
2676
  async extractTrend({ content, sourceEvents = [], tags = [], occurredAt, ttlDays } = {}) {