dsh-layers-hippocampus 1.6.8 → 1.6.9
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 +61 -2
- package/README.md +23 -3
- package/docs/ARCHITECTURE.zh.md +2 -2
- package/index.js +113 -11
- package/package.json +1 -1
- package/src/config.js +48 -0
- package/src/dream.js +76 -6
- package/src/entityAlias.js +330 -0
- package/src/index/buildIndex.js +27 -6
- package/src/index/indexManager.js +30 -1
- package/src/memory.js +186 -5
- package/src/policy.js +14 -0
- package/src/retrieval.js +136 -6
- package/src/tagGraph.js +123 -0
- package/src/utils/promptLayout.js +29 -1
- package/src/webRoutes.js +5 -0
package/CHANGELOG.md
CHANGED
|
@@ -4,6 +4,59 @@ 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.9] — 2026-11-22
|
|
8
|
+
|
|
9
|
+
**全链路记忆机制:写入时归并、检索时联想、装配时只给指针。**
|
|
10
|
+
在 1.6.8 的「密文不写入」之后,这一版补上另外三处漏点——
|
|
11
|
+
**标签会分裂**(`entity:红薯` 与 `entity:烤红薯` 各自成节点)、
|
|
12
|
+
**联想靠自觉**(模型不主动 `recall` 就不会碰到相关记忆)、
|
|
13
|
+
**上下文靠运气**(同一件事从不跨轮次自动进入 Prompt)。
|
|
14
|
+
|
|
15
|
+
- **Added — 本地实体归并(零 Token,写侧)**:新增 `src/entityAlias.js`。`entity:` 标签在
|
|
16
|
+
`stage()` 写入前先折名,三条判据按顺序:① 别名字典命中(`state/entity_alias.json`);
|
|
17
|
+
② **子串包含**——已有 `entity:红薯` 时写入 `entity:烤红薯` 直接折向较短的既有词;
|
|
18
|
+
③ **编辑距离**——相似度 ≥0.8 且长度差 ≤2 时归并(收拾拼写错误)。
|
|
19
|
+
折名记录写进事件的 `meta.entity_merged`(`{from,to,reason:'alias'|'substring'|'fuzzy'}`),
|
|
20
|
+
`entity` 字段同步规范化。**修掉一个真根因**:`_resolveTags()` 原先用原始 tags 覆盖合并结果,
|
|
21
|
+
导致合并看似生效、实际仍分裂出新标签。
|
|
22
|
+
- **Added — 别名字典(`state/entity_alias.json`,schema 1,原子写)**:`EntityAliasStore` 提供
|
|
23
|
+
`load/map/list/resolve/learn/status`。索引构建期 `buildIndex()` 通过 `canonicalTag()` 再折一次,
|
|
24
|
+
所以**日志永远不被改写**:所谓「转移旧节点事件、删除空节点」,是索引重建后自然收敛,
|
|
25
|
+
原始记录仍在 `raw/` 与 `log/` 里可查。
|
|
26
|
+
- **Added — Dream 学同义词**:`DreamEngine.learnAliases()` 取过去 24h 新增的 `entity:` 词,
|
|
27
|
+
发一个小的 JSON 请求让模型输出 `{"aliases":{"地瓜":"红薯"}}`,经
|
|
28
|
+
`sanitiseAliasPairs(pairs, { known })` 过滤后写入字典——**只允许折向已存在的规范词**,
|
|
29
|
+
否则等于让模型凭空造节点。学完置 `markDirty()` + `invalidateAdjacency()`,下轮读取即生效;
|
|
30
|
+
它排在月记与 Dream **之后**,失败只记 `executeDream().entityAliasError`,绝不拖垮蒸馏。
|
|
31
|
+
- **Added — 1 跳共现联想(严格 O(1))**:新增 `src/tagGraph.js`。`buildAdjacency()` 把
|
|
32
|
+
`state/graph.json` 的共现边折成 `Map<tag,[{tag,weight}]>`(对称、权重降序、每点最多 8 邻居);
|
|
33
|
+
`recall()` 命中查询标签后只做一次 `Map.get()` 取最强邻居——**不建队列、不记 visited,没有 BFS/DFS**。
|
|
34
|
+
联想语义条目按 `score × 0.5` 返回并标注 `association:{via,penalty,hops:1}`,
|
|
35
|
+
`recall` 结果里的 `associative.{hops,tags,seeds,semantic}` 让「为什么带回了这条」可审计。
|
|
36
|
+
`entitySeedsMentioned()` 会把**查询文本里直接出现的 entity 词**当种子,
|
|
37
|
+
所以 `entity:红薯` 不需要用户显式写标签也能触发联想。
|
|
38
|
+
- **Added — `maxAssociativeHops` 硬上限 1**:`assertAssociativeHops()` 在 `recall()`、
|
|
39
|
+
`_recallLocal()` 与工具入口**最先**执行(空索引也照样校验);`>1` 直接抛
|
|
40
|
+
`MEM_E_INVALID_INPUT`(「associative recall is a single O(1) lookup, not a graph walk」);
|
|
41
|
+
`0` 可关掉联想。**性能是契约,不是建议。**
|
|
42
|
+
- **Added — 时间窗加成**:`policy.retrieval.recentWindowTurns`(默认 50)取最近 N 个事件的时间范围,
|
|
43
|
+
窗口内事件按贴近程度拿 **1.2x–1.5x**(`RECENT_BOOST_MIN/MAX`)。
|
|
44
|
+
因为 `timeBoost` 上限由 1.3 提到 1.5,剪枝上界 `PRUNE_BOUND_FACTOR` 同步 **3.9 → 4.5**
|
|
45
|
+
(否则 `salience × 3.9` 不再是硬上界,早停会剪错)。
|
|
46
|
+
- **Added — 自动指针注入(`context.autoInjectIndex`)**:默认
|
|
47
|
+
`{ enabled: true, everyNTurns: 3, maxPointers: 3, maxChars: 300 }`(也接受布尔简写)。
|
|
48
|
+
插件就绪 / 会话切换即布防,**第一轮就**输出 `[Memory Index]` 段;此后每 N 个 user turn 重新布防。
|
|
49
|
+
行格式 `- [memory <eventId>] <tag> · <title>`——**只有指针,没有正文**,整段硬限 300 字符。
|
|
50
|
+
注入过的 eventId 进 `runtime.injection.ids` 去重池;活跃标签签名没变就不再重复注入。
|
|
51
|
+
这是「模型不会主动 recall 怎么办」的答案:不逼它调用工具,只把索引放到它眼前。
|
|
52
|
+
- **Changed — 可配置 / 可观测**:`context.autoInjectIndex.{enabled,everyNTurns,maxPointers,maxChars}`
|
|
53
|
+
四个键进 `EDITABLE_CONFIG_KEYS`;`recall` 结果带 `associative` 与 `recentWindow`;
|
|
54
|
+
`memory.status()` 暴露 `entityAliasStatus()` 与 `associativeStatus()`。
|
|
55
|
+
- **Tests**:新增 `test/v169.fullchain.test.js`(6 例)——`烤红薯` 因子串包含折进 `红薯`;
|
|
56
|
+
Dream 识别 `地瓜 → 红薯` 且重定向到索引、日志未被改写;查 `红薯` 带回 `吃饭` 的联想摘要且仅 1 跳;
|
|
57
|
+
近期记忆得分高于同权重旧记忆;`maxAssociativeHops > 1` 抛错、`0` 关闭;
|
|
58
|
+
首轮即注入指针、同会话不重复、标签未变仍不重复。
|
|
59
|
+
全量 **541/541**(85 个测试文件)。
|
|
7
60
|
## [1.6.8] — 2026-11-20
|
|
8
61
|
|
|
9
62
|
**写侧护栏:拒绝高熵密文 / 加密载荷。** raw 日志与 L1 事件日志是本插件承诺「永远保留」
|
|
@@ -30,7 +83,13 @@ and the project adheres to [Semantic Versioning](https://semver.org/).
|
|
|
30
83
|
(会话里粘一段密钥不该让日志被 warn 淹没),其他错误仍照旧上抛。
|
|
31
84
|
- **Tests**:新增 `test/v168.encrypted.test.js`(8 例):熵函数基准、7 类正常内容零误判、
|
|
32
85
|
base64/hex/PEM 三判据各自的拒绝理由、raw store 拒绝且磁盘无残留、auto-capture 的 skip
|
|
33
|
-
语义、`remember()` 同规则且普通写入不受影响。全量 **
|
|
86
|
+
语义、`remember()` 同规则且普通写入不受影响。全量 **541/541**(85 个测试文件)。
|
|
87
|
+
- **Fixed — `/memory maintain` 的计数全是空的**:该命令把 `report.rawArchive.archived`
|
|
88
|
+
与 `report.rawPrune.removed` 当数字插值,而它们其实是**数组**,于是输出成了
|
|
89
|
+
`维护完成:;L2 合并 0 组;冷归档 个。`(分段用空数组拼出来就是空串)。现在统一走
|
|
90
|
+
`count()`(数组取 length、数字取原值),并且只推入有内容的分段;本轮真的什么都没做时
|
|
91
|
+
明确回答「本轮无变更」。新增回归用例(`test/v165.micokernel.test.js` 第 9 例)锁住
|
|
92
|
+
「无空分段 + 冷归档必须带数字」。
|
|
34
93
|
- **Docs**:`记忆插件-未完成表.md` 从「2026-11-05 待办审计」重写为「当前状态表」——
|
|
35
94
|
A1–A21 逐项给出关闭依据,13 项关闭、2 项 superseded、2 项并入 M3/M6、4 项明确不做
|
|
36
95
|
(并写明为什么不做),另列仍需外部动作的四项(npm 账号封控等)。
|
|
@@ -103,7 +162,7 @@ M1 则是本版的主线功能——每轮 Prompt 不再为记忆**正文**付
|
|
|
103
162
|
sink 收到 payload 且被计数、sink 抛错只记 `sink-error` 不外溢、`externalSeams()` 如实报告
|
|
104
163
|
「通知与高峰缺席、价格回退本地时间窗」、注入 `notifier` 服务后被自动发现并可用、
|
|
105
164
|
注入 `priceTip` 后外部价格**优先于**本地时钟窗口。
|
|
106
|
-
全量 **
|
|
165
|
+
全量 **541/541**(85 个测试文件)。
|
|
107
166
|
|
|
108
167
|
## [1.6.6] — 2026-11-16
|
|
109
168
|
|
package/README.md
CHANGED
|
@@ -7,7 +7,7 @@
|
|
|
7
7
|
|
|
8
8
|
| | |
|
|
9
9
|
| --- | --- |
|
|
10
|
-
| 版本 | **1.6.
|
|
10
|
+
| 版本 | **1.6.9** |
|
|
11
11
|
| 包名 | `dsh-layers-hippocampus` |
|
|
12
12
|
| 仓库 | <https://github.com/382quaii/dsh-Layers-Hippocampus> |
|
|
13
13
|
| 许可证 | MIT |
|
|
@@ -124,6 +124,26 @@
|
|
|
124
124
|
`capabilities.externalSeams` 会如实报告 `{wired, source}`,所以「没装」是可见事实。
|
|
125
125
|
**高峰期不丢任务**:LLM 蒸馏在高峰只被写入持久化队列并在谷时唤醒,不是跳过。
|
|
126
126
|
|
|
127
|
+
### 全链路记忆:写入归并 / 检索联想 / 自动指针(1.6.9)
|
|
128
|
+
|
|
129
|
+
- **写入时归并实体**:`entity:` 标签先查别名字典,再按**子串包含**(已有 `entity:红薯`,写入
|
|
130
|
+
`entity:烤红薯` 直接折向短词)与**编辑距离**(相似度 ≥0.8 且长度差 ≤2)合并。
|
|
131
|
+
折名记在事件的 `meta.entity_merged` 里,日志本身不改写——「旧节点消失」是索引重建的结果,
|
|
132
|
+
原始记录仍可 `deep_raw` 取回。
|
|
133
|
+
- **Dream 学同义词**:后台蒸馏时额外取 24h 内新增的实体词,让模型给出
|
|
134
|
+
`{"aliases":{"地瓜":"红薯"}}` 这样的映射写入 `state/entity_alias.json`;
|
|
135
|
+
**只允许折向已存在的规范词**,避免模型凭空造节点。
|
|
136
|
+
- **1 跳联想**:`recall` 命中 `entity:红薯` 后,从共现图谱的邻接表里**一次 `Map.get()`** 取最强
|
|
137
|
+
邻居(如 `topic:吃饭`),把该标签下最多 2 条语义摘要以 `score × 0.5` 一并返回,
|
|
138
|
+
并在 `associative` 里写明来源。没有图遍历:`maxAssociativeHops` 只接受 `0` 或 `1`,
|
|
139
|
+
`>1` 直接抛错。
|
|
140
|
+
- **时间窗加成**:最近 `policy.retrieval.recentWindowTurns`(默认 50)个事件内,
|
|
141
|
+
越新越接近 **1.2x–1.5x** 加成(旧记忆不会被删除,只是不再抢先)。
|
|
142
|
+
- **自动指针注入**:不再指望模型主动 `recall`。插件就绪或会话切换时立即布防,
|
|
143
|
+
每 `everyNTurns`(默认 3)个 user turn 输出一段 `[Memory Index]`:
|
|
144
|
+
`- [memory ev_xxx] lesson:npm-publish · 标题`——**只有 eventId + 标签 + 标题,没有正文**,
|
|
145
|
+
整段硬限 `maxChars`(默认 300)。注入过的 id 进去重池,标签签名不变时不重复注入。
|
|
146
|
+
`context.autoInjectIndex: false` 可整体关闭。
|
|
127
147
|
### `/memory` 指令集(0 Token)
|
|
128
148
|
|
|
129
149
|
引擎半侧不驱动对话:它只提供存储、检索、蒸馏和纯文本指令。四条子命令通过宿主的
|
|
@@ -212,7 +232,7 @@ raw 层提供三档,覆盖从“只留关键”到“全留”:
|
|
|
212
232
|
pnpm add dsh-layers-hippocampus
|
|
213
233
|
|
|
214
234
|
# 或从 GitHub 指定 tag
|
|
215
|
-
pnpm add "github:382quaii/dsh-Layers-Hippocampus#v1.6.
|
|
235
|
+
pnpm add "github:382quaii/dsh-Layers-Hippocampus#v1.6.9"
|
|
216
236
|
```
|
|
217
237
|
|
|
218
238
|
### 2. 挂到 profile
|
|
@@ -283,7 +303,7 @@ node scripts/wait-for-routes.mjs
|
|
|
283
303
|
### 6. 验证
|
|
284
304
|
|
|
285
305
|
```bash
|
|
286
|
-
npm test # 进程内全量用例(
|
|
306
|
+
npm test # 进程内全量用例(541 个)
|
|
287
307
|
npm run check # 语法检查 + 全量测试
|
|
288
308
|
```
|
|
289
309
|
|
package/docs/ARCHITECTURE.zh.md
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
# @local/dsh-memory — 分层长期记忆 Host 插件
|
|
2
2
|
|
|
3
|
-
> 版本:**1.6.
|
|
3
|
+
> 版本:**1.6.9** | 全量用例:**541/541** | 运行时依赖:**零**
|
|
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
|
+
535 个用例(85 个文件)覆盖:
|
|
685
685
|
|
|
686
686
|
- 索引与标签:重建 digest 一致、行号漂移防护(eventId 不变、行号变)、同义合并、活跃集 cap 挤出、规则变更不改清单、空活跃集降级、top-k 有界有序去重。
|
|
687
687
|
- 衰减与删除:30 天半衰期、reinforce 移动锚点(不存字段)、仅文本粗筛、标签过滤、维护代切换且旧代可读、boot 检查、压缩不丢记录、并发维护串行化、四阶段删除、archive 可回滚 vs purge 不可、strict 巩固暂停与恢复、任务重放幂等、错误 id 零变更。
|
package/index.js
CHANGED
|
@@ -35,7 +35,7 @@ import { MigrationRunner } from './src/migrationRunner.js';
|
|
|
35
35
|
import { CronScheduler } from './src/scheduler.js';
|
|
36
36
|
import { asMemoryError, ErrorCodes, MemoryError } from './src/errors.js';
|
|
37
37
|
import { Memory, turnFromSessionEvent } from './src/memory.js';
|
|
38
|
-
import { composePrompt, renderActiveTask } from './src/utils/promptLayout.js';
|
|
38
|
+
import { composePrompt, renderActiveTask, renderPointers } from './src/utils/promptLayout.js';
|
|
39
39
|
import { renderMemoryHints, selectRelevantTags } from './src/utils/memoryHints.js';
|
|
40
40
|
import { HostBridge } from './src/hostBridge.js';
|
|
41
41
|
import { isLowValley, nextLowValleyStart, windowInfo } from './src/priceWindow.js';
|
|
@@ -63,7 +63,7 @@ export { resolveConfig, DEFAULT_CONFIG };
|
|
|
63
63
|
* of letting a raw 404 reach the user.
|
|
64
64
|
*/
|
|
65
65
|
export const CAPABILITIES = Object.freeze({
|
|
66
|
-
version: '1.6.
|
|
66
|
+
version: '1.6.9',
|
|
67
67
|
spaces: true,
|
|
68
68
|
memories: true,
|
|
69
69
|
transferConsent: true,
|
|
@@ -436,6 +436,15 @@ export function createRuntime({ ctx = null, config, options, clock, raw = null,
|
|
|
436
436
|
* made the model look like it was rereading the same page.
|
|
437
437
|
*/
|
|
438
438
|
runtime.injection = { sessionId: null, ids: new Set(), tags: new Set(), handoffAt: null };
|
|
439
|
+
/**
|
|
440
|
+
* v1.6.9 (module 3): automatic INDEX pointer injection state.
|
|
441
|
+
*
|
|
442
|
+
* `armed` starts true on purpose: the first request after a plugin restart gets one
|
|
443
|
+
* pointer block, which is the whole point of the feature (a model that never calls
|
|
444
|
+
* recall would otherwise never learn the memories exist). After that it is re-armed
|
|
445
|
+
* by the turn counter, never by a timer.
|
|
446
|
+
*/
|
|
447
|
+
runtime.pointers = { armed: true, userTurns: 0, lastSignature: null, lastAt: null, injected: 0 };
|
|
439
448
|
/**
|
|
440
449
|
* v1.6.3 cold-start state (replaces the v1.6.0 boolean `coldStartPending`).
|
|
441
450
|
*
|
|
@@ -608,6 +617,82 @@ export function createRuntime({ ctx = null, config, options, clock, raw = null,
|
|
|
608
617
|
return !pending.sessionId && !pending.agentId && !sessionId && !agentId;
|
|
609
618
|
};
|
|
610
619
|
|
|
620
|
+
/** The hottest N tags, by the priority the maintenance pass computed. */
|
|
621
|
+
runtime.pointerEntries = () => {
|
|
622
|
+
const settings = runtime.config?.context?.autoInjectIndex ?? {};
|
|
623
|
+
const limit = Math.max(1, Math.min(10, Number(settings.maxPointers) || 3));
|
|
624
|
+
const view = memory.indexManager?.snapshot?.();
|
|
625
|
+
const entries = view?.activeSet?.entries ?? [];
|
|
626
|
+
const ranked = [...entries]
|
|
627
|
+
.filter((entry) => entry && typeof entry.tag === 'string' && !/^(?:status:|month:)/.test(entry.tag))
|
|
628
|
+
.sort((left, right) => (right.priority ?? right.eventCount ?? 0) - (left.priority ?? left.eventCount ?? 0))
|
|
629
|
+
.slice(0, limit);
|
|
630
|
+
if (ranked.length === 0) return [];
|
|
631
|
+
// One pass over the events for ALL candidate ids (a per-tag scan would be O(tags x events)).
|
|
632
|
+
const wanted = new Set();
|
|
633
|
+
for (const entry of ranked) {
|
|
634
|
+
for (const posting of view?.tags?.[entry.tag]?.postings ?? []) wanted.add(posting.eventId);
|
|
635
|
+
}
|
|
636
|
+
if (wanted.size === 0) return [];
|
|
637
|
+
const byId = new Map();
|
|
638
|
+
for (const event of view?.events ?? []) {
|
|
639
|
+
if (wanted.has(event.eventId)) byId.set(event.eventId, event);
|
|
640
|
+
}
|
|
641
|
+
const picked = [];
|
|
642
|
+
for (const entry of ranked) {
|
|
643
|
+
const postings = [...(view?.tags?.[entry.tag]?.postings ?? [])].sort(
|
|
644
|
+
(left, right) => (right.strength ?? 0) - (left.strength ?? 0),
|
|
645
|
+
);
|
|
646
|
+
const best = postings.find((posting) => byId.has(posting.eventId));
|
|
647
|
+
if (!best) continue;
|
|
648
|
+
const event = byId.get(best.eventId);
|
|
649
|
+
// A pointer already delivered in this session is never repeated.
|
|
650
|
+
if (runtime.injection.ids.has(event.eventId)) continue;
|
|
651
|
+
const title = snippet(String(event.content ?? ''), 60);
|
|
652
|
+
picked.push({ eventId: event.eventId, tags: [entry.tag], title });
|
|
653
|
+
}
|
|
654
|
+
return picked;
|
|
655
|
+
};
|
|
656
|
+
|
|
657
|
+
/**
|
|
658
|
+
* v1.6.9: the pointer block for THIS prompt, or ''. Consumes the arm flag.
|
|
659
|
+
*
|
|
660
|
+
* Guard rails, all deliberate:
|
|
661
|
+
* - disabled config -> never renders (and never clears the arm);
|
|
662
|
+
* - unchanged hot-tag signature -> nothing new to say, so nothing is injected;
|
|
663
|
+
* - every emitted id joins `runtime.injection.ids`, so one memory cannot be
|
|
664
|
+
* injected twice (as a pointer or later as a full block).
|
|
665
|
+
*/
|
|
666
|
+
runtime.pointerText = () => {
|
|
667
|
+
const settings = runtime.config?.context?.autoInjectIndex ?? {};
|
|
668
|
+
if (runtime.phase !== 'ready' || settings.enabled !== true) return '';
|
|
669
|
+
if (runtime.pointers.armed !== true) return '';
|
|
670
|
+
try {
|
|
671
|
+
const entries = runtime.pointerEntries();
|
|
672
|
+
runtime.pointers.armed = false;
|
|
673
|
+
runtime.pointers.lastAt = memory.clock.now();
|
|
674
|
+
const signature = entries.map((entry) => `${entry.tags.join(',')}:${entry.eventId}`).join('|');
|
|
675
|
+
if (entries.length === 0 || signature === runtime.pointers.lastSignature) return '';
|
|
676
|
+
const text = renderPointers(entries, { maxChars: settings.maxChars });
|
|
677
|
+
if (!text) return '';
|
|
678
|
+
runtime.pointers.lastSignature = signature;
|
|
679
|
+
runtime.pointers.injected += 1;
|
|
680
|
+
for (const entry of entries) runtime.injection.ids.add(entry.eventId);
|
|
681
|
+
return text;
|
|
682
|
+
} catch {
|
|
683
|
+
return '';
|
|
684
|
+
}
|
|
685
|
+
};
|
|
686
|
+
|
|
687
|
+
/** Called for every captured USER turn: the only clock this feature uses. */
|
|
688
|
+
runtime.noteUserTurn = () => {
|
|
689
|
+
const settings = runtime.config?.context?.autoInjectIndex ?? {};
|
|
690
|
+
if (settings.enabled !== true) return;
|
|
691
|
+
runtime.pointers.userTurns += 1;
|
|
692
|
+
const every = Math.max(1, Number(settings.everyNTurns) || 3);
|
|
693
|
+
if (runtime.pointers.userTurns % every === 0) runtime.pointers.armed = true;
|
|
694
|
+
};
|
|
695
|
+
|
|
611
696
|
/**
|
|
612
697
|
* v1.6.0 / v1.6.3: one-shot cold-start block for a conversation that just started
|
|
613
698
|
* after a handoff.
|
|
@@ -738,6 +823,9 @@ export function createRuntime({ ctx = null, config, options, clock, raw = null,
|
|
|
738
823
|
for (const tag of freshTags) runtime.injection.tags.add(tag);
|
|
739
824
|
if (selected.length > 0) runtime.lastHintTags = selected;
|
|
740
825
|
const hints = hintsMuted ? '' : renderMemoryHints(freshTags, { toolName: `${config.toolPrefix}_recall` });
|
|
826
|
+
// v1.6.9 (module 3): computed AFTER hints (the most volatile of all) and rendered
|
|
827
|
+
// below them, so the cacheable prefix never moves.
|
|
828
|
+
const pointers = runtime.pointerText();
|
|
741
829
|
|
|
742
830
|
// v1.5.6: [Active Task] is unconditional when a handoff summary or a `task:`
|
|
743
831
|
// event exists — injected once per session.
|
|
@@ -781,7 +869,7 @@ export function createRuntime({ ctx = null, config, options, clock, raw = null,
|
|
|
781
869
|
// must say so — otherwise the model reads a title as if it were the memory.
|
|
782
870
|
const rules = memory.context.injectMode === 'full' ? PROMPT_STATE_RULES : PROMPT_STATE_RULES_INDEX;
|
|
783
871
|
return (
|
|
784
|
-
composePrompt({ rules, activeTask: activeTaskBlock, blocks, hints }) +
|
|
872
|
+
composePrompt({ rules, activeTask: activeTaskBlock, blocks, hints, pointers }) +
|
|
785
873
|
marker +
|
|
786
874
|
(coldStart ? `\n${coldStart}` : '')
|
|
787
875
|
);
|
|
@@ -2127,13 +2215,20 @@ export async function apply(ctx, rawConfig = {}) {
|
|
|
2127
2215
|
if (sessionId && sessionId !== runtime.coldStart.lastSessionId) {
|
|
2128
2216
|
runtime.coldStart.lastSessionId = sessionId;
|
|
2129
2217
|
runtime.noteColdStart({ sessionId, source: 'session-switch' });
|
|
2218
|
+
// v1.6.9: a new conversation is exactly when a pointer block is worth its
|
|
2219
|
+
// tokens — the "re-arm after restart / new session" half of module 3.
|
|
2220
|
+
runtime.pointers.armed = true;
|
|
2221
|
+
runtime.pointers.userTurns = 0;
|
|
2130
2222
|
}
|
|
2131
2223
|
// v1.5.6: remember the latest USER turn as the relevance input for
|
|
2132
2224
|
// `[Memory Hints]`. This is the only place the current input is available:
|
|
2133
2225
|
// prompt assembly receives no message text.
|
|
2134
2226
|
try {
|
|
2135
2227
|
const turn = turnFromSessionEvent(event);
|
|
2136
|
-
if (turn && turn.role === 'user' && turn.text && turn.contextOnly !== true)
|
|
2228
|
+
if (turn && turn.role === 'user' && turn.text && turn.contextOnly !== true) {
|
|
2229
|
+
runtime.lastUserText = turn.text;
|
|
2230
|
+
runtime.noteUserTurn();
|
|
2231
|
+
}
|
|
2137
2232
|
} catch {
|
|
2138
2233
|
/* hint relevance must never affect capture */
|
|
2139
2234
|
}
|
|
@@ -2919,13 +3014,20 @@ export async function apply(ctx, rawConfig = {}) {
|
|
|
2919
3014
|
if (runtime.maintenanceInFlight) return fail('维护已在运行中,本次请求被忽略。');
|
|
2920
3015
|
const result = await runtime.runMaintenance('manual');
|
|
2921
3016
|
const report = result?.report ?? {};
|
|
2922
|
-
|
|
2923
|
-
|
|
2924
|
-
|
|
2925
|
-
|
|
2926
|
-
|
|
2927
|
-
|
|
2928
|
-
|
|
3017
|
+
// Every counter below is optional and several are ARRAYS (`rawArchive.archived`,
|
|
3018
|
+
// `rawPrune.removed`): interpolating an array prints "" or the element, never a
|
|
3019
|
+
// count. Build segments defensively and never emit an empty one — the first
|
|
3020
|
+
// version printed `维护完成:;L2 合并 0 组;冷归档 个`.
|
|
3021
|
+
const count = (value) => (Array.isArray(value) ? value.length : Number(value) || 0);
|
|
3022
|
+
const parts = [];
|
|
3023
|
+
if (report.logGen) parts.push(`日志代 ${report.logGen}`);
|
|
3024
|
+
if (report.indexGen) parts.push(`索引代 ${report.indexGen}`);
|
|
3025
|
+
if (report.l2Merge) parts.push(`L2 合并 ${count(report.l2Merge.merged)} 组`);
|
|
3026
|
+
if (report.dream) parts.push(`Dream ${count(report.dream.merged)} 条`);
|
|
3027
|
+
if (report.rawArchive) parts.push(`冷归档 ${count(report.rawArchive.archived)} 个`);
|
|
3028
|
+
if (report.rawPrune) parts.push(`raw 清理 ${count(report.rawPrune.removed)} 个分片`);
|
|
3029
|
+
if (report.reviewConsume) parts.push(`复习消费 ${count(report.reviewConsume.consumed)} 条`);
|
|
3030
|
+
return ok(parts.length > 0 ? `维护完成:${parts.join(';')}。` : '维护完成:本轮无变更。');
|
|
2929
3031
|
}
|
|
2930
3032
|
|
|
2931
3033
|
if (verb === 'status') {
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "dsh-layers-hippocampus",
|
|
3
|
-
"version": "1.6.
|
|
3
|
+
"version": "1.6.9",
|
|
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
|
@@ -208,6 +208,11 @@ export const DEFAULT_CONFIG = Object.freeze({
|
|
|
208
208
|
// host now CONTINUES the same conversation after the marker instead of opening a
|
|
209
209
|
// second one, so a client-side "start a fresh session" controller only spawned a
|
|
210
210
|
// useless empty conversation. Legacy keys are stripped by `migrateConfig`.
|
|
211
|
+
// v1.6.9 (module 3): automatically point the model at the hottest memories.
|
|
212
|
+
// This is an INDEX injection (eventId + tags + title), never a body, and it is
|
|
213
|
+
// rate-limited by user turns so a long session cannot accumulate hundreds of
|
|
214
|
+
// lines. `true`/`false` is accepted as a shorthand for `{ enabled }`.
|
|
215
|
+
autoInjectIndex: { enabled: true, everyNTurns: 3, maxPointers: 3, maxChars: 300 },
|
|
211
216
|
// v1.6.0 cold-start injection switches (user request 2026-11-06):
|
|
212
217
|
// - summary: inject the previous handoff summary so the first turn inherits context
|
|
213
218
|
// - recentTurns: inject the last few turns of the handed-off conversation
|
|
@@ -901,6 +906,42 @@ function buildResolvedConfig(raw = {}, { env = process.env } = {}) {
|
|
|
901
906
|
'context.requireExplicitConsentForTransfer',
|
|
902
907
|
);
|
|
903
908
|
|
|
909
|
+
// v1.6.9 (module 3): auto pointer injection. Boolean shorthand first, because
|
|
910
|
+
// the most common override is a plain on/off, then the three bounds.
|
|
911
|
+
const autoInjectRaw = contextIn.autoInjectIndex === undefined ? defaults.context.autoInjectIndex : contextIn.autoInjectIndex;
|
|
912
|
+
let autoInjectGroup;
|
|
913
|
+
if (typeof autoInjectRaw === 'boolean') {
|
|
914
|
+
autoInjectGroup = { ...defaults.context.autoInjectIndex, enabled: autoInjectRaw };
|
|
915
|
+
} else if (autoInjectRaw && typeof autoInjectRaw === 'object' && !Array.isArray(autoInjectRaw)) {
|
|
916
|
+
autoInjectGroup = autoInjectRaw;
|
|
917
|
+
} else {
|
|
918
|
+
throw configError(ErrorCodes.CONFIG_INVALID_TYPE, 'config.context.autoInjectIndex must be a boolean or an object', {
|
|
919
|
+
key: 'context.autoInjectIndex',
|
|
920
|
+
got: autoInjectRaw,
|
|
921
|
+
});
|
|
922
|
+
}
|
|
923
|
+
const autoInjectEnabled = requireBoolean(
|
|
924
|
+
autoInjectGroup.enabled === undefined ? defaults.context.autoInjectIndex.enabled : autoInjectGroup.enabled,
|
|
925
|
+
'context.autoInjectIndex.enabled',
|
|
926
|
+
);
|
|
927
|
+
const autoInjectEveryNTurns = requireInteger(
|
|
928
|
+
autoInjectGroup.everyNTurns === undefined
|
|
929
|
+
? defaults.context.autoInjectIndex.everyNTurns
|
|
930
|
+
: autoInjectGroup.everyNTurns,
|
|
931
|
+
'context.autoInjectIndex.everyNTurns',
|
|
932
|
+
{ min: 1, max: 100 },
|
|
933
|
+
);
|
|
934
|
+
const autoInjectMaxPointers = requireInteger(
|
|
935
|
+
autoInjectGroup.maxPointers === undefined ? defaults.context.autoInjectIndex.maxPointers : autoInjectGroup.maxPointers,
|
|
936
|
+
'context.autoInjectIndex.maxPointers',
|
|
937
|
+
{ min: 1, max: 10 },
|
|
938
|
+
);
|
|
939
|
+
const autoInjectMaxChars = requireInteger(
|
|
940
|
+
autoInjectGroup.maxChars === undefined ? defaults.context.autoInjectIndex.maxChars : autoInjectGroup.maxChars,
|
|
941
|
+
'context.autoInjectIndex.maxChars',
|
|
942
|
+
{ min: 40, max: 2000 },
|
|
943
|
+
);
|
|
944
|
+
|
|
904
945
|
// ---- inverted-index physical limits (v1.5.0) -----------------------------
|
|
905
946
|
const indexIn = input.index ?? {};
|
|
906
947
|
const indexMaxPostingsPerTag = requireInteger(
|
|
@@ -1418,6 +1459,13 @@ function buildResolvedConfig(raw = {}, { env = process.env } = {}) {
|
|
|
1418
1459
|
target: contextTarget,
|
|
1419
1460
|
injectPrompt: contextInjectPrompt,
|
|
1420
1461
|
injectMode: contextInjectMode,
|
|
1462
|
+
// v1.6.9 auto pointer injection (module 3).
|
|
1463
|
+
autoInjectIndex: {
|
|
1464
|
+
enabled: autoInjectEnabled,
|
|
1465
|
+
everyNTurns: autoInjectEveryNTurns,
|
|
1466
|
+
maxPointers: autoInjectMaxPointers,
|
|
1467
|
+
maxChars: autoInjectMaxChars,
|
|
1468
|
+
},
|
|
1421
1469
|
// v1.6.3 cold-start injection switches (independent booleans).
|
|
1422
1470
|
coldStartInjectSummary: contextColdStartInjectSummary,
|
|
1423
1471
|
coldStartInjectRecentTurns: contextColdStartInjectRecentTurns,
|
package/src/dream.js
CHANGED
|
@@ -22,6 +22,7 @@
|
|
|
22
22
|
import path from 'node:path';
|
|
23
23
|
import { ensureDir, readJson, writeJsonAtomic, snippet } from './util.js';
|
|
24
24
|
import { ErrorCodes, MemoryError } from './errors.js';
|
|
25
|
+
import { aliasPrompt, parseAliasReply, sanitiseAliasPairs, isEntityTag, entityWord } from './entityAlias.js';
|
|
25
26
|
|
|
26
27
|
/** Tag carried by every distilled record; also the re-merge guard. */
|
|
27
28
|
export const DREAM_TAG = 'status:dream';
|
|
@@ -360,7 +361,12 @@ export class DreamEngine {
|
|
|
360
361
|
return groups;
|
|
361
362
|
}
|
|
362
363
|
|
|
363
|
-
|
|
364
|
+
/**
|
|
365
|
+
* v1.6.9: one JSON chat completion. Extracted from `_callLlm` so the entity-alias
|
|
366
|
+
* pass reuses the SAME timeout, abort, auth and fallback code instead of growing
|
|
367
|
+
* a second network path that would drift.
|
|
368
|
+
*/
|
|
369
|
+
async _chat({ system, user, config, maxTokens }) {
|
|
364
370
|
const llm = config.llm;
|
|
365
371
|
if (!isLlmConfigured(llm)) {
|
|
366
372
|
throw new MemoryError(DREAM_FALLBACK_CODE, 'dream LLM is not configured (baseUrl/model missing)', { phase: 'config' });
|
|
@@ -395,11 +401,11 @@ export class DreamEngine {
|
|
|
395
401
|
body: JSON.stringify({
|
|
396
402
|
model: llm.model,
|
|
397
403
|
temperature: 0,
|
|
398
|
-
max_tokens:
|
|
404
|
+
max_tokens: maxTokens,
|
|
399
405
|
response_format: { type: 'json_object' },
|
|
400
406
|
messages: [
|
|
401
|
-
{ role: 'system', content:
|
|
402
|
-
{ role: 'user', content:
|
|
407
|
+
{ role: 'system', content: system },
|
|
408
|
+
{ role: 'user', content: user },
|
|
403
409
|
],
|
|
404
410
|
}),
|
|
405
411
|
signal: controller.signal,
|
|
@@ -418,13 +424,23 @@ export class DreamEngine {
|
|
|
418
424
|
return content;
|
|
419
425
|
})();
|
|
420
426
|
try {
|
|
421
|
-
|
|
422
|
-
return parseDistillation(content, { maxSummaryChars: config.maxSummaryChars });
|
|
427
|
+
return await Promise.race([request, timeout]);
|
|
423
428
|
} finally {
|
|
424
429
|
if (timer) clearTimeout(timer);
|
|
425
430
|
}
|
|
426
431
|
}
|
|
427
432
|
|
|
433
|
+
/** Distil one tag group through the shared chat call. */
|
|
434
|
+
async _callLlm({ tag, sources, config }) {
|
|
435
|
+
const content = await this._chat({
|
|
436
|
+
system: systemPrompt(config),
|
|
437
|
+
user: userPrompt(tag, sources, config),
|
|
438
|
+
config,
|
|
439
|
+
maxTokens: Math.max(64, Math.ceil(config.maxSummaryChars * 2) + 64),
|
|
440
|
+
});
|
|
441
|
+
return parseDistillation(content, { maxSummaryChars: config.maxSummaryChars });
|
|
442
|
+
}
|
|
443
|
+
|
|
428
444
|
async _distillGroup({ tag, events }, { config, now, logger }) {
|
|
429
445
|
const sources = events
|
|
430
446
|
.slice()
|
|
@@ -511,6 +527,60 @@ export class DreamEngine {
|
|
|
511
527
|
};
|
|
512
528
|
}
|
|
513
529
|
|
|
530
|
+
/**
|
|
531
|
+
* v1.6.9 (module 1.3): learn entity synonyms from the last 24h of writes.
|
|
532
|
+
*
|
|
533
|
+
* This is a SMALL request by design: only entity words, only those written today,
|
|
534
|
+
* and only when there are at least two of them (a single word has nothing to be
|
|
535
|
+
* merged with). Failure is not an error: the local substring/edit-distance merge
|
|
536
|
+
* already ran at write time, so nothing is lost by skipping the LLM pass.
|
|
537
|
+
*
|
|
538
|
+
* @returns {Promise<{skipped?: string, checked: number, added: object, total: number}>}
|
|
539
|
+
*/
|
|
540
|
+
async learnAliases({ now = this.clock.now(), logger = undefined, windowMs = 24 * 60 * 60 * 1000, fetchImpl = null } = {}) {
|
|
541
|
+
const config = this.config();
|
|
542
|
+
const store = this.memory?.entityAliases;
|
|
543
|
+
if (!store) return { skipped: 'no-store', checked: 0, added: {}, total: 0 };
|
|
544
|
+
if (config.useLlm !== true || !isLlmConfigured(config.llm) || !this._circuitAllows(now)) {
|
|
545
|
+
return { skipped: 'llm-unavailable', checked: 0, added: {}, total: store.map().size };
|
|
546
|
+
}
|
|
547
|
+
const cutoff = now - Math.max(1, Number(windowMs) || 0);
|
|
548
|
+
const words = new Set();
|
|
549
|
+
const view = this.memory.indexManager?.snapshot?.();
|
|
550
|
+
for (const event of view?.events ?? []) {
|
|
551
|
+
const anchor = Number(event.anchorTime ?? event.eventTime) || 0;
|
|
552
|
+
if (anchor < cutoff) continue;
|
|
553
|
+
for (const tag of event.tags ?? []) {
|
|
554
|
+
const name = typeof tag === 'string' ? tag : tag?.tag;
|
|
555
|
+
if (isEntityTag(name)) words.add(entityWord(name));
|
|
556
|
+
}
|
|
557
|
+
}
|
|
558
|
+
const known = [...words].filter(Boolean).sort();
|
|
559
|
+
// Nothing to compare against: one word cannot be a synonym of anything.
|
|
560
|
+
if (known.length < 2) return { skipped: 'not-enough-words', checked: known.length, added: {}, total: store.map().size };
|
|
561
|
+
const prompt = aliasPrompt(known);
|
|
562
|
+
const previousFetch = this.fetchImpl;
|
|
563
|
+
if (fetchImpl) this.fetchImpl = fetchImpl;
|
|
564
|
+
try {
|
|
565
|
+
const content = await this._chat({
|
|
566
|
+
system: prompt.system,
|
|
567
|
+
user: prompt.user,
|
|
568
|
+
config,
|
|
569
|
+
maxTokens: Math.max(128, Math.ceil(known.length * 8) + 64),
|
|
570
|
+
});
|
|
571
|
+
const pairs = sanitiseAliasPairs(parseAliasReply(content), { known });
|
|
572
|
+
const learned = store.learn(pairs);
|
|
573
|
+
this._recordLlmSuccess();
|
|
574
|
+
return { checked: known.length, added: learned.added, changed: learned.changed, total: learned.total };
|
|
575
|
+
} catch (error) {
|
|
576
|
+
this._recordLlmFailure(now, config);
|
|
577
|
+
this._warn(logger ?? this.logger, { tag: 'entity-alias', reason: 'llm-error', at: now, error });
|
|
578
|
+
return { skipped: 'llm-error', checked: known.length, added: {}, total: store.map().size, errorCode: error?.code ?? null };
|
|
579
|
+
} finally {
|
|
580
|
+
this.fetchImpl = previousFetch;
|
|
581
|
+
}
|
|
582
|
+
}
|
|
583
|
+
|
|
514
584
|
/**
|
|
515
585
|
* Run one offline Dream pass. LLM calls are strictly serial (one group at a
|
|
516
586
|
* time) and the whole run is single-flight: a concurrent call is refused, not
|