dsh-layers-hippocampus 1.6.8 → 1.7.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +121 -2
- package/README.md +23 -3
- package/docs/ARCHITECTURE.zh.md +2 -2
- package/index.js +240 -22
- package/package.json +1 -1
- package/src/config.js +57 -0
- package/src/dream.js +134 -10
- package/src/entityAlias.js +330 -0
- package/src/index/buildIndex.js +27 -6
- package/src/index/indexManager.js +30 -1
- package/src/memory.js +201 -7
- package/src/policy.js +14 -0
- package/src/privacy.js +63 -0
- package/src/retrieval.js +140 -6
- package/src/semantic/dimensions.js +169 -0
- package/src/semantic/semanticStore.js +18 -2
- package/src/tagGraph.js +123 -0
- package/src/utils/promptLayout.js +29 -1
- package/src/webRoutes.js +6 -0
package/CHANGELOG.md
CHANGED
|
@@ -4,6 +4,119 @@ All notable changes to `dsh-layers-hippocampus` are documented here.
|
|
|
4
4
|
The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
|
|
5
5
|
and the project adheres to [Semantic Versioning](https://semver.org/).
|
|
6
6
|
|
|
7
|
+
## [1.7.0] — 2026-11-24
|
|
8
|
+
|
|
9
|
+
**全链路记忆的第二半:写入侧去重(实体)、检索侧联想(1 跳)、语义侧分层(六维人格)、
|
|
10
|
+
隐私侧闸门(secret)、以及“模型不知道自己有哪些工具”的可观测性。**
|
|
11
|
+
|
|
12
|
+
- **Added — 实体归并(M1 本地半,零 Token)**。新增 `src/entityAlias.js`:
|
|
13
|
+
`entity:` 标签在**写入前**折向已有规范词——先查 `state/entity_alias.json` 字典,
|
|
14
|
+
再判子串包含(已有 `entity:红薯` 时 `entity:烤红薯` 直接折向短词),最后是编辑距离
|
|
15
|
+
(相似度 ≥0.8 且长度差 ≤2,专治拼写错误)。折名结果改写的是**写入形状**,raw 日志照旧
|
|
16
|
+
append-only;同一批写入里连续出现的实体也互通(`_recentEntityWords` 兜住索引未跟上的窗口)。
|
|
17
|
+
折名发生在 `stage()` 内、`_resolveTags()` 之前;早先传原始 tags 会让合并结果被整体覆盖。
|
|
18
|
+
- **Added — 别名字典落盘**。`state/entity_alias.json`(schema 1,`writeJsonAtomic`),
|
|
19
|
+
词表可由 Dream 自动扩充,也可人工编辑。
|
|
20
|
+
- **Added — 离线同义词学习**。`DreamEngine.learnAliases()`:取过去 24h 新增 `entity:` 词
|
|
21
|
+
(<2 个词直接 skip),走与蒸馏**同一套** fetch 超时/鉴权/熔断设施发一次小请求
|
|
22
|
+
(`maxTokens = max(128, 词数×8+64)`),只接受 `{"aliases":{variant:canonical}}`;
|
|
23
|
+
`sanitiseAliasPairs(..., {known})` 要求 canonical **必须已存在**,否则等于凭空造节点。
|
|
24
|
+
学到新词后 `markDirty()` + `invalidateAdjacency()`,索引重建时旧事件自动折到新节点
|
|
25
|
+
(日志不动,删空节点只是派生视图的事)。
|
|
26
|
+
- **Added — 1 跳联想召回(M2)**。新增 `src/tagGraph.js`:`buildAdjacency()` 把共现边编成
|
|
27
|
+
`Map<tag, [{tag,weight}]>`(对称、去重、权重降序、每节点最多 8 个邻居),
|
|
28
|
+
`expandOneHop()` 每条种子只做**一次** `Map.get`——没有队列、没有 visited 集,因此不存在图遍历。
|
|
29
|
+
`recall()` 新增 `adjacency` / `maxAssociativeHops`(默认 1)/ `associativeLimit`(默认 2):
|
|
30
|
+
>1 直接抛 `MEM_E_INVALID_INPUT: maxAssociativeHops must be <= 1: associative recall is a single
|
|
31
|
+
O(1) lookup, not a graph walk`(空索引也照样抛,参数错误不该被数据量掩盖);
|
|
32
|
+
0 则完全关闭联想。命中的邻居以 `ASSOCIATION_PENALTY`(0.5)参与打分,
|
|
33
|
+
最相似的 1–2 条 L3 摘要以半权重返回,并在 `associative` 里说明“经由哪个标签、几跳”。
|
|
34
|
+
种子来自三处:显式查询标签、文本分词命中的标签、以及**在查询文本里被点名的实体**
|
|
35
|
+
(`entitySeedsMentioned()`,硬上限 200 次扫描)——所以“红薯怎么做”也能顺着图谱摸到 `topic:吃饭`。
|
|
36
|
+
- **Added — 时间窗加成**。`recall()` 的 `recentWindow`(`retrieval.recentWindowTurns`,默认 50 轮):
|
|
37
|
+
窗口内事件按“离窗口末尾多近”给 1.2×–1.5× 加成。因为上限从 1.3 抬到 1.5,
|
|
38
|
+
剪枝硬上界同步从 `salience × 3.9` 改为 **`salience × 4.5`**(剪枝仍是精确的,测试逐位比对)。
|
|
39
|
+
- **Added — 自动指针注入(M3)**。`context.autoInjectIndex`(默认 `{enabled:true, everyNTurns:3,
|
|
40
|
+
maxPointers:3, maxChars:300}`,也接受 `true`/`false` 简写):每 N 个 user turn 在
|
|
41
|
+
`[Memory Hints]` 之后追加 `[Memory Index]`,格式 `- [memory <eventId>] <tag> · <title>`,
|
|
42
|
+
**绝不注入正文**;单次硬限 300 字符;注入过的 eventId 进入同一个 `injectedIds` 去重池;
|
|
43
|
+
活跃标签签名没变就保持沉默(不重复刷同一批指针);新会话 / 插件重启后立刻重新布防一次
|
|
44
|
+
——这正是“重启后上下文空白”那个缺口的补丁。`/memory status` 会报 `[Memory Index]` 状态。
|
|
45
|
+
- **Added — L3 六维人格(M2)**。新增 `src/semantic/dimensions.js`:persona / preferences /
|
|
46
|
+
facts-rules / relationships / skills-patterns / boundaries;`upsert()` 接受 `dimension`
|
|
47
|
+
并落 `dim:<dim>` 标签(**标签不变量仍按调用方原始 tags 校验**,`dim:` 不能当免标签后门);
|
|
48
|
+
未指定时按 tag → 标题 → 关键词推断。`personaTraitsText()` 按维度排序并**逐行剥离生理状态**
|
|
49
|
+
(`PHYSIOLOGY_TERMS`:疲劳/心率/体温/激素…)——“不是人体,是人格”。
|
|
50
|
+
- **Added — 隐私闸门(M3)**。新增 `src/privacy.js`:带 `privacy:secret` 标签或
|
|
51
|
+
`meta.privacy='secret'` 的记录,`recall` **默认过滤**并在 `notes` 记 `privacy-withheld:<n>`;
|
|
52
|
+
只有显式 `includeSecret`(工具参数 `include_secret`)才返回;secret 既不进
|
|
53
|
+
`[Memory Index]` 指针,也不做联想种子(不然隐私会从邻边漏出来)。
|
|
54
|
+
判定与打标由调用方(情感插件)负责,本插件只提供接口与过滤。
|
|
55
|
+
- **Added — Dream 事实来源(M4)**。蒸馏输出契约扩展为
|
|
56
|
+
`{"summary","confidence","facts":[{"text","source"}],"dimension"}`;`source` 只认
|
|
57
|
+
`user`/`self`,**无主或非法的条目直接丢弃**(绝不默认成“用户说”),机械兜底
|
|
58
|
+
`localDistillation()` 也按事件 role 标注。facts 与 dimension 落进该 L3 记录的 `meta`。
|
|
59
|
+
- **Added — 交接摘要结构化(M1)**。`getLatestHandoffSummary()` 在保留 `text` 的同时新增
|
|
60
|
+
`activeTask` / `recentFacts` / `personaTraits` / `lastRawTurns`;`lastRawTurns` 条数由
|
|
61
|
+
`context.handoffSummaryTurns`(默认 4,范围 3–5)控制,**每条都带 role**——不接受无主纯文本。
|
|
62
|
+
- **Added — 工具使用证据(M5)**。`runtime.toolUsage` 统计每个工具的真实调用次数,
|
|
63
|
+
`/memory status` 新增「工具使用(本进程)」段;`remember/recall/capture/deep_raw`
|
|
64
|
+
长期 0 次时直接建议 `/memory tools disable`。不新增任何模型请求。
|
|
65
|
+
- **Tests**:新增 `test/v170.dimensions.test.js`(7 例)。全量 **548/548**(86 个测试文件)。
|
|
66
|
+
|
|
67
|
+
## [1.6.9] — 2026-11-22
|
|
68
|
+
|
|
69
|
+
**全链路记忆机制:写入时归并、检索时联想、装配时只给指针。**
|
|
70
|
+
在 1.6.8 的「密文不写入」之后,这一版补上另外三处漏点——
|
|
71
|
+
**标签会分裂**(`entity:红薯` 与 `entity:烤红薯` 各自成节点)、
|
|
72
|
+
**联想靠自觉**(模型不主动 `recall` 就不会碰到相关记忆)、
|
|
73
|
+
**上下文靠运气**(同一件事从不跨轮次自动进入 Prompt)。
|
|
74
|
+
|
|
75
|
+
- **Added — 本地实体归并(零 Token,写侧)**:新增 `src/entityAlias.js`。`entity:` 标签在
|
|
76
|
+
`stage()` 写入前先折名,三条判据按顺序:① 别名字典命中(`state/entity_alias.json`);
|
|
77
|
+
② **子串包含**——已有 `entity:红薯` 时写入 `entity:烤红薯` 直接折向较短的既有词;
|
|
78
|
+
③ **编辑距离**——相似度 ≥0.8 且长度差 ≤2 时归并(收拾拼写错误)。
|
|
79
|
+
折名记录写进事件的 `meta.entity_merged`(`{from,to,reason:'alias'|'substring'|'fuzzy'}`),
|
|
80
|
+
`entity` 字段同步规范化。**修掉一个真根因**:`_resolveTags()` 原先用原始 tags 覆盖合并结果,
|
|
81
|
+
导致合并看似生效、实际仍分裂出新标签。
|
|
82
|
+
- **Added — 别名字典(`state/entity_alias.json`,schema 1,原子写)**:`EntityAliasStore` 提供
|
|
83
|
+
`load/map/list/resolve/learn/status`。索引构建期 `buildIndex()` 通过 `canonicalTag()` 再折一次,
|
|
84
|
+
所以**日志永远不被改写**:所谓「转移旧节点事件、删除空节点」,是索引重建后自然收敛,
|
|
85
|
+
原始记录仍在 `raw/` 与 `log/` 里可查。
|
|
86
|
+
- **Added — Dream 学同义词**:`DreamEngine.learnAliases()` 取过去 24h 新增的 `entity:` 词,
|
|
87
|
+
发一个小的 JSON 请求让模型输出 `{"aliases":{"地瓜":"红薯"}}`,经
|
|
88
|
+
`sanitiseAliasPairs(pairs, { known })` 过滤后写入字典——**只允许折向已存在的规范词**,
|
|
89
|
+
否则等于让模型凭空造节点。学完置 `markDirty()` + `invalidateAdjacency()`,下轮读取即生效;
|
|
90
|
+
它排在月记与 Dream **之后**,失败只记 `executeDream().entityAliasError`,绝不拖垮蒸馏。
|
|
91
|
+
- **Added — 1 跳共现联想(严格 O(1))**:新增 `src/tagGraph.js`。`buildAdjacency()` 把
|
|
92
|
+
`state/graph.json` 的共现边折成 `Map<tag,[{tag,weight}]>`(对称、权重降序、每点最多 8 邻居);
|
|
93
|
+
`recall()` 命中查询标签后只做一次 `Map.get()` 取最强邻居——**不建队列、不记 visited,没有 BFS/DFS**。
|
|
94
|
+
联想语义条目按 `score × 0.5` 返回并标注 `association:{via,penalty,hops:1}`,
|
|
95
|
+
`recall` 结果里的 `associative.{hops,tags,seeds,semantic}` 让「为什么带回了这条」可审计。
|
|
96
|
+
`entitySeedsMentioned()` 会把**查询文本里直接出现的 entity 词**当种子,
|
|
97
|
+
所以 `entity:红薯` 不需要用户显式写标签也能触发联想。
|
|
98
|
+
- **Added — `maxAssociativeHops` 硬上限 1**:`assertAssociativeHops()` 在 `recall()`、
|
|
99
|
+
`_recallLocal()` 与工具入口**最先**执行(空索引也照样校验);`>1` 直接抛
|
|
100
|
+
`MEM_E_INVALID_INPUT`(「associative recall is a single O(1) lookup, not a graph walk」);
|
|
101
|
+
`0` 可关掉联想。**性能是契约,不是建议。**
|
|
102
|
+
- **Added — 时间窗加成**:`policy.retrieval.recentWindowTurns`(默认 50)取最近 N 个事件的时间范围,
|
|
103
|
+
窗口内事件按贴近程度拿 **1.2x–1.5x**(`RECENT_BOOST_MIN/MAX`)。
|
|
104
|
+
因为 `timeBoost` 上限由 1.3 提到 1.5,剪枝上界 `PRUNE_BOUND_FACTOR` 同步 **3.9 → 4.5**
|
|
105
|
+
(否则 `salience × 3.9` 不再是硬上界,早停会剪错)。
|
|
106
|
+
- **Added — 自动指针注入(`context.autoInjectIndex`)**:默认
|
|
107
|
+
`{ enabled: true, everyNTurns: 3, maxPointers: 3, maxChars: 300 }`(也接受布尔简写)。
|
|
108
|
+
插件就绪 / 会话切换即布防,**第一轮就**输出 `[Memory Index]` 段;此后每 N 个 user turn 重新布防。
|
|
109
|
+
行格式 `- [memory <eventId>] <tag> · <title>`——**只有指针,没有正文**,整段硬限 300 字符。
|
|
110
|
+
注入过的 eventId 进 `runtime.injection.ids` 去重池;活跃标签签名没变就不再重复注入。
|
|
111
|
+
这是「模型不会主动 recall 怎么办」的答案:不逼它调用工具,只把索引放到它眼前。
|
|
112
|
+
- **Changed — 可配置 / 可观测**:`context.autoInjectIndex.{enabled,everyNTurns,maxPointers,maxChars}`
|
|
113
|
+
四个键进 `EDITABLE_CONFIG_KEYS`;`recall` 结果带 `associative` 与 `recentWindow`;
|
|
114
|
+
`memory.status()` 暴露 `entityAliasStatus()` 与 `associativeStatus()`。
|
|
115
|
+
- **Tests**:新增 `test/v169.fullchain.test.js`(6 例)——`烤红薯` 因子串包含折进 `红薯`;
|
|
116
|
+
Dream 识别 `地瓜 → 红薯` 且重定向到索引、日志未被改写;查 `红薯` 带回 `吃饭` 的联想摘要且仅 1 跳;
|
|
117
|
+
近期记忆得分高于同权重旧记忆;`maxAssociativeHops > 1` 抛错、`0` 关闭;
|
|
118
|
+
首轮即注入指针、同会话不重复、标签未变仍不重复。
|
|
119
|
+
全量 **541/541**(85 个测试文件)。
|
|
7
120
|
## [1.6.8] — 2026-11-20
|
|
8
121
|
|
|
9
122
|
**写侧护栏:拒绝高熵密文 / 加密载荷。** raw 日志与 L1 事件日志是本插件承诺「永远保留」
|
|
@@ -30,7 +143,13 @@ and the project adheres to [Semantic Versioning](https://semver.org/).
|
|
|
30
143
|
(会话里粘一段密钥不该让日志被 warn 淹没),其他错误仍照旧上抛。
|
|
31
144
|
- **Tests**:新增 `test/v168.encrypted.test.js`(8 例):熵函数基准、7 类正常内容零误判、
|
|
32
145
|
base64/hex/PEM 三判据各自的拒绝理由、raw store 拒绝且磁盘无残留、auto-capture 的 skip
|
|
33
|
-
语义、`remember()` 同规则且普通写入不受影响。全量 **
|
|
146
|
+
语义、`remember()` 同规则且普通写入不受影响。全量 **541/541**(85 个测试文件)。
|
|
147
|
+
- **Fixed — `/memory maintain` 的计数全是空的**:该命令把 `report.rawArchive.archived`
|
|
148
|
+
与 `report.rawPrune.removed` 当数字插值,而它们其实是**数组**,于是输出成了
|
|
149
|
+
`维护完成:;L2 合并 0 组;冷归档 个。`(分段用空数组拼出来就是空串)。现在统一走
|
|
150
|
+
`count()`(数组取 length、数字取原值),并且只推入有内容的分段;本轮真的什么都没做时
|
|
151
|
+
明确回答「本轮无变更」。新增回归用例(`test/v165.micokernel.test.js` 第 9 例)锁住
|
|
152
|
+
「无空分段 + 冷归档必须带数字」。
|
|
34
153
|
- **Docs**:`记忆插件-未完成表.md` 从「2026-11-05 待办审计」重写为「当前状态表」——
|
|
35
154
|
A1–A21 逐项给出关闭依据,13 项关闭、2 项 superseded、2 项并入 M3/M6、4 项明确不做
|
|
36
155
|
(并写明为什么不做),另列仍需外部动作的四项(npm 账号封控等)。
|
|
@@ -103,7 +222,7 @@ M1 则是本版的主线功能——每轮 Prompt 不再为记忆**正文**付
|
|
|
103
222
|
sink 收到 payload 且被计数、sink 抛错只记 `sink-error` 不外溢、`externalSeams()` 如实报告
|
|
104
223
|
「通知与高峰缺席、价格回退本地时间窗」、注入 `notifier` 服务后被自动发现并可用、
|
|
105
224
|
注入 `priceTip` 后外部价格**优先于**本地时钟窗口。
|
|
106
|
-
全量 **
|
|
225
|
+
全量 **541/541**(85 个测试文件)。
|
|
107
226
|
|
|
108
227
|
## [1.6.6] — 2026-11-16
|
|
109
228
|
|
package/README.md
CHANGED
|
@@ -7,7 +7,7 @@
|
|
|
7
7
|
|
|
8
8
|
| | |
|
|
9
9
|
| --- | --- |
|
|
10
|
-
| 版本 | **1.
|
|
10
|
+
| 版本 | **1.7.0** |
|
|
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.
|
|
235
|
+
pnpm add "github:382quaii/dsh-Layers-Hippocampus#v1.7.0"
|
|
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 # 进程内全量用例(548 个)
|
|
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.
|
|
3
|
+
> 版本:**1.7.0** | 全量用例:**548/548** | 运行时依赖:**零**
|
|
4
4
|
|
|
5
5
|
给 DSH 智能体一份"活得比会话久"的记忆:**追加式原始日志是唯一真相源**,标签索引、日记、活跃集合全部是可丢弃、可重建的读模型,语义摘要独立于原始日志生死。
|
|
6
6
|
|
|
@@ -681,7 +681,7 @@ window.__ModuleLoader__.load({
|
|
|
681
681
|
|
|
682
682
|
运行器带**看门狗**:默认 **60s**(`MEM_TEST_TIMEOUT_MS` 可调)仍未退出,就打印**卡住时正在导入/执行的文件、最后完成的测试名与完成数、活动资源、尚未触发的定时器**,然后 `process.exit(1)`。它不会用 `process.exit(0)` 掩盖超时——挂起即失败。`MEM_TEST_TRACE=1` 可看文件级进度,`MEM_TEST_ONLY=<子串>` 只跑一组。
|
|
683
683
|
|
|
684
|
-
|
|
684
|
+
548 个用例(86 个文件)覆盖:
|
|
685
685
|
|
|
686
686
|
- 索引与标签:重建 digest 一致、行号漂移防护(eventId 不变、行号变)、同义合并、活跃集 cap 挤出、规则变更不改清单、空活跃集降级、top-k 有界有序去重。
|
|
687
687
|
- 衰减与删除:30 天半衰期、reinforce 移动锚点(不存字段)、仅文本粗筛、标签过滤、维护代切换且旧代可读、boot 检查、压缩不丢记录、并发维护串行化、四阶段删除、archive 可回滚 vs purge 不可、strict 巩固暂停与恢复、任务重放幂等、错误 id 零变更。
|
package/index.js
CHANGED
|
@@ -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';
|
|
@@ -43,6 +43,8 @@ import { DreamTimer } from './src/dreamTimer.js';
|
|
|
43
43
|
import { probeCompression, resolveEngine } from './src/compression.js';
|
|
44
44
|
import { LIVE_COMPACT_DEFAULTS, liveCompactSession } from './src/context/liveCompact.js';
|
|
45
45
|
import { snippet } from './src/util.js';
|
|
46
|
+
import { dimensionOf, groupByDimension, stripPhysiology, containsPhysiology } from './src/semantic/dimensions.js';
|
|
47
|
+
import { isSecretRecord } from './src/privacy.js';
|
|
46
48
|
import { MEMORY_API, registerMemoryRoutes } from './src/webRoutes.js';
|
|
47
49
|
|
|
48
50
|
export const name = 'memory';
|
|
@@ -63,7 +65,7 @@ export { resolveConfig, DEFAULT_CONFIG };
|
|
|
63
65
|
* of letting a raw 404 reach the user.
|
|
64
66
|
*/
|
|
65
67
|
export const CAPABILITIES = Object.freeze({
|
|
66
|
-
version: '1.
|
|
68
|
+
version: '1.7.0',
|
|
67
69
|
spaces: true,
|
|
68
70
|
memories: true,
|
|
69
71
|
transferConsent: true,
|
|
@@ -386,6 +388,12 @@ export function createRuntime({ ctx = null, config, options, clock, raw = null,
|
|
|
386
388
|
};
|
|
387
389
|
|
|
388
390
|
/** Called by every tool: keeps the dream idle clock honest. */
|
|
391
|
+
/**
|
|
392
|
+
* v1.7.0 (M5): per-tool call counts for THIS process (no model request, no file).
|
|
393
|
+
* The point is evidence: a tool that never gets called is prompt budget spent for
|
|
394
|
+
* nothing, and `/memory status` can say so.
|
|
395
|
+
*/
|
|
396
|
+
runtime.toolUsage = { counts: new Map(), since: null };
|
|
389
397
|
runtime.recordToolCall = ({ landed = false } = {}) => {
|
|
390
398
|
runtime.syncAgentPreset();
|
|
391
399
|
runtime.touch();
|
|
@@ -436,6 +444,15 @@ export function createRuntime({ ctx = null, config, options, clock, raw = null,
|
|
|
436
444
|
* made the model look like it was rereading the same page.
|
|
437
445
|
*/
|
|
438
446
|
runtime.injection = { sessionId: null, ids: new Set(), tags: new Set(), handoffAt: null };
|
|
447
|
+
/**
|
|
448
|
+
* v1.6.9 (module 3): automatic INDEX pointer injection state.
|
|
449
|
+
*
|
|
450
|
+
* `armed` starts true on purpose: the first request after a plugin restart gets one
|
|
451
|
+
* pointer block, which is the whole point of the feature (a model that never calls
|
|
452
|
+
* recall would otherwise never learn the memories exist). After that it is re-armed
|
|
453
|
+
* by the turn counter, never by a timer.
|
|
454
|
+
*/
|
|
455
|
+
runtime.pointers = { armed: true, userTurns: 0, lastSignature: null, lastAt: null, injected: 0 };
|
|
439
456
|
/**
|
|
440
457
|
* v1.6.3 cold-start state (replaces the v1.6.0 boolean `coldStartPending`).
|
|
441
458
|
*
|
|
@@ -494,18 +511,42 @@ export function createRuntime({ ctx = null, config, options, clock, raw = null,
|
|
|
494
511
|
.sort()
|
|
495
512
|
.join(',')}`;
|
|
496
513
|
if (runtime._personaCache?.signature === signature) return runtime._personaCache.text;
|
|
497
|
-
const
|
|
514
|
+
const byConfidence = (left, right) =>
|
|
515
|
+
(Number(right.confidence) || 0) - (Number(left.confidence) || 0) ||
|
|
516
|
+
String(right.summaryId ?? '').localeCompare(String(left.summaryId ?? ''));
|
|
517
|
+
const oneLine = (value) => String(value ?? '').replace(/\s+/g, ' ').trim().slice(0, 240);
|
|
518
|
+
// v1.7.0 (M2): six dimensions, and NOTHING physiological. This plugin models a
|
|
519
|
+
// persona, not a body: a summary line that talks about fatigue/mood/heart-rate is
|
|
520
|
+
// dropped line-by-line (the rest of the same summary may still be persona), and a
|
|
521
|
+
// summary left with nothing is not rendered at all.
|
|
522
|
+
const cleaned = [];
|
|
523
|
+
for (const summary of [...summaries].sort(byConfidence)) {
|
|
524
|
+
const text = stripPhysiology(summary.text ?? '');
|
|
525
|
+
if (!text) continue;
|
|
526
|
+
cleaned.push({ ...summary, text });
|
|
527
|
+
if (cleaned.length >= 18) break;
|
|
528
|
+
}
|
|
529
|
+
if (cleaned.length === 0) return '';
|
|
530
|
+
// The dimension is a PREFIX, not a section header: one line per trait keeps the
|
|
531
|
+
// block the same size it was, and the order is grouped by dimension so a reader
|
|
532
|
+
// (human or model) can still scan it by category.
|
|
533
|
+
const dimensionOrder = new Map(
|
|
534
|
+
['persona', 'preferences', 'facts-rules', 'relationships', 'skills-patterns', 'boundaries'].map((id, index) => [id, index]),
|
|
535
|
+
);
|
|
536
|
+
const ordered = cleaned
|
|
537
|
+
.map((summary) => ({ ...summary, dimension: dimensionOf(summary) }))
|
|
498
538
|
.sort(
|
|
499
539
|
(left, right) =>
|
|
500
|
-
(
|
|
501
|
-
|
|
540
|
+
(dimensionOrder.get(left.dimension) ?? 99) - (dimensionOrder.get(right.dimension) ?? 99) ||
|
|
541
|
+
byConfidence(left, right),
|
|
502
542
|
)
|
|
503
543
|
.slice(0, 10);
|
|
504
|
-
if (
|
|
505
|
-
const oneLine = (value) => String(value ?? '').replace(/\s+/g, ' ').trim().slice(0, 240);
|
|
544
|
+
if (ordered.length === 0) return '';
|
|
506
545
|
const text = [
|
|
507
546
|
'[Persona & Traits]',
|
|
508
|
-
...
|
|
547
|
+
...ordered.map(
|
|
548
|
+
(summary) => `- [${summary.dimension}] ${oneLine(summary.title) || summary.dimension}: ${oneLine(summary.text)}`,
|
|
549
|
+
),
|
|
509
550
|
].join('\n');
|
|
510
551
|
runtime._personaCache = { signature, text };
|
|
511
552
|
return text;
|
|
@@ -608,6 +649,85 @@ export function createRuntime({ ctx = null, config, options, clock, raw = null,
|
|
|
608
649
|
return !pending.sessionId && !pending.agentId && !sessionId && !agentId;
|
|
609
650
|
};
|
|
610
651
|
|
|
652
|
+
/** The hottest N tags, by the priority the maintenance pass computed. */
|
|
653
|
+
runtime.pointerEntries = () => {
|
|
654
|
+
const settings = runtime.config?.context?.autoInjectIndex ?? {};
|
|
655
|
+
const limit = Math.max(1, Math.min(10, Number(settings.maxPointers) || 3));
|
|
656
|
+
const view = memory.indexManager?.snapshot?.();
|
|
657
|
+
const entries = view?.activeSet?.entries ?? [];
|
|
658
|
+
const ranked = [...entries]
|
|
659
|
+
.filter((entry) => entry && typeof entry.tag === 'string' && !/^(?:status:|month:)/.test(entry.tag))
|
|
660
|
+
.sort((left, right) => (right.priority ?? right.eventCount ?? 0) - (left.priority ?? left.eventCount ?? 0))
|
|
661
|
+
.slice(0, limit);
|
|
662
|
+
if (ranked.length === 0) return [];
|
|
663
|
+
// One pass over the events for ALL candidate ids (a per-tag scan would be O(tags x events)).
|
|
664
|
+
const wanted = new Set();
|
|
665
|
+
for (const entry of ranked) {
|
|
666
|
+
for (const posting of view?.tags?.[entry.tag]?.postings ?? []) wanted.add(posting.eventId);
|
|
667
|
+
}
|
|
668
|
+
if (wanted.size === 0) return [];
|
|
669
|
+
const byId = new Map();
|
|
670
|
+
for (const event of view?.events ?? []) {
|
|
671
|
+
if (wanted.has(event.eventId)) byId.set(event.eventId, event);
|
|
672
|
+
}
|
|
673
|
+
const picked = [];
|
|
674
|
+
for (const entry of ranked) {
|
|
675
|
+
const postings = [...(view?.tags?.[entry.tag]?.postings ?? [])].sort(
|
|
676
|
+
(left, right) => (right.strength ?? 0) - (left.strength ?? 0),
|
|
677
|
+
);
|
|
678
|
+
const best = postings.find((posting) => byId.has(posting.eventId));
|
|
679
|
+
if (!best) continue;
|
|
680
|
+
const event = byId.get(best.eventId);
|
|
681
|
+
// v1.7.0 (M3): a secret memory is never advertised as a pointer — the index
|
|
682
|
+
// would otherwise leak its existence into every prompt.
|
|
683
|
+
if (isSecretRecord(event)) continue;
|
|
684
|
+
// A pointer already delivered in this session is never repeated.
|
|
685
|
+
if (runtime.injection.ids.has(event.eventId)) continue;
|
|
686
|
+
const title = snippet(String(event.content ?? ''), 60);
|
|
687
|
+
picked.push({ eventId: event.eventId, tags: [entry.tag], title });
|
|
688
|
+
}
|
|
689
|
+
return picked;
|
|
690
|
+
};
|
|
691
|
+
|
|
692
|
+
/**
|
|
693
|
+
* v1.6.9: the pointer block for THIS prompt, or ''. Consumes the arm flag.
|
|
694
|
+
*
|
|
695
|
+
* Guard rails, all deliberate:
|
|
696
|
+
* - disabled config -> never renders (and never clears the arm);
|
|
697
|
+
* - unchanged hot-tag signature -> nothing new to say, so nothing is injected;
|
|
698
|
+
* - every emitted id joins `runtime.injection.ids`, so one memory cannot be
|
|
699
|
+
* injected twice (as a pointer or later as a full block).
|
|
700
|
+
*/
|
|
701
|
+
runtime.pointerText = () => {
|
|
702
|
+
const settings = runtime.config?.context?.autoInjectIndex ?? {};
|
|
703
|
+
if (runtime.phase !== 'ready' || settings.enabled !== true) return '';
|
|
704
|
+
if (runtime.pointers.armed !== true) return '';
|
|
705
|
+
try {
|
|
706
|
+
const entries = runtime.pointerEntries();
|
|
707
|
+
runtime.pointers.armed = false;
|
|
708
|
+
runtime.pointers.lastAt = memory.clock.now();
|
|
709
|
+
const signature = entries.map((entry) => `${entry.tags.join(',')}:${entry.eventId}`).join('|');
|
|
710
|
+
if (entries.length === 0 || signature === runtime.pointers.lastSignature) return '';
|
|
711
|
+
const text = renderPointers(entries, { maxChars: settings.maxChars });
|
|
712
|
+
if (!text) return '';
|
|
713
|
+
runtime.pointers.lastSignature = signature;
|
|
714
|
+
runtime.pointers.injected += 1;
|
|
715
|
+
for (const entry of entries) runtime.injection.ids.add(entry.eventId);
|
|
716
|
+
return text;
|
|
717
|
+
} catch {
|
|
718
|
+
return '';
|
|
719
|
+
}
|
|
720
|
+
};
|
|
721
|
+
|
|
722
|
+
/** Called for every captured USER turn: the only clock this feature uses. */
|
|
723
|
+
runtime.noteUserTurn = () => {
|
|
724
|
+
const settings = runtime.config?.context?.autoInjectIndex ?? {};
|
|
725
|
+
if (settings.enabled !== true) return;
|
|
726
|
+
runtime.pointers.userTurns += 1;
|
|
727
|
+
const every = Math.max(1, Number(settings.everyNTurns) || 3);
|
|
728
|
+
if (runtime.pointers.userTurns % every === 0) runtime.pointers.armed = true;
|
|
729
|
+
};
|
|
730
|
+
|
|
611
731
|
/**
|
|
612
732
|
* v1.6.0 / v1.6.3: one-shot cold-start block for a conversation that just started
|
|
613
733
|
* after a handoff.
|
|
@@ -738,6 +858,9 @@ export function createRuntime({ ctx = null, config, options, clock, raw = null,
|
|
|
738
858
|
for (const tag of freshTags) runtime.injection.tags.add(tag);
|
|
739
859
|
if (selected.length > 0) runtime.lastHintTags = selected;
|
|
740
860
|
const hints = hintsMuted ? '' : renderMemoryHints(freshTags, { toolName: `${config.toolPrefix}_recall` });
|
|
861
|
+
// v1.6.9 (module 3): computed AFTER hints (the most volatile of all) and rendered
|
|
862
|
+
// below them, so the cacheable prefix never moves.
|
|
863
|
+
const pointers = runtime.pointerText();
|
|
741
864
|
|
|
742
865
|
// v1.5.6: [Active Task] is unconditional when a handoff summary or a `task:`
|
|
743
866
|
// event exists — injected once per session.
|
|
@@ -781,7 +904,7 @@ export function createRuntime({ ctx = null, config, options, clock, raw = null,
|
|
|
781
904
|
// must say so — otherwise the model reads a title as if it were the memory.
|
|
782
905
|
const rules = memory.context.injectMode === 'full' ? PROMPT_STATE_RULES : PROMPT_STATE_RULES_INDEX;
|
|
783
906
|
return (
|
|
784
|
-
composePrompt({ rules, activeTask: activeTaskBlock, blocks, hints }) +
|
|
907
|
+
composePrompt({ rules, activeTask: activeTaskBlock, blocks, hints, pointers }) +
|
|
785
908
|
marker +
|
|
786
909
|
(coldStart ? `\n${coldStart}` : '')
|
|
787
910
|
);
|
|
@@ -1380,15 +1503,67 @@ export function createRuntime({ ctx = null, config, options, clock, raw = null,
|
|
|
1380
1503
|
tailTurns: Array.isArray(handoff?.tailTurns) ? handoff.tailTurns.map((turn) => ({ ...turn })) : [],
|
|
1381
1504
|
text: null,
|
|
1382
1505
|
found: false,
|
|
1506
|
+
// v1.7.0 (M1): a router plugin needs FIELDS, not a wall of prose. Every raw
|
|
1507
|
+
// turn below carries a role, so nothing here is unattributed text.
|
|
1508
|
+
activeTask: null,
|
|
1509
|
+
recentFacts: [],
|
|
1510
|
+
personaTraits: [],
|
|
1511
|
+
lastRawTurns: [],
|
|
1383
1512
|
};
|
|
1384
|
-
|
|
1513
|
+
const structured = () => {
|
|
1514
|
+
const turns = Math.max(3, Math.min(5, Number(runtime.config?.context?.handoffSummaryTurns) || 4));
|
|
1515
|
+
const tail = Array.isArray(base.tailTurns)
|
|
1516
|
+
? base.tailTurns.filter((turn) => turn && typeof turn.text === 'string' && turn.text.length > 0)
|
|
1517
|
+
: [];
|
|
1518
|
+
const lastRawTurns = tail
|
|
1519
|
+
.slice(-turns)
|
|
1520
|
+
.map((turn) => ({ role: turn.role === 'assistant' ? 'assistant' : 'user', text: String(turn.text).slice(0, 600) }));
|
|
1521
|
+
let activeTask = null;
|
|
1522
|
+
try {
|
|
1523
|
+
const task = memory.promptActiveTask?.();
|
|
1524
|
+
if (task?.text) {
|
|
1525
|
+
activeTask = {
|
|
1526
|
+
eventId: task.eventId ?? null,
|
|
1527
|
+
text: String(task.text).replace(/\s+/g, ' ').trim().slice(0, 600),
|
|
1528
|
+
};
|
|
1529
|
+
}
|
|
1530
|
+
} catch {
|
|
1531
|
+
activeTask = null;
|
|
1532
|
+
}
|
|
1533
|
+
let summaries = [];
|
|
1534
|
+
try {
|
|
1535
|
+
summaries = typeof memory.semanticStore?.list === 'function' ? memory.semanticStore.list() : [];
|
|
1536
|
+
} catch {
|
|
1537
|
+
summaries = [];
|
|
1538
|
+
}
|
|
1539
|
+
const buckets = groupByDimension(summaries.filter((summary) => !containsPhysiology(summary.text ?? '')));
|
|
1540
|
+
const slim = (list, dimension, limit) =>
|
|
1541
|
+
(list ?? [])
|
|
1542
|
+
.slice()
|
|
1543
|
+
.sort((left, right) => (Number(right.confidence) || 0) - (Number(left.confidence) || 0))
|
|
1544
|
+
.slice(0, limit)
|
|
1545
|
+
.map((summary) => ({
|
|
1546
|
+
dimension,
|
|
1547
|
+
summaryId: summary.summaryId ?? null,
|
|
1548
|
+
text: String(stripPhysiology(summary.text ?? '') || '').replace(/\s+/g, ' ').trim().slice(0, 300),
|
|
1549
|
+
}))
|
|
1550
|
+
.filter((entry) => entry.text.length > 0);
|
|
1551
|
+
return {
|
|
1552
|
+
...base,
|
|
1553
|
+
activeTask,
|
|
1554
|
+
recentFacts: slim(buckets.get('facts-rules'), 'facts-rules', 5),
|
|
1555
|
+
personaTraits: slim(buckets.get('persona'), 'persona', 5),
|
|
1556
|
+
lastRawTurns,
|
|
1557
|
+
};
|
|
1558
|
+
};
|
|
1559
|
+
if (!handoff?.summaryEventId) return { ...base, ...structured() };
|
|
1385
1560
|
try {
|
|
1386
1561
|
const events = memory.indexManager.snapshot()?.events ?? [];
|
|
1387
1562
|
const event = events.find((entry) => entry?.eventId === handoff.summaryEventId);
|
|
1388
|
-
if (!event?.content) return base;
|
|
1389
|
-
return { ...base, text: String(event.content).slice(0, 4000), found: true };
|
|
1563
|
+
if (!event?.content) return { ...base, ...structured() };
|
|
1564
|
+
return { ...base, ...structured(), text: String(event.content).slice(0, 4000), found: true };
|
|
1390
1565
|
} catch {
|
|
1391
|
-
return base;
|
|
1566
|
+
return { ...base, ...structured() };
|
|
1392
1567
|
}
|
|
1393
1568
|
};
|
|
1394
1569
|
|
|
@@ -2108,7 +2283,18 @@ export async function apply(ctx, rawConfig = {}) {
|
|
|
2108
2283
|
ctx.logger?.info?.(`hippocampus: tool ${definition.name} skipped by disabled feature flags`);
|
|
2109
2284
|
return;
|
|
2110
2285
|
}
|
|
2111
|
-
|
|
2286
|
+
// v1.7.0 (M5): count calls per tool so `/memory status` can show real usage
|
|
2287
|
+
// evidence instead of guessing. Wrapping here (one place) keeps the 10 tool
|
|
2288
|
+
// definitions untouched and costs no model tokens.
|
|
2289
|
+
const counted = {
|
|
2290
|
+
...definition,
|
|
2291
|
+
execute: (args, context) => {
|
|
2292
|
+
const name = String(definition.name ?? '').replace(`${config.toolPrefix}_`, '');
|
|
2293
|
+
if (name) runtime.toolUsage.counts.set(name, (runtime.toolUsage.counts.get(name) ?? 0) + 1);
|
|
2294
|
+
return definition.execute(args, context);
|
|
2295
|
+
},
|
|
2296
|
+
};
|
|
2297
|
+
disposers.push(ctx.tools.register(counted));
|
|
2112
2298
|
};
|
|
2113
2299
|
const toolLine = (suffix, text) =>
|
|
2114
2300
|
disabledToolSuffixes.has(suffix) || featureDisabledSuffix(suffix) ? null : `- ${config.toolPrefix}_${suffix}: ${text}`;
|
|
@@ -2127,13 +2313,20 @@ export async function apply(ctx, rawConfig = {}) {
|
|
|
2127
2313
|
if (sessionId && sessionId !== runtime.coldStart.lastSessionId) {
|
|
2128
2314
|
runtime.coldStart.lastSessionId = sessionId;
|
|
2129
2315
|
runtime.noteColdStart({ sessionId, source: 'session-switch' });
|
|
2316
|
+
// v1.6.9: a new conversation is exactly when a pointer block is worth its
|
|
2317
|
+
// tokens — the "re-arm after restart / new session" half of module 3.
|
|
2318
|
+
runtime.pointers.armed = true;
|
|
2319
|
+
runtime.pointers.userTurns = 0;
|
|
2130
2320
|
}
|
|
2131
2321
|
// v1.5.6: remember the latest USER turn as the relevance input for
|
|
2132
2322
|
// `[Memory Hints]`. This is the only place the current input is available:
|
|
2133
2323
|
// prompt assembly receives no message text.
|
|
2134
2324
|
try {
|
|
2135
2325
|
const turn = turnFromSessionEvent(event);
|
|
2136
|
-
if (turn && turn.role === 'user' && turn.text && turn.contextOnly !== true)
|
|
2326
|
+
if (turn && turn.role === 'user' && turn.text && turn.contextOnly !== true) {
|
|
2327
|
+
runtime.lastUserText = turn.text;
|
|
2328
|
+
runtime.noteUserTurn();
|
|
2329
|
+
}
|
|
2137
2330
|
} catch {
|
|
2138
2331
|
/* hint relevance must never affect capture */
|
|
2139
2332
|
}
|
|
@@ -2313,6 +2506,12 @@ export async function apply(ctx, rawConfig = {}) {
|
|
|
2313
2506
|
max_tokens: { type: 'number', description: 'deep_raw only: result token budget, default from raw.maxResultTokens' },
|
|
2314
2507
|
hash: { type: 'string', description: 'deep_raw only: restore one raw turn verbatim by sha256 (from [Slimmed] hash_…)' },
|
|
2315
2508
|
regex: { type: 'boolean', description: 'deep_raw only: treat text as a restricted regular expression' },
|
|
2509
|
+
include_secret: {
|
|
2510
|
+
type: 'boolean',
|
|
2511
|
+
description:
|
|
2512
|
+
'Include memories tagged privacy:secret. Omitted by default: secret records are filtered out and only ' +
|
|
2513
|
+
'a count appears in notes (privacy-withheld:N).',
|
|
2514
|
+
},
|
|
2316
2515
|
},
|
|
2317
2516
|
output: { schema: { type: 'string' }, render: (_args, value) => toolResult(value) },
|
|
2318
2517
|
execute: async (args = {}) =>
|
|
@@ -2344,6 +2543,7 @@ export async function apply(ctx, rawConfig = {}) {
|
|
|
2344
2543
|
tags: args.tags ?? [],
|
|
2345
2544
|
topK: Math.min(args.top_k ?? config.retrieval.topK, config.maxRecallTopK),
|
|
2346
2545
|
targetSpaceId: args.target_space_id,
|
|
2546
|
+
includeSecret: args.include_secret === true,
|
|
2347
2547
|
});
|
|
2348
2548
|
runtime.recordToolCall({
|
|
2349
2549
|
landed: (result.hits ?? []).length > 0 || (result.ghostHints ?? []).length > 0,
|
|
@@ -2919,15 +3119,31 @@ export async function apply(ctx, rawConfig = {}) {
|
|
|
2919
3119
|
if (runtime.maintenanceInFlight) return fail('维护已在运行中,本次请求被忽略。');
|
|
2920
3120
|
const result = await runtime.runMaintenance('manual');
|
|
2921
3121
|
const report = result?.report ?? {};
|
|
2922
|
-
|
|
2923
|
-
|
|
2924
|
-
|
|
2925
|
-
|
|
2926
|
-
|
|
2927
|
-
|
|
2928
|
-
|
|
3122
|
+
// Every counter below is optional and several are ARRAYS (`rawArchive.archived`,
|
|
3123
|
+
// `rawPrune.removed`): interpolating an array prints "" or the element, never a
|
|
3124
|
+
// count. Build segments defensively and never emit an empty one — the first
|
|
3125
|
+
// version printed `维护完成:;L2 合并 0 组;冷归档 个`.
|
|
3126
|
+
const count = (value) => (Array.isArray(value) ? value.length : Number(value) || 0);
|
|
3127
|
+
const parts = [];
|
|
3128
|
+
if (report.logGen) parts.push(`日志代 ${report.logGen}`);
|
|
3129
|
+
if (report.indexGen) parts.push(`索引代 ${report.indexGen}`);
|
|
3130
|
+
if (report.l2Merge) parts.push(`L2 合并 ${count(report.l2Merge.merged)} 组`);
|
|
3131
|
+
if (report.dream) parts.push(`Dream ${count(report.dream.merged)} 条`);
|
|
3132
|
+
if (report.rawArchive) parts.push(`冷归档 ${count(report.rawArchive.archived)} 个`);
|
|
3133
|
+
if (report.rawPrune) parts.push(`raw 清理 ${count(report.rawPrune.removed)} 个分片`);
|
|
3134
|
+
if (report.reviewConsume) parts.push(`复习消费 ${count(report.reviewConsume.consumed)} 条`);
|
|
3135
|
+
return ok(parts.length > 0 ? `维护完成:${parts.join(';')}。` : '维护完成:本轮无变更。');
|
|
2929
3136
|
}
|
|
2930
3137
|
|
|
3138
|
+
const toolUsageLine = () => {
|
|
3139
|
+
const counts = [...runtime.toolUsage.counts.entries()].sort((left, right) => right[1] - left[1]);
|
|
3140
|
+
if (counts.length === 0) return '本进程尚无工具调用(重启会清零)';
|
|
3141
|
+
const shown = counts.slice(0, 6).map(([name, count]) => `${name} ${count}`);
|
|
3142
|
+
const idle = ['remember', 'recall', 'capture', 'deep_raw'].filter((name) => !runtime.toolUsage.counts.get(name));
|
|
3143
|
+
const advice = idle.length > 0 ? `;长时间 0 次:${idle.join('/')}(可考虑 /memory tools disable)` : '';
|
|
3144
|
+
return `${shown.join(' · ')}${advice}`;
|
|
3145
|
+
};
|
|
3146
|
+
|
|
2931
3147
|
if (verb === 'status') {
|
|
2932
3148
|
if (runtime.phase !== 'ready') return fail(`记忆引擎状态:${runtime.phase}${runtime.phaseError ? `(${asMemoryError(runtime.phaseError).code})` : ''}`);
|
|
2933
3149
|
const payload = await runtime.uiPayload();
|
|
@@ -2952,6 +3168,8 @@ export async function apply(ctx, rawConfig = {}) {
|
|
|
2952
3168
|
`交接标记:${session.handoffActive ? `active(${session.handoffAt ?? '?'})` : '无'} · 冷启动待注入 ${runtime.coldStart.pending.size} 条 / 已注入 ${runtime.coldStart.injected.size} 次`,
|
|
2953
3169
|
tagList.length ? `活跃标签 Top:${tagList.join('、')}` : '活跃标签:无',
|
|
2954
3170
|
`[Memory Hints]:${runtime.hintsMuted ? '已静默(/memory unmute 恢复)' : '开启'}`,
|
|
3171
|
+
// v1.7.0 (M5): usage EVIDENCE, computed from in-process counters only.
|
|
3172
|
+
`工具使用(本进程):${toolUsageLine()}`,
|
|
2955
3173
|
].join('\n'),
|
|
2956
3174
|
);
|
|
2957
3175
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "dsh-layers-hippocampus",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.7.0",
|
|
4
4
|
"private": false,
|
|
5
5
|
"description": "Layered long-term memory for DeepSeek Harness: append-only event log, rebuildable tag index, day diaries, independent semantic layer, L2.5 trend quarantine, offline knowledge graph and a Web UI panel.",
|
|
6
6
|
"type": "module",
|