dsh-layers-hippocampus 1.6.4 → 1.6.5
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 +42 -0
- package/README.md +25 -3
- package/docs/ARCHITECTURE.zh.md +2 -2
- package/index.js +191 -10
- package/package.json +1 -1
- package/src/dream.js +19 -1
- package/src/memory.js +56 -10
package/CHANGELOG.md
CHANGED
|
@@ -4,6 +4,48 @@ 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
|
+
- **Tests**:新增 `test/v165.micokernel.test.js`(8 例):`/memory` 注册与全部子命令返回
|
|
43
|
+
纯文本、**网络调用数为 0**、静默真的不注入提示、`resume` 在无交接时明确报错且服务接口
|
|
44
|
+
与它同源、`executeDream()` 先跑月记并把日记标进 `promoted`、`maintain()` 不再产出月记、
|
|
45
|
+
已晋升日记在下一轮仍被排除、以及上面那条「无 UI/追加模式监听」的源码扫描。
|
|
46
|
+
`test/flow.test.js` 与 `test/v156.federation.test.js` 的月记断言随调度器迁移改为
|
|
47
|
+
`executeDream()`。全量 **502/502**(80 个测试文件)。
|
|
48
|
+
|
|
7
49
|
## [1.6.4] — 2026-11-14
|
|
8
50
|
|
|
9
51
|
**修复 1M 上下文溢出(`CONTEXT_WINDOW_EXCEEDED`):交接判定的分母、分子与状态机三处
|
package/README.md
CHANGED
|
@@ -7,7 +7,7 @@
|
|
|
7
7
|
|
|
8
8
|
| | |
|
|
9
9
|
| --- | --- |
|
|
10
|
-
| 版本 | **1.6.
|
|
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.
|
|
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 # 进程内全量用例(
|
|
260
|
+
npm test # 进程内全量用例(502 个)
|
|
239
261
|
npm run check # 语法检查 + 全量测试
|
|
240
262
|
```
|
|
241
263
|
|
package/docs/ARCHITECTURE.zh.md
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
# @local/dsh-memory — 分层长期记忆 Host 插件
|
|
2
2
|
|
|
3
|
-
> 版本:**1.6.
|
|
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
|
-
|
|
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.
|
|
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 =
|
|
693
|
-
|
|
694
|
-
|
|
695
|
-
|
|
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.
|
|
@@ -1280,6 +1307,39 @@ export function createRuntime({ ctx = null, config, options, clock, raw = null,
|
|
|
1280
1307
|
};
|
|
1281
1308
|
};
|
|
1282
1309
|
|
|
1310
|
+
/**
|
|
1311
|
+
* v1.6.5: the ATOMIC read model an outside router plugin needs — no prompt
|
|
1312
|
+
* assembly, no session bookkeeping, no side effects.
|
|
1313
|
+
*
|
|
1314
|
+
* `text` is the distilled handoff summary itself (not the marker), so a caller can
|
|
1315
|
+
* paste it into its own UI or prompt; `tailTurns` carries the last few verbatim
|
|
1316
|
+
* turns when the marker has them. A marker that exists but whose summary event is
|
|
1317
|
+
* not in the index yet returns `text: null` instead of pretending there is one.
|
|
1318
|
+
*/
|
|
1319
|
+
runtime.latestHandoffSummary = () => {
|
|
1320
|
+
const handoff = memory.handoffState();
|
|
1321
|
+
const base = {
|
|
1322
|
+
active: handoff?.active === true,
|
|
1323
|
+
state: handoff?.state ?? null,
|
|
1324
|
+
at: handoff?.at ?? null,
|
|
1325
|
+
sessionId: handoff?.sessionId ?? null,
|
|
1326
|
+
summaryEventId: handoff?.summaryEventId ?? null,
|
|
1327
|
+
agentPreset: handoff?.agentPreset ?? runtime.agentPreset ?? null,
|
|
1328
|
+
tailTurns: Array.isArray(handoff?.tailTurns) ? handoff.tailTurns.map((turn) => ({ ...turn })) : [],
|
|
1329
|
+
text: null,
|
|
1330
|
+
found: false,
|
|
1331
|
+
};
|
|
1332
|
+
if (!handoff?.summaryEventId) return base;
|
|
1333
|
+
try {
|
|
1334
|
+
const events = memory.indexManager.snapshot()?.events ?? [];
|
|
1335
|
+
const event = events.find((entry) => entry?.eventId === handoff.summaryEventId);
|
|
1336
|
+
if (!event?.content) return base;
|
|
1337
|
+
return { ...base, text: String(event.content).slice(0, 4000), found: true };
|
|
1338
|
+
} catch {
|
|
1339
|
+
return base;
|
|
1340
|
+
}
|
|
1341
|
+
};
|
|
1342
|
+
|
|
1283
1343
|
/** "+ 新建空间": creates the child store lazily, then returns the updated list. */
|
|
1284
1344
|
runtime.ensureSpace = async (spaceId) => {
|
|
1285
1345
|
if (runtime.phase !== 'ready') throw runtime.notReady('spaces');
|
|
@@ -2596,7 +2656,7 @@ export async function apply(ctx, rawConfig = {}) {
|
|
|
2596
2656
|
/** false after this plugin fiber is disposed; callers must re-resolve the service. */
|
|
2597
2657
|
available: !serviceDisposed,
|
|
2598
2658
|
l3Traits: 10,
|
|
2599
|
-
service: { remember: true, recall: true, maintenance: true, handoff: true, promptState: true, stats: true },
|
|
2659
|
+
service: { remember: true, recall: true, maintenance: true, handoff: true, promptState: true, stats: true, latestHandoffSummary: true },
|
|
2600
2660
|
}),
|
|
2601
2661
|
async remember(input = {}) {
|
|
2602
2662
|
if (serviceDisposed) throw new MemoryError(ErrorCodes.SERVICE_DISPOSED, 'hippocampus service is disposed');
|
|
@@ -2675,6 +2735,11 @@ export async function apply(ctx, rawConfig = {}) {
|
|
|
2675
2735
|
return runtime.uiPayload();
|
|
2676
2736
|
},
|
|
2677
2737
|
handoffView: () => (serviceDisposed ? null : runtime.handoffView()),
|
|
2738
|
+
/**
|
|
2739
|
+
* v1.6.5: atomic accessor for external router plugins. Read-only, no prompt
|
|
2740
|
+
* assembly and no handoff consumption — the caller decides what to do with it.
|
|
2741
|
+
*/
|
|
2742
|
+
getLatestHandoffSummary: () => (serviceDisposed ? null : runtime.latestHandoffSummary()),
|
|
2678
2743
|
promptState: () => (serviceDisposed ? null : runtime.promptState()),
|
|
2679
2744
|
onDispose(callback) {
|
|
2680
2745
|
if (typeof callback !== 'function') return () => {};
|
|
@@ -2688,6 +2753,122 @@ export async function apply(ctx, rawConfig = {}) {
|
|
|
2688
2753
|
if (typeof ctx.provide === 'function') {
|
|
2689
2754
|
disposers.push(ctx.provide('hippocampus', hippocampusService));
|
|
2690
2755
|
}
|
|
2756
|
+
|
|
2757
|
+
/**
|
|
2758
|
+
* v1.6.5 — `/memory` command set.
|
|
2759
|
+
*
|
|
2760
|
+
* The host executes a registered command WITHOUT sending it to the model
|
|
2761
|
+
* (`commands.execute()` is documented as "parse and execute a known command
|
|
2762
|
+
* without sending it to the model"), so every sub-command below costs **zero
|
|
2763
|
+
* model tokens**. They only return plain text to the UI.
|
|
2764
|
+
*
|
|
2765
|
+
* The registration is OPTIONAL on purpose: `ctx.get('commands')` is probed, so a
|
|
2766
|
+
* host without the command service still loads this plugin (the memory core does
|
|
2767
|
+
* not depend on the UI half).
|
|
2768
|
+
*/
|
|
2769
|
+
const MEMORY_COMMAND_HELP = [
|
|
2770
|
+
'用法:/memory <resume|maintain|status|mute|unmute>',
|
|
2771
|
+
' resume 拉取上一次交接摘要并注入当前上下文(不计入模型 Token)',
|
|
2772
|
+
' maintain 立即触发一次后台维护(索引重建 / 冷热归档 / 蒸馏)',
|
|
2773
|
+
' status 查看当前记忆规模、活跃标签与会话压力',
|
|
2774
|
+
' mute 静默 [Memory Hints] 注入(紧急降噪)',
|
|
2775
|
+
' unmute 恢复 [Memory Hints] 注入',
|
|
2776
|
+
].join('\n');
|
|
2777
|
+
|
|
2778
|
+
runtime.memoryCommand = async (invocation) => {
|
|
2779
|
+
const raw = String(invocation?.rawInput ?? '').trim();
|
|
2780
|
+
const [verbRaw, ...rest] = raw.split(/\s+/);
|
|
2781
|
+
const verb = (verbRaw ?? '').toLowerCase();
|
|
2782
|
+
const sessionId = runtime.memory?.sessionUsage?.()?.sessionId ?? null;
|
|
2783
|
+
const agentId = invocation?.agent?.id ?? null;
|
|
2784
|
+
const ok = (text) => ({ kind: 'success', text });
|
|
2785
|
+
const fail = (text) => ({ kind: 'error', text });
|
|
2786
|
+
|
|
2787
|
+
if (verb === '' || verb === 'help') return ok(MEMORY_COMMAND_HELP);
|
|
2788
|
+
|
|
2789
|
+
if (verb === 'resume') {
|
|
2790
|
+
const summary = runtime.latestHandoffSummary();
|
|
2791
|
+
if (!summary?.summaryEventId) return fail('没有可恢复的交接摘要:尚未发生过交接。');
|
|
2792
|
+
// Re-arm the cold-start injection for THIS conversation even if it was already
|
|
2793
|
+
// delivered once — an explicit command outranks the once-per-epoch dedupe.
|
|
2794
|
+
runtime.armColdStartNow({ sessionId, agentId, source: 'command-resume' });
|
|
2795
|
+
const head = summary.found
|
|
2796
|
+
? `已注入上一次交接摘要(${summary.summaryEventId}${summary.active ? ',交接标记仍 active' : ''})。`
|
|
2797
|
+
: `交接摘要事件 ${summary.summaryEventId} 暂不在索引中(可能尚未重建),已请求重新注入。`;
|
|
2798
|
+
const tail = summary.tailTurns?.length ? `\n附带上一次对话最后 ${summary.tailTurns.length} 轮原话。` : '';
|
|
2799
|
+
return ok(head + tail);
|
|
2800
|
+
}
|
|
2801
|
+
|
|
2802
|
+
if (verb === 'maintain') {
|
|
2803
|
+
if (rest.length > 0 && rest[0] !== 'now') return fail('用法:/memory maintain');
|
|
2804
|
+
if (runtime.phase !== 'ready') return fail(`记忆引擎尚未就绪(${runtime.phase}),稍后再试。`);
|
|
2805
|
+
if (runtime.maintenanceInFlight) return fail('维护已在运行中,本次请求被忽略。');
|
|
2806
|
+
const result = await runtime.runMaintenance('manual');
|
|
2807
|
+
const report = result?.report ?? {};
|
|
2808
|
+
const parts = ['维护完成:'];
|
|
2809
|
+
if (report.logGen) parts.push(`日志代 ${report.logGen} / 索引代 ${report.indexGen}`);
|
|
2810
|
+
if (report.monthly) parts.push(`月记 ${report.monthly.generated} 条`);
|
|
2811
|
+
if (report.l2Merge) parts.push(`L2 合并 ${report.l2Merge.merged ?? 0} 组`);
|
|
2812
|
+
if (report.dream) parts.push(`Dream ${report.dream.merged ?? 0} 条`);
|
|
2813
|
+
if (report.rawArchive) parts.push(`冷归档 ${report.rawArchive.archived ?? 0} 个`);
|
|
2814
|
+
return ok(parts.join(';'));
|
|
2815
|
+
}
|
|
2816
|
+
|
|
2817
|
+
if (verb === 'status') {
|
|
2818
|
+
if (runtime.phase !== 'ready') return fail(`记忆引擎状态:${runtime.phase}${runtime.phaseError ? `(${asMemoryError(runtime.phaseError).code})` : ''}`);
|
|
2819
|
+
const payload = await runtime.uiPayload();
|
|
2820
|
+
const panel = payload?.panel ?? {};
|
|
2821
|
+
// `/memory status` must read the SAME contract the panel does. `panel.global`
|
|
2822
|
+
// holds the counters; `activeTags` there is a NUMBER, and the tag NAMES live in
|
|
2823
|
+
// the index snapshot's active set.
|
|
2824
|
+
const global = panel.global ?? {};
|
|
2825
|
+
const session = panel.session ?? {};
|
|
2826
|
+
const snapshot = runtime.memory?.indexManager?.snapshot?.();
|
|
2827
|
+
const tagList = (snapshot?.activeSet?.entries ?? [])
|
|
2828
|
+
.slice()
|
|
2829
|
+
.sort((left, right) => (right.eventCount ?? 0) - (left.eventCount ?? 0))
|
|
2830
|
+
.slice(0, 8)
|
|
2831
|
+
.map((entry) => entry.tag)
|
|
2832
|
+
.filter(Boolean);
|
|
2833
|
+
return ok(
|
|
2834
|
+
[
|
|
2835
|
+
`记忆引擎:ready(v${CAPABILITIES.version})`,
|
|
2836
|
+
`事件 ${global.events ?? '?'} 条 · L3 摘要 ${global.semanticSummaries ?? '?'} 条 · 活跃标签 ${global.activeTags ?? '?'} 个(上限 ${runtime.config?.activeSet?.cap ?? '?'})`,
|
|
2837
|
+
`会话 ${session.sessionId ?? '未知'} · 已用 ${session.tokens ?? 0} + 预留 ${session.reservedTokens ?? 0} = ${session.projectedTokens ?? 0} / 窗口 ${session.nativeTokenLimit ?? '?'}(来源 ${session.windowSource ?? 'config'})`,
|
|
2838
|
+
`交接标记:${session.handoffActive ? `active(${session.handoffAt ?? '?'})` : '无'} · 冷启动待注入 ${runtime.coldStart.pending.size} 条 / 已注入 ${runtime.coldStart.injected.size} 次`,
|
|
2839
|
+
tagList.length ? `活跃标签 Top:${tagList.join('、')}` : '活跃标签:无',
|
|
2840
|
+
`[Memory Hints]:${runtime.hintsMuted ? '已静默(/memory unmute 恢复)' : '开启'}`,
|
|
2841
|
+
].join('\n'),
|
|
2842
|
+
);
|
|
2843
|
+
}
|
|
2844
|
+
|
|
2845
|
+
if (verb === 'mute' || verb === 'unmute') {
|
|
2846
|
+
const next = verb === 'mute';
|
|
2847
|
+
if (runtime.hintsMuted === next) return ok(next ? '已经是静默状态。' : '当前并未静默。');
|
|
2848
|
+
runtime.hintsMuted = next;
|
|
2849
|
+
if (next) runtime.injection.tags.clear();
|
|
2850
|
+
return ok(next ? '已静默 [Memory Hints](记忆写入与召回不受影响,/memory unmute 恢复)。' : '已恢复 [Memory Hints] 注入。');
|
|
2851
|
+
}
|
|
2852
|
+
|
|
2853
|
+
return fail(`未知子命令 "${verbRaw}"。\n${MEMORY_COMMAND_HELP}`);
|
|
2854
|
+
};
|
|
2855
|
+
|
|
2856
|
+
try {
|
|
2857
|
+
const commands = typeof ctx.get === 'function' ? ctx.get('commands') : null;
|
|
2858
|
+
if (commands && typeof commands.register === 'function') {
|
|
2859
|
+
disposers.push(
|
|
2860
|
+
commands.register({
|
|
2861
|
+
name: 'memory',
|
|
2862
|
+
description: '海马体:恢复交接摘要 / 触发维护 / 查看状态 / 静默提示',
|
|
2863
|
+
input: { hint: 'resume | maintain | status | mute | unmute' },
|
|
2864
|
+
handler: (invocation) => runtime.memoryCommand(invocation),
|
|
2865
|
+
}),
|
|
2866
|
+
);
|
|
2867
|
+
}
|
|
2868
|
+
} catch (error) {
|
|
2869
|
+
// A host without a command service is a valid host; the memory core is unaffected.
|
|
2870
|
+
ctx?.logger?.debug?.(`hippocampus: /memory command not registered: ${asMemoryError(error).code}`);
|
|
2871
|
+
}
|
|
2691
2872
|
disposers.push(() => {
|
|
2692
2873
|
serviceDisposed = true;
|
|
2693
2874
|
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.
|
|
3
|
+
"version": "1.6.5",
|
|
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
|
-
|
|
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
|
-
//
|
|
2180
|
-
//
|
|
2181
|
-
|
|
2182
|
-
|
|
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
|
-
|
|
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 {
|
|
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 } = {}) {
|