dsh-layers-hippocampus 1.7.1 → 1.7.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,9 +1,31 @@
1
- # Changelog
2
-
3
- All notable changes to `dsh-layers-hippocampus` are documented here.
4
- The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
5
- and the project adheres to [Semantic Versioning](https://semver.org/).
6
-
1
+ # Changelog
2
+
3
+ All notable changes to `dsh-layers-hippocampus` are documented here.
4
+ The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
5
+ and the project adheres to [Semantic Versioning](https://semver.org/).
6
+
7
+ ## [1.7.2] — 2026-11-25
8
+
9
+ **设置页结构重构:17 张卡片按用途收进 5 个分组,左侧竖排目录导航;能力与配置一字未改。**
10
+
11
+ - **Changed — 设置页从「一条长滚动」变成「分组 + 目录」**:`ui/client.js` 里 17 个
12
+ `Section` 按用途分成五组——`identity`(身份与行为)、`context`(上下文与注入)、
13
+ `ingest`(摄入与蒸馏)、`retention`(留存与归档)、`space`(空间与存储)。
14
+ 每组由 `SettingsGroup` 渲染(组名 + 一句说明 + 卡片原样),卡片本身**逐字搬进**
15
+ `SettingsIdentityGroup` / `SettingsContextGroup` / `SettingsIngestGroup` /
16
+ `SettingsRetentionGroup` / `SettingsSpaceGroup`,控件、校验、跨字段联动一个字没改。
17
+ - **Changed — 左侧竖排目录**:`SettingsNav` 是**独立滚动的固定栏**——外面的 shell 高度在挂载时量一次
18
+ (`window.innerHeight - shell.top - 24`,`resize` 时重量),目录与卡片各自拥有滚动条,
19
+ 点目录滚卡片、滚卡片目录不动。最初用 `position: sticky` 实现,实际**不生效**:宿主 shell
20
+ 的 overflow 包裹层不是滚动容器,sticky 子元素会随内容一起滚走。滚动高亮改用
21
+ `IntersectionObserver`(`root` 指向卡片滚动容器,`rootMargin: '-8% 0px -70% 0px'`)。
22
+ - **Changed — 表单宽度**:`maxWidth` 720 → 980,目录 148px 固定、内容 `flex: 1 1 460px`,
23
+ 窄屏自动折行(`flexWrap: 'wrap'`)。
24
+ - **保持不变 — 简洁模式**:仍然只显示四组(`identity` / `context` / `retention` / `space`),
25
+ `ingest` 整组不渲染;`hidden: simpleMode` 语义与 `SIMPLE_PATCH_KEYS` 白名单完全照旧。
26
+ - **Tests**:`test/v163.ui.test.js` 新增 `settingsBody()`,把 `MemorySettings` 与五个分组
27
+ 组件体拼起来断言卡片存在/被隐藏,避免结构重构后测试假绿或假红。全量 **555/555**(87 个测试文件)。
28
+
7
29
  ## [1.7.1] — 2026-11-24
8
30
 
9
31
  **把注入面从“多给点信息”改成“只给还没过期的信息”:摘要卫生常开,提示标签单向静默,
@@ -107,1848 +129,1848 @@ and the project adheres to [Semantic Versioning](https://semver.org/).
107
129
  长期 0 次时直接建议 `/memory tools disable`。不新增任何模型请求。
108
130
  - **Tests**:新增 `test/v170.dimensions.test.js`(7 例)。全量 **548/548**(86 个测试文件)。
109
131
 
110
- ## [1.6.9] — 2026-11-22
111
-
112
- **全链路记忆机制:写入时归并、检索时联想、装配时只给指针。**
113
- 在 1.6.8 的「密文不写入」之后,这一版补上另外三处漏点——
114
- **标签会分裂**(`entity:红薯` 与 `entity:烤红薯` 各自成节点)、
115
- **联想靠自觉**(模型不主动 `recall` 就不会碰到相关记忆)、
116
- **上下文靠运气**(同一件事从不跨轮次自动进入 Prompt)。
117
-
118
- - **Added — 本地实体归并(零 Token,写侧)**:新增 `src/entityAlias.js`。`entity:` 标签在
119
- `stage()` 写入前先折名,三条判据按顺序:① 别名字典命中(`state/entity_alias.json`);
120
- ② **子串包含**——已有 `entity:红薯` 时写入 `entity:烤红薯` 直接折向较短的既有词;
121
- ③ **编辑距离**——相似度 ≥0.8 且长度差 ≤2 时归并(收拾拼写错误)。
122
- 折名记录写进事件的 `meta.entity_merged`(`{from,to,reason:'alias'|'substring'|'fuzzy'}`),
123
- `entity` 字段同步规范化。**修掉一个真根因**:`_resolveTags()` 原先用原始 tags 覆盖合并结果,
124
- 导致合并看似生效、实际仍分裂出新标签。
125
- - **Added — 别名字典(`state/entity_alias.json`,schema 1,原子写)**:`EntityAliasStore` 提供
126
- `load/map/list/resolve/learn/status`。索引构建期 `buildIndex()` 通过 `canonicalTag()` 再折一次,
127
- 所以**日志永远不被改写**:所谓「转移旧节点事件、删除空节点」,是索引重建后自然收敛,
128
- 原始记录仍在 `raw/` 与 `log/` 里可查。
129
- - **Added — Dream 学同义词**:`DreamEngine.learnAliases()` 取过去 24h 新增的 `entity:` 词,
130
- 发一个小的 JSON 请求让模型输出 `{"aliases":{"地瓜":"红薯"}}`,经
131
- `sanitiseAliasPairs(pairs, { known })` 过滤后写入字典——**只允许折向已存在的规范词**,
132
- 否则等于让模型凭空造节点。学完置 `markDirty()` + `invalidateAdjacency()`,下轮读取即生效;
133
- 它排在月记与 Dream **之后**,失败只记 `executeDream().entityAliasError`,绝不拖垮蒸馏。
134
- - **Added — 1 跳共现联想(严格 O(1))**:新增 `src/tagGraph.js`。`buildAdjacency()` 把
135
- `state/graph.json` 的共现边折成 `Map<tag,[{tag,weight}]>`(对称、权重降序、每点最多 8 邻居);
136
- `recall()` 命中查询标签后只做一次 `Map.get()` 取最强邻居——**不建队列、不记 visited,没有 BFS/DFS**。
137
- 联想语义条目按 `score × 0.5` 返回并标注 `association:{via,penalty,hops:1}`,
138
- `recall` 结果里的 `associative.{hops,tags,seeds,semantic}` 让「为什么带回了这条」可审计。
139
- `entitySeedsMentioned()` 会把**查询文本里直接出现的 entity 词**当种子,
140
- 所以 `entity:红薯` 不需要用户显式写标签也能触发联想。
141
- - **Added — `maxAssociativeHops` 硬上限 1**:`assertAssociativeHops()` 在 `recall()`、
142
- `_recallLocal()` 与工具入口**最先**执行(空索引也照样校验);`>1` 直接抛
143
- `MEM_E_INVALID_INPUT`(「associative recall is a single O(1) lookup, not a graph walk」);
144
- `0` 可关掉联想。**性能是契约,不是建议。**
145
- - **Added — 时间窗加成**:`policy.retrieval.recentWindowTurns`(默认 50)取最近 N 个事件的时间范围,
146
- 窗口内事件按贴近程度拿 **1.2x–1.5x**(`RECENT_BOOST_MIN/MAX`)。
147
- 因为 `timeBoost` 上限由 1.3 提到 1.5,剪枝上界 `PRUNE_BOUND_FACTOR` 同步 **3.9 → 4.5**
148
- (否则 `salience × 3.9` 不再是硬上界,早停会剪错)。
149
- - **Added — 自动指针注入(`context.autoInjectIndex`)**:默认
150
- `{ enabled: true, everyNTurns: 3, maxPointers: 3, maxChars: 300 }`(也接受布尔简写)。
151
- 插件就绪 / 会话切换即布防,**第一轮就**输出 `[Memory Index]` 段;此后每 N 个 user turn 重新布防。
152
- 行格式 `- [memory <eventId>] <tag> · <title>`——**只有指针,没有正文**,整段硬限 300 字符。
153
- 注入过的 eventId 进 `runtime.injection.ids` 去重池;活跃标签签名没变就不再重复注入。
154
- 这是「模型不会主动 recall 怎么办」的答案:不逼它调用工具,只把索引放到它眼前。
155
- - **Changed — 可配置 / 可观测**:`context.autoInjectIndex.{enabled,everyNTurns,maxPointers,maxChars}`
156
- 四个键进 `EDITABLE_CONFIG_KEYS`;`recall` 结果带 `associative` 与 `recentWindow`;
157
- `memory.status()` 暴露 `entityAliasStatus()` 与 `associativeStatus()`。
158
- - **Tests**:新增 `test/v169.fullchain.test.js`(6 例)——`烤红薯` 因子串包含折进 `红薯`;
159
- Dream 识别 `地瓜 → 红薯` 且重定向到索引、日志未被改写;查 `红薯` 带回 `吃饭` 的联想摘要且仅 1 跳;
160
- 近期记忆得分高于同权重旧记忆;`maxAssociativeHops > 1` 抛错、`0` 关闭;
161
- 首轮即注入指针、同会话不重复、标签未变仍不重复。
162
- 全量 **541/541**(85 个测试文件)。
163
- ## [1.6.8] — 2026-11-20
164
-
165
- **写侧护栏:拒绝高熵密文 / 加密载荷。** raw 日志与 L1 事件日志是本插件承诺「永远保留」
166
- 的两样东西,而密文块恰恰是唯一无法被召回(没有可搜索的子串)、无法被蒸馏(没有可说的
167
- 语义)、也无法被打标的载荷——它只会永久占用保留期与存储预算。这是审计项 A4,自
168
- 1.5.7 起挂着「文档已规划但代码未实现」,本版补上。
169
-
170
- - **Added — `src/entropy.js`**:纯函数检测器,零依赖。
171
- - `shannonEntropy(text)`:香农熵(保留 3 位小数)。
172
- - `detectCiphertext(text, { minRunChars })` → `null` 或
173
- `{ reason: 'pem'|'base64'|'hex', runLength, entropy, at, sample }`。
174
- - 三条判据各自有下限:base64 连续 ≥512 字符且熵 ≥4.5;hex 连续 ≥512 字符且熵 ≥3.5;
175
- PEM 甲壳(`-----BEGIN PGP MESSAGE-----` 等 5 种标记)**即使很短**也拒绝。
176
- - 保守优先:散文、源码、URL、Windows 路径、低熵长串、短 base64 data URI 全部放行。
177
- - **Added — `MEM_E_ENCRYPTED_RAW_REJECTED`**(`src/errors.js`),details 带
178
- `{ reason, runLength, entropy, at }`,调用方不必解析消息文本。
179
- - **Changed — 三条写路径统一护栏**:
180
- - `src/rawStore.js#capture`:在非空校验之后、门槛判定之前检测,**拒绝且零落盘**
181
- (不入队、不刷盘、分片里不会出现该载荷)。
182
- - `src/memory.js#remember`:同规则,且**先于**旧的 base64-media 守卫——对一个密文块,
183
- 叫调用方「改用 media_url」是错误建议,正确诊断是「这是密文」。
184
- - `src/memory.js#captureSessionEvent`:auto-capture 遇到密文时返回
185
- `{ stored: false, skipped: 'encrypted-blob', reason }`,**不作为 capture 失败刷警告**
186
- (会话里粘一段密钥不该让日志被 warn 淹没),其他错误仍照旧上抛。
187
- - **Tests**:新增 `test/v168.encrypted.test.js`(8 例):熵函数基准、7 类正常内容零误判、
188
- base64/hex/PEM 三判据各自的拒绝理由、raw store 拒绝且磁盘无残留、auto-capture 的 skip
189
- 语义、`remember()` 同规则且普通写入不受影响。全量 **541/541**(85 个测试文件)。
132
+ ## [1.6.9] — 2026-11-22
133
+
134
+ **全链路记忆机制:写入时归并、检索时联想、装配时只给指针。**
135
+ 在 1.6.8 的「密文不写入」之后,这一版补上另外三处漏点——
136
+ **标签会分裂**(`entity:红薯` 与 `entity:烤红薯` 各自成节点)、
137
+ **联想靠自觉**(模型不主动 `recall` 就不会碰到相关记忆)、
138
+ **上下文靠运气**(同一件事从不跨轮次自动进入 Prompt)。
139
+
140
+ - **Added — 本地实体归并(零 Token,写侧)**:新增 `src/entityAlias.js`。`entity:` 标签在
141
+ `stage()` 写入前先折名,三条判据按顺序:① 别名字典命中(`state/entity_alias.json`);
142
+ ② **子串包含**——已有 `entity:红薯` 时写入 `entity:烤红薯` 直接折向较短的既有词;
143
+ ③ **编辑距离**——相似度 ≥0.8 且长度差 ≤2 时归并(收拾拼写错误)。
144
+ 折名记录写进事件的 `meta.entity_merged`(`{from,to,reason:'alias'|'substring'|'fuzzy'}`),
145
+ `entity` 字段同步规范化。**修掉一个真根因**:`_resolveTags()` 原先用原始 tags 覆盖合并结果,
146
+ 导致合并看似生效、实际仍分裂出新标签。
147
+ - **Added — 别名字典(`state/entity_alias.json`,schema 1,原子写)**:`EntityAliasStore` 提供
148
+ `load/map/list/resolve/learn/status`。索引构建期 `buildIndex()` 通过 `canonicalTag()` 再折一次,
149
+ 所以**日志永远不被改写**:所谓「转移旧节点事件、删除空节点」,是索引重建后自然收敛,
150
+ 原始记录仍在 `raw/` 与 `log/` 里可查。
151
+ - **Added — Dream 学同义词**:`DreamEngine.learnAliases()` 取过去 24h 新增的 `entity:` 词,
152
+ 发一个小的 JSON 请求让模型输出 `{"aliases":{"地瓜":"红薯"}}`,经
153
+ `sanitiseAliasPairs(pairs, { known })` 过滤后写入字典——**只允许折向已存在的规范词**,
154
+ 否则等于让模型凭空造节点。学完置 `markDirty()` + `invalidateAdjacency()`,下轮读取即生效;
155
+ 它排在月记与 Dream **之后**,失败只记 `executeDream().entityAliasError`,绝不拖垮蒸馏。
156
+ - **Added — 1 跳共现联想(严格 O(1))**:新增 `src/tagGraph.js`。`buildAdjacency()` 把
157
+ `state/graph.json` 的共现边折成 `Map<tag,[{tag,weight}]>`(对称、权重降序、每点最多 8 邻居);
158
+ `recall()` 命中查询标签后只做一次 `Map.get()` 取最强邻居——**不建队列、不记 visited,没有 BFS/DFS**。
159
+ 联想语义条目按 `score × 0.5` 返回并标注 `association:{via,penalty,hops:1}`,
160
+ `recall` 结果里的 `associative.{hops,tags,seeds,semantic}` 让「为什么带回了这条」可审计。
161
+ `entitySeedsMentioned()` 会把**查询文本里直接出现的 entity 词**当种子,
162
+ 所以 `entity:红薯` 不需要用户显式写标签也能触发联想。
163
+ - **Added — `maxAssociativeHops` 硬上限 1**:`assertAssociativeHops()` 在 `recall()`、
164
+ `_recallLocal()` 与工具入口**最先**执行(空索引也照样校验);`>1` 直接抛
165
+ `MEM_E_INVALID_INPUT`(「associative recall is a single O(1) lookup, not a graph walk」);
166
+ `0` 可关掉联想。**性能是契约,不是建议。**
167
+ - **Added — 时间窗加成**:`policy.retrieval.recentWindowTurns`(默认 50)取最近 N 个事件的时间范围,
168
+ 窗口内事件按贴近程度拿 **1.2x–1.5x**(`RECENT_BOOST_MIN/MAX`)。
169
+ 因为 `timeBoost` 上限由 1.3 提到 1.5,剪枝上界 `PRUNE_BOUND_FACTOR` 同步 **3.9 → 4.5**
170
+ (否则 `salience × 3.9` 不再是硬上界,早停会剪错)。
171
+ - **Added — 自动指针注入(`context.autoInjectIndex`)**:默认
172
+ `{ enabled: true, everyNTurns: 3, maxPointers: 3, maxChars: 300 }`(也接受布尔简写)。
173
+ 插件就绪 / 会话切换即布防,**第一轮就**输出 `[Memory Index]` 段;此后每 N 个 user turn 重新布防。
174
+ 行格式 `- [memory <eventId>] <tag> · <title>`——**只有指针,没有正文**,整段硬限 300 字符。
175
+ 注入过的 eventId 进 `runtime.injection.ids` 去重池;活跃标签签名没变就不再重复注入。
176
+ 这是「模型不会主动 recall 怎么办」的答案:不逼它调用工具,只把索引放到它眼前。
177
+ - **Changed — 可配置 / 可观测**:`context.autoInjectIndex.{enabled,everyNTurns,maxPointers,maxChars}`
178
+ 四个键进 `EDITABLE_CONFIG_KEYS`;`recall` 结果带 `associative` 与 `recentWindow`;
179
+ `memory.status()` 暴露 `entityAliasStatus()` 与 `associativeStatus()`。
180
+ - **Tests**:新增 `test/v169.fullchain.test.js`(6 例)——`烤红薯` 因子串包含折进 `红薯`;
181
+ Dream 识别 `地瓜 → 红薯` 且重定向到索引、日志未被改写;查 `红薯` 带回 `吃饭` 的联想摘要且仅 1 跳;
182
+ 近期记忆得分高于同权重旧记忆;`maxAssociativeHops > 1` 抛错、`0` 关闭;
183
+ 首轮即注入指针、同会话不重复、标签未变仍不重复。
184
+ 全量 **541/541**(85 个测试文件)。
185
+ ## [1.6.8] — 2026-11-20
186
+
187
+ **写侧护栏:拒绝高熵密文 / 加密载荷。** raw 日志与 L1 事件日志是本插件承诺「永远保留」
188
+ 的两样东西,而密文块恰恰是唯一无法被召回(没有可搜索的子串)、无法被蒸馏(没有可说的
189
+ 语义)、也无法被打标的载荷——它只会永久占用保留期与存储预算。这是审计项 A4,自
190
+ 1.5.7 起挂着「文档已规划但代码未实现」,本版补上。
191
+
192
+ - **Added — `src/entropy.js`**:纯函数检测器,零依赖。
193
+ - `shannonEntropy(text)`:香农熵(保留 3 位小数)。
194
+ - `detectCiphertext(text, { minRunChars })` → `null` 或
195
+ `{ reason: 'pem'|'base64'|'hex', runLength, entropy, at, sample }`。
196
+ - 三条判据各自有下限:base64 连续 ≥512 字符且熵 ≥4.5;hex 连续 ≥512 字符且熵 ≥3.5;
197
+ PEM 甲壳(`-----BEGIN PGP MESSAGE-----` 等 5 种标记)**即使很短**也拒绝。
198
+ - 保守优先:散文、源码、URL、Windows 路径、低熵长串、短 base64 data URI 全部放行。
199
+ - **Added — `MEM_E_ENCRYPTED_RAW_REJECTED`**(`src/errors.js`),details 带
200
+ `{ reason, runLength, entropy, at }`,调用方不必解析消息文本。
201
+ - **Changed — 三条写路径统一护栏**:
202
+ - `src/rawStore.js#capture`:在非空校验之后、门槛判定之前检测,**拒绝且零落盘**
203
+ (不入队、不刷盘、分片里不会出现该载荷)。
204
+ - `src/memory.js#remember`:同规则,且**先于**旧的 base64-media 守卫——对一个密文块,
205
+ 叫调用方「改用 media_url」是错误建议,正确诊断是「这是密文」。
206
+ - `src/memory.js#captureSessionEvent`:auto-capture 遇到密文时返回
207
+ `{ stored: false, skipped: 'encrypted-blob', reason }`,**不作为 capture 失败刷警告**
208
+ (会话里粘一段密钥不该让日志被 warn 淹没),其他错误仍照旧上抛。
209
+ - **Tests**:新增 `test/v168.encrypted.test.js`(8 例):熵函数基准、7 类正常内容零误判、
210
+ base64/hex/PEM 三判据各自的拒绝理由、raw store 拒绝且磁盘无残留、auto-capture 的 skip
211
+ 语义、`remember()` 同规则且普通写入不受影响。全量 **541/541**(85 个测试文件)。
190
212
  - **Fixed — `/memory maintain` 的计数全是空的**:该命令把 `report.rawArchive.archived`
191
213
  与 `report.rawPrune.removed` 当数字插值,而它们其实是**数组**,于是输出成了
192
214
  `维护完成:;L2 合并 0 组;冷归档 个。`(分段用空数组拼出来就是空串)。现在统一走
193
215
  `count()`(数组取 length、数字取原值),并且只推入有内容的分段;本轮真的什么都没做时
194
216
  明确回答「本轮无变更」。新增回归用例(`test/v165.micokernel.test.js` 第 9 例)锁住
195
217
  「无空分段 + 冷归档必须带数字」。
196
- - **Docs**:`记忆插件-未完成表.md` 从「2026-11-05 待办审计」重写为「当前状态表」——
197
- A1–A21 逐项给出关闭依据,13 项关闭、2 项 superseded、2 项并入 M3/M6、4 项明确不做
198
- (并写明为什么不做),另列仍需外部动作的四项(npm 账号封控等)。
199
-
200
- ## [1.6.7] — 2026-11-17
201
-
202
- **发布链完整性修正 + 索引式提示注入(M1)。1.6.6 在 npm 上的制品(`gitHead 99a07cb`)
203
- 是从一份**旧 checkout** 发布的,只带来 Live Compact 修复,**不含** M3(测试跨包解耦)
204
- 与 M5(错误码边界)。1.6.7 把这两项送往 npm,并让仓库历史与已发布标签不再分叉;
205
- M1 则是本版的主线功能——每轮 Prompt 不再为记忆**正文**付费。**
206
-
207
- - **Added — 外部价格 / 通知接缝(M2)**。`dsh-price-tip` / `dsh-peak-runner` /
208
- `dsh-notify-plugin` 在本机**并不存在**,因此没有「接线真实 API」可做——凭空猜服务名
209
- 等于发明接口。本版只做**可验证的可选接缝**:
210
- - `HostBridge.setNotifier(sink)` + `notify({title,text,kind,at})`:没有 sink 时返回
211
- `{delivered:false, reason:'no-notifier'}` 并只记计数,**绝不发明投递通道、绝不抛错**;
212
- sink 抛错也只记 `sink-error`,不会污染维护流程。
213
- - `index.js` 探测一组**约定键**(`priceTip` / `notifier` / `peakRunner`,或 `notify` / `peak`),
214
- 并接受多种方法形状(`isLowValley|lowValley|isLow|price`、`notify|send|post`、
215
- `isPeak|peak|isHigh`)。外部价格服务优先于内置时间窗;`DSH_DREAM_PRICE` 仍可强制覆盖。
216
- - `capabilities.externalSeams` 报告**哪条接缝真的接上了**(`{wired, source}`),
217
- 所以「没装」是可见事实而不是静默降级。
218
- - 一旦通知接缝可用,「Dream 因高峰被推迟」会通过它播报(内含 `dueAt`);没有接缝时
219
- 这件事仍由持久化队列与 `dream-deferred` 事件表达,行为不变。
220
- - **排队本来就是实装的**:`index.js` 的 `tick()` 在高峰把 LLM 蒸馏写入 `dreamQueue`
221
- 并在谷时唤醒(`reason: 'peak-hour'`),不是丢弃,本次未改动该逻辑。
222
- - **Changed — 多空间开关的语义澄清(M6)**。`features.multiSpace` 默认 `true`,但只有注入了
223
- 能创建空间适配器的 `orchestrator` 服务时才真正生效——以前这个差异是**静默**的:
224
- 用户以为开了多空间,实际在跑单空间。现在新增 `multiSpaceReason()`,返回
225
- `'active'` / `'disabled-by-config'` / `'orchestrator-missing'` 三态,
226
- 通过 `capabilities.multiSpaceReason` + `capabilities.multiSpaceRequested` 与
227
- `panel.spaces.{requested,reason}` 同时暴露,设置页在多空间卡片里直接写明
228
- 「当前被配置关闭:features.multiSpace=false」,不再把「没装适配器」和「你关了它」
229
- 混成一个 `spaces:false`。**开关本身没有改默认值**(改默认会静默改变已部署 profile 的行为),
230
- 改的是可观测性与文档;并有用例锁住「布尔值与理由不可能互相矛盾」。
231
- - **Changed — 索引式提示注入(M1)**。`context.injectMode` 新增两个取值:
232
- - `index`(**新默认**):每个记忆块只注入一行指针
233
- `- [memory <eventId>] 标签 · 标签 · 标题`。正文不进 Prompt,需要细节时用
234
- `memory_recall` 按 eventId / 标签取。`[Memory Blocks]` 标记名保持不变,因此缓存前缀
235
- 语义不变;规则段多一行「这些是索引指针,正文须调 recall」,**只在 index 模式下出现**。
236
- - `full`:沿用旧版渲染(正文前 200 字)与旧版计费(整段正文),一行代码即可回退。
237
- - **窗口计费随渲染形态走**:`ContextEngine.tokensOf()` 在 index 模式下只计指针行,
238
- 在 full 模式下仍计整段正文(旧口径,不动既有调优);调用方**显式传入的 `tokens`
239
- 永远优先**,折叠与驱逐的排序不变。
240
- - `index` 模式下 `tokens()` 的实测差异是数量级的:8,000 字符的正文约 2,000 tokens,
241
- 指针行通常 < 60 tokens。
242
- - `briefing` 块(运营方钉死的策略)**永不降级为指针**,始终整段渲染。
243
- - 可编辑键新增 `context.injectMode`(`index` / `full`,非法值 fail-fast),设置页
244
- 「上下文窗口」卡片新增下拉;简洁模式下同样可见可存。
245
- - **Changed — 测试与兄弟包解耦(M3)**。`test/orchestrator.js` 先按包名 `dsh-layers-orchestrator/src/*`
246
- 解析、失败再退回同级 checkout(`via: 'package' | 'sibling'`);22 个真正依赖多空间的用例改走
247
- `orchestratorTest()`,缺包时注册为 **skipped 并带原因**而不是 import 阶段崩掉整套测试。
248
- `makeMemory()` 的 `multiSpace` 默认值改为 `MULTI_SPACE_AVAILABLE`,杜绝 `new null()`。
249
- 实测:两包在位 **510/510**(skipped 0);单独 checkout 时 **454 pass / 0 fail / 56 skipped**。
250
- - **Changed — 错误码边界(M5)**。`dsh-orchestrator` 内两套命名空间是**故意**并存的:
251
- `MEM_E_*`(从核心搬出去的引擎沿用,客户端 HTTP 映射依赖它)与 `ORCH_E_*`(路由器/去重/联邦/授权)。
252
- 海马体侧新增单一边界 `src/errors.js#fromOrchestratorError()` + `ORCHESTRATOR_CODE_MAP`:
253
- `ORCH_E_CONSENT_*` → `MEM_E_REQUIRE_USER_CONSENT`(三个都映射到同一处,因为修法是去问人而不是重试)、
254
- `ORCH_E_SPACE_INVALID` → `MEM_E_SPACE_INVALID`、`ORCH_E_INVALID_INPUT` → `MEM_E_INVALID_INPUT`、
255
- `ORCH_E_NOT_READY` → `MEM_E_NOT_READY`、`ORCH_E_FEDERATION_CONFLICT` → `MEM_E_FEDERATION_FAILED`;
256
- **未列入的 `ORCH_E_*` 不会被拍平成 `MEM_E_IO`**,原始码保留在 `details.orchestratorCode` 里可审计。
257
- 映射表同步写进 `dsh-orchestrator/README.md` 的「错误码边界」一节。
258
- - **Tests**:新增 `test/v166.errorContract.test.js`(7 例)与 `test/v167.m1.test.js`(9 例:
259
- 默认 index、指针行构成、index 计费 = 渲染行、full 保留旧渲染与旧计费、显式权重优先、
260
- briefing 不降级、标题截断与回退、`injectMode` 校验与可编辑、规则段只在 index 出现、
261
- recall 命中把标签与标题带进窗口且正文尾巴不出现);
262
- `test/v156.features.test.js` 新增 M6 用例(`multiSpaceReason` 三态 + 显式关闭优先于
263
- 缺适配器 + 「布尔值与理由不可能矛盾」的交叉断言);
264
- `test/v167.m2.test.js`(6 例)锁住 M2 接缝:无 sink 时为 `no-notifier` 的记账型空操作、
265
- sink 收到 payload 且被计数、sink 抛错只记 `sink-error` 不外溢、`externalSeams()` 如实报告
266
- 「通知与高峰缺席、价格回退本地时间窗」、注入 `notifier` 服务后被自动发现并可用、
267
- 注入 `priceTip` 后外部价格**优先于**本地时钟窗口。
268
- 全量 **541/541**(85 个测试文件)。
269
-
270
- ## [1.6.6] — 2026-11-16
271
-
272
- **发布修正版:1.6.5 在 npm 上发布的是「每轮请求都裁剪工具结果」的版本——那个把上下文
273
- 从 10% 悄悄缩到 7% 的缺陷没有随任何已发布制品走出去。1.6.6 补上这条修复。**
274
-
275
- > **发布实况(事后核对)**:1.6.6 的 npm 制品 `gitHead 99a07cb` 来自旧 checkout,
276
- > **只含**下面的 Live Compact 修复——M3 与 M5 当时已在主线上、但没有进这个 tarball。
277
- > 那两项随 **1.6.7** 发出。本地 `v1.6.6` tag 已指向 `99a07cb`,与 npm/GitHub 一致;
278
- > `99a07cb` 也已并入 `main` 历史,发布可追溯。
279
- > 1.6.5 同理不可覆盖(`gitHead 28776c7`),其 tag 亦指向该提交。
280
-
281
- - **Fixed — 上下文在每轮请求里被悄悄缩水("从 10% 直接掉到 7%")**。
282
- `guardRequest` 曾在**每一次** `agent/request` 上调用宿主的 `toolResultPruner.pruneSession()`。
283
- 宿主的 `pruneContent()` 用的是**预设预算**(ptc 预设 `thresholdChars: 8192` → 4k 头 + 1k 尾),
284
- 而且它**只在 `compaction-basic` 的 `context-overflow` 分支里**才被调用——我们把「溢出时裁剪」
285
- 变成了「每轮都裁剪」,一次 pass 就能掉约 80k tokens。
286
- 现在 Live Compact **只跑本插件自己的保守策略**(`context.liveCompact`,默认 200,000 字符阈值 /
287
- 4,000 头 / 2,000 尾 / 每请求最多 4 个节点),不再委托宿主 pruner;
288
- 回归用例 `the guard never rewrites an ordinary tool result on a healthy request`
289
- 断言宿主 pruner 在健康请求上**一次都不被调用**。
290
- - **Tests**:`test/v164.windowGuard.test.js` 增加上述回归用例(12 例)。全量 **503/503**(79 个测试文件)。
291
-
292
- ## [1.6.5] — 2026-11-15
293
-
294
- **回归微内核:引擎只负责存储、检索与蒸馏,绝不驱动对话;蒸馏只有一个总调度器;
295
- 面板的全部能力收进 `/memory` 指令集,且不花一分模型 Token。**
296
-
297
- - **Added — `/memory` 指令集(0 Token)**。四条子命令通过宿主的 `commands` 服务注册,
298
- `commands.execute()` 的语义是「parse and execute a known command **without sending it
299
- to the model**」,因此不产生任何模型请求(测试用 `fetch` 计数断言为 0):
300
- - `/memory resume`:拉取上一次交接摘要并**强制重新注入**当前上下文。它绕过「每会话
301
- 每交接批次只注入一次」的去重(`armColdStartNow()` 先删掉该 `session|epoch` 的投递
302
- 记录再布防),所以用户可以随时把摘要拉回来;没有交接时明确回「没有可恢复的交接摘要」。
303
- - `/memory maintain`:立即触发一次后台维护(索引重建 / 月记 / L2 合并 / Dream / 冷归档),
304
- 回报各阶段计数;已在运行时直接拒绝而不是排队。
305
- - `/memory status`:事件数、L3 摘要数、活跃标签列表、会话 token 与窗口来源
306
- (`host`/`config`/`default`)、静默状态、冷启动队列长度。
307
- 这些数字全部取自面板同一份契约(`panel.global.*` + 索引快照的活跃集合),
308
- 不再各自拼字段——早期实现读错了契约,导致整行显示成 `?`。
309
- - `/memory mute` / `/memory unmute`:紧急静默 `[Memory Hints]`。静音时**不消费标签**,
310
- 所以解除后提示会原样回来,而不是被会话级去重池吃掉。
311
- - **Fixed — 月记与 Dream 重复咀嚼同一批日记**。L2.5 月记原本挂在 `maintain()` 上,与
312
- Dream 各走各的调度,同一条 L2 日记可能先被压进月记、再被按标签蒸馏一次。
313
- 现在 **`executeDream()` 是唯一的蒸馏总调度器**:先跑月记(只处理已结束的自然月),
314
- 再让 Dream 处理剩下的材料。被月记吸收的事件 id 记入 `state/months.json` 的
315
- `promoted` 映射(即 `promoted_to_monthly`),`DreamEngine.collectGroups()` 直接跳过,
316
- 并在报告里给出 `skippedPromoted` 计数。
317
- **为什么不写进事件本身**:raw 日志是 append-only 的唯一真相源,永不改写;标记放在
318
- 派生状态里,语义等价且可重建。
319
- - **Added — 原子服务接口 `getLatestHandoffSummary()`**。`ctx.get('hippocampus')
320
- .getLatestHandoffSummary()` 返回 `{ active, state, at, sessionId, summaryEventId,
321
- agentPreset, tailTurns, text, found }`,纯读:不装配 prompt、不消费 marker、不产生副作用。
322
- 外部路由插件想自己决定「什么时候续上、怎么展示」时用它,而不是去解析提示词。
323
- - **Changed — 微内核边界**。引擎半侧(`index.js` + `src/**`)不含任何宿主 UI 或追加模式
324
- 监听:`autoNewSession` 整链已在 1.6.3 删除,本次用测试把这条边界**锁死**——源码扫描
325
- 禁止出现 `uiWorkspace` / `startSession(` / `sessionStorage` / `appendMode` /
326
- `onSlot(` / `slots.register(` / `ctx.slots =`。会话控制交给外部路由插件。
327
- - **Fixed — 上下文在每轮请求里被悄悄缩水(“从 10% 直接掉到 7%”)**。1.6.4 的
328
- `guardRequest` 在**每一次** `agent/request` 上都把宿主 `toolResultPruner.pruneSession()`
329
- 委托执行了一遍。两处都错:
330
- - 宿主用的预算是 **预设自己的**(ptc: `thresholdChars 8192` → 留 4k 头 + 1k 尾),
331
- 于是一次普通的 20 KB 文件读取在下一次请求就被腰斩;
332
- - 宿主自己只在 compaction-basic 的 `context-overflow` 分支里调它
333
- (`this.ctx.get('toolResultPruner')?.pruneSession(agent.session)`),
334
- 「溢出时裁剪」被我们变成了「每一轮都裁剪」。实测一次 pass 可掉 **~80k tokens**。
335
- 现在 Live Compact **只跑我们自己的保守裁剪**:单条 `tool/result` 超过
336
- `context.liveCompact.thresholdChars`(默认 200,000 字符)才指针化,头部 4k / 尾部 2k
337
- 原样保留、中间换成 `deep_raw` 可取回的指针行。健康的对话**永远不会被改写**——
338
- 宿主压缩链路的裁剪仍由宿主在真溢出时负责。
339
- 新增回归用例锁定:请求里即使注入了假 `toolResultPruner`,`pruneSession` 的调用次数也必须为 0,
340
- 且一条 20k 字符的正常结果不产生任何 surface 改写。
341
- - **Tests**:新增 `test/v165.micokernel.test.js`(8 例):`/memory` 注册与全部子命令返回
342
- 纯文本、**网络调用数为 0**、静默真的不注入提示、`resume` 在无交接时明确报错且服务接口
343
- 与它同源、`executeDream()` 先跑月记并把日记标进 `promoted`、`maintain()` 不再产出月记、
344
- 已晋升日记在下一轮仍被排除、以及上面那条「无 UI/追加模式监听」的源码扫描。
345
- `test/flow.test.js` 与 `test/v156.federation.test.js` 的月记断言随调度器迁移改为
346
- `executeDream()`。全量 **502/502**(80 个测试文件)。
347
-
348
- > **发布说明**:1.6.5 发布到 npm 的制品(`gitHead 28776c7`)**不包含**上面那条 Live Compact
349
- > 修复——它是在 1.6.5 发布之后才提交的。该修复进入 **1.6.6**;M3 与 M5 实际进入 **1.6.7**
350
- > (1.6.6 的制品同样来自旧 checkout,只含 Live Compact)。
351
-
352
- ## [1.6.4] — 2026-11-14
353
-
354
- **修复 1M 上下文溢出(`CONTEXT_WINDOW_EXCEEDED`):交接判定的分母、分子与状态机三处
355
- 同时失效,外加单轮超大工具输出没有任何熔断。这是一次独立的安全发版——1.6.3 从未
356
- 发布过,它的全部内容已并入本版。**
357
-
358
- - **Fixed — 分母错源:接入宿主真实模型窗口**。新增 `src/context/windowGuard.js` 的
359
- `resolveWindow()`:**宿主适配器上报的窗口优先**(`llm.resolveModelInfo().context.contextWindow`,
360
- 也接受 `tokenMeter.contextPressure().contextWindow`),`context.nativeTokenLimit` 降级为
361
- 用户覆盖,只在宿主不可用时兜底。`panel.session.windowSource` 暴露本次用的是
362
- `host` / `config` / `default`,事后可审计。此前本机 profile 写的 `8000` 被当成模型窗口,
363
- 模型真实窗口是 **1,048,576**。
364
- - **Fixed — 分子不再靠猜:`used + reserved` 公式**。判定改为
365
- `used_tokens + reserved_completion_tokens >= window × threshold`。
366
- 已用优先取宿主 `tokenMeter` 的测量值(含系统提示、工具 schema、历史重放),
367
- `Math.ceil(字符数 ÷ 4)` 的自估降为下限;`reserved` 取本次请求真实的 `maxTokens`
368
- (默认 256,000)。事故数字 854,668 + 256,000 = 1,110,668 > 1,048,576 现在能直接判出来。
369
- - **Fixed — Fail-Fast 兜底**。新增 `agent/request` 中间件:拿到最终请求配置后重新判定,
370
- **必定放不进窗口的请求在本地就被拦下**,抛 `MEM_E_CONTEXT_EXCEEDED`,details 里带
371
- `usedTokens / reservedTokens / projectedTokens / window / windowSource / ratio`,
372
- 并明确写出 “Nothing was sent to the provider”。宿主缺少 `llm` / `tokenMeter` 服务时
373
- **绝不阻断**(降级为原有行为)。
374
- - **Fixed — 交接状态机死锁(“80% 了却不交接”)**。`checkHandoff()` 里
375
- `if (marker.active) return base;` 会让首次交接后的同一会话**永远**不再交接
376
- (1.6.3 移除自动开新会话后,session id 不再变化,marker 就永久 active)。
377
- 改为 `rehandoffDecision()`:同会话压力再涨 ≥5 个百分点(`pressure-growth`)或投影
378
- ≥95% 硬上限(`near-hard-limit`)时清掉旧 marker 重新蒸馏;不同会话仍走原有消费路径。
379
- - **Added — Live Compact:单轮超大工具输出熔断**。新增 `src/context/liveCompact.js`:
380
- 单个 `tool/result` 的文本超过 `context.liveCompact.thresholdChars`(默认 200,000 字符)时,
381
- 保留头 4,000 / 尾 2,000 字符,中间压成一行指针
382
- (`[[hippocampus:live-compact: removed N chars … (seq=…, call=…, tool=…)]`),
383
- 原文仍可用 `deep_raw` 取回。走宿主 surface 协议
384
- (`append('compaction/prune')` + `append('tool/result', { surfaceOp: { op: 'replace' } })`),
385
- 宿主自带 `toolResultPruner` 时优先委托给它。指针化按 code point 切,不会劈开代理对。
386
- - **Tests**:新增 `test/v164.windowGuard.test.js`(11 例)锁定本次修复:宿主窗口优先于配置覆盖、
387
- 引擎 `windowSource` 可审计、`used + reserved` 判定(含那组真实数字 854,668 + 256,000)、
388
- `nativeState` 优先采用宿主测量值、`rehandoffDecision` 的四种判定、
389
- 超大工具结果的指针化(含代理对不被劈开、`surfaceOp replace` 的实际形状)、
390
- 同会话内 marker 仍 active 时 `checkHandoff` 会续交、以及
391
- `guardRequest` 在「必超限」时抛 `MEM_E_CONTEXT_EXCEEDED` / 在「放得下」时放行 /
392
- 在没有宿主服务时绝不阻断(降级为原有行为)。
393
- 全量 **494/494**(79 个测试文件)。
394
-
395
- ## [1.6.3] — 2026-11-13
396
-
397
- **配置加载器加固:把 1.6.2 的“旧配置启动阻断”事故固化为引擎能力——先迁移、再严格校验、
398
- 必要时安全降级,绝不让 DSH 客户端卡在“正在启动…”。**
399
-
400
- - **Added — 冷启动注入可观测性**:`/stats` 新增 `coldStart{ pending[], injected, lastSessionId }`,
401
- `panel.startup` / `panel.configVersion` / `panel.configWarnings` 与
402
- `CAPABILITIES.startup` 同源(此前 `toMemoryOptions()` 没把迁移结果传给引擎,panel 报
403
- `migrated:false` 而 capabilities 报 `true`)。
404
- - **Fixed — 复习队列只报不消费(积压到 337 条)**:`maintain()` 现在按
405
- `review.consumeBatchSize`(默认 40,上限 200/轮)分批消费到期行,批间
406
- `await setImmediate` 让出主线程;每批一次 `reviews.advanceMany()` 落盘(不是每条一次写),
407
- 并对该批做一次 `reinforce` 权重强化。`review.autoConsume` 可整体关闭。
408
- - **Fixed — 1.6.2 遗留的两个启动/保留缺陷**:旧 profile(`retentionDays: 30` 且没有
409
- `archiveAfterDays`)由 `migrateConfig` 派生 `29` 而不是启动失败;`prune()` 现在也会按
410
- 月清理过期的 `.jsonl.br/.zst/.gz` 冷归档(此前只删明文,归档变相突破保留期)。
411
-
412
- - **Added — 配置 schema 版本与迁移机制**:`src/config.js` 新增
413
- `CONFIG_SCHEMA_VERSION = 3`;配置对象可携带 `configVersion`。加载顺序变为
414
- **`migrateConfig()` → 严格校验**:迁移阶段只做“补值 + 告警”,从不抛错,也绝不覆盖
415
- 用户显式写下的值。缺少 `configVersion` 的旧配置被视为 legacy(`fromVersion: 0`)并
416
- 升级到当前版本。
417
- - 首次落地的迁移规则:`raw.archiveAfterDays` 缺失且
418
- `raw.retentionDays <= 新默认值(90)` 时,派生为 `Math.max(1, retentionDays - 1)`
419
- (即 30 → 29),从而满足 `archiveAfterDays < retentionDays` 的硬约束。
420
- - 每条迁移都写入 `console.warn`(前缀 `hippocampus/config-migration:`)并携带在
421
- `config.warnings` 里,`apply()` 再经 `ctx.logger.warn` 输出一次——**迁移永不被静默**。
422
- - 空配置 `{}` 视为“使用默认值”,不算 legacy,因此内部调用不会产生噪声告警。
423
- - **Added — `strictStartup`(默认 `true`)启动安全网**:显式设为 `false` 时,若严格校验
424
- 抛出 `MEM_E_CONFIG_OUT_OF_RANGE`,引擎会丢弃该越界键、回退到安全值并继续启动,同时
425
- 置 `config.startup.degraded = true`、记录 `degradedReason{code,key,message}`、
426
- 输出 `hippocampus/config-degraded:` 警告,并在 `apply()` 里额外 warn
427
- `STARTED DEGRADED (strictStartup=false)`。
428
- - 降级**只**覆盖越界值:`MEM_E_CONFIG_INVALID_TYPE` / `MEM_E_CONFIG_UNKNOWN_KEY`
429
- 仍然 fail-fast(拼写错误不该被宽容)。
430
- - `strictStartup` 自身必须是布尔值。
431
- - **Added — 启动状态进入可观测面**:`CAPABILITIES.startup` / `CAPABILITIES.configVersion`
432
- 与 `memory_admin action=status` 的 `panel.startup` / `panel.configVersion` /
433
- `panel.configWarnings`。设置页与运维方可以直接看到“这份配置来自哪个 schema 版本、
434
- 是否迁移过、是否降级启动”。
435
- - **Added — 设置页「简洁模式」(纯显示层)**:设置页顶部新增“简洁模式 / 专业模式”切换。
436
- 简洁模式只渲染四块——**身份、上下文窗口、系统级存储位置迁移、原始回合留存(raw)**;
437
- raw 卡内再收敛为三项(`raw.mode`、`raw.maxTotalMb`、`raw.compressionEngine`),
438
- 最小显著度 / 保留期 / 冷压缩阈值 / deep_raw 扫描上限全部隐藏。
439
- - 隐藏是**纯 UI 行为,不碰配置值**:保存时 patch 被过滤为
440
- `SIMPLE_PATCH_KEYS`(9 个可见键),文件里未显示的项保持原值;新装即默认值,
441
- 专业模式下调过的不会被简洁模式覆盖。
442
- - 校验同步收敛:只检查可见数字键,隐藏项的越界值不会阻断保存,Cron 非空检查也跳过。
443
- - 模式偏好存浏览器 `localStorage`(键 `hippocampus:settings-mode`),不进插件配置、
444
- 不影响引擎行为;读写失败一律退回专业模式。
445
- - **Removed — 交接时“自动开启新会话”(`context.autoNewSession*`)**:交接就发生在对话
446
- 中间,宿主会在标记后**继续同一个对话**;客户端再调 `uiWorkspace.startSession()` 只会
447
- 额外弹出一个空对话,在“追加到原对话”的用法下毫无意义还打断体验。因此彻底移除:
448
- - 配置层:`autoNewSession` / `autoNewSessionPoll` / `autoNewSessionIntervalSeconds`
449
- 三个键从 `DEFAULT_CONFIG`、校验、resolved 与 HTTP 可编辑白名单中删除。
450
- - `migrateConfig` 会**静默剥离**旧 profile 残留的这三个键并 warn(否则老用户会撞上
451
- 未知键阻断启动)。
452
- - 可观测面:`CAPABILITIES.autoNewSession` 与 `handoffView().autoNewSession` 删除。
453
- - 客户端:三个设置控件、`startAutoNewSession()` 轮询器与其 `ctx.effect` 注册全部删除;
454
- 设置页不再渲染任何“自动开新会话”开关。
455
- - **Fixed — 新对话拿不到交接摘要与前几轮原话**(2026-11-13 用户报告):
456
- - 根因:冷启动注入是一个**进程级一次性布尔** `coldStartPending`,被**第一个组装
457
- prompt 的 agent** 抢先消费(子代理、标题生成等),用户真正的新对话拿到的是空。
458
- - 改为**按会话幂等**:`runtime.coldStart = { pending: Map, injected: Set, lastSessionId }`,
459
- 以 `session|handoffEpoch` 为键;`noteColdStart()` 在「新 session id 的首个
460
- `session/event`」与「`agent/created`」两处布防(同键复用、已被注入过的直接跳过、
461
- 过期 5 分钟未消费自动丢弃、最多 8 条 pending 有界淘汰),
462
- `promptState(assemblyContext)` 用宿主传给 `systemPrompt.context` 的
463
- `assemblyContext.agent.id` 与当前 session id 做匹配,注入后写入 `injected` 集合并
464
- 有界淘汰(64)。**兄弟 agent 先装配不会再吞掉用户的注入**——这是单槽位实现仍会
465
- 踩的坑:标题生成器或子代理随后布防会覆盖并且消费掉用户的那一条。
466
- - `handoff.json` 标记新增 `tailTurns`:交接蒸馏时把最后 5 轮(role + 文本,每条
467
- ≤400 字,内存环形缓冲 12 条、跨会话自动清空)写进标记;
468
- `[Previous Context Tail]` 优先回放这些**原话**(`- user: …` / `- assistant: …`),
469
- 没有 tailTurns 时才回退到最近业务事件。
470
- - `context.coldStartInjectRecentTurns` 默认由 `false` 改为 **`true`**:只给摘要会让
471
- 新对话接不上具体语境。
472
- - 即使两个开关全关,匹配到的 pending 也会被消费掉,不会遗留到下一次无关会话。
473
- - **可观测**:`/stats` 新增 `coldStart{ pending[], injected, lastSessionId }`(`runtime.coldStartView()`),
474
- 运维方不必读 prompt 就能区分“已布防未装配”与“已注入”。
475
- - **`panel.startup` / `panel.configVersion` / `panel.configWarnings` 与 `capabilities.startup`
476
- 对齐**:此前 `toMemoryOptions()` 没有把迁移结果传给引擎,panel 报的是“未迁移”默认值,
477
- 而 capabilities 报的是真相——同一个进程两处说法不一致,现由 `toMemoryOptions` 一并透传。
478
- - **Fixed — 复习队列只报不消费(积压到 337 条)**:`maintain()` 里
479
- `ReviewSchedule.tick()` 的结果只被写进报告,**从来没有人推进它**,于是新装用户的
480
- `state/reviews.json` 里每条都是 `lastAt: null`、`dueAt` 停在初始间隔,队列只增不减
481
- (现场:`total 346 / due 337`)。两个后果:复习面板永远是“全到期”,且 recall 拿不到
482
- 强化锚点——衰减曲线相当于“写下之后从未被碰过”。
483
- - 现在 `maintain()` 会真正消费到期行:`_consumeDueReviews()` 取出到期 id,
484
- **分批**(默认 30–50 条,`review.consumeBatchSize = 40`)调用批量 `reinforce()`
485
- (权重 1,日志即锚点,不改任何字段),再用 `ReviewSchedule.advanceMany()` 一次性
486
- 推进 `lastAt` / `step` / `dueAt`。
487
- - **性能防线**:每批之间 `await new Promise(setImmediate)` 让出事件循环,HTTP 路由与
488
- prompt 组装不会被一个巨大积压卡住;单次维护总量上限 `review.consumeMaxPerRun = 200`,
489
- 再多就跨多次维护轮次排空(报告里的 `remaining` 说明还剩多少)。
490
- - **一次文件写/批**:新增的 `advanceMany()` 把“逐条 advance = 每条一次读+一次原子写”
491
- 变成“整批一次”,337 条积压不再是 337 次 fsync。
492
- - 开关:`review.autoConsume`(默认 `true`)可关;`review.enabled: false` 时不会消费。
493
- 失败的批次不中断维护(`lastAt` 保持 null,下一轮自然重试),错误写进
494
- `report.reviewConsumeError`。三条新键均进入 HTTP 可编辑白名单。
495
- - **Fixed — 1.6.2 遗留的两个启动/保留缺陷(随 1.6.3 一并锁定)**:
496
- - **旧 profile 启动阻断**:旧配置只写 `raw.retentionDays: 30`、没有 `archiveAfterDays`,
497
- 而 1.6.2 的新默认值是 90,硬校验 `archiveAfterDays < retentionDays` 直接抛错,
498
- `apply()` 失败 → 插件整体不注册 → `/api/hippocampus/*` 全部 404,设置页永远停在
499
- “正在启动…”。现在 `migrateConfig()` 在**未显式配置**且冲突时自适应派生
500
- `Math.max(1, retentionDays - 1)`(30 → 29)并告警;**显式**写下越界值仍然 fail-fast。
501
- - **`.jsonl.br` 冷归档永不清理**:`prune()` 原先只删明文分片,Brotli/Gzip/Zstd 归档
502
- 变成“保留期之外的永久副本”,等于变相突破 `retentionDays`。现在 `prune()` 按
503
- `cutoffMonth` 整月删除过期归档,并同步从 `state/raw-archive.json` 抹掉记录
504
- (返回 `removedArchives`)。
505
- - **Tests**:`test/v163.migration.test.js`(9 例)锁定本次教训——旧配置(仅
506
- `retentionDays: 30`)可启动且 `archiveAfterDays` 派生为 29;显式冲突在
507
- `strictStartup: true` 下阻断、在 `false` 下降级启动;降级不吞类型错误与未知键;
508
- 以及 1.6.2 生产 profile 的原始形状可被完整解析。`test/helpers.js` 的夹具改走同一
509
- 迁移步骤,`test/status.test.js` 的 panel 形状契约同步新增三个字段。
510
- `test/v163.ui.test.js`(5 例)锁定简洁模式契约:`Section` 的 `hidden` 短路、
511
- 14 个专业模式卡片全部带 `hidden: simpleMode`、raw 只剩三项、保存与校验按白名单收敛。
512
- `test/v163.reviewQueue.test.js`(5 例)锁定复习消费契约:到期行被消费且 `step`/`lastAt`
513
- 前进、强化记录数 == 消费数、超出单轮预算的积压跨轮次排空、`autoConsume:false` 不动队列、
514
- 整批只写一次 `reviews.json`。
515
- `test/v156.autoSession.test.js` 重写为「该功能已移除」契约(配置无该键、旧 profile
516
- 迁移剥离、路由/能力面不暴露、客户端无轮询器);
517
- `test/v160.coldStart.test.js` 重写为按会话注入契约(无标记不布防、摘要+尾部各一次、
518
- 兄弟 agent 先装配不吞注入、两个会话各注入一次、**两条 pending 先布防后装配也各得其份**、
519
- 双关不遗留 pending、tailTurns 优先、stats 暴露 coldStart 状态)。
520
- 全量 **483/483**(78 个测试文件)。
521
-
522
- ## [1.6.2] — 2026-11-11
523
-
524
- **补丁版:修复冷数据归档与保留期的时间冲突,并把“打破日志线性增长”的三层机制并入正式记录。**
525
-
526
- - **Fixed — 设置页卡在“正在启动…”并报 `MEM_E_NETWORK: HTTP 404`**(2026-11-13):
527
- 1.6.2 的强校验 `archiveAfterDays < retentionDays` 与**旧 profile**(`raw.retentionDays: 30`、
528
- 从未写过 `archiveAfterDays`)冲突,`apply()` 抛 `MEM_E_CONFIG_OUT_OF_RANGE`,插件根本没加载,
529
- 所有 `/api/hippocampus/*` 路由缺失 → UI 永远 404。现在:
530
- - `archiveAfterDays` **未被显式配置**时按 `retentionDays - 1` 派生,并置
531
- `raw.archiveAfterDaysDerived: true`(旧 profile 可直接启动);
532
- - **显式**给出越界的 `archiveAfterDays` 仍然 fail-fast(配置错误不该被静默原谅)。
533
- - **Fixed — 归档文件不受 retention 约束**:`prune()` 原来只删 `.jsonl` 明文分片,`.jsonl.br`
534
- 归档会永久堆积,等于变相突破保留期。现在整月归档的末日晚于 cutoff 才保留,否则连
535
- `state/raw-archive.json` 记录一起删除,返回 `removedArchives`。
536
-
537
- - **修复冷数据归档时间冲突**:冷归档阈值与 TTL 保留期原本互相挤压(`archiveAfterDays` 与
538
- `retentionDays` 同为 30/90 量级,冷分片常在归档前就被 TTL 删除)。现在默认值上调为
539
- `archiveAfterDays: 90`、`retentionDays: 365`,并保留 fail-fast 校验
540
- (`archiveAfterDays` 必须严格小于 `retentionDays`),同时新增 `raw.coldAccessWindowDays: 90`,
541
- 也就是“近 90 天零访问”才允许归档。
542
- - **实施多档保留策略(含遗忘性保存与全保存)**:raw 层保留谱系落地为
543
- `raw.mode: off | salience | all` ——
544
- `off` 为不保存(遗忘性保存,仅保留 L1 之上的记忆)、`salience` 为默认的高价值保存、
545
- `all` 为全保存(受 `maxTurnKb` / `maxBytesPerDay` / `maxTotalMb` 预算约束);
546
- 另加 `raw.distillPrune`(默认 false):蒸馏产物覆盖第 i 天、且该分片已出
547
- `raw.hotWindowDays` 热窗时,允许物理清理 raw 原文,**必经 Tombstone 防复活**。
548
- L2 继续走同类项合并(`l2Merge`),L3 增加硬熔断 `semantic.maxEntries`(默认 100)+ LRU 淘汰,
549
- 语义层随“事件重要性”而非“对话条数”增长。
550
- - **优化长窗口压缩与高频引用去重**:
551
- - 冷归档默认改用 **Brotli quality 11**(`.jsonl.br`,极限压缩),`gzip`(9) / `zstd` 仍可选,
552
- 全部来自 Node 内置 `node:zlib`,零外部依赖;读取按扩展名流式解压、命中即停。
553
- - 高频重复的超长内容(工具 schema / 系统提示块,≥512 字符且出现 ≥2 次)在建索引时
554
- 只存一份到 `templates.json`,事件侧改为 `contentRef` 引用(`src/index/templates.js`),
555
- 索引加载时还原原文;**日志本体不参与替换**,raw 逐行真相、`deep_raw` 与行级游标不受影响。
556
- - 稀疏行索引(每 64 行采样)继续用于跳过时间窗不重叠的分片并复用 `lineCount`。
557
-
558
- ### 1.6.2 详细变更
559
-
560
- - **Breaking the linear log curve — three layers** (`test/v162.nonlinear.test.js`, 9 cases):
561
- - **Compression layer**: cold classification is now MULTI-dimensional (age >
562
- `raw.archiveAfterDays` **AND** zero access for `raw.coldAccessWindowDays` **AND** no
563
- `pinned` / `status:handoff` / hot-tag record). Defaults move to
564
- `archiveAfterDays=90`, `coldAccessWindowDays=90`, `retentionDays=365`. Cold
565
- archives default to **Brotli quality 11** (`.jsonl.br`, "极限压缩") instead of
566
- gzip; `gzip`/`zstd` stay selectable and all three are Node built-ins.
567
- Recently-read old shards stay PLAINTEXT for O(1) cursor scans.
568
- - **Encoding layer (referential dedup, NOT columnar)**: repeated long content
569
- (tool schemas / system prompt blocks, ≥512 chars, ≥2 occurrences) is stored ONCE
570
- in `templates.json` at the INDEX layer; events carry `contentRef` instead of a
571
- duplicate copy. Index loads resolve refs, so readers always see exact content —
572
- the log itself is untouched (`src/index/templates.js`).
573
- - **Semantic layer**: raw stops being the only home of truth. `raw.distillPrune`
574
- (opt-in) lets `maintain()` physically clean raw shards that are outside
575
- `raw.hotWindowDays` **and** already covered by an L3 summary — always through the
576
- tombstone path, so nothing resurrects. L3 gains a hard capacity breaker
577
- (`semantic.maxEntries`, default 100) with LRU retirement recorded as append-only
578
- `semantic_retire` events.
579
-
580
- ## [1.6.1] — 2026-11-07
581
-
582
- **Version fully un-frozen (user directive 2026-11-07): normal semantic versioning
583
- resumes; 1.6.1 was the release that followed 1.6.0.**
584
-
585
- - **Archive month detail UI**: the panel's raw section now shows `indexedShards` /
586
- `archiveCount` StatCards plus a **collapsible month table** (月份 / 引擎 / 归档大小 /
587
- 归档时间, month-DESC, collapsed by default). `panel.raw` carries `archivedBytes`,
588
- `totalBytes`, `engines:{gzip,zstd}`, `savedBytes`, `compressionRatio` (null when
589
- unmeasured) and `archiveMonths[]` with `at`/`bytesBefore`/`bytesAfter`; older hosts
590
- degrade to “—” instead of breaking the panel.
591
- - **Segment-token audit** (`docs/AUDIT-2026-11-07-segment-token.md`): no P0
592
- same-segment re-injection exists; the six injection surfaces are documented with
593
- their dedup mechanisms. Its two P3 items are now IMPLEMENTED:
594
- - **P3-1** the `[Active Task]` event id also joins the block dedup pool, so one
595
- event can never be injected both as Active Task and as a recall block;
596
- - **P3-2** `[Persona & Traits]` is memoized by the L3 shape (`summaryId` +
597
- `updatedAt` + count); unchanged L3 costs one signature, not a re-render.
598
- - **Raw cold-tier archiving (zero external deps)**: on `maintain()`, daily shards
599
- older than `raw.archiveAfterDays` (default **7**) are merged per calendar month
600
- into one `raw-archive-YYYY-MM.jsonl.gz` via Node's built-in `zlib`, then the
601
- plaintext shard is removed. Archiving runs at most once per month and SKIPS any
602
- shard that is recently read (`state/raw-access.json`), `pinned`,
603
- `status:handoff`, or carries a hot active-set tag. `deep_raw` and hash restore
604
- stream the archive with `createGunzip()` line-by-line (no full read), report
605
- `archiveErrors`/`notes: archive-corrupt:<name>` for a corrupt archive, and keep
606
- plaintext `.jsonl` reads unchanged. `raw.retentionDays` default moves **30 → 90**
607
- and must stay strictly above `archiveAfterDays` (fail-fast otherwise).
608
- - **`/stats` panel: archive + index visualization**: `panel.raw` now reports
609
- `archiveCount`, `archivedBytes`, `totalBytes`, `archiveMonths`, `engines`
610
- (`{gzip,zstd}`), `savedBytes` (sum of bytesBefore−bytesAfter), `compressionRatio`
611
- (null when no measured archive) and `indexedShards`. Each archive records
612
- `bytesBefore`/`bytesAfter` in `state/raw-archive.json`, so the ratio and saved
613
- bytes are real measurements, not estimates. The panel gains two StatCards
614
- (“raw 索引覆盖”, “raw 冷归档”) with graceful “—” for an older host, plus a
615
- collapsible **archive month table** (月份 / 引擎 / 归档大小 / 归档时间, month-DESC,
616
- collapsed by default); `archiveMonths` rows carry `at`/`bytesBefore`/`bytesAfter`.
617
- 4 cases in `test/v161.stats.test.js` + 2 UI contract cases.
618
- - **Sparse line index for raw shards** (performance audit item C): one
619
- `<day>.jsonl.idx.json` per shard, sampled every 64 lines with
620
- `{line, offset, timestamp}` plus `bytes/mtimeMs/lineCount/minTs/maxTs/sorted`.
621
- `deep_raw` uses it to SKIP a shard whose time range cannot overlap the window
622
- (without opening the file) and to reuse `lineCount` for absolute `hit.line`
623
- numbers (no second pass). Built offline by `maintain()` (50 shards/round,
624
- progressive), deleted with its shard by `prune()`, and silently bypassed when
625
- missing, stale (bytes/mtime mismatch), corrupt, or non-monotonic. `stats()`
626
- reports `indexedShards`. 6 cases in `test/v161.rawIndex.test.js`.
627
- - **Compression-engine selection (zero install)**: `raw.compressionEngine`
628
- (`gzip` default | `zstd`) + a settings-page engine picker with an
629
- enable/disable button. Zstd uses Node's BUILT-IN `node:zlib` zstd — nothing is
630
- downloaded and there is no package to uninstall; "停用" switches back to gzip.
631
- Archives are `raw-archive-YYYY-MM.jsonl.gz` / `.jsonl.zst`, dispatch is by
632
- extension, and a legacy gzip archive stays readable after switching to zstd.
633
- When the runtime lacks zstd the config silently falls back to gzip and
634
- `capabilities.compression` reports `{engine, fallback, zstd, node}` for the UI.
635
- - **Raw retention tiers documented**: the raw layer exposes exactly three modes —
636
- `off` (keep nothing), `salience` (default: high-value turns/code/stack/errors only),
637
- `all` (bounded by `maxTurnKb`/`maxBytesPerDay`/`maxTotalMb`) — plus
638
- `retentionDays` (default 90) and `pinned` never pruned. README/ARCHITECTURE now
639
- describe these implemented tiers only.
640
- - **Fixed — settings page rendered blank**: the compression-engine card referenced a
641
- bare `payload` that only exists in other components' scopes; it now uses the local
642
- `statsPayload` and the shared `Select` component (not a fake `type:'select'` on
643
- `Field`). `test/v161.ui.test.js` pins the scope rule so the whole settings page
644
- cannot be taken down by one card again.
645
-
646
- - **Recall bound-based early exit** (performance audit item A): every score is
647
- `salience × decay × tagAffinity(≤3) × lexicalBoost(≤1) × association(≤1) ×
648
- timeBoost(≤1.3) × handoff(≤1)`, so `salience × 3.9` is a hard upper bound.
649
- Candidates are visited salience-DESC and scoring stops as soon as that bound
650
- cannot beat the current k-th score. `pinned` hits bypass the cut, the best-k
651
- window keeps the bound exact (ties still visited), and the result reports
652
- `pruned` + `notes: pruned:<n>`. Complexity unchanged in the worst case
653
- (`O(K log K)` ordering) but the per-candidate decay/similarity work is skipped
654
- for the long low-salience tail.
655
- - Regression: pinned decay stays exactly 1 (bypass path), monthly memos unchanged.
656
- - **456 tests green** (64 files).
657
-
658
- ## [1.6.0] — 2026-11-06
659
-
660
- > Version note: 1.6.0 was the FIRST release after the temporary 1.5.7 freeze; the
661
- > 2026-11-07 directive removed all freeze language and resumed normal versioning.
662
- Cold-start wake-up + user-controlled cold-start injection:
663
-
664
- - **Anti-"customer service" wake-up** (static `memory:policy` prefix): the model is
665
- told it has continuous long-term memory, must not open with "how may I help you",
666
- and should recall the recent topic before replying.
667
- - **`context.coldStartInjectSummary`** (default **true**): on the first prompt
668
- assembly of a brand-new conversation, inject `[Cold-Start Summary]` — the handoff
669
- summary event when present, else the top-3 L3 semantic summaries (≤800 chars).
670
- - **`context.coldStartInjectRecentTurns`** (default **false**): inject
671
- `[Previous Context Tail]` with the last ≤5 business episodes (200 chars each).
672
- - **`[Cold-Start Detected: Active Space=…, Recent Topic=…]`** header when either
673
- switch is on; the block is volatile-tail only (prompt-cache prefix untouched) and
674
- is consumed exactly once per new conversation.
675
- - Both switches off → no historical blocks; the static wake-up policy still ships.
676
- - UI: two independent toggles in the settings page's session group; HTTP-editable.
677
- - **416 tests green** (64 files).
678
-
679
- ## [1.5.7] — 2026-11-04
680
-
681
- > Historical note: 1.5.7 shipped under a temporary version freeze; the 2026-11-07
682
- > directive removed ALL freeze language and resumed normal semantic versioning
683
- > (current version: 1.6.2). The sentence below is the historical 1.5.7 statement.
684
-
685
- **Version freeze (historical, superseded): 1.5.7 was the shipped release.**
686
- This release folds in everything added after the 1.5.6 draft — Orchestrator
687
- federation/dedupe wiring, read-time merge, cross-space recall aggregation (opt-in
688
- `features.crossSpaceRecall`), durable Orchestrator state, the settings-page GitHub
689
- installer, the verified automatic new-conversation handoff (with configurable
690
- once/interval detection), low-valley Dream Phase 2, space deletion, graph
691
- interaction, and the rest of the 1.5.6 section below. Annotations of the form
692
- `v1.5.6:` below record the version in which a feature was introduced; they are
693
- history, not the current version. **411 tests green** (64 files).
694
-
695
- ## [1.5.6] — 2026-11-03
696
-
697
- **`deep_raw` now scans by line cursor: a huge day shard is never loaded whole.**
698
- The black box is read newest-first in fixed chunks; peak memory is one chunk plus
699
- one partial line (test-locked), not the file size. `hit.line` keeps its absolute
700
- 1-based semantics. **411 tests green** (was 303).
701
-
702
- ### Changed — raw scan / restore (zero-dependency, O(chunk) memory)
703
-
704
- - **`readLinesReverse(file, {chunkSize, onBuffer})`** (`src/rawStore.js`): reads a
705
- file backwards in 64 KiB chunks, yielding one line at a time; the trailing
706
- newline does not produce a phantom empty line. `onBuffer` reports the live
707
- buffer size for tests.
708
- - **`deep_raw` scan** rewrote the whole-shard `readFileSync + split` path:
709
- newest-first, one `JSON.parse` per line, line bytes counted as they are read,
710
- hit results collected per shard. `hit.line` is computed from the shard's line
711
- count via ONE extra bounded streaming pass, paid only when that shard produced
712
- a hit (so a miss costs no counting pass).
713
- - **`restoreByHash`** streams forward via `readline`; **`_loadTombstones`** streams
714
- synchronously with a `StringDecoder` (multi-byte boundaries preserved);
715
- **`_hashesFor`** streams asynchronously (so `RawStore.capture()` is now async —
716
- only internal callers exist; the public `captureRaw()` contract is unchanged).
717
- - **Engine-side result ceiling**: `MAX_SCAN_RESULTS = 500` caps one scan even if an
718
- embedder passes `limit: 5000`; `budget.maxHits` is reported, `truncated` is true
719
- when the cap is reached.
720
- - **Observability**: `scanned.peakBufferBytes` exposes the largest buffer the
721
- scanner ever held (proves the memory bound).
722
-
723
- ### Added — stability hardening (same 1.5.6, no extra version bump)
724
-
725
- - **Recall response cap**: `context.maxInjectTokens` (default 4000, 256–100 000,
726
- fail-fast) bounds the JSON one recall returns. `Memory.applyPayloadBudget()`
727
- keeps hits in rank order (the first is always kept), then semantic/temp summaries;
728
- a cut is loud: `truncated: true`, `payload: {maxTokens, estimatedTokens, dropped}`
729
- and a `payload-budget` note. Editable over HTTP and rendered in the settings page
730
- with a tooltip.
731
- - **`Memory.close()` releases resources**: `RawStore.close()` clears the flush timer
732
- and synchronously persists queued turns before the log closes; `Memory.close()`
733
- then detaches the scheduler, clears oversized-tag hints and calls
734
- `IndexManager.release()` to drop the A/B views. Idempotent.
735
- - **Event-loop lag monitoring**: `src/eventLoop.js` (`createLagMonitor`) wraps
736
- `perf_hooks.monitorEventLoopDelay`; `maintain()` yields 50ms between phases and
737
- `IndexManager.rebuild` yields between read/build/catch-up/swap once the measured
738
- max delay crosses 100ms. The report carries
739
- `eventLoop: {maxMs, p99Ms, meanMs, yields, thresholdMs}`. Honest boundary: a
740
- synchronous builder cannot be preempted, so the granularity is phase-level and the
741
- numbers expose an oversized phase.
742
-
743
- ### Added — pre-ingest tagging (same 1.5.6, no extra version bump)
744
-
745
- - **`src/tagging.js` / `extractTags()`**: deterministic anchors derived from content
746
- shape — named error types (`error:typeerror`), Node errno codes
747
- (`error:econnrefused`), fenced-code language (`lang:python`), HTTP status
748
- (`http:500`), file path basename (`file:index.js`) and explicit task statements
749
- (`task:…`). No LLM, no dependencies, stable ordering.
750
- - **Write gate** (`Memory.stage`): model-provided tags always win; only an untagged
751
- write runs the heuristic. Tags are deduplicated and capped by `tagging.maxTags`
752
- (1–5, default 2). Inferred anchors are recorded on `meta.auto_tagged` /
753
- `meta.auto_tags` (provenance, not a silent rewrite of what the caller asserted).
754
- - **raw stays pure**: the black box still receives exactly
755
- `{turn_id, timestamp, role, content}` — the test locks the four-field shape.
756
- - **Miss is a warning**: `MEM_E_AUTO_TAG_MISS` goes to the Host log via
757
- `Memory.setWarnHook` (wired in `index.js`) and increments
758
- `panel.autoTag.misses`; the write proceeds untagged.
759
- - **Config**: `tagging.autoTag` (default true) and `tagging.maxTags` (1–5), both
760
- fail-fast, HTTP-editable and rendered in the settings page.
761
-
762
- ### Added — pinned memory (same 1.5.6, no extra version bump)
763
-
764
- - **`remember({ pinned: true })`**: a lesson/experience that must survive time.
765
- It stores `meta.pinned = true` (provenance included in `content_hash`) and is
766
- refused with **`MEM_E_PINNED_TAG_REQUIRED`** unless the caller supplies at least
767
- one tag — an untriggerable lesson would be dead memory.
768
- - **Never decays**: `projectEpisode` exposes `pinned`; `deriveTagTable` gives a
769
- pinned event `decay = 1`, keeps its tag un-archived, and protected from the
770
- `maxPostingsPerTag` drop; `deriveActiveSet` admits pinned tags regardless of
771
- score or the cap.
772
- - **Ranks first**: recall gives every matching pinned record `decay = 1`, exempts
773
- it from `minScore`, and orders pinned hits ahead of all others
774
- (`pinned-first:N` note).
775
- - **Observability**: `panel.global.pinned` counts pinned records.
776
- - Tool surface: `memory_remember.pinned` (boolean) is documented and passed
777
- through; `bulk_ingest` items accept the same field.
778
-
779
- ### Changed — relevance-first prompt hints (same 1.5.6, no extra version bump)
780
-
781
- - **Global "most active tags" map removed from the prompt.** `runtime.promptState()`
782
- now renders only tags that lexically overlap the CURRENT user turn (max 5), via
783
- `src/utils/memoryHints.js` (`selectRelevantTags` / `renderMemoryHints`).
784
- Internal bookkeeping tags (`status:*`, `month:*`, `context:*`, `active_task`)
785
- are never hinted; no match means the section is simply absent (no padding).
786
- - **Cache-safe placement**: `[Memory Hints]` is rendered AFTER `[Memory Blocks]`,
787
- so a per-turn hint never disturbs the cacheable prefix (rules only).
788
- - **Input source**: prompt assembly receives no message text, so the plugin tracks
789
- the last `user/message` from `session/event` (`runtime.lastUserText`); other
790
- surface events never overwrite it.
791
- - The legacy `renderMemoryMap` / `composePrompt({map})` API remains for callers
792
- and is still unit-tested, but the plugin no longer injects the map.
793
-
794
- ### Added — capability flags & microkernel boundary (same 1.5.6, no extra version bump)
795
-
796
- - **`features.multiSpace` (default true)** and **`features.crossSpaceTransfer`**
797
- (default mirrors multiSpace). Both are fail-fast, HTTP-editable and rendered in
798
- the settings page; turning multiSpace off implies crossSpaceTransfer off, and the
799
- explicit contradictory combination is refused.
800
- - **Strict single-space mode**: with multiSpace off, every routed read/write whose
801
- `targetSpaceId` is not `default` answers **`MEM_E_FEATURE_DISABLED`** (before any
802
- I/O); `createSpace` / `ensureSpace` / `warmup` refuse too, and the `/spaces` route
803
- reports `['default']` with `capabilities.spaces=false` so the client hides
804
- create/selector affordances instead of 404-ing.
805
- - **Tools follow the flags**: `space_transfer` / `transfer_to_global` are neither
806
- registered nor advertised in the prompt section when the capability is off.
807
- - **`Memory.open('/abs/dir')`** is now the single-space form (the Orchestrator owns
808
- the multi-space walk); the options-object form stays supported.
809
- - **`Memory.warmup({targetSpaceId?, dataDir?})`**: lazy, read-only index warm-up for
810
- the UI / Orchestrator — no maintenance, no writes; unknown/relative dataDir fails
811
- fast.
812
-
813
- ### Added — host lifecycle: compensating Dream (same 1.5.6, no extra version bump)
814
-
815
- - **`src/hostBridge.js`** subscribes to the Host's process-local events
816
- `agent/created` and `session/created` (the "session start" signals) through a plain
817
- `{on, off}` bus seam, plus `agent/disposed` for teardown.
818
- - **Compensation rule**: on a session start, if no Dream ran for
819
- `dream.compensateAfterHours` (default 24, 1–720, fail-fast) AND the price window
820
- permits, run exactly ONE compensating Dream through the shared
821
- `runtime.runMaintenance('compensate')` gate — never a second concurrent run, never
822
- a queue.
823
- - **Price is injected, never guessed**: `setPriceProbe(fn)` / `DSH_DREAM_PRICE=low|high`.
824
- Unknown price + an LLM-backed Dream ⇒ skip (`price-unknown`); unknown + local-only
825
- Dream ⇒ allowed. A known peak ⇒ skip (`peak`).
826
- - **Observability**: `runtime.hostStatus()` and `/stats`'s top-level `host` report
827
- `sessionStarts / compensations / skipped / lastSkipReason / dreamDue / lowValley`.
828
- - `enableDream:false` disables compensation; `agent/created`/`session/created` do not
829
- otherwise affect memory writes (raw capture remains on `session/event`).
830
-
831
- ### Added — Dream tunables in the settings page (same 1.5.6, no extra version bump)
832
-
833
- - The **safe** Dream subset is now exposed to `/stats` + `/config` and rendered in
834
- the settings page: `useLlm`, `minGroupSize`, `maxGroupsPerRun`, `maxSummaryChars`,
835
- `maxSourceChars`, `maxEventsPerGroup`, `llmTimeoutMs`, `failureThreshold`,
836
- `cooldownMinutes`, `compensateAfterHours` (all fail-fast validated).
837
- - **Credentials stay private**: `dream.llm.{baseUrl,model,apiKey}` is neither exposed
838
- by the routes nor editable over HTTP nor rendered in the form; it comes only from
839
- the profile or `DSH_DREAM_LLM_*` env. A test asserts the key never appears in the
840
- `/stats` payload.
841
-
842
- ### Added — L2 multi-merge (`merged_into`, same 1.5.6, no extra version bump)
843
-
844
- - **`src/l2Merge.js`** condenses duplicate same-tag L2 episodes into ONE durable
845
- record, offline at the end of `maintain()` (after monthly memos; a failure never
846
- fails maintenance).
847
- - **Pinned and ordinary groups are strictly separated** — pinned merges only with
848
- pinned; ordinary only with ordinary. A pinned merge keeps `pinned: true` and
849
- inherits every tag.
850
- - **Text**: earliest/latest time + deduplicated core text (each source capped), the
851
- whole line capped by `l2Merge.maxSummaryChars` (ASCII ellipsis so identity
852
- canonicalisation cannot make it longer).
853
- - **Federated metadata**: `meta.global_tags` is copied into the merged record's
854
- `meta` and **never becomes a tag**, so it cannot enter the sub-space inverted index;
855
- `projectEpisode` exposes it as `event.globalTags` for the merge layer only.
856
- - **Append-only marking**: sources are recorded as merged in
857
- `state/l2-merge.json` (`mergedSourceIds`); the log is untouched and originals stay
858
- recoverable. A second pass merges nothing (idempotent) and `status().panel.l2Merge`
859
- reports the bookkeeping.
860
- - **Config `l2Merge`**: `enabled` (default true), `minGroupSize` (2–20, default 2),
861
- `maxGroupsPerRun` (1–50, default 5), `maxSummaryChars` (100–2000, default 400);
862
- fail-fast, HTTP-editable and rendered in the settings page.
863
-
864
- ### Added — L3 semantic tag invariant (same 1.5.6, no extra version bump)
865
-
866
- - **`SemanticStore.upsert` is strict**: an L3 summary with zero usable tags is
867
- refused with **`MEM_E_SEMANTIC_TAG_REQUIRED`** — such a summary could never be
868
- reached by tag-driven retrieval (dead knowledge).
869
- - **Offline paths degrade instead of failing**: delete-consolidation and trend
870
- promotion derive tags from content heuristics (`extractTags`) and, if even that
871
- yields nothing, write an explicit provenance anchor (`origin:unlabelled-episode` /
872
- `origin:unlabelled-trend`). Maintenance and the two-phase delete pipeline therefore
873
- never break on historical untagged events.
874
- - **Historical data is read-only degraded**: summaries written before the invariant
875
- remain readable and are marked `degraded: true` in `list()` /
876
- `semanticSummaries()`; nothing is silently rewritten.
877
-
878
- ### Added — working mode survives a handoff (same 1.5.6, no extra version bump)
879
-
880
- - **Handoff marker carries the Host agent preset** (the UI's “工作模式”): the marker
881
- written at rollover now records `agentPreset`, fed by the live adapter through
882
- `memory.setHandoffPresetProvider()`.
883
- - **A new conversation restores it before its first turn**: `agent/created` is a
884
- serial Host event, so the bridge awaits `agentPresets.select(agent, preset)` for
885
- `source === 'startup'` from a different session. `resume`, the marker-owner session
886
- and markers without a preset are never overridden.
887
- - **Never breaks agent creation**: a failed `select` is reported in
888
- `runtime.lastPresetInherit` and the log, then creation proceeds.
889
- - **Tracking**: `agent-preset/selected` updates the mode; tool boundaries and prompt
890
- assembly opportunistically read `agents.currentInitiator()` + `agentPresets
891
- .composedPreset()` and **backfill an older marker** that predates this feature.
892
- - **Observability**: `/stats` exposes `agentPreset` + `presetInherit`, and
893
- `hostStatus().presetSelections` counts observed selections.
894
-
895
- ### Changed — physical split: multi-space engine moved out (same 1.5.6)
896
-
897
- - **`src/spaces/spaceRouter.js` and `src/spaces/transfer.js` are GONE from this
898
- package.** The full multi-space router (per-space FIFO chains, lazy child stores,
899
- `MEM_E_*` validation) and the cross-space transfer engine now live in
900
- `dsh-orchestrator` (`src/spaceRouter.js`, `src/transfer.js`).
901
- - The core compiles only `src/spaces/singleSpace.js`: the `default` space is the
902
- owner handle; every named-space operation answers **`MEM_E_FEATURE_DISABLED`** with
903
- an explicit "install dsh-orchestrator" hint. No silent fallback to `default`.
904
- - **Adapter injection is the wiring seam**: the Host's optional `orchestrator`
905
- service supplies `createSpaceAdapter({owner, dataDir, openChild})` and `transfer`;
906
- `Memory.open({spaces|spacesFactory, transfer})` accepts the same seam for embedders.
907
- Without the service the plugin advertises `capabilities.spaces=false`, registers
908
- only the eight single-space tools, and `/spaces` reports `default` only.
909
- - A profile with `features.multiSpace:true` but no Orchestrator logs a loud warning
910
- and runs the strict single-space core (visible in `/stats.capabilities`), instead
911
- of pretending the capability exists.
912
-
913
- ### Added — first batch: orchestrator service + 3 experience fixes (same 1.5.6)
914
-
915
- - **Orchestrator service registration**: `apply()` now installs a real Host service
916
- (`ctx.provide('orchestrator', …)` inside `ctx.effect`, so unloading removes it).
917
- It exposes `createSpaceAdapter`, `transfer`, `dirFor`, `status`, `federation`,
918
- `dedupe`, `consent` and `router`. The core decides the capability through
919
- `config.multiSpaceActive(config, hasOrchestrator)`.
920
- - **Reserved system tags isolated from display**: `status:*`, `folded-summary` and
921
- `active_task` are filtered out of the knowledge graph (`buildGraph` + defensive
922
- `view`) and the L1.5 tag tree (`rebuildTree` + persisted-tree/ghost filtering).
923
- The inverted index still keeps them (handoff/recall internals need them).
924
- - **`[Active Task]` injection**: prompt assembly prefers the active handoff summary,
925
- otherwise the newest event carrying a `task:` tag, and renders it as an
926
- unconditional top block (`[Active Task]`) once per session.
927
- - **Fallback hints**: `selectRelevantTags` accepts `fallbackTags`; when the current
928
- input has no lexical overlap (e.g. “继续”), the previous turn's matched tags (max 2)
929
- are carried into `[Memory Hints]`.
930
- - **Session-scoped injection dedup**: `runtime.injection` keeps per-session `ids` and
931
- `tags`; hints, `[Active Task]` and recall blocks already injected are filtered on
932
- later turns. SessionStart and rollover reset the pool, so the next session receives
933
- the handoff content again.
934
- - **Space deletion (UI + engine)**: `SpaceRouter.deleteSpace(id, {confirm})` closes
935
- the child handle, evicts its queues/caches and removes the directory (refusing
936
- `default` and requiring `confirm:true`). `Memory.deleteSpace` / `runtime.deleteSpace`
937
- gate the same rules (named space only; `MEM_E_FEATURE_DISABLED` in the strict
938
- single-space core). The HTTP route reuses `POST /spaces` with
939
- `{action:'delete', space_id, confirm:true}`; an **unknown action is a 400** and
940
- never falls through to CREATE. The SpaceSelector renders `🗑 删除空间` only for a
941
- named space AND only when the new **`capabilities.spacesDelete`** handshake is
942
- true — an old/pre-delete host therefore hides the button instead of answering the
943
- misleading “空间已存在”. When `capabilities.spaces` is false the entire space UI
944
- (selector, create/delete, current-space chip) disappears silently.
945
-
946
- ### Added — local low-valley Dream scheduling (same 1.5.6)
947
-
948
- - **No external price plugin required**: `src/priceWindow.js` computes Beijing-time
949
- peak/valley locally (weekday 09–12 / 14–18 peak; lunch, nights and weekends low).
950
- Chinese holidays are NOT modelled (the calendar moves yearly); `DSH_DREAM_PRICE=low|high`
951
- or a Host price probe still override it.
952
- - **The Host bridge gets a default probe** from `isLowValley()`, so a compensating
953
- Dream skips peaks (`reason:'peak'`) and runs locally in the valley.
954
- - **Idle LLM Dream defers instead of spending at peak**: `runtime.tick()` writes a
955
- durable `state/dream-queue.json` (`pending, dueAt, reason:'peak-hour'`), emits
956
- `dream-deferred`, and runs the queued Dream as soon as the valley opens — the queue
957
- survives a restart, so a missed window is not lost.
958
- - **Config `dream.onlyLowValley`** (default true; fail-fast, HTTP-editable, settings
959
- toggle). A local-only Dream (no LLM) is never gated by price.
960
- - `/stats` exposes `dreamWindow` (low/reason/nextLowAt), `dreamQueue` and `dreamTimer`.
961
- - **Phase 2 — wake timer + sleep correction**: `src/dreamTimer.js` arms ONE wake-up
962
- at the queued due time / next valley (injectable timers, `unref`ed). On fire it
963
- re-reads the CLOCK and the WINDOW: a late wake after an OS sleep is reported
964
- (`lateMs`, `catchUp`) and runs; a wake that lands in a peak re-arms for the next
965
- valley instead of spending. Boot arms from the persisted queue, so a queue left by
966
- a previous run catches up with delay 0. Disposal cancels the timer.
967
- `dreamTimer` status (arms/wakes/lateWakes/reschedules/runs) is exposed on `/stats`.
968
-
969
- ### Added — Federation / cross-space dedupe wiring (same 1.5.6)
970
-
971
- - **Federation on write**: after a successful write the engine reports the record's
972
- BUSINESS tags (never `status:*` / `month:*` / `active_task`) to the Orchestrator's
973
- global `FederationMap` with the space id; a tag seen in two spaces becomes ONE
974
- global node listing both. A missing/broken service can never fail the write.
975
- - **Dedupe on monthly memos**: `generateMonthlyMemos()` claims `sha256(content)` in
976
- the Orchestrator's `ContentRegistry` as `monthly:<spaceId>`; a sibling space with
977
- the identical monthly workload skips its copy and reports
978
- `monthly.skipped`/`skippedEntries` (owner traceable). Same-space reruns are
979
- idempotent.
980
- - Services arrive through the existing `orchestrator` adapter extras; spaces carry
981
- their own `spaceId` (`path.basename(childDir)`), the default space is `default`.
982
- - **Read-time merge on recall**: monthly memos now persist `meta.source_event_ids`,
983
- and `projectEpisode` exposes `sourceEventIds`. `Memory.mergeRecallHits()` feeds the
984
- recalled hits through `ContentRegistry.mergeForRead()`: a memo wins over the events
985
- it owns, duplicate `contentHash` collapses monthly-first, and the payload reports
986
- `merge: {space,monthly,droppedOwnedByMonthly,droppedDuplicateContent,total}`. Only
987
- when the Orchestrator dedupe service is present; the pure core payload shape is
988
- unchanged.
989
- - **Cross-space recall aggregation**: `Memory.recallAcrossSpaces()` queries every open
990
- space under its own lock, tags each hit with `spaceId`, and folds the union through
991
- the same `mergeForRead()` (raw hits are requested with `mergeRecall:false` so the
992
- aggregation sees owned events before the memo hides them). It is **opt-in**:
993
- `features.crossSpaceRecall` defaults to **false**, is fail-fast (true without
994
- multiSpace is a contradiction), HTTP-editable and rendered in the settings page.
995
- Only when `crossSpaceRecall:true` does `runtime.recall()` use this path; otherwise
996
- the single-space payload is unchanged (`mode` is never `cross-space`).
997
- `mode:'cross-space'`, `spaces`, `merge` and per-hit `spaceId` are reported.
998
-
999
- ### Tests
1000
-
1001
- - New `test/v156.rawscan.test.js` (5 cases): newest-first + absolute line number
1002
- (5000-line shard), turn-budget truncation without reading the head, engine result
1003
- ceiling, `readLinesReverse` peak buffer ≤ chunk + one line over a 20k-line file,
1004
- and `restoreByHash` over the streaming path.
1005
- - New `test/v156.hardening.test.js` (5 cases): recall payload truncation and
1006
- under-budget pass-through, `maxInjectTokens` fail-fast, `close()` resource release
1007
- and idempotency, lag monitor yield after a 120ms block, maintenance `eventLoop`.
1008
- - New `test/v156.tagging.test.js` (7 cases): extraction matrix, untagged write gets
1009
- an anchor and becomes recallable, raw purity (four fields), manual tags win +
1010
- dedupe, miss warning + panel counter, `autoTag:false`, config fail-fast.
1011
- - New `test/v156.pinned.test.js` (3 cases): pinned without tags refused and no
1012
- write, one-year decay still `decay=1` + index/tag flags + pinned-first ranking,
1013
- pinned tag stays in the active set after a 400-day maintenance.
1014
- - New `test/v156.hints.test.js` (4 cases): selector matrix (match/unrelated/internal/
1015
- empty), hint rendering, prompt tail contains only matching tags after the block
1016
- marker with a stable prefix, `session/event` user turn tracking.
1017
- - New `test/v156.features.test.js` (5 cases): flag fail-fast + implied transfer-off,
1018
- strict single-space engine + capabilities/tools absent, transfer-only-off,
1019
- defaults unchanged, `Memory.open(string)` + lazy `warmup()`.
1020
- - New `test/v156.host.test.js` (6 cases): price normalisation; session start runs one
1021
- compensating Dream; unknown price + LLM skipped; peak skipped; not-due / disabled /
1022
- in-flight refused; MockHostEnvironment integration through `apply()` + `hostStatus`
1023
- surfaced on `/stats`; `dream.compensateAfterHours` fail-fast.
1024
- - New `test/v156.dreamui.test.js` (3 cases): safe Dream subset exposed / credentials
1025
- absent from the payload; tunables editable over HTTP while `dream.llm.*` is not;
1026
- settings page renders the section and offers no credential field.
1027
- - New `test/v156.l2merge.test.js` (4 cases): pinned/ordinary strict separation with
1028
- global-tag metadata preserved as meta (never a tag); a lone ordinary record is not
1029
- dragged into the pinned group; `maxSummaryChars` cap + `enabled:false`; config
1030
- fail-fast. Older fixtures disable `l2Merge` so their exact index-count assertions
1031
- stay deterministic.
1032
- - New `test/v156.l3tag.test.js` (4 cases): strict upsert refusal; delete-consolidation
1033
- derives `error:typeerror` / `origin:unlabelled-episode` instead of dead knowledge;
1034
- trend promotion derives tags before writing L3; historical untagged summaries are
1035
- readable but `degraded`.
1036
- - New `test/v156.preset.test.js` (6 cases): marker records the working mode; a new
1037
- conversation restores it through `agentPresets.select`; older markers are
1038
- backfilled from the live agent; resume / same-session / marker-without-preset never
1039
- override; a failed select does not fail creation; `agent-preset/selected` keeps the
1040
- tracked mode current.
1041
- - New `test/v156.singleSpace.test.js` (3 cases): the core works for `default` and
1042
- refuses named read/write/create/ensure/transfer; without the Orchestrator the plugin
1043
- advertises `spaces:false`, registers eight tools and never advertises a dead tool in
1044
- the prompt; injecting the adapter restores ten tools and `spaces:true`.
1045
- - Updated: manifest 1.5.5 → 1.5.6; settings page gains `context.maxInjectTokens`,
1046
- the pre-ingest tagging section, Dream tunables and the L2-merge section; editable
1047
- contract gains `tagging`, `features`, `dream` and `l2Merge`; panel contract gains
1048
- `global.pinned`, `autoTag` and `l2Merge`; `plugin.test` prompt contract now asserts
1049
- relevance hints instead of the removed global map.
1050
- - New `test/v156.firstBatch.test.js` (5 cases): reserved status tags never reach the
1051
- graph/tag tree; `[Active Task]` from the handoff summary and from a `task:` event;
1052
- fallback hints reuse the previous turn's tags; session dedup blocks the second
1053
- injection and resets on a new session.
1054
- - New `test/v156.spaceDelete.test.js` (5 cases): engine deletion with confirm/default/
1055
- missing rules; strict single-space refusal; **`capabilities.spacesDelete` versioned
1056
- handshake** (an old host hides the button, so a delete request can never be
1057
- misread as CREATE); `POST /spaces {action:'delete'}` removes the store and returns
1058
- the refreshed list; unknown actions answer 400 instead of falling through to
1059
- CREATE; the UI source carries the capability guard, the button, the human confirm
1060
- and the default-space guard.
1061
- - **Graph interaction layer** (`test/v156.graph.test.js`, 4 cases): Ctrl/Cmd+drag
1062
- pans the canvas (plain drag still moves a node), Ctrl/Cmd+wheel zooms around the
1063
- cursor via a non-passive native listener (plain wheel keeps page scroll),
1064
- double-click on blank space resets the view, and the frozen initial layout runs
1065
- through `separateOverlaps()` so nodes never start piled on top of each other.
1066
- The header/footer advertise the interaction.
1067
- - New `test/v156.lowValley.test.js` (4 cases): Beijing peak/valley boundaries and
1068
- next-low computation; `dream.onlyLowValley` fail-fast + editable; a peak-hour idle
1069
- Dream is deferred durably and runs at the valley; the Host bridge probe follows the
1070
- window while `DSH_DREAM_PRICE` remains an override.
1071
- - New `test/v156.federation.test.js` (2 cases): business tags federate into one
1072
- global node across spaces while internal tags are skipped; the first space claims a
1073
- cross-space monthly memo and the sibling reports `skipped` with the owner.
1074
- - New `test/v156.lowValley2.test.js` (4 cases): peak wake re-arms (never runs); a
1075
- sleep-delayed wake reports `lateMs`/`catchUp`; a past-due queue in the valley arms
1076
- delay 0; runtime integration: peak deferral -> timer fire -> queue cleared and
1077
- `dreamTimer.runs === 1`.
1078
- - New `test/v156.readMerge.test.js` (2 cases): a recalled monthly memo drops the
1079
- events it owns and reports merge stats; without the dedupe service the recall
1080
- payload is unchanged.
1081
- - New `test/v156.crossSpaceRecall.test.js` (2 cases): a recall returns hits from every
1082
- open space with provenance; a monthly memo hides its owned event even when recorder
1083
- in another space, while the other space still contributes.
1084
- - New `test/v156.crossSpaceRecallFlag.test.js` (3 cases): default false + fail-fast
1085
- (`true` without multiSpace is a contradiction, non-boolean rejected); flag true
1086
- aggregates open spaces; flag false keeps the single-space payload.
1087
- - **Settings-page GitHub installer**: new `POST /api/hippocampus/orchestrator/install`
1088
- (requires `{confirm:true}`) delegates to the Host's
1089
- `pluginManager.installBundle('git+https://github.com/382quaii/dsh-Layers-Orchestrator.git', {enabled:true})`,
1090
- short-circuits when the service is already present, and reports
1091
- `applied | restart-required | manual | failed`. The settings page ships a
1092
- “从 GitHub 安装 dsh-orchestrator” button (human confirm dialog) plus the repo link;
1093
- without `pluginManager` it shows the exact manual steps instead of failing silently.
1094
- - **Automatic new conversation on handoff (verified feasible)**: the Host exposes
1095
- `agents.create/resume` and, decisively, the CLIENT service
1096
- `uiWorkspace.startSession()` — the same action the “+” button uses. A client-half
1097
- controller polls `/stats`, and when `handoff.active && handoff.autoNewSession` it
1098
- calls `uiWorkspace.startSession(undefined, {agentPreset})` once per handoff marker
1099
- (sessionStorage guard, lifecycle-owned interval, capability-guarded no-op on old
1100
- hosts). New config `context.autoNewSession` (default **true**, fail-fast,
1101
- HTTP-editable, settings toggle), plus `context.autoNewSessionPoll`
1102
- (`interval` | `once`, default `interval`) and
1103
- `context.autoNewSessionIntervalSeconds` (5–3600, default 15): the settings page
1104
- now exposes a “按间隔轮询 / 只检查一次” select and an interval slider; the client
1105
- configures its timer from the FIRST stats response (`once` clears the recurring
1106
- timer). The workspace-file handoff scheme is no longer needed and stays documented
1107
- only as a fallback.
1108
- - **Fixed — new-conversation failure `tool "subagent" is already registered`**:
1109
- handoff preset inheritance no longer calls `agentPresets.select()` when the new
1110
- session is ALREADY composed with the marker's preset. A redundant recompose
1111
- re-mounted the preset's `@deepseek-ai/dsh-tool-subagent` row and aborted session
1112
- creation; the skip is recorded as `presetInherit.reason='already-composed'` and
1113
- locked by a regression test in `test/v156.preset.test.js`.
1114
- - **Persona section + generic custom decay (v1.5.7)**:
1115
- - `[Persona & Traits]` is its own prompt section (`name:'persona'`, **order 100**),
1116
- rendering the ≤10 highest-confidence L3 semantic summaries (live store read, not
1117
- the recall cache). The memory block/policy/reflection sections keep 2450/2455/2460.
1118
- - `service.remember()` accepts **`customDecayRate`** (finite, 0 < rate ≤ 10) OR
1119
- **`customHalfLifeDays`** (integer 1–36500), never both. The value is normalised to
1120
- `meta.decay_rate`, projected as `decayRate`, and applied as
1121
- `effectiveHalfLife = policyHalfLife / decayRate` for THAT record only. No
1122
- tag-prefix logic exists anywhere in the engine — an emotion plugin decides the
1123
- semantics by passing the parameter.
1124
- - **Cross-plugin `ctx.provide('hippocampus', service)`** (user decision 2026-11-05:
1125
- in-process service only, NO HTTP write surface): `apiVersion=1`, `ready()`,
1126
- `capabilities()` (declares `l3Traits:10` plus per-method support), `remember()`
1127
- (L2-only; non-L2 layers are redirected with a warning; returns
1128
- `{status,eventId,eventTime,duplicate}`), `recall()`, `runMaintenance(source)`
1129
- (never queues: a running pass answers `MEM_E_MAINTENANCE_RUNNING`; manual passes
1130
- are rate-limited to 30 s while `cron` bypasses), `stats()/handoffView()/
1131
- promptState()` read-only snapshots and `onDispose()` hooks. The service disappears
1132
- with its plugin fiber; later calls answer `MEM_E_SERVICE_DISPOSED`. New codes
1133
- `MEM_E_MAINTENANCE_RUNNING`, `MEM_E_SERVICE_DISPOSED`, `MEM_E_FEDERATION_FAILED`
1134
- are registered append-only (8 cases in `test/v157.service.test.js`).
1135
- - **Durable Orchestrator state**: `<root>/state/orchestrator.json` now persists the
1136
- global federation map and the monthly-memo claims (atomic tmp+rename on every
1137
- mutation); it is loaded before the services become observable, and a corrupt file
1138
- is treated as empty instead of failing activation — a restart no longer forgets
1139
- cross-space dedupe.
1140
- - Full suite: **411 tests / 411 pass / 0 fail**, 64 test files. Orchestrator:
1141
- **31/31** (`service` + `spaces` deletion + `persistence` round-trip/corrupt state).
1142
- **Installed locally**: desktop profile gets a `link:` dependency + an ordered patch
1143
- insert BEFORE the hippocampus entries, so the service exists at activation. Two
1144
- Cordis constraints were fixed on the way: `apply()` must return **undefined**
1145
- (the return value is treated as an effect → `TypeError: Invalid effect`), and the
1146
- service is registered directly with `ctx.provide` (itself an effect). The market
1147
- catalog still does **not** list it: that needs an npm publish / catalog submission.
1148
- - Added `docs/RELEASE-1.5.6.md`: release notes + the exact push/tag/npm/market
1149
- commands that require the operator's credentials (none executed here).
1150
-
1151
- ## [1.5.5] — 2026-11-03
1152
-
1153
- **Offline Dream distillation: an optional LLM pass that can never take Dream down.**
1154
- Same-tag L2 records are distilled into one durable, provenance-carrying record.
1155
- The LLM leg uses **Node's built-in `fetch` only** (charter v2.0 #1: still zero
1156
- dependencies); endpoint / model / key are injected through config or
1157
- `DSH_DREAM_LLM_*` env and are never hard-coded, logged, or returned by HTTP.
1158
- Every failure — no config, network down, timeout, non-JSON — silently degrades to
1159
- the deterministic local merge and records `MEM_E_DREAM_LLM_FALLBACK`. **303 tests
1160
- green** (was 295).
1161
-
1162
- ### Added — Dream LLM distillation (`src/dream.js`, `Memory.executeDream`)
1163
-
1164
- - **Structured output**: the model must answer JSON `{"summary","confidence"}`;
1165
- `summary` is capped at `dream.maxSummaryChars` (default 200). Fenced code,
1166
- non-JSON, missing fields and over-long summaries are all treated as LLM failure.
1167
- - **Zero-dependency transport**: Node's global `fetch` against an
1168
- OpenAI-compatible `/chat/completions`; `Authorization: Bearer` only when a key is
1169
- configured. No SDK, no `node-fetch`, no new `package.json` dependency (test-locked).
1170
- - **Absolute timeout**: `AbortController` + `Promise.race` under
1171
- `dream.llmTimeoutMs` (default 15s); the timer is always cleared in `finally`.
1172
- - **Local fallback**: earliest/latest time + deduplicated core text, capped to
1173
- `maxSummaryChars`. Degradation warns `MEM_E_DREAM_LLM_FALLBACK` and is visible in
1174
- `status().panel.dream.lastFallback`.
1175
- - **Provenance**: the distilled record always carries
1176
- `meta.source_event_ids` (deduped, sorted) and `meta.distilled_by` (`llm|local`);
1177
- a re-run never merges the same source twice (`state/dream.json` bookkeeping).
1178
- - **Circuit breaker**: `failureThreshold` (default 3) consecutive failures open the
1179
- breaker for `cooldownMinutes` (default 60); afterwards a half-open state allows
1180
- exactly one probe — success closes it, failure re-opens. Exposed as
1181
- `panel.dream.circuit`.
1182
- - **Single-flight + serial**: a concurrent `executeDream()` is refused
1183
- (`dream-in-flight`); within one run groups are processed strictly serially, so a
1184
- slow provider can never exhaust connections or accumulate queued work.
1185
- - **Offline only**: `executeDream()` is called exclusively from the `dream` branch
1186
- of the maintenance gate, after `maintain()` converged; the online
1187
- `recall`/`remember` paths never touch the network.
1188
-
1189
- ### Config
1190
-
1191
- - New `dream` group (fail-fast validated): `useLlm`, `minGroupSize` (2–50),
1192
- `maxGroupsPerRun` (1–50), `maxSummaryChars` (40–2000), `maxSourceChars`
1193
- (80–4000), `maxEventsPerGroup` (2–50), `llmTimeoutMs` (500–120000),
1194
- `failureThreshold` (1–20), `cooldownMinutes` (1–1440), and
1195
- `llm.{baseUrl,model,apiKey}`. The `llm` block is deliberately **not** part of the
1196
- UI/HTTP config projection, so a credential can never leak through the panel.
1197
-
1198
- ### Tests
1199
-
1200
- - New `test/v155.dream.test.js` (8 cases): no-config local fallback with full
1201
- provenance; LLM success (URL/header/body/JSON parse); non-JSON degradation;
1202
- fetch timeout degradation; single-flight refusal; circuit open → no fetch →
1203
- half-open single probe → close; `dream` config fail-fast matrix; `package.json`
1204
- dependency red line.
1205
- - Updated: status-panel contract gains `dream`; manifest 1.5.4 → 1.5.5.
1206
- - Full suite: **303 tests / 303 pass / 0 fail**, 41 test files.
1207
-
1208
- ## [1.5.4] — 2026-11-02
1209
-
1210
- **Hotfix: the automatic handoff state machine can no longer wedge a session, and
1211
- recursive handoff summaries are cut off at the source.** Incident: recursive
1212
- `交接摘要` generations inflated the ratio past the native window and a handoff that
1213
- failed could leave the machine stuck, blocking new sessions. **295 tests green**
1214
- (was 286).
1215
-
1216
- ### Fixed — state machine (no deadlock, Fail-Fast with graceful degradation)
1217
-
1218
- - **`checkHandoff()` never rejects**: a distillation error, a timeout (default 5s,
1219
- injectable per call) or a marker-write failure degrade to a `state:"failed"`
1220
- marker carrying `summaryError` and return immediately. The next session starts
1221
- regardless.
1222
- - **New-session transition resets everything**: `observeSessionTokens()` always
1223
- establishes the new session's own baseline, consumes a marker belonging to a
1224
- different session, and **releases `_handoffInFlight`**, so a hung handoff guard
1225
- can never own the next session. A same-key restart (estimate halved after reset)
1226
- is treated as a new baseline too.
1227
- - **Stale marker consumption happens before early returns**, so a fresh session
1228
- cannot inherit "handoff active" forever.
1229
- - **Outer watchdog in `_maybeAutoHandoff()`** in addition to the inner one: even if
1230
- `checkHandoff` itself hangs, the in-flight flag is released in `finally`.
1231
-
1232
- ### Fixed — recursion
1233
-
1234
- - **`_distillHandoffTail()` refuses handoff content** by tag (`status:handoff`) and
1235
- by the `交接摘要` text prefix, in both the live-context path and the indexed
1236
- fallback. Output is hard-capped at 1200 characters; the idempotency key includes
1237
- the timestamp so distinct epochs never collide. (No more summary-of-summary.)
1238
- - **`status:handoff` is internal**: 2% weight in normal recall and excluded from the
1239
- recent-memory list, so real facts always outrank handoff bookkeeping.
1240
-
1241
- ### Added — escape hatches and cleanup
1242
-
1243
- - **`Memory.resetSessionState()` / `memory_admin action=reset_session` /
1244
- `POST /api/hippocampus/session/reset` / settings-page 「强制重置交接状态(逃生舱)」**:
1245
- clears the live token baseline, the in-flight guard and the active marker. It
1246
- rewrites only `state/`; durable memories are untouched.
1247
- - **`Memory.repairHandoffSummaries()` + `scripts/repair-handoff.mjs`
1248
- (`npm run repair-handoff`)**: finds recursive/excess handoff generations
1249
- (recursive = >=2 `交接摘要` markers) and parks them in the two-phase
1250
- `pending_delete` queue. Dry-run by default; `--reset-marker` consumes a stuck
1251
- marker.
1252
- - Panel session status now exposes `handoffState` / `handoffDegraded` /
1253
- `handoffErrorCode`; a degraded handoff is visible in the status bar instead of
1254
- silently locking.
1255
- - New error code **`MEM_E_HANDOFF_FAILED`**.
1256
-
1257
- ### Tests
1258
-
1259
- - New `test/v156.handoff.test.js` (9 tests): recursion refused by tag/prefix and
1260
- fallback path; throwing/hanging distillation degrades without rejecting; new
1261
- session resets ratio and releases the stuck guard; handoff summary ranking and
1262
- list isolation; `resetSessionState` preserves memories; repair dry-run + pending
1263
- delete; admin tool + HTTP escape hatch (route table 8).
1264
- - Route contract 7 → 8, manifest 1.5.4.
1265
- - Full suite: **295 tests / 295 pass / 0 fail**, 40 test files.
1266
-
1267
- ## [1.5.3] — 2026-11-02
1268
-
1269
- **Hotfix: space creation no longer exposes a raw `MEM_E_SPACES: HTTP 404`, and
1270
- invalid/conflicting space names are rejected by the ENGINE with
1271
- `MEM_E_SPACE_INVALID`.** Incident: a new client bundle called
1272
- `/api/hippocampus/spaces` against a host process that predated the route (the same
1273
- process also 404s `/memories`). Fixed on three layers plus a route-drift test.
1274
- **286 tests green** (was 270).
1275
-
1276
- ### Added — release hygiene
1277
-
1278
- - **Benchmark Protocol v1 (`scripts/bench-protocol.mjs`, `npm run bench`)**: the only
1279
- sanctioned way to publish a throughput number. Each measured run gets a fresh
1280
- `os.tmpdir()` store, one discarded same-process warmup precedes 5 measured runs,
1281
- and the report carries MEDIAN + min/max/spread. It makes no speed assertions
1282
- (a shared/AV-scanned machine must report, not fail), so single-run noise cannot
1283
- become an architecture conclusion again. Replaces the deleted single-run
1284
- `scripts/confidence-ab.mjs`.
1285
- - **Multi-space fixed-overhead coverage (`test/v154.release.test.js`)**: N=10
1286
- physical spaces — bounded per-space boot (<500ms median), lazy root boot
1287
- (`spaces.open=[]`, children never eagerly opened), uniform per-space storage
1288
- (max/min ≤1.35), linear total bytes (≤1.3×N), per-space fixed overhead <256KB.
1289
- - **Dead config removal**: `context.minInjectConfidence` is gone end-to-end
1290
- (default/validation/projection, HTTP-editable key,
1291
- `applyConfidence`/`MIN_INJECT_CONFIDENCE` retrieval pass, recall
1292
- `confidence`/`lowConfidence` annotations and low-confidence notes, obsolete A/B
1293
- script). Supplying the old key fails fast with `MEM_E_CONFIG_UNKNOWN_KEY`
1294
- (`details.removedIn = "1.5.3"`), so a profile cannot keep believing it works.
1295
- - Test watchdog default 30s → 60s (the in-process suite boots real stores/spaces and
1296
- legitimately takes ~15–25s; the watchdog now only fires on real hangs).
1297
-
1298
- ### Added — tool schema pruning
1299
-
1300
- - **`tools.disabled` config (default `[]`)**: every registered tool definition costs its
1301
- JSON schema in prompt tokens on EVERY turn (~1.1–1.2k tokens of baseline tax). A
1302
- closed suffix vocabulary (`remember/checkpoint/recall/capture/bulk_ingest/reinforce/forget/space_transfer/transfer_to_global/admin`)
1303
- lets an operator prune low-frequency tools; `remember`/`recall`/`admin` are CORE
1304
- and cannot be disabled. A typo/prefix/full name, a core tool, or a duplicate aborts
1305
- config resolution with **`MEM_E_INVALID_TOOL_NAME`** (fail-fast, never silently
1306
- ignored). The register wrapper skips disabled suffixes AND the `memory` prompt
1307
- section stops advertising them, so the schema prune cannot lie to the model.
1308
- Editable over HTTP (`tools.disabled`) and rendered in the settings page as a
1309
- checkbox catalog with core-不可关闭 / low-frequency tooltips. Takes effect on the
1310
- next host start/reload (tool registration happens at activation).
1311
-
1312
- ### Fixed
1313
-
1314
- - **Route-drift lock**: a new test parses the client `API` constant table and
1315
- proves every path equals the backend `MEMORY_API` value verbatim, and that the
1316
- registered route table contains them all. Adding a route on one side without the
1317
- other now fails CI instead of 404-ing in production.
1318
- - **Capability handshake**: `/stats` (ready AND booting) and `GET /spaces` now carry
1319
- `capabilities: { version, spaces, memories, transferConsent, multiSpace }`.
1320
- The client checks `capabilities.spaces` BEFORE calling `POST /spaces`; if the
1321
- host is older it shows a version hint and disables the action instead of firing a
1322
- request that 404s. `memories` is gated the same way (old host → "当前宿主版本不
1323
- 支持记忆列表", not `MEM_E_MEMORIES`).
1324
- - **Human error copy**: every space-create failure now renders a complete sentence.
1325
- 404 / route-missing / network → `创建失败:底层引擎未响应,请检查版本或联系架构师`;
1326
- invalid name → `创建失败:空间名称无效——需以小写字母/数字开头,只能含 a-z 0-9 . _ -(最长 64)`;
1327
- duplicate → `创建失败:空间「33」已存在,请换一个名称`; reserved → `创建失败:该名称是
1328
- 系统保留名,请换一个`. The `MEM_E_SPACES: HTTP 404` template is gone from the bundle.
1329
- - **`MEM_E_SPACE_INVALID` (400)**: `validateNewSpaceId` + `Memory.createSpace` reject,
1330
- before any directory/JSONL write: empty/whitespace, wrong charset (`Bad`, `bad id!`,
1331
- path separators, `..`, `.`), >64 chars, trailing dot (Windows alias), Windows
1332
- device names (`con`, `nul`, `com1`, …), `default` (always exists), an existing
1333
- space (conflict), and a non-directory path collision. Creation returns `201`,
1334
- conflicts/invalid ids `400 MEM_E_SPACE_INVALID`.
1335
- - Fresh spaces are created from `POST /spaces` with a strict non-idempotent
1336
- `runtime.createSpace`; the lazy `ensureSpace` used by transfer keeps its
1337
- idempotent semantics.
1338
-
1339
- ### Tests
1340
-
1341
- - New `test/v153.spaces.test.js` (7 tests): client↔backend route-path equality
1342
- (the anti-404 lock), a real dispatch through the CLIENT path against the
1343
- registered host route table (handler answers 201, never a router 404),
1344
- invalid/reserved matrix, engine conflict-before-write, HTTP 201/400 + capability
1345
- handshake, human-copy mapper (no raw 404), capability gating for old hosts.
1346
- - Updated: `POST /spaces` assertions 200 → 201 strict creation; manifest 1.5.3.
1347
- - Full suite: **286 tests / 286 pass / 0 fail**, 39 test files (includes
1348
- `v154.release.test.js`).
1349
- - **Note (deployment)**: the live host process observed during the incident still
1350
- 404s `/spaces` and `/memories` — it must be restarted/reloaded for the new routes
1351
- to serve; until then the new client degrades with the version hint above instead
1352
- of a naked 404.
1353
-
1354
- ## [1.5.2] — 2026-11-02
1355
-
1356
- **Architecture correction: physical storage migration vs. business-data transfer
1357
- are now physically decoupled, and the UI has a real global SpaceSelector.** The
1358
- v1.5.0/v1.5.1 UI mixed two unrelated concerns and let the user type
1359
- `target_space_id`/`event_ids` by hand. Fixed and locked by tests. **270 tests
1360
- green** (was 263).
1361
-
1362
- ### Changed — UI (module decoupling)
1363
-
1364
- - **Physical dataDir migration extracted** into `StorageMigratorUI`, a SYSTEM/DATA
1365
- MANAGEMENT section at the bottom of the settings page. It owns only the A/B
1366
- double-buffer state machine: `POST { dataDir }` → `202 state=migrating` → copy →
1367
- verify → swap, old directory kept as a backup. No event ids, no spaces.
1368
- - **Business cross-space transfer removed from the settings form**: the manual
1369
- `event_ids` / `target_space_id` text inputs, the copy/cut buttons and the
1370
- inline confirmation are gone. Business transfer now exists ONLY in the panel's
1371
- regulated flow (below).
1372
- - **Global `SpaceSelector`** in the panel header: a dropdown of the physical spaces
1373
- (friendly labels: 默认空间 / 工作空间 / 私人空间 / 全局空间, unknown ids verbatim)
1374
- with `+ 新建空间` (creates an EMPTY space — never a copy). The selection is
1375
- app-global (`spaceStore` + `space-changed` bus event), so the panel and the
1376
- settings page follow it.
1377
- - **Every UI read follows the selected space**: `useMemoryStats`, `useGraph` and
1378
- `useRecentMemories` append `?space=<id>`; the backend routes `stats`, `graph` and
1379
- `memories` to that physical store. Memory list, graph, L1 log/index counts, L2.5
1380
- quarantine, L3 semantic count, L1.5 tag tree and the session status bar are all
1381
- that space's only — switching spaces cannot blend views or contexts.
1382
- - **Regulated cross-space flow (UI_TASK_3)**: check memories in the current space →
1383
- `移动到…` → dialog step 1 states `即将向 [目标空间] 发起迁移请求` → step 2 is the
1384
- SECOND explicit consent (`二次确认 · 安全红线`, with the cut warning when 剪切) →
1385
- only then is `user_approved: true` sent. Target is a dropdown of known spaces,
1386
- never a free-text id.
1387
- - `h(StorageMigratorUI)` is a separate component, so the two state machines can no
1388
- longer share draft state or validation.
1389
-
1390
- ### Added — backend routing
1391
-
1392
- - **`GET/POST /api/hippocampus/spaces`**: list the router's spaces / create an empty
1393
- one (`space_id`). The selector and `+ 新建空间` use it.
1394
- - **`?space=<id>` on `/api/hippocampus/stats` and `/api/hippocampus/graph`**:
1395
- `runtime.uiPayload(spaceId)` / `runtime.graphPayload(spaceId)` return that space's
1396
- panel/graph via `Memory.status({ targetSpaceId })` and
1397
- `Memory.graphForSpace({ targetSpaceId })`; a new space reports zeros (empty), so a
1398
- switched view is never a fallback to the default store.
1399
- - `Memory.ensureSpace()` (root router) and `runtime.spaceList()`.
1400
- - Panel status `panel.spaces.current` now reports the SELECTED space (was always
1401
- `default`), and `stats`/`graph` responses carry a top-level `spaceId`.
1402
-
1403
- ### Security (unchanged red line, stricter transport)
1404
-
1405
- - The HTTP transfer route no longer fabricates consent: it forwards
1406
- `user_approved` from the request and the ENGINE gate rejects a request that lacks
1407
- it with `MEM_E_REQUIRE_USER_CONSENT`. The UI only sets the flag after step 2. An
1408
- agent tool call and a raw POST that "bypasses the UI" therefore hit the same
1409
- wall.
1410
- - `dataDir` migration Fail-Fast strengthened: `validateMigrationPaths` now also
1411
- rejects an existing non-empty target (`MEM_E_MIGRATION_TARGET_BUSY`) and a
1412
- non-directory target (`MEM_E_MIGRATION_PATH`) synchronously, before a 202/job.
1413
- The old store remains authoritative on any rejection.
1414
-
1415
- ### Tests
1416
-
1417
- - New `test/v152.refactor.test.js` (7 tests): dataDir validation matrix
1418
- (missing/relative/same/inside/root/non-empty/non-dir) + `startMigration`
1419
- fail-fast with the old dir intact; space isolation for stats/graph/memories/
1420
- session/recall with `?space=`; `ensureSpace` empty space + spaces route;
1421
- unauthorized transfer blocked at engine AND HTTP, authorized passes; UI wiring
1422
- (SpaceSelector header mount, checkbox flow, no manual inputs, isolated
1423
- StorageMigratorUI).
1424
- - Updated contract assertions: HTTP routes 6 → 7 (spaces), transfer route requires
1425
- explicit `user_approved`, settings order now context → space/session → system
1426
- storage, cut second-confirmation now lives in the panel dialog, manifest 1.5.2.
1427
- - Full suite: **270 tests, 270 pass, 0 fail**.
1428
-
1429
- ## [1.5.1] — 2026-11-02
1430
-
1431
- **Security patch: cross-space transfer now requires EXPLICIT user consent.** Moving
1432
- memories between spaces is a data-egress action, not a memory optimisation. Two
1433
- independent locks (prompt + engine), plus a human-only UI path. **263 tests green**
1434
- (was 254).
1435
-
1436
- ### Added
1437
-
1438
- - **Prompt red line (`memory:policy`)**: a static `【🚨最高安全红线】` block forbids
1439
- the model from calling `memory_space_transfer` / `memory_transfer_to_global` on
1440
- its own judgement, sympathy, or "better cross-device sharing". The only allowed
1441
- trigger is a direct user command in the current conversation; when unsure the
1442
- model must ask `您需要我把这条信息同步到其他空间吗?`. It also documents the
1443
- `user_approved: true` retry protocol for `MEM_E_REQUIRE_USER_CONSENT` and states
1444
- that the intercept is never a one-off obstacle to bypass.
1445
- - **`memory_transfer_to_global` tool**: copy/move memories from a space into the
1446
- canonical `global` space, with the same privacy screen, raw_turn stripping, fresh
1447
- target ids and consent gate as `memory_space_transfer`. Both tool schemas expose
1448
- `user_approved` and their descriptions carry the security warning.
1449
- - **`context.requireExplicitConsentForTransfer`** (default **true**, validated
1450
- boolean, HTTP-editable and exposed in the settings page): the operator's master
1451
- switch for the engine gate. The settings toggle explains the risk.
1452
- - **`GET /api/hippocampus/memories`** (`limit`, `space`): bounded recent-memory
1453
- projection (`eventId`, `day`, `tags`, `snippet`) used by the panel's per-memory
1454
- detail rows. `Memory.recentMemories()` is read-only and index-snapshot based.
1455
- - **UI per-memory 分享/转移 button**: the panel now lists the 20 most recent
1456
- memories with a human-initiated transfer dialog (target space, copy/cut toggle,
1457
- second confirmation for cut). It calls the transfer route directly — **bypassing
1458
- the model entirely** — and the browser request is the consenting human.
1459
-
1460
- ### Fixed / Security
1461
-
1462
- - `Memory.transferEvents()` now throws
1463
- **`MEM_E_REQUIRE_USER_CONSENT`** with the fixed message
1464
- `[系统拦截] 跨空间传递需要用户明确授权。请向用户确认后再试。` when
1465
- `context.requireExplicitConsentForTransfer` is true and the call does not carry
1466
- `userApproved === true`. The gate runs **before** space ids are validated, before
1467
- any store is opened, before content is read and before any pending-delete record
1468
- is written, so a refused call is provably side-effect free.
1469
- - `POST /api/hippocampus/transfer` is documented and implemented as the **human
1470
- channel**: it marks `userApproved: true` itself (same-origin authenticated
1471
- browser request). The agent half cannot reach HTTP routes, so a UI click needs no
1472
- model involvement and a model call still hits the gate.
1473
- - The consent gate is strict: `userApproved` must be the boolean `true`; the
1474
- config value must be a boolean (a string like `"yes"` fails fast).
1475
-
1476
- ### Tests
1477
-
1478
- - New `test/v151.consent.test.js` (9 tests): default-on config + fail-fast type
1479
- check; engine gate fires before validation/IO (invalid target still answers
1480
- CONSENT, nothing parked, source untouched); agent tool blocked then succeeds only
1481
- with `user_approved: true`; `memory_transfer_to_global` same contract; explicit
1482
- config opt-out; engine-level facade contract; prompt red-line markers; HTTP route
1483
- marks consent; UI 分享/转移 + direct-API contract.
1484
- - Intentional contract growth updates: tools 9 → 10, HTTP routes 5 → 6, v150 UI
1485
- route/transfer assertions extended with `userApproved`, manifest 1.5.1.
1486
- - Full suite: **263 tests, 263 pass, 0 fail**.
1487
-
1488
- ## [1.5.0] — 2026-11-02
1489
-
1490
- Tag-explosion defence, physical multi-space routing, session handoff and the
1491
- cross-space transfer API. The plugin stays deliberately permission-free: the
1492
- complex permission choreography belongs to the future Orchestrator plugin, while
1493
- this engine owns only physical memory. **253 tests green** (was 200).
1494
-
1495
- ### Added — module 1: tag-explosion defence (P0)
1496
-
1497
- - **`index.maxPostingsPerTag` (default 500, 1–100000)**: derives the inverted index
1498
- with a hard physical cap per tag. When a tag exceeds it, the retained pointers are
1499
- chosen by `salience desc -> eventTime desc -> eventId asc` and re-sorted for
1500
- retrieval (`eventTime desc`, then id). `eventCount`, `mass` and `lastSeen` are
1501
- still aggregated over **all** events, so the counts the degradation layer reports
1502
- are honest; only the in-memory posting pointers are dropped (the JSONL log is
1503
- untouched and rebuildable). Tags expose `postingsLimit` / `postingsTruncated` /
1504
- `postingsDropped`; index stats expose `postingsTruncated` / `postingsDropped`.
1505
- - **Recall degradation for oversized tags**: an EXPLICIT query tag holding more than
1506
- 50 memories (`TAG_OVERFLOW_THRESHOLD`) is not expanded into the candidate pool.
1507
- The response carries `oversizedTagHints: [{ tag, total, code:
1508
- 'MEM_E_TAG_OVERFLOW', hint: '[系统提示] 发现关于 [tag] 的记忆共 N 条,数据量过大。
1509
- 请提供更精确的 startTime/endTime 或使用 deep_raw 查阅。', window }]` and the
1510
- course-block fallback is suppressed so the flood cannot re-enter through the back
1511
- door. If the caller insists (a second recall on the same tag), only the **3 most
1512
- recent** summaries are returned (`oversizedRecent: true`,
1513
- `oversized-tag-recent:3`). Graph neighbours of an oversized tag are never woken.
1514
- - **`deep_raw` super-tag gate**: a query touching a tag with more than 500
1515
- associations (`SUPER_TAG_THRESHOLD`) without `start_time`/`end_time` now throws
1516
- **`MEM_E_TIME_RANGE_REQUIRED`** (narrow queries keep the old
1517
- `MEM_E_INVALID_INPUT` contract). One authority decides: the tool no longer
1518
- pre-validates the window.
1519
-
1520
- ### Added — module 2: multi-space routing & session handoff (physical layer)
1521
-
1522
- - **Config** `context.autoSpaceFollow` (false), `context.autoRolloverEnabled`
1523
- (true), `context.autoRolloverThreshold` (0.85, 0.5–0.99),
1524
- `context.nativeTokenLimit` (8000, 512–1000000) — validated fail-fast, editable
1525
- over HTTP and in the UI.
1526
- - **`SpaceRouter`** (`src/spaces/spaceRouter.js`): `targetSpaceId` on
1527
- `remember`/`recall` routes to an isolated physical store
1528
- (`<dataDir>/spaces/<id>`, `default` = the existing store, so every old path is
1529
- byte-identical). One FIFO promise chain **per space**: same-space operations are
1530
- serialised, different spaces run concurrently (a single global lock would
1531
- reintroduce the cross-space stalls spaces exist to remove). Ids become directory
1532
- names, so `^[a-z0-9][a-z0-9._-]{0,63}$` is enforced and a typo fails with
1533
- `MEM_E_INVALID_INPUT` instead of silently writing into the default space.
1534
- `runMany` acquires in sorted order (no ABBA deadlock).
1535
- - **Qwen native fidelity**: `ContextEngine.nativeState()` reports
1536
- `mode: 'native' | 'layered'`; below `nativeTokenLimit` nothing is folded (folding
1537
- is a layered-mode operation), above it the L1.5 layered fold runs. The legacy
1538
- `maxTokens` paging threshold is untouched.
1539
- - **Automatic handoff (转生)**: when the session reaches
1540
- `autoRolloverThreshold x nativeTokenLimit`, the tail is distilled into ONE durable
1541
- L1.5 summary (`status:handoff`), `state/handoff.json` is marked active and the
1542
- `memory-state` prompt appends `[交接标记] … 本插件不能保证一个会话永生不死,只能
1543
- 保证人格不死。`. A new session consumes the marker. Handoffs are idempotent (one
1544
- summary per handoff) and self-trigger from the `session/event` stream and from
1545
- tool boundaries. With `autoRolloverEnabled: false` no marker is written and
1546
- ContextEngine force-evicts at 95% (`reason: 'native-force'`, down to
1547
- `target x nativeTokenLimit`).
1548
- - **Panel/status**: `panel.session` (`mode`, `tokens`, `nativeTokenLimit`,
1549
- `threshold`, `remainingTokens`, `rolloverEnabled`, `handoffActive`, …) and
1550
- `panel.spaces` (`current`, `ids`, `open`) are part of the UI contract.
1551
-
1552
- ### Added — module 3: atomic cross-space transfer
1553
-
1554
- - **`memory_space_transfer` tool** (`event_ids`, `target_space_id`,
1555
- `transfer_mode: 'copy' | 'move'` default copy, optional `source_space_id`) and
1556
- `Memory.transferEvents()`.
1557
- - **Safety rails enforced by the engine, not the caller**: privacy screening aborts
1558
- the whole batch with **`MEM_E_PRIVACY_BLOCKED`** (ID cards, CN phones, bank cards,
1559
- emails, credential assignments, PEM private keys; matched bytes never leave the
1560
- scanner) before any write; `raw_turn` / `rawTurn` / `raw_*` pointers are stripped
1561
- from meta at every depth; the TARGET space regenerates `event_id`s
1562
- (`dedupe:false`, never reuses the source identity) and tags copies
1563
- `transferred:from:<source>` + `transferred:to:<target>`.
1564
- - **State difference**: `copy` leaves the source untouched (`state: 'retained'`);
1565
- `move` parks the source ids in the **two-phase pending_delete queue**
1566
- (`state: 'pending_delete'`, `dueAt`, cancellable with `restore`) only after every
1567
- target write succeeded — never a direct physical delete, and a partial target
1568
- failure leaves the source untouched.
1569
- - **HTTP**: `POST /api/hippocampus/transfer` (same-origin, validated body) for the
1570
- UI migration button.
1571
-
1572
- ### Added — module 4: UI
1573
-
1574
- - **Space panel**: soft-follow toggle (`context.autoSpaceFollow`), auto-rollover
1575
- toggle, trigger-ratio slider, native-window field, single-tag index cap control,
1576
- and a live status bar: `[当前: 原生模式 | 剩余 X Tokens 触发交接]` (also
1577
- `分层折叠` / `已交接` variants).
1578
- - **Migration interaction**: copy/cut (复制/剪切) toggle next to the transfer button;
1579
- choosing 剪切 requires a **second confirmation warning** before any request is
1580
- sent.
1581
- - **Philosophy footer** (bold, bottom of the settings page): **本插件不能保证一个
1582
- 会话永生不死,只能保证人格不死。**
1583
- - **Subtraction**: the tag search box uses the host-native Enter key only — no
1584
- debounce, no timer, no effect. `filterGraphByQuery` is pure and testable; the
1585
- force layout is not re-run by filtering.
1586
-
1587
- ### Changed
1588
-
1589
- - `uiConfig` exposes `index`; `Memory.applyLiveConfig()` projects a validated config
1590
- onto the facade **and every open child space**, including the context engine's
1591
- native/rollover overrides.
1592
- - `Memory` opens child spaces lazily with the same policy input; `close()` closes
1593
- children first; a child failure never blocks the rest.
1594
- - The `memory-state` prompt only gains the handoff block when a marker is active,
1595
- so the cache-stable prefix is unchanged in the common case.
1596
-
1597
- ### Tests
1598
-
1599
- - New files: `v150.index.test.js` (truncation/degradation/super-tag gate),
1600
- `v150.space.test.js` (per-space concurrency, native boundary, forced eviction),
1601
- `v150.transfer.test.js` (copy/move state difference, privacy, raw_turn strip,
1602
- fresh ids), `v150.ui.test.js` (bundle contract, helpers, no debounce, footer,
1603
- transfer route), `v150.lifecycle.test.js` (Qwen mode, threshold handoff, marker
1604
- consumption, `targetSpaceId` isolation, ninth tool surface),
1605
- `v150.config.test.js` (new groups, ranges, HTTP editability).
1606
- - Intentional contract updates in old tests: 8 -> 9 tools, 4 -> 5 routes,
1607
- `panel.session`/`panel.spaces` added to the panel snapshot, manifest 1.5.0.
1608
- - Full suite: **253 tests, 253 pass, 0 fail** (old 200 cases included unchanged).
1609
-
1610
- ## [1.4.3] — 2026-11-02
1611
-
1612
- Two measured blockers from the 2026-11-02 handoff, both fixed and locked by tests.
1613
-
1614
- ### Added
1615
-
1616
- - **`raw.maxScanTurns` config (500–50000, default 5000)**: `deep_raw`'s scan budget
1617
- was a hidden constant and is now a validated, UI-editable knob (`raw.maxScanTurns`).
1618
- - **`stage()` / `commitMany()`**: remember is now a `stage -> commitMany` composition.
1619
- `stage()` validates and builds a record (identity + idempotency, no log/index I/O);
1620
- `commitMany()` performs ONE durable append, ONE ledger checkpoint and ONE index
1621
- delta for a whole batch. `bulkIngest` uses it, so a 50-item chunk is one write
1622
- instead of 50.
1623
- - **`memory-state` prompt is now composed** via `composePrompt`: stable rules →
1624
- `[Memory Map]` (active tags + counts) → `[Memory Blocks]` (the only per-turn
1625
- volatile tail). The old single-line `briefing()` is no longer the prompt body
1626
- (it changed on every write and broke the prefix cache). Full-chain tests lock the
1627
- prefix to be byte-identical before/after a recall injects a block.
1628
- - **`scripts/confidence-ab.mjs`**: local A/B benchmark for `context.minInjectConfidence`
1629
- (100 noise + 10/3 relevant; characters, hits, low-confidence hints, mis-degraded
1630
- relevant memories). Run it with `node scripts/confidence-ab.mjs`.
1631
- - **Crash-restart test**: kills the process inside the 200ms checkpoint window
1632
- (cancelled timer, no `close()`), reopens the same directory, and asserts the fresh
1633
- instance reports `stale` (`unflushed-bytes`), rebuilds the index and can recall the
1634
- unflushed tail.
1635
-
1636
- ### Fixed
1637
-
1638
- - **`injectRecall()` crashed on any L3 semantic hit**: it used `summary.id` while
1639
- `rankSemantic()` returns `summaryId`, so a recall with a distilled summary and
1640
- `context.injectPrompt` failed with `MEM_E_IO: ContextEngine.inject requires an id`.
1641
- Now it uses `summaryId ?? id` and skips invalid summaries. Found by the new
1642
- prompt/tag-tree full-chain test.
1643
- - `logStore.status()` now exposes `unflushedBytes` (shard size minus manifest bytes)
1644
- so an unclean shutdown cannot hide the uncheckpointed tail behind equal counters.
1645
-
1646
- ### Changed
1647
-
1648
- - **`deep_raw` scans NEWEST-FIRST** (per shard, tail to head). The old head-first
1649
- scan burned its whole budget on the oldest 5000 turns of a day file — in a 10k
1650
- shard the newest turn could never be found. A hit beyond the window now returns
1651
- `truncated: true` with a note instead of pretending the turn does not exist.
1652
- - **Buffered log append**: the hot path keeps one append handle without fsync +
1653
- manifest rewrite per record. A 200ms checkpoint (and `close()`, and any
1654
- rewrite/compaction) fsyncs and publishes the manifest; `status().unflushedBytes`
1655
- plus the boot check make a mid-burst crash visible as stale instead of silently
1656
- "up to date".
1657
- - **Identity ledger checkpoint is debounced** (500ms / `close()`): it is a derived
1658
- startup hint rebuilt from the log, so rewriting it per append was pure O(n²) cost.
1659
- - **Index appends are lazy**: `applyRecords` records the delta and marks the view
1660
- dirty; the next `snapshot()` folds it once. N writes cost one index build, and
1661
- read-your-writes still holds because the fold happens on the read path.
1662
- - **Briefing is dirty-driven**: a write marks the prompt-state line stale; the next
1663
- `briefing()` / panel poll rebuilds it once instead of every append.
1664
-
1665
- ### Measured
1666
-
1667
- - Sequential `memory.remember` x1000: **119/s -> 9104/s** (8.4s -> 110ms).
1668
- - 10,000-line raw shard, newest query: **0 hits -> 1 hit** (`deep_raw` now starts at
1669
- the tail; hash restore and redaction regression-guarded).
1670
- - **`deep_raw` tail-scan bias documented**: beyond `raw.maxScanTurns` (default 5000)
1671
- per shard, only the newest N turns are covered; older history needs a larger budget
1672
- or time-window pagination (`end_time` moved backwards). `truncated: true` + notes
1673
- always say so.
1674
- - **Confidence A/B (measured)**: `minInjectConfidence=0.6` cuts the tool payload by
1675
- **49.7%** (10 relevant / 100 noise) and **75.8%** (3 relevant / 100 noise), with
1676
- **0 relevant hits mis-degraded**; the prompt window only shrinks when the top-8
1677
- contains noise (0% vs 59.7% in the two scenarios), so the honest claim is
1678
- "long-tail payload + anti-hallucination", not "always fewer prompt tokens".
1679
- - 197 tests green (was 189); after the prompt/tag-tree full-chain wiring and the
1680
- crash-restart test: **200**.
1681
-
1682
- ## [1.4.2] — 2026-11-01
1683
-
1684
- ### Added
1685
-
1686
- - **L1.5 标签层级树**: hierarchical tags (`tech/frontend/vue3`) now have a
1687
- three-level lifecycle — immortal roots, leaves that die when their reference
1688
- count reaches zero, and mids that enter a grace window when they lose their last
1689
- child. A mid inside that window is a **ghost**: it can be revived by a new leaf,
1690
- and it is what the UI's history view shows. The tree is a **derived cache**
1691
- (`state/tag-tree.json`) built by `maintain()` from the converged index; the
1692
- previous cache is carried forward (`refCount = 0`, orphans dropped) so the
1693
- lifecycle is observable across maintenance runs. Deleting the file loses only
1694
- ghost history.
1695
- - **Bounded prune queue**: dead leaves are queued and consumed one
1696
- `tagTree.pruneBatchSize` batch per maintenance run; the remaining queue is
1697
- persisted in the same atomic write, so a 10k-leaf storm drains across runs
1698
- instead of causing a maintenance storm.
1699
- - **Anti-hallucination recall degradation**: a `memory_recall` hit reached only
1700
- through a fading mid is **removed from `hits` entirely** (body, snippet and score
1701
- never reach the model or the prompt window) and replaced by one metadata hint per
1702
- mid: path, count, remaining grace days and the exact `deep_raw` time window. A
1703
- query that names a fading mid with no live episode returns a `count: 0` hint
1704
- instead of silence.
1705
- - **`panel.tagTree`**: node/root/mid/leaf/ghost/queue counts for the Web panel, and
1706
- `GET /api/hippocampus/graph` now returns `tagTree.ghosts` in the same response as
1707
- the cached graph.
1708
- - **UI**: `tagTree.*` sliders with numeric boxes and hover tooltips in the settings
1709
- section; ghost nodes rendered in the force graph as translucent dashed circles
1710
- hanging under their parent root, with a `仅活跃 / 历史全貌` toggle that cross-fades
1711
- them via CSS opacity (the force layout does not re-run when toggling).
1712
- - **Config `tagTree` group** (fail-fast, editable over HTTP and in the UI):
1713
- `midHalfLifeMultiplier` (1–10), `midGracePeriodDays` (7–180),
1714
- `pruneBatchSize` (10–500), `leafDecayFloor` (0–1). `midHalfLifeMultiplier` is the
1715
- only source of the mid half-life — no silent hard-coded lifetime.
1716
-
1717
- ### Changed
1718
-
1719
- - `maintain()` now rebuilds/prunes/persists the tag tree after the index
1720
- generation converges; a tag-tree failure is reported as `report.tagTreeError`
1721
- and can never fail maintenance or block recall.
1722
- - `applyConfig` now projects the validated config onto the running `Memory` facade,
1723
- so live UI edits (raw limits, tagTree lifetimes, …) actually reach the running
1724
- objects instead of waiting for a reload.
1725
- - `pruneBatch` re-derives decay against the pass's `now` (a frozen build-time score
1726
- made grace windows meaningless), rejects `O(mids × nodes)` rescans, and keeps
1727
- parent child counts truthful when a mid dies.
1728
-
1729
- ## [1.4.1] — 2026-11-01
1730
-
1731
- ### Added
1732
-
1733
- - **Prompt discipline (soft interception)**: a static `memory:policy` section tells
1734
- the model to prefer `memory_recall` for history/files/system facts, and to treat
1735
- a `[Slimmed]` response as an invitation to answer from the summary unless the
1736
- `recovery_hash` must be dereferenced.
1737
- - **Own-tool output slimming**: `memory_recall`/`memory_admin` responses over the
1738
- budget (default 2000 tokens) are captured to raw first, then returned as
1739
- `{slimmed, summary, topics, key_entities, recovery_hash, hint}`; the hint points
1740
- at `memory_recall(mode="deep_raw", hash=…)`, which restores the exact payload.
1741
- - **Retrieval confidence**: hits below `context.minInjectConfidence` (default 0.6)
1742
- carry a short hint instead of their full body, plus a `low-confidence-hints:N` note.
1743
- - **Write flood guard**: writes above 80% of `storageBudgetMb` throw
1744
- `MEM_E_WRITE_FLOOD`; `memory.bulkIngest` chunks 50 items per await and ships as
1745
- `memory_bulk_ingest`.
1746
- - **raw.captureRatio** (0 | 0.5 | 1): deterministic sampling by content hash;
1747
- ratio 0 disables capture and `deep_raw` returns an explicit warning.
1748
-
1749
- ### Changed
1750
-
1751
- - `memory_recall` gains `hash` (exact raw restore) and confidence fields; deep_raw
1752
- results honour the token budget before returning.
1753
- - `promptLayout` composes stable rules → memory map → `[Memory Blocks]` tail.
1754
-
1755
- ## [1.4.0] — 2026-10-31
1756
-
1757
- ### Added
1758
-
1759
- - **Raw-turn forensics (`memory_capture`, `memory_recall mode:"deep_raw"`)**: a
1760
- separate day-sharded JSONL store (`raw/`) that is never indexed, never loaded at
1761
- boot, and never touched by normal recall. Gated by `raw.mode` (default
1762
- `salience`: high-salience, code, stack traces, tool output, or `force`), deduped
1763
- by content hash, secret-redacted, and capped by `maxTurnKb` (head+tail
1764
- truncation), `maxBytesPerDay`, `maxTotalMb`, and `retentionDays` (pruned by
1765
- maintenance; code shards keep 90 days). `deep_raw` scans newest→oldest under a
1766
- byte/turn budget and reports `truncated: true` instead of pretending it saw
1767
- everything.
1768
- - **Spaced repetition**: engine-owned schedule (`1,2,4,7,15,30` days) persisted in
1769
- `state/reviews.json`; `maintain()` reconciles due items and `reinforce` advances
1770
- the step. Exposed as `memory_admin action="reviews"`.
1771
- - **Two-phase delete**: `forget` parks the event for `delete.graceHours`
1772
- (default 24) in `pending_deletes`; `restore` cancels it, and `maintain()`
1773
- promotes expired requests into the 4-phase pipeline. Unknown ids now fail
1774
- immediately, before parking.
1775
- - **UI data-dir migration**: `dataDir` is editable in the settings page. Saving it
1776
- takes `.migration.lock`, returns HTTP 202 with `state=migrating`, copies with
1777
- `fs.promises.cp` in the background, verifies `recordCount` on both sides, and
1778
- only then switches and reloads the store. A mismatch removes the target and
1779
- keeps the old store authoritative; the source is never deleted.
1780
- - New config groups: `raw.*`, `delete.graceHours`, `review.enabled`,
1781
- `migration.timeoutMs` (all fail-fast validators, UI tooltips included).
1782
- - **Raw-turn black box (minimal schema)**: each line is exactly
1783
- `{turn_id, timestamp, role, content}` — no tags, salience, decay, event ids,
1784
- graph links, session ids or metadata. Addressing is by `(day file, line number)`;
1785
- append-only keeps lines stable (the one lawful line-pointer exception).
1786
- Writes are queued and flushed in batches (10 records / 1s), never sync.
1787
- - **Read-side redaction**: the shard keeps 100% plaintext (forensic integrity);
1788
- secrets are redacted when `deep_raw` returns snippets, before any text reaches a
1789
- model prompt. README states local storage is plaintext.
1790
- - **Tombstones**: a committed purge appends `raw_tombstone {hash, timestamp}`;
1791
- scans skip tombstoned content hashes (no resurrection).
1792
- - **deep_raw constraints**: `start_time` and `end_time` are mandatory (missing →
1793
- `MEM_E_INVALID_INPUT`), results are capped by `raw.maxResultTokens` (default
1794
- 1000) and carry the truncation notice when cut.
1795
- - **TTL**: maintenance deletes whole day files strictly older than
1796
- `today - raw.retentionDays`; today's shard is never touched. Raw bytes are
1797
- surfaced as `panel.storage.rawBytes` and counted in the dashboard ring.
1798
- - **Automatic raw capture**: the plugin subscribes to `dsh-session`'s
1799
- `session/event` and stores every user/assistant surface message verbatim
1800
- (`raw.autoCapture: true`). The Host-injected `Current runtime context.` block is
1801
- stripped out of `content` and kept (truncated) in `metadata.runtimeContext`, so
1802
- `deep_raw` stays signal-clean. Tool output is opt-in (`raw.captureTools: false`),
1803
- **except failed tool results** (`isError`), which are always captured as
1804
- `kind: "error"`. Budgets, dedupe and retention still apply.
1805
-
1806
- ### Changed
1807
-
1808
- - Panel adds `raw`, `reviews`, and `pendingDeletes`; the settings page renders a
1809
- migration progress card while `state=migrating`.
1810
- - `Memory._scheduler` cron now reads `runtime.config` per tick, so a hot config
1811
- update changes the schedule without a restart.
1812
-
1813
- ## [1.3.1] — 2026-10-30
1814
-
1815
- ### Fixed
1816
-
1817
- - **Cold-start 404 (root cause)**: `webServer` is provided by the web-app row, which
1818
- activates *after* this plugin's `apply()`. The old code called
1819
- `ctx.get('webServer')` once and silently skipped registration when it was
1820
- absent — every cold start had no routes, while a warm reload worked. Route
1821
- registration now lives in `ctx.inject(['webServer'], child => …)`, so the child
1822
- fiber activates the moment the service appears and the routes are always
1823
- mounted. Verified live (404 → 200) and covered by a deferred-inject test.
1824
- - **Front-end death spiral**: a bodiless 404 used to be synthesized into a JSON
1825
- error, which the old retry counter treated as a protocol failure and gave up
1826
- after six attempts. `getJson` now keeps "no JSON" distinct, and the pure
1827
- `decideRetry` policy retries bodiless 404s with exponential backoff (capped at
1828
- 5s) for up to 10 minutes before surfacing `MEM_E_BOOT_TIMEOUT` with a manual
1829
- reconnect button.
1830
- - **Diagnostics**: `apply()` prints `[Hippocampus] Route registered at <iso>
1831
- (<paths>) phase=<phase>` when the routes are mounted, and
1832
- `[Hippocampus] Route registration FAILED: <reason>` if the service never
1833
- provides one.
1834
-
1835
- ## [1.3.0] — 2026-10-30
1836
-
1837
- ### Added
1838
-
1839
- - **Context folding (推币机)**: blocks evicted from the context window are no longer
1840
- dropped. A light rule folds the most recent batch into one `folded_summary`
1841
- episode tagged `status:folded` — extracting names, task statements and core
1842
- conclusions — and writes it back to the L1 log.
1843
- - **Graph association (在线联想)**: when a query touches a tag, retrieval reads the
1844
- cached graph and pulls that tag's three strongest neighbours into the candidate
1845
- pool with an explicit `penalty: 0.5`; such hits are marked `association.via` and
1846
- can never outrank a direct hit.
1847
- - **Monthly memos (月记)**: `maintain()` condenses a finished natural month into one
1848
- `status:monthly` episode. Memos do not decay (`decay = 1`) and are pulled in
1849
- first for fuzzy historical queries ("上个月", "2023-10", "去年" …).
1850
-
1851
- ### Changed
1852
-
1853
- - HTTP routes are now registered **before** tools, prompts and scheduling inside
1854
- `apply()`, so a page that wins the boot race hits a live handler answering
1855
- `state=pending` instead of a 404. The Host-side assumption is documented in the
1856
- code: `apply()` awaits nothing, and route service is expected once it returns.
1857
-
1858
- ## [1.2.0] — 2026-10-30
1859
-
1860
- ### Added
1861
-
1862
- - **`memory_checkpoint`** (`task_id`, `progress`, `updated_at`): exactly one active
1863
- heavy task. A new checkpoint demotes the previous one, one not refreshed for
1864
- seven days is demoted by `maintain()`, and `memory_admin action="active_task"`
1865
- reads it straight from the index — the active-set cap of 200 does not apply.
1866
- - **Multimodal pointers**: `memory_remember` accepts `media_url` (absolute path or
1867
- http(s) URL) plus `media_type` (`image|video|document|audio`). Inline base64 in
1868
- `content` is rejected with `MEM_E_INVALID_MEDIA` from 256 consecutive base64
1869
- characters; 200 characters is still ordinary text.
1870
- - **`decay.halfLifeDays`** (default 30, 7–365) and **`activeSet.cap`** (default 200,
1871
- 100–1000): both declared in `DEFAULT_CONFIG`, validated fail-fast by
1872
- `resolveConfig`, projected into `policy`, and editable from the settings page.
1873
- - **State handshake**: every route response now carries `state`
1874
- (`pending|in_progress|ready|failed`), and the UI retries on `state` rather than
1875
- on the HTTP status. A bodiless 404 during boot is treated as `pending` for a
1876
- 120s grace window (the routes are only mounted once the Host runs `apply()`).
1877
-
1878
- ### Changed
1879
-
1880
- - Writes before READY are refused loudly: `POST /api/hippocampus/config` answers
1881
- `409` with `MEM_E_NOT_READY` and the current state; tools already answered
1882
- `MEM_E_NOT_READY`, and their error details now include `state` and `retryable`.
1883
- - The settings page covers the full editable surface (18 keys), with the documented
1884
- hints for `storageBudgetMb`, `context.maxTokens`, `decay.halfLifeDays` and
1885
- `activeSet.cap`; saving before READY is disabled in the UI and rejected by the API.
1886
-
1887
- ## [1.1.0] — 2026-10-29
1888
-
1889
- ### Added
1890
-
1891
- - **Graph dragging**: nodes are movable with pointer events. The dragged node is
1892
- pinned for the duration, coordinates are mutated in a ref and painted straight
1893
- to the DOM (no `setState` per frame), and release unpins it and runs a short
1894
- alpha relaxation over its 1-hop neighbourhood. A pointer travel under 4px is
1895
- still a click, so selecting a label can never move the node by accident.
1896
- - **`storageBudgetMb`** (integer, default 50, range 10–1000): the storage ring's
1897
- budget is now configurable instead of hard-coded, and the ring recomputes the
1898
- moment the value is saved.
1899
- - **Full settings UI**: every editable config key is in the settings section —
1900
- switches for booleans, bounded number inputs, a select for
1901
- `identity.eventTimePolicy`, and a text field for the maintenance cron. Saving
1902
- posts one dotted-path patch through the same fail-fast validator as startup;
1903
- a rejected value shows a red banner with the `MEM_E_CONFIG_*` code and nothing
1904
- is applied. A successful save broadcasts `config-changed` so the panel
1905
- refetches stats and graph immediately.
1906
-
1907
- ### Fixed
1908
-
1909
- - Dotted config paths deeper than one level (`identity.eventTimePolicy`,
1910
- `retrieval.topK`) now nest correctly instead of producing a literal key.
1911
-
1912
- ## [1.0.0] — 2026-10-29
1913
-
1914
- First public release. The package was previously developed under the working
1915
- names `@local/dsh-memory` / `Layers-Hippocampus`; the data directory is
1916
- unchanged and legacy folders are migrated automatically.
1917
-
1918
- ### Added
1919
-
1920
- - **Layers**: append-only event log, rebuildable tag index (A/B generations),
1921
- day diaries, independent semantic layer, L2.5 trend quarantine with promotion
1922
- and burst detection.
1923
- - **Identity discipline**: canonical `content_hash`, `event_id =
1924
- hash(content_hash + event_time + occurrence_index)`, separate idempotency
1925
- index, tombstones that survive log compaction.
1926
- - **Context paging**: token budget, eviction thresholds, cumulative saved-token
1927
- accounting persisted in `state/context.json`.
1928
- - **Maintenance**: one gate for cron and Dream (`runtime.runMaintenance`), no
1929
- queueing and no backfill; a missed window is skipped, not replayed.
1930
- - **Config fail-fast**: `enableDream`, `dreamIdleMinutes`, `enableReflection`,
1931
- `graphMaxEdges` (100–2000, default 500), cron, context and temp ranges are
1932
- validated by `resolveConfig`; HTTP hot updates go through the same validator.
1933
- - **Async startup state machine** `pending → in_progress → ready | failed`, with
1934
- `POST /api/hippocampus/retry` and a UI retry banner.
1935
- - **Offline knowledge graph**: built at the end of `maintain()` from the index
1936
- (log minus tombstones), per-node Top-N neighbours, global weight order, cached
1937
- at `state/graph.json`, hard cap 2000 edges.
1938
- - **Web UI**: sidebar icon, main panel (SVG storage ring, stats, force-directed
1939
- graph with progressive reveal), and a settings section.
1940
- - **HTTP API** (same-origin, behind the Host's browser auth):
1941
- `GET /api/hippocampus/stats`, `GET|POST /api/hippocampus/config`,
1942
- `GET /api/hippocampus/graph`, `POST /api/hippocampus/retry`.
1943
- - **Tests**: 106 in-process cases (Node `node:test`) covering identity,
1944
- retrieval, L2.5, maintenance, migration, routes, graph and the client bundle
1945
- contract.
1946
-
1947
- ### Security
1948
-
1949
- - The UI never receives credentials and never calls agent tools; every number is
1950
- read through the Host's authenticated JSON routes.
1951
- - The graph route returns at most `graphMaxEdges` edges from a cached file — no
1952
- query language, no path input.
1953
-
1954
- [1.0.0]: https://github.com/382quaii/dsh-Layers-Hippocampus/releases/tag/v1.0.0
218
+ - **Docs**:`记忆插件-未完成表.md` 从「2026-11-05 待办审计」重写为「当前状态表」——
219
+ A1–A21 逐项给出关闭依据,13 项关闭、2 项 superseded、2 项并入 M3/M6、4 项明确不做
220
+ (并写明为什么不做),另列仍需外部动作的四项(npm 账号封控等)。
221
+
222
+ ## [1.6.7] — 2026-11-17
223
+
224
+ **发布链完整性修正 + 索引式提示注入(M1)。1.6.6 在 npm 上的制品(`gitHead 99a07cb`)
225
+ 是从一份**旧 checkout** 发布的,只带来 Live Compact 修复,**不含** M3(测试跨包解耦)
226
+ 与 M5(错误码边界)。1.6.7 把这两项送往 npm,并让仓库历史与已发布标签不再分叉;
227
+ M1 则是本版的主线功能——每轮 Prompt 不再为记忆**正文**付费。**
228
+
229
+ - **Added — 外部价格 / 通知接缝(M2)**。`dsh-price-tip` / `dsh-peak-runner` /
230
+ `dsh-notify-plugin` 在本机**并不存在**,因此没有「接线真实 API」可做——凭空猜服务名
231
+ 等于发明接口。本版只做**可验证的可选接缝**:
232
+ - `HostBridge.setNotifier(sink)` + `notify({title,text,kind,at})`:没有 sink 时返回
233
+ `{delivered:false, reason:'no-notifier'}` 并只记计数,**绝不发明投递通道、绝不抛错**;
234
+ sink 抛错也只记 `sink-error`,不会污染维护流程。
235
+ - `index.js` 探测一组**约定键**(`priceTip` / `notifier` / `peakRunner`,或 `notify` / `peak`),
236
+ 并接受多种方法形状(`isLowValley|lowValley|isLow|price`、`notify|send|post`、
237
+ `isPeak|peak|isHigh`)。外部价格服务优先于内置时间窗;`DSH_DREAM_PRICE` 仍可强制覆盖。
238
+ - `capabilities.externalSeams` 报告**哪条接缝真的接上了**(`{wired, source}`),
239
+ 所以「没装」是可见事实而不是静默降级。
240
+ - 一旦通知接缝可用,「Dream 因高峰被推迟」会通过它播报(内含 `dueAt`);没有接缝时
241
+ 这件事仍由持久化队列与 `dream-deferred` 事件表达,行为不变。
242
+ - **排队本来就是实装的**:`index.js` 的 `tick()` 在高峰把 LLM 蒸馏写入 `dreamQueue`
243
+ 并在谷时唤醒(`reason: 'peak-hour'`),不是丢弃,本次未改动该逻辑。
244
+ - **Changed — 多空间开关的语义澄清(M6)**。`features.multiSpace` 默认 `true`,但只有注入了
245
+ 能创建空间适配器的 `orchestrator` 服务时才真正生效——以前这个差异是**静默**的:
246
+ 用户以为开了多空间,实际在跑单空间。现在新增 `multiSpaceReason()`,返回
247
+ `'active'` / `'disabled-by-config'` / `'orchestrator-missing'` 三态,
248
+ 通过 `capabilities.multiSpaceReason` + `capabilities.multiSpaceRequested` 与
249
+ `panel.spaces.{requested,reason}` 同时暴露,设置页在多空间卡片里直接写明
250
+ 「当前被配置关闭:features.multiSpace=false」,不再把「没装适配器」和「你关了它」
251
+ 混成一个 `spaces:false`。**开关本身没有改默认值**(改默认会静默改变已部署 profile 的行为),
252
+ 改的是可观测性与文档;并有用例锁住「布尔值与理由不可能互相矛盾」。
253
+ - **Changed — 索引式提示注入(M1)**。`context.injectMode` 新增两个取值:
254
+ - `index`(**新默认**):每个记忆块只注入一行指针
255
+ `- [memory <eventId>] 标签 · 标签 · 标题`。正文不进 Prompt,需要细节时用
256
+ `memory_recall` 按 eventId / 标签取。`[Memory Blocks]` 标记名保持不变,因此缓存前缀
257
+ 语义不变;规则段多一行「这些是索引指针,正文须调 recall」,**只在 index 模式下出现**。
258
+ - `full`:沿用旧版渲染(正文前 200 字)与旧版计费(整段正文),一行代码即可回退。
259
+ - **窗口计费随渲染形态走**:`ContextEngine.tokensOf()` 在 index 模式下只计指针行,
260
+ 在 full 模式下仍计整段正文(旧口径,不动既有调优);调用方**显式传入的 `tokens`
261
+ 永远优先**,折叠与驱逐的排序不变。
262
+ - `index` 模式下 `tokens()` 的实测差异是数量级的:8,000 字符的正文约 2,000 tokens,
263
+ 指针行通常 < 60 tokens。
264
+ - `briefing` 块(运营方钉死的策略)**永不降级为指针**,始终整段渲染。
265
+ - 可编辑键新增 `context.injectMode`(`index` / `full`,非法值 fail-fast),设置页
266
+ 「上下文窗口」卡片新增下拉;简洁模式下同样可见可存。
267
+ - **Changed — 测试与兄弟包解耦(M3)**。`test/orchestrator.js` 先按包名 `dsh-layers-orchestrator/src/*`
268
+ 解析、失败再退回同级 checkout(`via: 'package' | 'sibling'`);22 个真正依赖多空间的用例改走
269
+ `orchestratorTest()`,缺包时注册为 **skipped 并带原因**而不是 import 阶段崩掉整套测试。
270
+ `makeMemory()` 的 `multiSpace` 默认值改为 `MULTI_SPACE_AVAILABLE`,杜绝 `new null()`。
271
+ 实测:两包在位 **510/510**(skipped 0);单独 checkout 时 **454 pass / 0 fail / 56 skipped**。
272
+ - **Changed — 错误码边界(M5)**。`dsh-orchestrator` 内两套命名空间是**故意**并存的:
273
+ `MEM_E_*`(从核心搬出去的引擎沿用,客户端 HTTP 映射依赖它)与 `ORCH_E_*`(路由器/去重/联邦/授权)。
274
+ 海马体侧新增单一边界 `src/errors.js#fromOrchestratorError()` + `ORCHESTRATOR_CODE_MAP`:
275
+ `ORCH_E_CONSENT_*` → `MEM_E_REQUIRE_USER_CONSENT`(三个都映射到同一处,因为修法是去问人而不是重试)、
276
+ `ORCH_E_SPACE_INVALID` → `MEM_E_SPACE_INVALID`、`ORCH_E_INVALID_INPUT` → `MEM_E_INVALID_INPUT`、
277
+ `ORCH_E_NOT_READY` → `MEM_E_NOT_READY`、`ORCH_E_FEDERATION_CONFLICT` → `MEM_E_FEDERATION_FAILED`;
278
+ **未列入的 `ORCH_E_*` 不会被拍平成 `MEM_E_IO`**,原始码保留在 `details.orchestratorCode` 里可审计。
279
+ 映射表同步写进 `dsh-orchestrator/README.md` 的「错误码边界」一节。
280
+ - **Tests**:新增 `test/v166.errorContract.test.js`(7 例)与 `test/v167.m1.test.js`(9 例:
281
+ 默认 index、指针行构成、index 计费 = 渲染行、full 保留旧渲染与旧计费、显式权重优先、
282
+ briefing 不降级、标题截断与回退、`injectMode` 校验与可编辑、规则段只在 index 出现、
283
+ recall 命中把标签与标题带进窗口且正文尾巴不出现);
284
+ `test/v156.features.test.js` 新增 M6 用例(`multiSpaceReason` 三态 + 显式关闭优先于
285
+ 缺适配器 + 「布尔值与理由不可能矛盾」的交叉断言);
286
+ `test/v167.m2.test.js`(6 例)锁住 M2 接缝:无 sink 时为 `no-notifier` 的记账型空操作、
287
+ sink 收到 payload 且被计数、sink 抛错只记 `sink-error` 不外溢、`externalSeams()` 如实报告
288
+ 「通知与高峰缺席、价格回退本地时间窗」、注入 `notifier` 服务后被自动发现并可用、
289
+ 注入 `priceTip` 后外部价格**优先于**本地时钟窗口。
290
+ 全量 **541/541**(85 个测试文件)。
291
+
292
+ ## [1.6.6] — 2026-11-16
293
+
294
+ **发布修正版:1.6.5 在 npm 上发布的是「每轮请求都裁剪工具结果」的版本——那个把上下文
295
+ 从 10% 悄悄缩到 7% 的缺陷没有随任何已发布制品走出去。1.6.6 补上这条修复。**
296
+
297
+ > **发布实况(事后核对)**:1.6.6 的 npm 制品 `gitHead 99a07cb` 来自旧 checkout,
298
+ > **只含**下面的 Live Compact 修复——M3 与 M5 当时已在主线上、但没有进这个 tarball。
299
+ > 那两项随 **1.6.7** 发出。本地 `v1.6.6` tag 已指向 `99a07cb`,与 npm/GitHub 一致;
300
+ > `99a07cb` 也已并入 `main` 历史,发布可追溯。
301
+ > 1.6.5 同理不可覆盖(`gitHead 28776c7`),其 tag 亦指向该提交。
302
+
303
+ - **Fixed — 上下文在每轮请求里被悄悄缩水("从 10% 直接掉到 7%")**。
304
+ `guardRequest` 曾在**每一次** `agent/request` 上调用宿主的 `toolResultPruner.pruneSession()`。
305
+ 宿主的 `pruneContent()` 用的是**预设预算**(ptc 预设 `thresholdChars: 8192` → 4k 头 + 1k 尾),
306
+ 而且它**只在 `compaction-basic` 的 `context-overflow` 分支里**才被调用——我们把「溢出时裁剪」
307
+ 变成了「每轮都裁剪」,一次 pass 就能掉约 80k tokens。
308
+ 现在 Live Compact **只跑本插件自己的保守策略**(`context.liveCompact`,默认 200,000 字符阈值 /
309
+ 4,000 头 / 2,000 尾 / 每请求最多 4 个节点),不再委托宿主 pruner;
310
+ 回归用例 `the guard never rewrites an ordinary tool result on a healthy request`
311
+ 断言宿主 pruner 在健康请求上**一次都不被调用**。
312
+ - **Tests**:`test/v164.windowGuard.test.js` 增加上述回归用例(12 例)。全量 **503/503**(79 个测试文件)。
313
+
314
+ ## [1.6.5] — 2026-11-15
315
+
316
+ **回归微内核:引擎只负责存储、检索与蒸馏,绝不驱动对话;蒸馏只有一个总调度器;
317
+ 面板的全部能力收进 `/memory` 指令集,且不花一分模型 Token。**
318
+
319
+ - **Added — `/memory` 指令集(0 Token)**。四条子命令通过宿主的 `commands` 服务注册,
320
+ `commands.execute()` 的语义是「parse and execute a known command **without sending it
321
+ to the model**」,因此不产生任何模型请求(测试用 `fetch` 计数断言为 0):
322
+ - `/memory resume`:拉取上一次交接摘要并**强制重新注入**当前上下文。它绕过「每会话
323
+ 每交接批次只注入一次」的去重(`armColdStartNow()` 先删掉该 `session|epoch` 的投递
324
+ 记录再布防),所以用户可以随时把摘要拉回来;没有交接时明确回「没有可恢复的交接摘要」。
325
+ - `/memory maintain`:立即触发一次后台维护(索引重建 / 月记 / L2 合并 / Dream / 冷归档),
326
+ 回报各阶段计数;已在运行时直接拒绝而不是排队。
327
+ - `/memory status`:事件数、L3 摘要数、活跃标签列表、会话 token 与窗口来源
328
+ (`host`/`config`/`default`)、静默状态、冷启动队列长度。
329
+ 这些数字全部取自面板同一份契约(`panel.global.*` + 索引快照的活跃集合),
330
+ 不再各自拼字段——早期实现读错了契约,导致整行显示成 `?`。
331
+ - `/memory mute` / `/memory unmute`:紧急静默 `[Memory Hints]`。静音时**不消费标签**,
332
+ 所以解除后提示会原样回来,而不是被会话级去重池吃掉。
333
+ - **Fixed — 月记与 Dream 重复咀嚼同一批日记**。L2.5 月记原本挂在 `maintain()` 上,与
334
+ Dream 各走各的调度,同一条 L2 日记可能先被压进月记、再被按标签蒸馏一次。
335
+ 现在 **`executeDream()` 是唯一的蒸馏总调度器**:先跑月记(只处理已结束的自然月),
336
+ 再让 Dream 处理剩下的材料。被月记吸收的事件 id 记入 `state/months.json` 的
337
+ `promoted` 映射(即 `promoted_to_monthly`),`DreamEngine.collectGroups()` 直接跳过,
338
+ 并在报告里给出 `skippedPromoted` 计数。
339
+ **为什么不写进事件本身**:raw 日志是 append-only 的唯一真相源,永不改写;标记放在
340
+ 派生状态里,语义等价且可重建。
341
+ - **Added — 原子服务接口 `getLatestHandoffSummary()`**。`ctx.get('hippocampus')
342
+ .getLatestHandoffSummary()` 返回 `{ active, state, at, sessionId, summaryEventId,
343
+ agentPreset, tailTurns, text, found }`,纯读:不装配 prompt、不消费 marker、不产生副作用。
344
+ 外部路由插件想自己决定「什么时候续上、怎么展示」时用它,而不是去解析提示词。
345
+ - **Changed — 微内核边界**。引擎半侧(`index.js` + `src/**`)不含任何宿主 UI 或追加模式
346
+ 监听:`autoNewSession` 整链已在 1.6.3 删除,本次用测试把这条边界**锁死**——源码扫描
347
+ 禁止出现 `uiWorkspace` / `startSession(` / `sessionStorage` / `appendMode` /
348
+ `onSlot(` / `slots.register(` / `ctx.slots =`。会话控制交给外部路由插件。
349
+ - **Fixed — 上下文在每轮请求里被悄悄缩水(“从 10% 直接掉到 7%”)**。1.6.4 的
350
+ `guardRequest` 在**每一次** `agent/request` 上都把宿主 `toolResultPruner.pruneSession()`
351
+ 委托执行了一遍。两处都错:
352
+ - 宿主用的预算是 **预设自己的**(ptc: `thresholdChars 8192` → 留 4k 头 + 1k 尾),
353
+ 于是一次普通的 20 KB 文件读取在下一次请求就被腰斩;
354
+ - 宿主自己只在 compaction-basic 的 `context-overflow` 分支里调它
355
+ (`this.ctx.get('toolResultPruner')?.pruneSession(agent.session)`),
356
+ 「溢出时裁剪」被我们变成了「每一轮都裁剪」。实测一次 pass 可掉 **~80k tokens**。
357
+ 现在 Live Compact **只跑我们自己的保守裁剪**:单条 `tool/result` 超过
358
+ `context.liveCompact.thresholdChars`(默认 200,000 字符)才指针化,头部 4k / 尾部 2k
359
+ 原样保留、中间换成 `deep_raw` 可取回的指针行。健康的对话**永远不会被改写**——
360
+ 宿主压缩链路的裁剪仍由宿主在真溢出时负责。
361
+ 新增回归用例锁定:请求里即使注入了假 `toolResultPruner`,`pruneSession` 的调用次数也必须为 0,
362
+ 且一条 20k 字符的正常结果不产生任何 surface 改写。
363
+ - **Tests**:新增 `test/v165.micokernel.test.js`(8 例):`/memory` 注册与全部子命令返回
364
+ 纯文本、**网络调用数为 0**、静默真的不注入提示、`resume` 在无交接时明确报错且服务接口
365
+ 与它同源、`executeDream()` 先跑月记并把日记标进 `promoted`、`maintain()` 不再产出月记、
366
+ 已晋升日记在下一轮仍被排除、以及上面那条「无 UI/追加模式监听」的源码扫描。
367
+ `test/flow.test.js` 与 `test/v156.federation.test.js` 的月记断言随调度器迁移改为
368
+ `executeDream()`。全量 **502/502**(80 个测试文件)。
369
+
370
+ > **发布说明**:1.6.5 发布到 npm 的制品(`gitHead 28776c7`)**不包含**上面那条 Live Compact
371
+ > 修复——它是在 1.6.5 发布之后才提交的。该修复进入 **1.6.6**;M3 与 M5 实际进入 **1.6.7**
372
+ > (1.6.6 的制品同样来自旧 checkout,只含 Live Compact)。
373
+
374
+ ## [1.6.4] — 2026-11-14
375
+
376
+ **修复 1M 上下文溢出(`CONTEXT_WINDOW_EXCEEDED`):交接判定的分母、分子与状态机三处
377
+ 同时失效,外加单轮超大工具输出没有任何熔断。这是一次独立的安全发版——1.6.3 从未
378
+ 发布过,它的全部内容已并入本版。**
379
+
380
+ - **Fixed — 分母错源:接入宿主真实模型窗口**。新增 `src/context/windowGuard.js` 的
381
+ `resolveWindow()`:**宿主适配器上报的窗口优先**(`llm.resolveModelInfo().context.contextWindow`,
382
+ 也接受 `tokenMeter.contextPressure().contextWindow`),`context.nativeTokenLimit` 降级为
383
+ 用户覆盖,只在宿主不可用时兜底。`panel.session.windowSource` 暴露本次用的是
384
+ `host` / `config` / `default`,事后可审计。此前本机 profile 写的 `8000` 被当成模型窗口,
385
+ 模型真实窗口是 **1,048,576**。
386
+ - **Fixed — 分子不再靠猜:`used + reserved` 公式**。判定改为
387
+ `used_tokens + reserved_completion_tokens >= window × threshold`。
388
+ 已用优先取宿主 `tokenMeter` 的测量值(含系统提示、工具 schema、历史重放),
389
+ `Math.ceil(字符数 ÷ 4)` 的自估降为下限;`reserved` 取本次请求真实的 `maxTokens`
390
+ (默认 256,000)。事故数字 854,668 + 256,000 = 1,110,668 > 1,048,576 现在能直接判出来。
391
+ - **Fixed — Fail-Fast 兜底**。新增 `agent/request` 中间件:拿到最终请求配置后重新判定,
392
+ **必定放不进窗口的请求在本地就被拦下**,抛 `MEM_E_CONTEXT_EXCEEDED`,details 里带
393
+ `usedTokens / reservedTokens / projectedTokens / window / windowSource / ratio`,
394
+ 并明确写出 “Nothing was sent to the provider”。宿主缺少 `llm` / `tokenMeter` 服务时
395
+ **绝不阻断**(降级为原有行为)。
396
+ - **Fixed — 交接状态机死锁(“80% 了却不交接”)**。`checkHandoff()` 里
397
+ `if (marker.active) return base;` 会让首次交接后的同一会话**永远**不再交接
398
+ (1.6.3 移除自动开新会话后,session id 不再变化,marker 就永久 active)。
399
+ 改为 `rehandoffDecision()`:同会话压力再涨 ≥5 个百分点(`pressure-growth`)或投影
400
+ ≥95% 硬上限(`near-hard-limit`)时清掉旧 marker 重新蒸馏;不同会话仍走原有消费路径。
401
+ - **Added — Live Compact:单轮超大工具输出熔断**。新增 `src/context/liveCompact.js`:
402
+ 单个 `tool/result` 的文本超过 `context.liveCompact.thresholdChars`(默认 200,000 字符)时,
403
+ 保留头 4,000 / 尾 2,000 字符,中间压成一行指针
404
+ (`[[hippocampus:live-compact: removed N chars … (seq=…, call=…, tool=…)]`),
405
+ 原文仍可用 `deep_raw` 取回。走宿主 surface 协议
406
+ (`append('compaction/prune')` + `append('tool/result', { surfaceOp: { op: 'replace' } })`),
407
+ 宿主自带 `toolResultPruner` 时优先委托给它。指针化按 code point 切,不会劈开代理对。
408
+ - **Tests**:新增 `test/v164.windowGuard.test.js`(11 例)锁定本次修复:宿主窗口优先于配置覆盖、
409
+ 引擎 `windowSource` 可审计、`used + reserved` 判定(含那组真实数字 854,668 + 256,000)、
410
+ `nativeState` 优先采用宿主测量值、`rehandoffDecision` 的四种判定、
411
+ 超大工具结果的指针化(含代理对不被劈开、`surfaceOp replace` 的实际形状)、
412
+ 同会话内 marker 仍 active 时 `checkHandoff` 会续交、以及
413
+ `guardRequest` 在「必超限」时抛 `MEM_E_CONTEXT_EXCEEDED` / 在「放得下」时放行 /
414
+ 在没有宿主服务时绝不阻断(降级为原有行为)。
415
+ 全量 **494/494**(79 个测试文件)。
416
+
417
+ ## [1.6.3] — 2026-11-13
418
+
419
+ **配置加载器加固:把 1.6.2 的“旧配置启动阻断”事故固化为引擎能力——先迁移、再严格校验、
420
+ 必要时安全降级,绝不让 DSH 客户端卡在“正在启动…”。**
421
+
422
+ - **Added — 冷启动注入可观测性**:`/stats` 新增 `coldStart{ pending[], injected, lastSessionId }`,
423
+ `panel.startup` / `panel.configVersion` / `panel.configWarnings` 与
424
+ `CAPABILITIES.startup` 同源(此前 `toMemoryOptions()` 没把迁移结果传给引擎,panel 报
425
+ `migrated:false` 而 capabilities 报 `true`)。
426
+ - **Fixed — 复习队列只报不消费(积压到 337 条)**:`maintain()` 现在按
427
+ `review.consumeBatchSize`(默认 40,上限 200/轮)分批消费到期行,批间
428
+ `await setImmediate` 让出主线程;每批一次 `reviews.advanceMany()` 落盘(不是每条一次写),
429
+ 并对该批做一次 `reinforce` 权重强化。`review.autoConsume` 可整体关闭。
430
+ - **Fixed — 1.6.2 遗留的两个启动/保留缺陷**:旧 profile(`retentionDays: 30` 且没有
431
+ `archiveAfterDays`)由 `migrateConfig` 派生 `29` 而不是启动失败;`prune()` 现在也会按
432
+ 月清理过期的 `.jsonl.br/.zst/.gz` 冷归档(此前只删明文,归档变相突破保留期)。
433
+
434
+ - **Added — 配置 schema 版本与迁移机制**:`src/config.js` 新增
435
+ `CONFIG_SCHEMA_VERSION = 3`;配置对象可携带 `configVersion`。加载顺序变为
436
+ **`migrateConfig()` → 严格校验**:迁移阶段只做“补值 + 告警”,从不抛错,也绝不覆盖
437
+ 用户显式写下的值。缺少 `configVersion` 的旧配置被视为 legacy(`fromVersion: 0`)并
438
+ 升级到当前版本。
439
+ - 首次落地的迁移规则:`raw.archiveAfterDays` 缺失且
440
+ `raw.retentionDays <= 新默认值(90)` 时,派生为 `Math.max(1, retentionDays - 1)`
441
+ (即 30 → 29),从而满足 `archiveAfterDays < retentionDays` 的硬约束。
442
+ - 每条迁移都写入 `console.warn`(前缀 `hippocampus/config-migration:`)并携带在
443
+ `config.warnings` 里,`apply()` 再经 `ctx.logger.warn` 输出一次——**迁移永不被静默**。
444
+ - 空配置 `{}` 视为“使用默认值”,不算 legacy,因此内部调用不会产生噪声告警。
445
+ - **Added — `strictStartup`(默认 `true`)启动安全网**:显式设为 `false` 时,若严格校验
446
+ 抛出 `MEM_E_CONFIG_OUT_OF_RANGE`,引擎会丢弃该越界键、回退到安全值并继续启动,同时
447
+ 置 `config.startup.degraded = true`、记录 `degradedReason{code,key,message}`、
448
+ 输出 `hippocampus/config-degraded:` 警告,并在 `apply()` 里额外 warn
449
+ `STARTED DEGRADED (strictStartup=false)`。
450
+ - 降级**只**覆盖越界值:`MEM_E_CONFIG_INVALID_TYPE` / `MEM_E_CONFIG_UNKNOWN_KEY`
451
+ 仍然 fail-fast(拼写错误不该被宽容)。
452
+ - `strictStartup` 自身必须是布尔值。
453
+ - **Added — 启动状态进入可观测面**:`CAPABILITIES.startup` / `CAPABILITIES.configVersion`
454
+ 与 `memory_admin action=status` 的 `panel.startup` / `panel.configVersion` /
455
+ `panel.configWarnings`。设置页与运维方可以直接看到“这份配置来自哪个 schema 版本、
456
+ 是否迁移过、是否降级启动”。
457
+ - **Added — 设置页「简洁模式」(纯显示层)**:设置页顶部新增“简洁模式 / 专业模式”切换。
458
+ 简洁模式只渲染四块——**身份、上下文窗口、系统级存储位置迁移、原始回合留存(raw)**;
459
+ raw 卡内再收敛为三项(`raw.mode`、`raw.maxTotalMb`、`raw.compressionEngine`),
460
+ 最小显著度 / 保留期 / 冷压缩阈值 / deep_raw 扫描上限全部隐藏。
461
+ - 隐藏是**纯 UI 行为,不碰配置值**:保存时 patch 被过滤为
462
+ `SIMPLE_PATCH_KEYS`(9 个可见键),文件里未显示的项保持原值;新装即默认值,
463
+ 专业模式下调过的不会被简洁模式覆盖。
464
+ - 校验同步收敛:只检查可见数字键,隐藏项的越界值不会阻断保存,Cron 非空检查也跳过。
465
+ - 模式偏好存浏览器 `localStorage`(键 `hippocampus:settings-mode`),不进插件配置、
466
+ 不影响引擎行为;读写失败一律退回专业模式。
467
+ - **Removed — 交接时“自动开启新会话”(`context.autoNewSession*`)**:交接就发生在对话
468
+ 中间,宿主会在标记后**继续同一个对话**;客户端再调 `uiWorkspace.startSession()` 只会
469
+ 额外弹出一个空对话,在“追加到原对话”的用法下毫无意义还打断体验。因此彻底移除:
470
+ - 配置层:`autoNewSession` / `autoNewSessionPoll` / `autoNewSessionIntervalSeconds`
471
+ 三个键从 `DEFAULT_CONFIG`、校验、resolved 与 HTTP 可编辑白名单中删除。
472
+ - `migrateConfig` 会**静默剥离**旧 profile 残留的这三个键并 warn(否则老用户会撞上
473
+ 未知键阻断启动)。
474
+ - 可观测面:`CAPABILITIES.autoNewSession` 与 `handoffView().autoNewSession` 删除。
475
+ - 客户端:三个设置控件、`startAutoNewSession()` 轮询器与其 `ctx.effect` 注册全部删除;
476
+ 设置页不再渲染任何“自动开新会话”开关。
477
+ - **Fixed — 新对话拿不到交接摘要与前几轮原话**(2026-11-13 用户报告):
478
+ - 根因:冷启动注入是一个**进程级一次性布尔** `coldStartPending`,被**第一个组装
479
+ prompt 的 agent** 抢先消费(子代理、标题生成等),用户真正的新对话拿到的是空。
480
+ - 改为**按会话幂等**:`runtime.coldStart = { pending: Map, injected: Set, lastSessionId }`,
481
+ 以 `session|handoffEpoch` 为键;`noteColdStart()` 在「新 session id 的首个
482
+ `session/event`」与「`agent/created`」两处布防(同键复用、已被注入过的直接跳过、
483
+ 过期 5 分钟未消费自动丢弃、最多 8 条 pending 有界淘汰),
484
+ `promptState(assemblyContext)` 用宿主传给 `systemPrompt.context` 的
485
+ `assemblyContext.agent.id` 与当前 session id 做匹配,注入后写入 `injected` 集合并
486
+ 有界淘汰(64)。**兄弟 agent 先装配不会再吞掉用户的注入**——这是单槽位实现仍会
487
+ 踩的坑:标题生成器或子代理随后布防会覆盖并且消费掉用户的那一条。
488
+ - `handoff.json` 标记新增 `tailTurns`:交接蒸馏时把最后 5 轮(role + 文本,每条
489
+ ≤400 字,内存环形缓冲 12 条、跨会话自动清空)写进标记;
490
+ `[Previous Context Tail]` 优先回放这些**原话**(`- user: …` / `- assistant: …`),
491
+ 没有 tailTurns 时才回退到最近业务事件。
492
+ - `context.coldStartInjectRecentTurns` 默认由 `false` 改为 **`true`**:只给摘要会让
493
+ 新对话接不上具体语境。
494
+ - 即使两个开关全关,匹配到的 pending 也会被消费掉,不会遗留到下一次无关会话。
495
+ - **可观测**:`/stats` 新增 `coldStart{ pending[], injected, lastSessionId }`(`runtime.coldStartView()`),
496
+ 运维方不必读 prompt 就能区分“已布防未装配”与“已注入”。
497
+ - **`panel.startup` / `panel.configVersion` / `panel.configWarnings` 与 `capabilities.startup`
498
+ 对齐**:此前 `toMemoryOptions()` 没有把迁移结果传给引擎,panel 报的是“未迁移”默认值,
499
+ 而 capabilities 报的是真相——同一个进程两处说法不一致,现由 `toMemoryOptions` 一并透传。
500
+ - **Fixed — 复习队列只报不消费(积压到 337 条)**:`maintain()` 里
501
+ `ReviewSchedule.tick()` 的结果只被写进报告,**从来没有人推进它**,于是新装用户的
502
+ `state/reviews.json` 里每条都是 `lastAt: null`、`dueAt` 停在初始间隔,队列只增不减
503
+ (现场:`total 346 / due 337`)。两个后果:复习面板永远是“全到期”,且 recall 拿不到
504
+ 强化锚点——衰减曲线相当于“写下之后从未被碰过”。
505
+ - 现在 `maintain()` 会真正消费到期行:`_consumeDueReviews()` 取出到期 id,
506
+ **分批**(默认 30–50 条,`review.consumeBatchSize = 40`)调用批量 `reinforce()`
507
+ (权重 1,日志即锚点,不改任何字段),再用 `ReviewSchedule.advanceMany()` 一次性
508
+ 推进 `lastAt` / `step` / `dueAt`。
509
+ - **性能防线**:每批之间 `await new Promise(setImmediate)` 让出事件循环,HTTP 路由与
510
+ prompt 组装不会被一个巨大积压卡住;单次维护总量上限 `review.consumeMaxPerRun = 200`,
511
+ 再多就跨多次维护轮次排空(报告里的 `remaining` 说明还剩多少)。
512
+ - **一次文件写/批**:新增的 `advanceMany()` 把“逐条 advance = 每条一次读+一次原子写”
513
+ 变成“整批一次”,337 条积压不再是 337 次 fsync。
514
+ - 开关:`review.autoConsume`(默认 `true`)可关;`review.enabled: false` 时不会消费。
515
+ 失败的批次不中断维护(`lastAt` 保持 null,下一轮自然重试),错误写进
516
+ `report.reviewConsumeError`。三条新键均进入 HTTP 可编辑白名单。
517
+ - **Fixed — 1.6.2 遗留的两个启动/保留缺陷(随 1.6.3 一并锁定)**:
518
+ - **旧 profile 启动阻断**:旧配置只写 `raw.retentionDays: 30`、没有 `archiveAfterDays`,
519
+ 而 1.6.2 的新默认值是 90,硬校验 `archiveAfterDays < retentionDays` 直接抛错,
520
+ `apply()` 失败 → 插件整体不注册 → `/api/hippocampus/*` 全部 404,设置页永远停在
521
+ “正在启动…”。现在 `migrateConfig()` 在**未显式配置**且冲突时自适应派生
522
+ `Math.max(1, retentionDays - 1)`(30 → 29)并告警;**显式**写下越界值仍然 fail-fast。
523
+ - **`.jsonl.br` 冷归档永不清理**:`prune()` 原先只删明文分片,Brotli/Gzip/Zstd 归档
524
+ 变成“保留期之外的永久副本”,等于变相突破 `retentionDays`。现在 `prune()` 按
525
+ `cutoffMonth` 整月删除过期归档,并同步从 `state/raw-archive.json` 抹掉记录
526
+ (返回 `removedArchives`)。
527
+ - **Tests**:`test/v163.migration.test.js`(9 例)锁定本次教训——旧配置(仅
528
+ `retentionDays: 30`)可启动且 `archiveAfterDays` 派生为 29;显式冲突在
529
+ `strictStartup: true` 下阻断、在 `false` 下降级启动;降级不吞类型错误与未知键;
530
+ 以及 1.6.2 生产 profile 的原始形状可被完整解析。`test/helpers.js` 的夹具改走同一
531
+ 迁移步骤,`test/status.test.js` 的 panel 形状契约同步新增三个字段。
532
+ `test/v163.ui.test.js`(5 例)锁定简洁模式契约:`Section` 的 `hidden` 短路、
533
+ 14 个专业模式卡片全部带 `hidden: simpleMode`、raw 只剩三项、保存与校验按白名单收敛。
534
+ `test/v163.reviewQueue.test.js`(5 例)锁定复习消费契约:到期行被消费且 `step`/`lastAt`
535
+ 前进、强化记录数 == 消费数、超出单轮预算的积压跨轮次排空、`autoConsume:false` 不动队列、
536
+ 整批只写一次 `reviews.json`。
537
+ `test/v156.autoSession.test.js` 重写为「该功能已移除」契约(配置无该键、旧 profile
538
+ 迁移剥离、路由/能力面不暴露、客户端无轮询器);
539
+ `test/v160.coldStart.test.js` 重写为按会话注入契约(无标记不布防、摘要+尾部各一次、
540
+ 兄弟 agent 先装配不吞注入、两个会话各注入一次、**两条 pending 先布防后装配也各得其份**、
541
+ 双关不遗留 pending、tailTurns 优先、stats 暴露 coldStart 状态)。
542
+ 全量 **483/483**(78 个测试文件)。
543
+
544
+ ## [1.6.2] — 2026-11-11
545
+
546
+ **补丁版:修复冷数据归档与保留期的时间冲突,并把“打破日志线性增长”的三层机制并入正式记录。**
547
+
548
+ - **Fixed — 设置页卡在“正在启动…”并报 `MEM_E_NETWORK: HTTP 404`**(2026-11-13):
549
+ 1.6.2 的强校验 `archiveAfterDays < retentionDays` 与**旧 profile**(`raw.retentionDays: 30`、
550
+ 从未写过 `archiveAfterDays`)冲突,`apply()` 抛 `MEM_E_CONFIG_OUT_OF_RANGE`,插件根本没加载,
551
+ 所有 `/api/hippocampus/*` 路由缺失 → UI 永远 404。现在:
552
+ - `archiveAfterDays` **未被显式配置**时按 `retentionDays - 1` 派生,并置
553
+ `raw.archiveAfterDaysDerived: true`(旧 profile 可直接启动);
554
+ - **显式**给出越界的 `archiveAfterDays` 仍然 fail-fast(配置错误不该被静默原谅)。
555
+ - **Fixed — 归档文件不受 retention 约束**:`prune()` 原来只删 `.jsonl` 明文分片,`.jsonl.br`
556
+ 归档会永久堆积,等于变相突破保留期。现在整月归档的末日晚于 cutoff 才保留,否则连
557
+ `state/raw-archive.json` 记录一起删除,返回 `removedArchives`。
558
+
559
+ - **修复冷数据归档时间冲突**:冷归档阈值与 TTL 保留期原本互相挤压(`archiveAfterDays` 与
560
+ `retentionDays` 同为 30/90 量级,冷分片常在归档前就被 TTL 删除)。现在默认值上调为
561
+ `archiveAfterDays: 90`、`retentionDays: 365`,并保留 fail-fast 校验
562
+ (`archiveAfterDays` 必须严格小于 `retentionDays`),同时新增 `raw.coldAccessWindowDays: 90`,
563
+ 也就是“近 90 天零访问”才允许归档。
564
+ - **实施多档保留策略(含遗忘性保存与全保存)**:raw 层保留谱系落地为
565
+ `raw.mode: off | salience | all` ——
566
+ `off` 为不保存(遗忘性保存,仅保留 L1 之上的记忆)、`salience` 为默认的高价值保存、
567
+ `all` 为全保存(受 `maxTurnKb` / `maxBytesPerDay` / `maxTotalMb` 预算约束);
568
+ 另加 `raw.distillPrune`(默认 false):蒸馏产物覆盖第 i 天、且该分片已出
569
+ `raw.hotWindowDays` 热窗时,允许物理清理 raw 原文,**必经 Tombstone 防复活**。
570
+ L2 继续走同类项合并(`l2Merge`),L3 增加硬熔断 `semantic.maxEntries`(默认 100)+ LRU 淘汰,
571
+ 语义层随“事件重要性”而非“对话条数”增长。
572
+ - **优化长窗口压缩与高频引用去重**:
573
+ - 冷归档默认改用 **Brotli quality 11**(`.jsonl.br`,极限压缩),`gzip`(9) / `zstd` 仍可选,
574
+ 全部来自 Node 内置 `node:zlib`,零外部依赖;读取按扩展名流式解压、命中即停。
575
+ - 高频重复的超长内容(工具 schema / 系统提示块,≥512 字符且出现 ≥2 次)在建索引时
576
+ 只存一份到 `templates.json`,事件侧改为 `contentRef` 引用(`src/index/templates.js`),
577
+ 索引加载时还原原文;**日志本体不参与替换**,raw 逐行真相、`deep_raw` 与行级游标不受影响。
578
+ - 稀疏行索引(每 64 行采样)继续用于跳过时间窗不重叠的分片并复用 `lineCount`。
579
+
580
+ ### 1.6.2 详细变更
581
+
582
+ - **Breaking the linear log curve — three layers** (`test/v162.nonlinear.test.js`, 9 cases):
583
+ - **Compression layer**: cold classification is now MULTI-dimensional (age >
584
+ `raw.archiveAfterDays` **AND** zero access for `raw.coldAccessWindowDays` **AND** no
585
+ `pinned` / `status:handoff` / hot-tag record). Defaults move to
586
+ `archiveAfterDays=90`, `coldAccessWindowDays=90`, `retentionDays=365`. Cold
587
+ archives default to **Brotli quality 11** (`.jsonl.br`, "极限压缩") instead of
588
+ gzip; `gzip`/`zstd` stay selectable and all three are Node built-ins.
589
+ Recently-read old shards stay PLAINTEXT for O(1) cursor scans.
590
+ - **Encoding layer (referential dedup, NOT columnar)**: repeated long content
591
+ (tool schemas / system prompt blocks, ≥512 chars, ≥2 occurrences) is stored ONCE
592
+ in `templates.json` at the INDEX layer; events carry `contentRef` instead of a
593
+ duplicate copy. Index loads resolve refs, so readers always see exact content —
594
+ the log itself is untouched (`src/index/templates.js`).
595
+ - **Semantic layer**: raw stops being the only home of truth. `raw.distillPrune`
596
+ (opt-in) lets `maintain()` physically clean raw shards that are outside
597
+ `raw.hotWindowDays` **and** already covered by an L3 summary — always through the
598
+ tombstone path, so nothing resurrects. L3 gains a hard capacity breaker
599
+ (`semantic.maxEntries`, default 100) with LRU retirement recorded as append-only
600
+ `semantic_retire` events.
601
+
602
+ ## [1.6.1] — 2026-11-07
603
+
604
+ **Version fully un-frozen (user directive 2026-11-07): normal semantic versioning
605
+ resumes; 1.6.1 was the release that followed 1.6.0.**
606
+
607
+ - **Archive month detail UI**: the panel's raw section now shows `indexedShards` /
608
+ `archiveCount` StatCards plus a **collapsible month table** (月份 / 引擎 / 归档大小 /
609
+ 归档时间, month-DESC, collapsed by default). `panel.raw` carries `archivedBytes`,
610
+ `totalBytes`, `engines:{gzip,zstd}`, `savedBytes`, `compressionRatio` (null when
611
+ unmeasured) and `archiveMonths[]` with `at`/`bytesBefore`/`bytesAfter`; older hosts
612
+ degrade to “—” instead of breaking the panel.
613
+ - **Segment-token audit** (`docs/AUDIT-2026-11-07-segment-token.md`): no P0
614
+ same-segment re-injection exists; the six injection surfaces are documented with
615
+ their dedup mechanisms. Its two P3 items are now IMPLEMENTED:
616
+ - **P3-1** the `[Active Task]` event id also joins the block dedup pool, so one
617
+ event can never be injected both as Active Task and as a recall block;
618
+ - **P3-2** `[Persona & Traits]` is memoized by the L3 shape (`summaryId` +
619
+ `updatedAt` + count); unchanged L3 costs one signature, not a re-render.
620
+ - **Raw cold-tier archiving (zero external deps)**: on `maintain()`, daily shards
621
+ older than `raw.archiveAfterDays` (default **7**) are merged per calendar month
622
+ into one `raw-archive-YYYY-MM.jsonl.gz` via Node's built-in `zlib`, then the
623
+ plaintext shard is removed. Archiving runs at most once per month and SKIPS any
624
+ shard that is recently read (`state/raw-access.json`), `pinned`,
625
+ `status:handoff`, or carries a hot active-set tag. `deep_raw` and hash restore
626
+ stream the archive with `createGunzip()` line-by-line (no full read), report
627
+ `archiveErrors`/`notes: archive-corrupt:<name>` for a corrupt archive, and keep
628
+ plaintext `.jsonl` reads unchanged. `raw.retentionDays` default moves **30 → 90**
629
+ and must stay strictly above `archiveAfterDays` (fail-fast otherwise).
630
+ - **`/stats` panel: archive + index visualization**: `panel.raw` now reports
631
+ `archiveCount`, `archivedBytes`, `totalBytes`, `archiveMonths`, `engines`
632
+ (`{gzip,zstd}`), `savedBytes` (sum of bytesBefore−bytesAfter), `compressionRatio`
633
+ (null when no measured archive) and `indexedShards`. Each archive records
634
+ `bytesBefore`/`bytesAfter` in `state/raw-archive.json`, so the ratio and saved
635
+ bytes are real measurements, not estimates. The panel gains two StatCards
636
+ (“raw 索引覆盖”, “raw 冷归档”) with graceful “—” for an older host, plus a
637
+ collapsible **archive month table** (月份 / 引擎 / 归档大小 / 归档时间, month-DESC,
638
+ collapsed by default); `archiveMonths` rows carry `at`/`bytesBefore`/`bytesAfter`.
639
+ 4 cases in `test/v161.stats.test.js` + 2 UI contract cases.
640
+ - **Sparse line index for raw shards** (performance audit item C): one
641
+ `<day>.jsonl.idx.json` per shard, sampled every 64 lines with
642
+ `{line, offset, timestamp}` plus `bytes/mtimeMs/lineCount/minTs/maxTs/sorted`.
643
+ `deep_raw` uses it to SKIP a shard whose time range cannot overlap the window
644
+ (without opening the file) and to reuse `lineCount` for absolute `hit.line`
645
+ numbers (no second pass). Built offline by `maintain()` (50 shards/round,
646
+ progressive), deleted with its shard by `prune()`, and silently bypassed when
647
+ missing, stale (bytes/mtime mismatch), corrupt, or non-monotonic. `stats()`
648
+ reports `indexedShards`. 6 cases in `test/v161.rawIndex.test.js`.
649
+ - **Compression-engine selection (zero install)**: `raw.compressionEngine`
650
+ (`gzip` default | `zstd`) + a settings-page engine picker with an
651
+ enable/disable button. Zstd uses Node's BUILT-IN `node:zlib` zstd — nothing is
652
+ downloaded and there is no package to uninstall; "停用" switches back to gzip.
653
+ Archives are `raw-archive-YYYY-MM.jsonl.gz` / `.jsonl.zst`, dispatch is by
654
+ extension, and a legacy gzip archive stays readable after switching to zstd.
655
+ When the runtime lacks zstd the config silently falls back to gzip and
656
+ `capabilities.compression` reports `{engine, fallback, zstd, node}` for the UI.
657
+ - **Raw retention tiers documented**: the raw layer exposes exactly three modes —
658
+ `off` (keep nothing), `salience` (default: high-value turns/code/stack/errors only),
659
+ `all` (bounded by `maxTurnKb`/`maxBytesPerDay`/`maxTotalMb`) — plus
660
+ `retentionDays` (default 90) and `pinned` never pruned. README/ARCHITECTURE now
661
+ describe these implemented tiers only.
662
+ - **Fixed — settings page rendered blank**: the compression-engine card referenced a
663
+ bare `payload` that only exists in other components' scopes; it now uses the local
664
+ `statsPayload` and the shared `Select` component (not a fake `type:'select'` on
665
+ `Field`). `test/v161.ui.test.js` pins the scope rule so the whole settings page
666
+ cannot be taken down by one card again.
667
+
668
+ - **Recall bound-based early exit** (performance audit item A): every score is
669
+ `salience × decay × tagAffinity(≤3) × lexicalBoost(≤1) × association(≤1) ×
670
+ timeBoost(≤1.3) × handoff(≤1)`, so `salience × 3.9` is a hard upper bound.
671
+ Candidates are visited salience-DESC and scoring stops as soon as that bound
672
+ cannot beat the current k-th score. `pinned` hits bypass the cut, the best-k
673
+ window keeps the bound exact (ties still visited), and the result reports
674
+ `pruned` + `notes: pruned:<n>`. Complexity unchanged in the worst case
675
+ (`O(K log K)` ordering) but the per-candidate decay/similarity work is skipped
676
+ for the long low-salience tail.
677
+ - Regression: pinned decay stays exactly 1 (bypass path), monthly memos unchanged.
678
+ - **456 tests green** (64 files).
679
+
680
+ ## [1.6.0] — 2026-11-06
681
+
682
+ > Version note: 1.6.0 was the FIRST release after the temporary 1.5.7 freeze; the
683
+ > 2026-11-07 directive removed all freeze language and resumed normal versioning.
684
+ Cold-start wake-up + user-controlled cold-start injection:
685
+
686
+ - **Anti-"customer service" wake-up** (static `memory:policy` prefix): the model is
687
+ told it has continuous long-term memory, must not open with "how may I help you",
688
+ and should recall the recent topic before replying.
689
+ - **`context.coldStartInjectSummary`** (default **true**): on the first prompt
690
+ assembly of a brand-new conversation, inject `[Cold-Start Summary]` — the handoff
691
+ summary event when present, else the top-3 L3 semantic summaries (≤800 chars).
692
+ - **`context.coldStartInjectRecentTurns`** (default **false**): inject
693
+ `[Previous Context Tail]` with the last ≤5 business episodes (200 chars each).
694
+ - **`[Cold-Start Detected: Active Space=…, Recent Topic=…]`** header when either
695
+ switch is on; the block is volatile-tail only (prompt-cache prefix untouched) and
696
+ is consumed exactly once per new conversation.
697
+ - Both switches off → no historical blocks; the static wake-up policy still ships.
698
+ - UI: two independent toggles in the settings page's session group; HTTP-editable.
699
+ - **416 tests green** (64 files).
700
+
701
+ ## [1.5.7] — 2026-11-04
702
+
703
+ > Historical note: 1.5.7 shipped under a temporary version freeze; the 2026-11-07
704
+ > directive removed ALL freeze language and resumed normal semantic versioning
705
+ > (current version: 1.6.2). The sentence below is the historical 1.5.7 statement.
706
+
707
+ **Version freeze (historical, superseded): 1.5.7 was the shipped release.**
708
+ This release folds in everything added after the 1.5.6 draft — Orchestrator
709
+ federation/dedupe wiring, read-time merge, cross-space recall aggregation (opt-in
710
+ `features.crossSpaceRecall`), durable Orchestrator state, the settings-page GitHub
711
+ installer, the verified automatic new-conversation handoff (with configurable
712
+ once/interval detection), low-valley Dream Phase 2, space deletion, graph
713
+ interaction, and the rest of the 1.5.6 section below. Annotations of the form
714
+ `v1.5.6:` below record the version in which a feature was introduced; they are
715
+ history, not the current version. **411 tests green** (64 files).
716
+
717
+ ## [1.5.6] — 2026-11-03
718
+
719
+ **`deep_raw` now scans by line cursor: a huge day shard is never loaded whole.**
720
+ The black box is read newest-first in fixed chunks; peak memory is one chunk plus
721
+ one partial line (test-locked), not the file size. `hit.line` keeps its absolute
722
+ 1-based semantics. **411 tests green** (was 303).
723
+
724
+ ### Changed — raw scan / restore (zero-dependency, O(chunk) memory)
725
+
726
+ - **`readLinesReverse(file, {chunkSize, onBuffer})`** (`src/rawStore.js`): reads a
727
+ file backwards in 64 KiB chunks, yielding one line at a time; the trailing
728
+ newline does not produce a phantom empty line. `onBuffer` reports the live
729
+ buffer size for tests.
730
+ - **`deep_raw` scan** rewrote the whole-shard `readFileSync + split` path:
731
+ newest-first, one `JSON.parse` per line, line bytes counted as they are read,
732
+ hit results collected per shard. `hit.line` is computed from the shard's line
733
+ count via ONE extra bounded streaming pass, paid only when that shard produced
734
+ a hit (so a miss costs no counting pass).
735
+ - **`restoreByHash`** streams forward via `readline`; **`_loadTombstones`** streams
736
+ synchronously with a `StringDecoder` (multi-byte boundaries preserved);
737
+ **`_hashesFor`** streams asynchronously (so `RawStore.capture()` is now async —
738
+ only internal callers exist; the public `captureRaw()` contract is unchanged).
739
+ - **Engine-side result ceiling**: `MAX_SCAN_RESULTS = 500` caps one scan even if an
740
+ embedder passes `limit: 5000`; `budget.maxHits` is reported, `truncated` is true
741
+ when the cap is reached.
742
+ - **Observability**: `scanned.peakBufferBytes` exposes the largest buffer the
743
+ scanner ever held (proves the memory bound).
744
+
745
+ ### Added — stability hardening (same 1.5.6, no extra version bump)
746
+
747
+ - **Recall response cap**: `context.maxInjectTokens` (default 4000, 256–100 000,
748
+ fail-fast) bounds the JSON one recall returns. `Memory.applyPayloadBudget()`
749
+ keeps hits in rank order (the first is always kept), then semantic/temp summaries;
750
+ a cut is loud: `truncated: true`, `payload: {maxTokens, estimatedTokens, dropped}`
751
+ and a `payload-budget` note. Editable over HTTP and rendered in the settings page
752
+ with a tooltip.
753
+ - **`Memory.close()` releases resources**: `RawStore.close()` clears the flush timer
754
+ and synchronously persists queued turns before the log closes; `Memory.close()`
755
+ then detaches the scheduler, clears oversized-tag hints and calls
756
+ `IndexManager.release()` to drop the A/B views. Idempotent.
757
+ - **Event-loop lag monitoring**: `src/eventLoop.js` (`createLagMonitor`) wraps
758
+ `perf_hooks.monitorEventLoopDelay`; `maintain()` yields 50ms between phases and
759
+ `IndexManager.rebuild` yields between read/build/catch-up/swap once the measured
760
+ max delay crosses 100ms. The report carries
761
+ `eventLoop: {maxMs, p99Ms, meanMs, yields, thresholdMs}`. Honest boundary: a
762
+ synchronous builder cannot be preempted, so the granularity is phase-level and the
763
+ numbers expose an oversized phase.
764
+
765
+ ### Added — pre-ingest tagging (same 1.5.6, no extra version bump)
766
+
767
+ - **`src/tagging.js` / `extractTags()`**: deterministic anchors derived from content
768
+ shape — named error types (`error:typeerror`), Node errno codes
769
+ (`error:econnrefused`), fenced-code language (`lang:python`), HTTP status
770
+ (`http:500`), file path basename (`file:index.js`) and explicit task statements
771
+ (`task:…`). No LLM, no dependencies, stable ordering.
772
+ - **Write gate** (`Memory.stage`): model-provided tags always win; only an untagged
773
+ write runs the heuristic. Tags are deduplicated and capped by `tagging.maxTags`
774
+ (1–5, default 2). Inferred anchors are recorded on `meta.auto_tagged` /
775
+ `meta.auto_tags` (provenance, not a silent rewrite of what the caller asserted).
776
+ - **raw stays pure**: the black box still receives exactly
777
+ `{turn_id, timestamp, role, content}` — the test locks the four-field shape.
778
+ - **Miss is a warning**: `MEM_E_AUTO_TAG_MISS` goes to the Host log via
779
+ `Memory.setWarnHook` (wired in `index.js`) and increments
780
+ `panel.autoTag.misses`; the write proceeds untagged.
781
+ - **Config**: `tagging.autoTag` (default true) and `tagging.maxTags` (1–5), both
782
+ fail-fast, HTTP-editable and rendered in the settings page.
783
+
784
+ ### Added — pinned memory (same 1.5.6, no extra version bump)
785
+
786
+ - **`remember({ pinned: true })`**: a lesson/experience that must survive time.
787
+ It stores `meta.pinned = true` (provenance included in `content_hash`) and is
788
+ refused with **`MEM_E_PINNED_TAG_REQUIRED`** unless the caller supplies at least
789
+ one tag — an untriggerable lesson would be dead memory.
790
+ - **Never decays**: `projectEpisode` exposes `pinned`; `deriveTagTable` gives a
791
+ pinned event `decay = 1`, keeps its tag un-archived, and protected from the
792
+ `maxPostingsPerTag` drop; `deriveActiveSet` admits pinned tags regardless of
793
+ score or the cap.
794
+ - **Ranks first**: recall gives every matching pinned record `decay = 1`, exempts
795
+ it from `minScore`, and orders pinned hits ahead of all others
796
+ (`pinned-first:N` note).
797
+ - **Observability**: `panel.global.pinned` counts pinned records.
798
+ - Tool surface: `memory_remember.pinned` (boolean) is documented and passed
799
+ through; `bulk_ingest` items accept the same field.
800
+
801
+ ### Changed — relevance-first prompt hints (same 1.5.6, no extra version bump)
802
+
803
+ - **Global "most active tags" map removed from the prompt.** `runtime.promptState()`
804
+ now renders only tags that lexically overlap the CURRENT user turn (max 5), via
805
+ `src/utils/memoryHints.js` (`selectRelevantTags` / `renderMemoryHints`).
806
+ Internal bookkeeping tags (`status:*`, `month:*`, `context:*`, `active_task`)
807
+ are never hinted; no match means the section is simply absent (no padding).
808
+ - **Cache-safe placement**: `[Memory Hints]` is rendered AFTER `[Memory Blocks]`,
809
+ so a per-turn hint never disturbs the cacheable prefix (rules only).
810
+ - **Input source**: prompt assembly receives no message text, so the plugin tracks
811
+ the last `user/message` from `session/event` (`runtime.lastUserText`); other
812
+ surface events never overwrite it.
813
+ - The legacy `renderMemoryMap` / `composePrompt({map})` API remains for callers
814
+ and is still unit-tested, but the plugin no longer injects the map.
815
+
816
+ ### Added — capability flags & microkernel boundary (same 1.5.6, no extra version bump)
817
+
818
+ - **`features.multiSpace` (default true)** and **`features.crossSpaceTransfer`**
819
+ (default mirrors multiSpace). Both are fail-fast, HTTP-editable and rendered in
820
+ the settings page; turning multiSpace off implies crossSpaceTransfer off, and the
821
+ explicit contradictory combination is refused.
822
+ - **Strict single-space mode**: with multiSpace off, every routed read/write whose
823
+ `targetSpaceId` is not `default` answers **`MEM_E_FEATURE_DISABLED`** (before any
824
+ I/O); `createSpace` / `ensureSpace` / `warmup` refuse too, and the `/spaces` route
825
+ reports `['default']` with `capabilities.spaces=false` so the client hides
826
+ create/selector affordances instead of 404-ing.
827
+ - **Tools follow the flags**: `space_transfer` / `transfer_to_global` are neither
828
+ registered nor advertised in the prompt section when the capability is off.
829
+ - **`Memory.open('/abs/dir')`** is now the single-space form (the Orchestrator owns
830
+ the multi-space walk); the options-object form stays supported.
831
+ - **`Memory.warmup({targetSpaceId?, dataDir?})`**: lazy, read-only index warm-up for
832
+ the UI / Orchestrator — no maintenance, no writes; unknown/relative dataDir fails
833
+ fast.
834
+
835
+ ### Added — host lifecycle: compensating Dream (same 1.5.6, no extra version bump)
836
+
837
+ - **`src/hostBridge.js`** subscribes to the Host's process-local events
838
+ `agent/created` and `session/created` (the "session start" signals) through a plain
839
+ `{on, off}` bus seam, plus `agent/disposed` for teardown.
840
+ - **Compensation rule**: on a session start, if no Dream ran for
841
+ `dream.compensateAfterHours` (default 24, 1–720, fail-fast) AND the price window
842
+ permits, run exactly ONE compensating Dream through the shared
843
+ `runtime.runMaintenance('compensate')` gate — never a second concurrent run, never
844
+ a queue.
845
+ - **Price is injected, never guessed**: `setPriceProbe(fn)` / `DSH_DREAM_PRICE=low|high`.
846
+ Unknown price + an LLM-backed Dream ⇒ skip (`price-unknown`); unknown + local-only
847
+ Dream ⇒ allowed. A known peak ⇒ skip (`peak`).
848
+ - **Observability**: `runtime.hostStatus()` and `/stats`'s top-level `host` report
849
+ `sessionStarts / compensations / skipped / lastSkipReason / dreamDue / lowValley`.
850
+ - `enableDream:false` disables compensation; `agent/created`/`session/created` do not
851
+ otherwise affect memory writes (raw capture remains on `session/event`).
852
+
853
+ ### Added — Dream tunables in the settings page (same 1.5.6, no extra version bump)
854
+
855
+ - The **safe** Dream subset is now exposed to `/stats` + `/config` and rendered in
856
+ the settings page: `useLlm`, `minGroupSize`, `maxGroupsPerRun`, `maxSummaryChars`,
857
+ `maxSourceChars`, `maxEventsPerGroup`, `llmTimeoutMs`, `failureThreshold`,
858
+ `cooldownMinutes`, `compensateAfterHours` (all fail-fast validated).
859
+ - **Credentials stay private**: `dream.llm.{baseUrl,model,apiKey}` is neither exposed
860
+ by the routes nor editable over HTTP nor rendered in the form; it comes only from
861
+ the profile or `DSH_DREAM_LLM_*` env. A test asserts the key never appears in the
862
+ `/stats` payload.
863
+
864
+ ### Added — L2 multi-merge (`merged_into`, same 1.5.6, no extra version bump)
865
+
866
+ - **`src/l2Merge.js`** condenses duplicate same-tag L2 episodes into ONE durable
867
+ record, offline at the end of `maintain()` (after monthly memos; a failure never
868
+ fails maintenance).
869
+ - **Pinned and ordinary groups are strictly separated** — pinned merges only with
870
+ pinned; ordinary only with ordinary. A pinned merge keeps `pinned: true` and
871
+ inherits every tag.
872
+ - **Text**: earliest/latest time + deduplicated core text (each source capped), the
873
+ whole line capped by `l2Merge.maxSummaryChars` (ASCII ellipsis so identity
874
+ canonicalisation cannot make it longer).
875
+ - **Federated metadata**: `meta.global_tags` is copied into the merged record's
876
+ `meta` and **never becomes a tag**, so it cannot enter the sub-space inverted index;
877
+ `projectEpisode` exposes it as `event.globalTags` for the merge layer only.
878
+ - **Append-only marking**: sources are recorded as merged in
879
+ `state/l2-merge.json` (`mergedSourceIds`); the log is untouched and originals stay
880
+ recoverable. A second pass merges nothing (idempotent) and `status().panel.l2Merge`
881
+ reports the bookkeeping.
882
+ - **Config `l2Merge`**: `enabled` (default true), `minGroupSize` (2–20, default 2),
883
+ `maxGroupsPerRun` (1–50, default 5), `maxSummaryChars` (100–2000, default 400);
884
+ fail-fast, HTTP-editable and rendered in the settings page.
885
+
886
+ ### Added — L3 semantic tag invariant (same 1.5.6, no extra version bump)
887
+
888
+ - **`SemanticStore.upsert` is strict**: an L3 summary with zero usable tags is
889
+ refused with **`MEM_E_SEMANTIC_TAG_REQUIRED`** — such a summary could never be
890
+ reached by tag-driven retrieval (dead knowledge).
891
+ - **Offline paths degrade instead of failing**: delete-consolidation and trend
892
+ promotion derive tags from content heuristics (`extractTags`) and, if even that
893
+ yields nothing, write an explicit provenance anchor (`origin:unlabelled-episode` /
894
+ `origin:unlabelled-trend`). Maintenance and the two-phase delete pipeline therefore
895
+ never break on historical untagged events.
896
+ - **Historical data is read-only degraded**: summaries written before the invariant
897
+ remain readable and are marked `degraded: true` in `list()` /
898
+ `semanticSummaries()`; nothing is silently rewritten.
899
+
900
+ ### Added — working mode survives a handoff (same 1.5.6, no extra version bump)
901
+
902
+ - **Handoff marker carries the Host agent preset** (the UI's “工作模式”): the marker
903
+ written at rollover now records `agentPreset`, fed by the live adapter through
904
+ `memory.setHandoffPresetProvider()`.
905
+ - **A new conversation restores it before its first turn**: `agent/created` is a
906
+ serial Host event, so the bridge awaits `agentPresets.select(agent, preset)` for
907
+ `source === 'startup'` from a different session. `resume`, the marker-owner session
908
+ and markers without a preset are never overridden.
909
+ - **Never breaks agent creation**: a failed `select` is reported in
910
+ `runtime.lastPresetInherit` and the log, then creation proceeds.
911
+ - **Tracking**: `agent-preset/selected` updates the mode; tool boundaries and prompt
912
+ assembly opportunistically read `agents.currentInitiator()` + `agentPresets
913
+ .composedPreset()` and **backfill an older marker** that predates this feature.
914
+ - **Observability**: `/stats` exposes `agentPreset` + `presetInherit`, and
915
+ `hostStatus().presetSelections` counts observed selections.
916
+
917
+ ### Changed — physical split: multi-space engine moved out (same 1.5.6)
918
+
919
+ - **`src/spaces/spaceRouter.js` and `src/spaces/transfer.js` are GONE from this
920
+ package.** The full multi-space router (per-space FIFO chains, lazy child stores,
921
+ `MEM_E_*` validation) and the cross-space transfer engine now live in
922
+ `dsh-orchestrator` (`src/spaceRouter.js`, `src/transfer.js`).
923
+ - The core compiles only `src/spaces/singleSpace.js`: the `default` space is the
924
+ owner handle; every named-space operation answers **`MEM_E_FEATURE_DISABLED`** with
925
+ an explicit "install dsh-orchestrator" hint. No silent fallback to `default`.
926
+ - **Adapter injection is the wiring seam**: the Host's optional `orchestrator`
927
+ service supplies `createSpaceAdapter({owner, dataDir, openChild})` and `transfer`;
928
+ `Memory.open({spaces|spacesFactory, transfer})` accepts the same seam for embedders.
929
+ Without the service the plugin advertises `capabilities.spaces=false`, registers
930
+ only the eight single-space tools, and `/spaces` reports `default` only.
931
+ - A profile with `features.multiSpace:true` but no Orchestrator logs a loud warning
932
+ and runs the strict single-space core (visible in `/stats.capabilities`), instead
933
+ of pretending the capability exists.
934
+
935
+ ### Added — first batch: orchestrator service + 3 experience fixes (same 1.5.6)
936
+
937
+ - **Orchestrator service registration**: `apply()` now installs a real Host service
938
+ (`ctx.provide('orchestrator', …)` inside `ctx.effect`, so unloading removes it).
939
+ It exposes `createSpaceAdapter`, `transfer`, `dirFor`, `status`, `federation`,
940
+ `dedupe`, `consent` and `router`. The core decides the capability through
941
+ `config.multiSpaceActive(config, hasOrchestrator)`.
942
+ - **Reserved system tags isolated from display**: `status:*`, `folded-summary` and
943
+ `active_task` are filtered out of the knowledge graph (`buildGraph` + defensive
944
+ `view`) and the L1.5 tag tree (`rebuildTree` + persisted-tree/ghost filtering).
945
+ The inverted index still keeps them (handoff/recall internals need them).
946
+ - **`[Active Task]` injection**: prompt assembly prefers the active handoff summary,
947
+ otherwise the newest event carrying a `task:` tag, and renders it as an
948
+ unconditional top block (`[Active Task]`) once per session.
949
+ - **Fallback hints**: `selectRelevantTags` accepts `fallbackTags`; when the current
950
+ input has no lexical overlap (e.g. “继续”), the previous turn's matched tags (max 2)
951
+ are carried into `[Memory Hints]`.
952
+ - **Session-scoped injection dedup**: `runtime.injection` keeps per-session `ids` and
953
+ `tags`; hints, `[Active Task]` and recall blocks already injected are filtered on
954
+ later turns. SessionStart and rollover reset the pool, so the next session receives
955
+ the handoff content again.
956
+ - **Space deletion (UI + engine)**: `SpaceRouter.deleteSpace(id, {confirm})` closes
957
+ the child handle, evicts its queues/caches and removes the directory (refusing
958
+ `default` and requiring `confirm:true`). `Memory.deleteSpace` / `runtime.deleteSpace`
959
+ gate the same rules (named space only; `MEM_E_FEATURE_DISABLED` in the strict
960
+ single-space core). The HTTP route reuses `POST /spaces` with
961
+ `{action:'delete', space_id, confirm:true}`; an **unknown action is a 400** and
962
+ never falls through to CREATE. The SpaceSelector renders `🗑 删除空间` only for a
963
+ named space AND only when the new **`capabilities.spacesDelete`** handshake is
964
+ true — an old/pre-delete host therefore hides the button instead of answering the
965
+ misleading “空间已存在”. When `capabilities.spaces` is false the entire space UI
966
+ (selector, create/delete, current-space chip) disappears silently.
967
+
968
+ ### Added — local low-valley Dream scheduling (same 1.5.6)
969
+
970
+ - **No external price plugin required**: `src/priceWindow.js` computes Beijing-time
971
+ peak/valley locally (weekday 09–12 / 14–18 peak; lunch, nights and weekends low).
972
+ Chinese holidays are NOT modelled (the calendar moves yearly); `DSH_DREAM_PRICE=low|high`
973
+ or a Host price probe still override it.
974
+ - **The Host bridge gets a default probe** from `isLowValley()`, so a compensating
975
+ Dream skips peaks (`reason:'peak'`) and runs locally in the valley.
976
+ - **Idle LLM Dream defers instead of spending at peak**: `runtime.tick()` writes a
977
+ durable `state/dream-queue.json` (`pending, dueAt, reason:'peak-hour'`), emits
978
+ `dream-deferred`, and runs the queued Dream as soon as the valley opens — the queue
979
+ survives a restart, so a missed window is not lost.
980
+ - **Config `dream.onlyLowValley`** (default true; fail-fast, HTTP-editable, settings
981
+ toggle). A local-only Dream (no LLM) is never gated by price.
982
+ - `/stats` exposes `dreamWindow` (low/reason/nextLowAt), `dreamQueue` and `dreamTimer`.
983
+ - **Phase 2 — wake timer + sleep correction**: `src/dreamTimer.js` arms ONE wake-up
984
+ at the queued due time / next valley (injectable timers, `unref`ed). On fire it
985
+ re-reads the CLOCK and the WINDOW: a late wake after an OS sleep is reported
986
+ (`lateMs`, `catchUp`) and runs; a wake that lands in a peak re-arms for the next
987
+ valley instead of spending. Boot arms from the persisted queue, so a queue left by
988
+ a previous run catches up with delay 0. Disposal cancels the timer.
989
+ `dreamTimer` status (arms/wakes/lateWakes/reschedules/runs) is exposed on `/stats`.
990
+
991
+ ### Added — Federation / cross-space dedupe wiring (same 1.5.6)
992
+
993
+ - **Federation on write**: after a successful write the engine reports the record's
994
+ BUSINESS tags (never `status:*` / `month:*` / `active_task`) to the Orchestrator's
995
+ global `FederationMap` with the space id; a tag seen in two spaces becomes ONE
996
+ global node listing both. A missing/broken service can never fail the write.
997
+ - **Dedupe on monthly memos**: `generateMonthlyMemos()` claims `sha256(content)` in
998
+ the Orchestrator's `ContentRegistry` as `monthly:<spaceId>`; a sibling space with
999
+ the identical monthly workload skips its copy and reports
1000
+ `monthly.skipped`/`skippedEntries` (owner traceable). Same-space reruns are
1001
+ idempotent.
1002
+ - Services arrive through the existing `orchestrator` adapter extras; spaces carry
1003
+ their own `spaceId` (`path.basename(childDir)`), the default space is `default`.
1004
+ - **Read-time merge on recall**: monthly memos now persist `meta.source_event_ids`,
1005
+ and `projectEpisode` exposes `sourceEventIds`. `Memory.mergeRecallHits()` feeds the
1006
+ recalled hits through `ContentRegistry.mergeForRead()`: a memo wins over the events
1007
+ it owns, duplicate `contentHash` collapses monthly-first, and the payload reports
1008
+ `merge: {space,monthly,droppedOwnedByMonthly,droppedDuplicateContent,total}`. Only
1009
+ when the Orchestrator dedupe service is present; the pure core payload shape is
1010
+ unchanged.
1011
+ - **Cross-space recall aggregation**: `Memory.recallAcrossSpaces()` queries every open
1012
+ space under its own lock, tags each hit with `spaceId`, and folds the union through
1013
+ the same `mergeForRead()` (raw hits are requested with `mergeRecall:false` so the
1014
+ aggregation sees owned events before the memo hides them). It is **opt-in**:
1015
+ `features.crossSpaceRecall` defaults to **false**, is fail-fast (true without
1016
+ multiSpace is a contradiction), HTTP-editable and rendered in the settings page.
1017
+ Only when `crossSpaceRecall:true` does `runtime.recall()` use this path; otherwise
1018
+ the single-space payload is unchanged (`mode` is never `cross-space`).
1019
+ `mode:'cross-space'`, `spaces`, `merge` and per-hit `spaceId` are reported.
1020
+
1021
+ ### Tests
1022
+
1023
+ - New `test/v156.rawscan.test.js` (5 cases): newest-first + absolute line number
1024
+ (5000-line shard), turn-budget truncation without reading the head, engine result
1025
+ ceiling, `readLinesReverse` peak buffer ≤ chunk + one line over a 20k-line file,
1026
+ and `restoreByHash` over the streaming path.
1027
+ - New `test/v156.hardening.test.js` (5 cases): recall payload truncation and
1028
+ under-budget pass-through, `maxInjectTokens` fail-fast, `close()` resource release
1029
+ and idempotency, lag monitor yield after a 120ms block, maintenance `eventLoop`.
1030
+ - New `test/v156.tagging.test.js` (7 cases): extraction matrix, untagged write gets
1031
+ an anchor and becomes recallable, raw purity (four fields), manual tags win +
1032
+ dedupe, miss warning + panel counter, `autoTag:false`, config fail-fast.
1033
+ - New `test/v156.pinned.test.js` (3 cases): pinned without tags refused and no
1034
+ write, one-year decay still `decay=1` + index/tag flags + pinned-first ranking,
1035
+ pinned tag stays in the active set after a 400-day maintenance.
1036
+ - New `test/v156.hints.test.js` (4 cases): selector matrix (match/unrelated/internal/
1037
+ empty), hint rendering, prompt tail contains only matching tags after the block
1038
+ marker with a stable prefix, `session/event` user turn tracking.
1039
+ - New `test/v156.features.test.js` (5 cases): flag fail-fast + implied transfer-off,
1040
+ strict single-space engine + capabilities/tools absent, transfer-only-off,
1041
+ defaults unchanged, `Memory.open(string)` + lazy `warmup()`.
1042
+ - New `test/v156.host.test.js` (6 cases): price normalisation; session start runs one
1043
+ compensating Dream; unknown price + LLM skipped; peak skipped; not-due / disabled /
1044
+ in-flight refused; MockHostEnvironment integration through `apply()` + `hostStatus`
1045
+ surfaced on `/stats`; `dream.compensateAfterHours` fail-fast.
1046
+ - New `test/v156.dreamui.test.js` (3 cases): safe Dream subset exposed / credentials
1047
+ absent from the payload; tunables editable over HTTP while `dream.llm.*` is not;
1048
+ settings page renders the section and offers no credential field.
1049
+ - New `test/v156.l2merge.test.js` (4 cases): pinned/ordinary strict separation with
1050
+ global-tag metadata preserved as meta (never a tag); a lone ordinary record is not
1051
+ dragged into the pinned group; `maxSummaryChars` cap + `enabled:false`; config
1052
+ fail-fast. Older fixtures disable `l2Merge` so their exact index-count assertions
1053
+ stay deterministic.
1054
+ - New `test/v156.l3tag.test.js` (4 cases): strict upsert refusal; delete-consolidation
1055
+ derives `error:typeerror` / `origin:unlabelled-episode` instead of dead knowledge;
1056
+ trend promotion derives tags before writing L3; historical untagged summaries are
1057
+ readable but `degraded`.
1058
+ - New `test/v156.preset.test.js` (6 cases): marker records the working mode; a new
1059
+ conversation restores it through `agentPresets.select`; older markers are
1060
+ backfilled from the live agent; resume / same-session / marker-without-preset never
1061
+ override; a failed select does not fail creation; `agent-preset/selected` keeps the
1062
+ tracked mode current.
1063
+ - New `test/v156.singleSpace.test.js` (3 cases): the core works for `default` and
1064
+ refuses named read/write/create/ensure/transfer; without the Orchestrator the plugin
1065
+ advertises `spaces:false`, registers eight tools and never advertises a dead tool in
1066
+ the prompt; injecting the adapter restores ten tools and `spaces:true`.
1067
+ - Updated: manifest 1.5.5 → 1.5.6; settings page gains `context.maxInjectTokens`,
1068
+ the pre-ingest tagging section, Dream tunables and the L2-merge section; editable
1069
+ contract gains `tagging`, `features`, `dream` and `l2Merge`; panel contract gains
1070
+ `global.pinned`, `autoTag` and `l2Merge`; `plugin.test` prompt contract now asserts
1071
+ relevance hints instead of the removed global map.
1072
+ - New `test/v156.firstBatch.test.js` (5 cases): reserved status tags never reach the
1073
+ graph/tag tree; `[Active Task]` from the handoff summary and from a `task:` event;
1074
+ fallback hints reuse the previous turn's tags; session dedup blocks the second
1075
+ injection and resets on a new session.
1076
+ - New `test/v156.spaceDelete.test.js` (5 cases): engine deletion with confirm/default/
1077
+ missing rules; strict single-space refusal; **`capabilities.spacesDelete` versioned
1078
+ handshake** (an old host hides the button, so a delete request can never be
1079
+ misread as CREATE); `POST /spaces {action:'delete'}` removes the store and returns
1080
+ the refreshed list; unknown actions answer 400 instead of falling through to
1081
+ CREATE; the UI source carries the capability guard, the button, the human confirm
1082
+ and the default-space guard.
1083
+ - **Graph interaction layer** (`test/v156.graph.test.js`, 4 cases): Ctrl/Cmd+drag
1084
+ pans the canvas (plain drag still moves a node), Ctrl/Cmd+wheel zooms around the
1085
+ cursor via a non-passive native listener (plain wheel keeps page scroll),
1086
+ double-click on blank space resets the view, and the frozen initial layout runs
1087
+ through `separateOverlaps()` so nodes never start piled on top of each other.
1088
+ The header/footer advertise the interaction.
1089
+ - New `test/v156.lowValley.test.js` (4 cases): Beijing peak/valley boundaries and
1090
+ next-low computation; `dream.onlyLowValley` fail-fast + editable; a peak-hour idle
1091
+ Dream is deferred durably and runs at the valley; the Host bridge probe follows the
1092
+ window while `DSH_DREAM_PRICE` remains an override.
1093
+ - New `test/v156.federation.test.js` (2 cases): business tags federate into one
1094
+ global node across spaces while internal tags are skipped; the first space claims a
1095
+ cross-space monthly memo and the sibling reports `skipped` with the owner.
1096
+ - New `test/v156.lowValley2.test.js` (4 cases): peak wake re-arms (never runs); a
1097
+ sleep-delayed wake reports `lateMs`/`catchUp`; a past-due queue in the valley arms
1098
+ delay 0; runtime integration: peak deferral -> timer fire -> queue cleared and
1099
+ `dreamTimer.runs === 1`.
1100
+ - New `test/v156.readMerge.test.js` (2 cases): a recalled monthly memo drops the
1101
+ events it owns and reports merge stats; without the dedupe service the recall
1102
+ payload is unchanged.
1103
+ - New `test/v156.crossSpaceRecall.test.js` (2 cases): a recall returns hits from every
1104
+ open space with provenance; a monthly memo hides its owned event even when recorder
1105
+ in another space, while the other space still contributes.
1106
+ - New `test/v156.crossSpaceRecallFlag.test.js` (3 cases): default false + fail-fast
1107
+ (`true` without multiSpace is a contradiction, non-boolean rejected); flag true
1108
+ aggregates open spaces; flag false keeps the single-space payload.
1109
+ - **Settings-page GitHub installer**: new `POST /api/hippocampus/orchestrator/install`
1110
+ (requires `{confirm:true}`) delegates to the Host's
1111
+ `pluginManager.installBundle('git+https://github.com/382quaii/dsh-Layers-Orchestrator.git', {enabled:true})`,
1112
+ short-circuits when the service is already present, and reports
1113
+ `applied | restart-required | manual | failed`. The settings page ships a
1114
+ “从 GitHub 安装 dsh-orchestrator” button (human confirm dialog) plus the repo link;
1115
+ without `pluginManager` it shows the exact manual steps instead of failing silently.
1116
+ - **Automatic new conversation on handoff (verified feasible)**: the Host exposes
1117
+ `agents.create/resume` and, decisively, the CLIENT service
1118
+ `uiWorkspace.startSession()` — the same action the “+” button uses. A client-half
1119
+ controller polls `/stats`, and when `handoff.active && handoff.autoNewSession` it
1120
+ calls `uiWorkspace.startSession(undefined, {agentPreset})` once per handoff marker
1121
+ (sessionStorage guard, lifecycle-owned interval, capability-guarded no-op on old
1122
+ hosts). New config `context.autoNewSession` (default **true**, fail-fast,
1123
+ HTTP-editable, settings toggle), plus `context.autoNewSessionPoll`
1124
+ (`interval` | `once`, default `interval`) and
1125
+ `context.autoNewSessionIntervalSeconds` (5–3600, default 15): the settings page
1126
+ now exposes a “按间隔轮询 / 只检查一次” select and an interval slider; the client
1127
+ configures its timer from the FIRST stats response (`once` clears the recurring
1128
+ timer). The workspace-file handoff scheme is no longer needed and stays documented
1129
+ only as a fallback.
1130
+ - **Fixed — new-conversation failure `tool "subagent" is already registered`**:
1131
+ handoff preset inheritance no longer calls `agentPresets.select()` when the new
1132
+ session is ALREADY composed with the marker's preset. A redundant recompose
1133
+ re-mounted the preset's `@deepseek-ai/dsh-tool-subagent` row and aborted session
1134
+ creation; the skip is recorded as `presetInherit.reason='already-composed'` and
1135
+ locked by a regression test in `test/v156.preset.test.js`.
1136
+ - **Persona section + generic custom decay (v1.5.7)**:
1137
+ - `[Persona & Traits]` is its own prompt section (`name:'persona'`, **order 100**),
1138
+ rendering the ≤10 highest-confidence L3 semantic summaries (live store read, not
1139
+ the recall cache). The memory block/policy/reflection sections keep 2450/2455/2460.
1140
+ - `service.remember()` accepts **`customDecayRate`** (finite, 0 < rate ≤ 10) OR
1141
+ **`customHalfLifeDays`** (integer 1–36500), never both. The value is normalised to
1142
+ `meta.decay_rate`, projected as `decayRate`, and applied as
1143
+ `effectiveHalfLife = policyHalfLife / decayRate` for THAT record only. No
1144
+ tag-prefix logic exists anywhere in the engine — an emotion plugin decides the
1145
+ semantics by passing the parameter.
1146
+ - **Cross-plugin `ctx.provide('hippocampus', service)`** (user decision 2026-11-05:
1147
+ in-process service only, NO HTTP write surface): `apiVersion=1`, `ready()`,
1148
+ `capabilities()` (declares `l3Traits:10` plus per-method support), `remember()`
1149
+ (L2-only; non-L2 layers are redirected with a warning; returns
1150
+ `{status,eventId,eventTime,duplicate}`), `recall()`, `runMaintenance(source)`
1151
+ (never queues: a running pass answers `MEM_E_MAINTENANCE_RUNNING`; manual passes
1152
+ are rate-limited to 30 s while `cron` bypasses), `stats()/handoffView()/
1153
+ promptState()` read-only snapshots and `onDispose()` hooks. The service disappears
1154
+ with its plugin fiber; later calls answer `MEM_E_SERVICE_DISPOSED`. New codes
1155
+ `MEM_E_MAINTENANCE_RUNNING`, `MEM_E_SERVICE_DISPOSED`, `MEM_E_FEDERATION_FAILED`
1156
+ are registered append-only (8 cases in `test/v157.service.test.js`).
1157
+ - **Durable Orchestrator state**: `<root>/state/orchestrator.json` now persists the
1158
+ global federation map and the monthly-memo claims (atomic tmp+rename on every
1159
+ mutation); it is loaded before the services become observable, and a corrupt file
1160
+ is treated as empty instead of failing activation — a restart no longer forgets
1161
+ cross-space dedupe.
1162
+ - Full suite: **411 tests / 411 pass / 0 fail**, 64 test files. Orchestrator:
1163
+ **31/31** (`service` + `spaces` deletion + `persistence` round-trip/corrupt state).
1164
+ **Installed locally**: desktop profile gets a `link:` dependency + an ordered patch
1165
+ insert BEFORE the hippocampus entries, so the service exists at activation. Two
1166
+ Cordis constraints were fixed on the way: `apply()` must return **undefined**
1167
+ (the return value is treated as an effect → `TypeError: Invalid effect`), and the
1168
+ service is registered directly with `ctx.provide` (itself an effect). The market
1169
+ catalog still does **not** list it: that needs an npm publish / catalog submission.
1170
+ - Added `docs/RELEASE-1.5.6.md`: release notes + the exact push/tag/npm/market
1171
+ commands that require the operator's credentials (none executed here).
1172
+
1173
+ ## [1.5.5] — 2026-11-03
1174
+
1175
+ **Offline Dream distillation: an optional LLM pass that can never take Dream down.**
1176
+ Same-tag L2 records are distilled into one durable, provenance-carrying record.
1177
+ The LLM leg uses **Node's built-in `fetch` only** (charter v2.0 #1: still zero
1178
+ dependencies); endpoint / model / key are injected through config or
1179
+ `DSH_DREAM_LLM_*` env and are never hard-coded, logged, or returned by HTTP.
1180
+ Every failure — no config, network down, timeout, non-JSON — silently degrades to
1181
+ the deterministic local merge and records `MEM_E_DREAM_LLM_FALLBACK`. **303 tests
1182
+ green** (was 295).
1183
+
1184
+ ### Added — Dream LLM distillation (`src/dream.js`, `Memory.executeDream`)
1185
+
1186
+ - **Structured output**: the model must answer JSON `{"summary","confidence"}`;
1187
+ `summary` is capped at `dream.maxSummaryChars` (default 200). Fenced code,
1188
+ non-JSON, missing fields and over-long summaries are all treated as LLM failure.
1189
+ - **Zero-dependency transport**: Node's global `fetch` against an
1190
+ OpenAI-compatible `/chat/completions`; `Authorization: Bearer` only when a key is
1191
+ configured. No SDK, no `node-fetch`, no new `package.json` dependency (test-locked).
1192
+ - **Absolute timeout**: `AbortController` + `Promise.race` under
1193
+ `dream.llmTimeoutMs` (default 15s); the timer is always cleared in `finally`.
1194
+ - **Local fallback**: earliest/latest time + deduplicated core text, capped to
1195
+ `maxSummaryChars`. Degradation warns `MEM_E_DREAM_LLM_FALLBACK` and is visible in
1196
+ `status().panel.dream.lastFallback`.
1197
+ - **Provenance**: the distilled record always carries
1198
+ `meta.source_event_ids` (deduped, sorted) and `meta.distilled_by` (`llm|local`);
1199
+ a re-run never merges the same source twice (`state/dream.json` bookkeeping).
1200
+ - **Circuit breaker**: `failureThreshold` (default 3) consecutive failures open the
1201
+ breaker for `cooldownMinutes` (default 60); afterwards a half-open state allows
1202
+ exactly one probe — success closes it, failure re-opens. Exposed as
1203
+ `panel.dream.circuit`.
1204
+ - **Single-flight + serial**: a concurrent `executeDream()` is refused
1205
+ (`dream-in-flight`); within one run groups are processed strictly serially, so a
1206
+ slow provider can never exhaust connections or accumulate queued work.
1207
+ - **Offline only**: `executeDream()` is called exclusively from the `dream` branch
1208
+ of the maintenance gate, after `maintain()` converged; the online
1209
+ `recall`/`remember` paths never touch the network.
1210
+
1211
+ ### Config
1212
+
1213
+ - New `dream` group (fail-fast validated): `useLlm`, `minGroupSize` (2–50),
1214
+ `maxGroupsPerRun` (1–50), `maxSummaryChars` (40–2000), `maxSourceChars`
1215
+ (80–4000), `maxEventsPerGroup` (2–50), `llmTimeoutMs` (500–120000),
1216
+ `failureThreshold` (1–20), `cooldownMinutes` (1–1440), and
1217
+ `llm.{baseUrl,model,apiKey}`. The `llm` block is deliberately **not** part of the
1218
+ UI/HTTP config projection, so a credential can never leak through the panel.
1219
+
1220
+ ### Tests
1221
+
1222
+ - New `test/v155.dream.test.js` (8 cases): no-config local fallback with full
1223
+ provenance; LLM success (URL/header/body/JSON parse); non-JSON degradation;
1224
+ fetch timeout degradation; single-flight refusal; circuit open → no fetch →
1225
+ half-open single probe → close; `dream` config fail-fast matrix; `package.json`
1226
+ dependency red line.
1227
+ - Updated: status-panel contract gains `dream`; manifest 1.5.4 → 1.5.5.
1228
+ - Full suite: **303 tests / 303 pass / 0 fail**, 41 test files.
1229
+
1230
+ ## [1.5.4] — 2026-11-02
1231
+
1232
+ **Hotfix: the automatic handoff state machine can no longer wedge a session, and
1233
+ recursive handoff summaries are cut off at the source.** Incident: recursive
1234
+ `交接摘要` generations inflated the ratio past the native window and a handoff that
1235
+ failed could leave the machine stuck, blocking new sessions. **295 tests green**
1236
+ (was 286).
1237
+
1238
+ ### Fixed — state machine (no deadlock, Fail-Fast with graceful degradation)
1239
+
1240
+ - **`checkHandoff()` never rejects**: a distillation error, a timeout (default 5s,
1241
+ injectable per call) or a marker-write failure degrade to a `state:"failed"`
1242
+ marker carrying `summaryError` and return immediately. The next session starts
1243
+ regardless.
1244
+ - **New-session transition resets everything**: `observeSessionTokens()` always
1245
+ establishes the new session's own baseline, consumes a marker belonging to a
1246
+ different session, and **releases `_handoffInFlight`**, so a hung handoff guard
1247
+ can never own the next session. A same-key restart (estimate halved after reset)
1248
+ is treated as a new baseline too.
1249
+ - **Stale marker consumption happens before early returns**, so a fresh session
1250
+ cannot inherit "handoff active" forever.
1251
+ - **Outer watchdog in `_maybeAutoHandoff()`** in addition to the inner one: even if
1252
+ `checkHandoff` itself hangs, the in-flight flag is released in `finally`.
1253
+
1254
+ ### Fixed — recursion
1255
+
1256
+ - **`_distillHandoffTail()` refuses handoff content** by tag (`status:handoff`) and
1257
+ by the `交接摘要` text prefix, in both the live-context path and the indexed
1258
+ fallback. Output is hard-capped at 1200 characters; the idempotency key includes
1259
+ the timestamp so distinct epochs never collide. (No more summary-of-summary.)
1260
+ - **`status:handoff` is internal**: 2% weight in normal recall and excluded from the
1261
+ recent-memory list, so real facts always outrank handoff bookkeeping.
1262
+
1263
+ ### Added — escape hatches and cleanup
1264
+
1265
+ - **`Memory.resetSessionState()` / `memory_admin action=reset_session` /
1266
+ `POST /api/hippocampus/session/reset` / settings-page 「强制重置交接状态(逃生舱)」**:
1267
+ clears the live token baseline, the in-flight guard and the active marker. It
1268
+ rewrites only `state/`; durable memories are untouched.
1269
+ - **`Memory.repairHandoffSummaries()` + `scripts/repair-handoff.mjs`
1270
+ (`npm run repair-handoff`)**: finds recursive/excess handoff generations
1271
+ (recursive = >=2 `交接摘要` markers) and parks them in the two-phase
1272
+ `pending_delete` queue. Dry-run by default; `--reset-marker` consumes a stuck
1273
+ marker.
1274
+ - Panel session status now exposes `handoffState` / `handoffDegraded` /
1275
+ `handoffErrorCode`; a degraded handoff is visible in the status bar instead of
1276
+ silently locking.
1277
+ - New error code **`MEM_E_HANDOFF_FAILED`**.
1278
+
1279
+ ### Tests
1280
+
1281
+ - New `test/v156.handoff.test.js` (9 tests): recursion refused by tag/prefix and
1282
+ fallback path; throwing/hanging distillation degrades without rejecting; new
1283
+ session resets ratio and releases the stuck guard; handoff summary ranking and
1284
+ list isolation; `resetSessionState` preserves memories; repair dry-run + pending
1285
+ delete; admin tool + HTTP escape hatch (route table 8).
1286
+ - Route contract 7 → 8, manifest 1.5.4.
1287
+ - Full suite: **295 tests / 295 pass / 0 fail**, 40 test files.
1288
+
1289
+ ## [1.5.3] — 2026-11-02
1290
+
1291
+ **Hotfix: space creation no longer exposes a raw `MEM_E_SPACES: HTTP 404`, and
1292
+ invalid/conflicting space names are rejected by the ENGINE with
1293
+ `MEM_E_SPACE_INVALID`.** Incident: a new client bundle called
1294
+ `/api/hippocampus/spaces` against a host process that predated the route (the same
1295
+ process also 404s `/memories`). Fixed on three layers plus a route-drift test.
1296
+ **286 tests green** (was 270).
1297
+
1298
+ ### Added — release hygiene
1299
+
1300
+ - **Benchmark Protocol v1 (`scripts/bench-protocol.mjs`, `npm run bench`)**: the only
1301
+ sanctioned way to publish a throughput number. Each measured run gets a fresh
1302
+ `os.tmpdir()` store, one discarded same-process warmup precedes 5 measured runs,
1303
+ and the report carries MEDIAN + min/max/spread. It makes no speed assertions
1304
+ (a shared/AV-scanned machine must report, not fail), so single-run noise cannot
1305
+ become an architecture conclusion again. Replaces the deleted single-run
1306
+ `scripts/confidence-ab.mjs`.
1307
+ - **Multi-space fixed-overhead coverage (`test/v154.release.test.js`)**: N=10
1308
+ physical spaces — bounded per-space boot (<500ms median), lazy root boot
1309
+ (`spaces.open=[]`, children never eagerly opened), uniform per-space storage
1310
+ (max/min ≤1.35), linear total bytes (≤1.3×N), per-space fixed overhead <256KB.
1311
+ - **Dead config removal**: `context.minInjectConfidence` is gone end-to-end
1312
+ (default/validation/projection, HTTP-editable key,
1313
+ `applyConfidence`/`MIN_INJECT_CONFIDENCE` retrieval pass, recall
1314
+ `confidence`/`lowConfidence` annotations and low-confidence notes, obsolete A/B
1315
+ script). Supplying the old key fails fast with `MEM_E_CONFIG_UNKNOWN_KEY`
1316
+ (`details.removedIn = "1.5.3"`), so a profile cannot keep believing it works.
1317
+ - Test watchdog default 30s → 60s (the in-process suite boots real stores/spaces and
1318
+ legitimately takes ~15–25s; the watchdog now only fires on real hangs).
1319
+
1320
+ ### Added — tool schema pruning
1321
+
1322
+ - **`tools.disabled` config (default `[]`)**: every registered tool definition costs its
1323
+ JSON schema in prompt tokens on EVERY turn (~1.1–1.2k tokens of baseline tax). A
1324
+ closed suffix vocabulary (`remember/checkpoint/recall/capture/bulk_ingest/reinforce/forget/space_transfer/transfer_to_global/admin`)
1325
+ lets an operator prune low-frequency tools; `remember`/`recall`/`admin` are CORE
1326
+ and cannot be disabled. A typo/prefix/full name, a core tool, or a duplicate aborts
1327
+ config resolution with **`MEM_E_INVALID_TOOL_NAME`** (fail-fast, never silently
1328
+ ignored). The register wrapper skips disabled suffixes AND the `memory` prompt
1329
+ section stops advertising them, so the schema prune cannot lie to the model.
1330
+ Editable over HTTP (`tools.disabled`) and rendered in the settings page as a
1331
+ checkbox catalog with core-不可关闭 / low-frequency tooltips. Takes effect on the
1332
+ next host start/reload (tool registration happens at activation).
1333
+
1334
+ ### Fixed
1335
+
1336
+ - **Route-drift lock**: a new test parses the client `API` constant table and
1337
+ proves every path equals the backend `MEMORY_API` value verbatim, and that the
1338
+ registered route table contains them all. Adding a route on one side without the
1339
+ other now fails CI instead of 404-ing in production.
1340
+ - **Capability handshake**: `/stats` (ready AND booting) and `GET /spaces` now carry
1341
+ `capabilities: { version, spaces, memories, transferConsent, multiSpace }`.
1342
+ The client checks `capabilities.spaces` BEFORE calling `POST /spaces`; if the
1343
+ host is older it shows a version hint and disables the action instead of firing a
1344
+ request that 404s. `memories` is gated the same way (old host → "当前宿主版本不
1345
+ 支持记忆列表", not `MEM_E_MEMORIES`).
1346
+ - **Human error copy**: every space-create failure now renders a complete sentence.
1347
+ 404 / route-missing / network → `创建失败:底层引擎未响应,请检查版本或联系架构师`;
1348
+ invalid name → `创建失败:空间名称无效——需以小写字母/数字开头,只能含 a-z 0-9 . _ -(最长 64)`;
1349
+ duplicate → `创建失败:空间「33」已存在,请换一个名称`; reserved → `创建失败:该名称是
1350
+ 系统保留名,请换一个`. The `MEM_E_SPACES: HTTP 404` template is gone from the bundle.
1351
+ - **`MEM_E_SPACE_INVALID` (400)**: `validateNewSpaceId` + `Memory.createSpace` reject,
1352
+ before any directory/JSONL write: empty/whitespace, wrong charset (`Bad`, `bad id!`,
1353
+ path separators, `..`, `.`), >64 chars, trailing dot (Windows alias), Windows
1354
+ device names (`con`, `nul`, `com1`, …), `default` (always exists), an existing
1355
+ space (conflict), and a non-directory path collision. Creation returns `201`,
1356
+ conflicts/invalid ids `400 MEM_E_SPACE_INVALID`.
1357
+ - Fresh spaces are created from `POST /spaces` with a strict non-idempotent
1358
+ `runtime.createSpace`; the lazy `ensureSpace` used by transfer keeps its
1359
+ idempotent semantics.
1360
+
1361
+ ### Tests
1362
+
1363
+ - New `test/v153.spaces.test.js` (7 tests): client↔backend route-path equality
1364
+ (the anti-404 lock), a real dispatch through the CLIENT path against the
1365
+ registered host route table (handler answers 201, never a router 404),
1366
+ invalid/reserved matrix, engine conflict-before-write, HTTP 201/400 + capability
1367
+ handshake, human-copy mapper (no raw 404), capability gating for old hosts.
1368
+ - Updated: `POST /spaces` assertions 200 → 201 strict creation; manifest 1.5.3.
1369
+ - Full suite: **286 tests / 286 pass / 0 fail**, 39 test files (includes
1370
+ `v154.release.test.js`).
1371
+ - **Note (deployment)**: the live host process observed during the incident still
1372
+ 404s `/spaces` and `/memories` — it must be restarted/reloaded for the new routes
1373
+ to serve; until then the new client degrades with the version hint above instead
1374
+ of a naked 404.
1375
+
1376
+ ## [1.5.2] — 2026-11-02
1377
+
1378
+ **Architecture correction: physical storage migration vs. business-data transfer
1379
+ are now physically decoupled, and the UI has a real global SpaceSelector.** The
1380
+ v1.5.0/v1.5.1 UI mixed two unrelated concerns and let the user type
1381
+ `target_space_id`/`event_ids` by hand. Fixed and locked by tests. **270 tests
1382
+ green** (was 263).
1383
+
1384
+ ### Changed — UI (module decoupling)
1385
+
1386
+ - **Physical dataDir migration extracted** into `StorageMigratorUI`, a SYSTEM/DATA
1387
+ MANAGEMENT section at the bottom of the settings page. It owns only the A/B
1388
+ double-buffer state machine: `POST { dataDir }` → `202 state=migrating` → copy →
1389
+ verify → swap, old directory kept as a backup. No event ids, no spaces.
1390
+ - **Business cross-space transfer removed from the settings form**: the manual
1391
+ `event_ids` / `target_space_id` text inputs, the copy/cut buttons and the
1392
+ inline confirmation are gone. Business transfer now exists ONLY in the panel's
1393
+ regulated flow (below).
1394
+ - **Global `SpaceSelector`** in the panel header: a dropdown of the physical spaces
1395
+ (friendly labels: 默认空间 / 工作空间 / 私人空间 / 全局空间, unknown ids verbatim)
1396
+ with `+ 新建空间` (creates an EMPTY space — never a copy). The selection is
1397
+ app-global (`spaceStore` + `space-changed` bus event), so the panel and the
1398
+ settings page follow it.
1399
+ - **Every UI read follows the selected space**: `useMemoryStats`, `useGraph` and
1400
+ `useRecentMemories` append `?space=<id>`; the backend routes `stats`, `graph` and
1401
+ `memories` to that physical store. Memory list, graph, L1 log/index counts, L2.5
1402
+ quarantine, L3 semantic count, L1.5 tag tree and the session status bar are all
1403
+ that space's only — switching spaces cannot blend views or contexts.
1404
+ - **Regulated cross-space flow (UI_TASK_3)**: check memories in the current space →
1405
+ `移动到…` → dialog step 1 states `即将向 [目标空间] 发起迁移请求` → step 2 is the
1406
+ SECOND explicit consent (`二次确认 · 安全红线`, with the cut warning when 剪切) →
1407
+ only then is `user_approved: true` sent. Target is a dropdown of known spaces,
1408
+ never a free-text id.
1409
+ - `h(StorageMigratorUI)` is a separate component, so the two state machines can no
1410
+ longer share draft state or validation.
1411
+
1412
+ ### Added — backend routing
1413
+
1414
+ - **`GET/POST /api/hippocampus/spaces`**: list the router's spaces / create an empty
1415
+ one (`space_id`). The selector and `+ 新建空间` use it.
1416
+ - **`?space=<id>` on `/api/hippocampus/stats` and `/api/hippocampus/graph`**:
1417
+ `runtime.uiPayload(spaceId)` / `runtime.graphPayload(spaceId)` return that space's
1418
+ panel/graph via `Memory.status({ targetSpaceId })` and
1419
+ `Memory.graphForSpace({ targetSpaceId })`; a new space reports zeros (empty), so a
1420
+ switched view is never a fallback to the default store.
1421
+ - `Memory.ensureSpace()` (root router) and `runtime.spaceList()`.
1422
+ - Panel status `panel.spaces.current` now reports the SELECTED space (was always
1423
+ `default`), and `stats`/`graph` responses carry a top-level `spaceId`.
1424
+
1425
+ ### Security (unchanged red line, stricter transport)
1426
+
1427
+ - The HTTP transfer route no longer fabricates consent: it forwards
1428
+ `user_approved` from the request and the ENGINE gate rejects a request that lacks
1429
+ it with `MEM_E_REQUIRE_USER_CONSENT`. The UI only sets the flag after step 2. An
1430
+ agent tool call and a raw POST that "bypasses the UI" therefore hit the same
1431
+ wall.
1432
+ - `dataDir` migration Fail-Fast strengthened: `validateMigrationPaths` now also
1433
+ rejects an existing non-empty target (`MEM_E_MIGRATION_TARGET_BUSY`) and a
1434
+ non-directory target (`MEM_E_MIGRATION_PATH`) synchronously, before a 202/job.
1435
+ The old store remains authoritative on any rejection.
1436
+
1437
+ ### Tests
1438
+
1439
+ - New `test/v152.refactor.test.js` (7 tests): dataDir validation matrix
1440
+ (missing/relative/same/inside/root/non-empty/non-dir) + `startMigration`
1441
+ fail-fast with the old dir intact; space isolation for stats/graph/memories/
1442
+ session/recall with `?space=`; `ensureSpace` empty space + spaces route;
1443
+ unauthorized transfer blocked at engine AND HTTP, authorized passes; UI wiring
1444
+ (SpaceSelector header mount, checkbox flow, no manual inputs, isolated
1445
+ StorageMigratorUI).
1446
+ - Updated contract assertions: HTTP routes 6 → 7 (spaces), transfer route requires
1447
+ explicit `user_approved`, settings order now context → space/session → system
1448
+ storage, cut second-confirmation now lives in the panel dialog, manifest 1.5.2.
1449
+ - Full suite: **270 tests, 270 pass, 0 fail**.
1450
+
1451
+ ## [1.5.1] — 2026-11-02
1452
+
1453
+ **Security patch: cross-space transfer now requires EXPLICIT user consent.** Moving
1454
+ memories between spaces is a data-egress action, not a memory optimisation. Two
1455
+ independent locks (prompt + engine), plus a human-only UI path. **263 tests green**
1456
+ (was 254).
1457
+
1458
+ ### Added
1459
+
1460
+ - **Prompt red line (`memory:policy`)**: a static `【🚨最高安全红线】` block forbids
1461
+ the model from calling `memory_space_transfer` / `memory_transfer_to_global` on
1462
+ its own judgement, sympathy, or "better cross-device sharing". The only allowed
1463
+ trigger is a direct user command in the current conversation; when unsure the
1464
+ model must ask `您需要我把这条信息同步到其他空间吗?`. It also documents the
1465
+ `user_approved: true` retry protocol for `MEM_E_REQUIRE_USER_CONSENT` and states
1466
+ that the intercept is never a one-off obstacle to bypass.
1467
+ - **`memory_transfer_to_global` tool**: copy/move memories from a space into the
1468
+ canonical `global` space, with the same privacy screen, raw_turn stripping, fresh
1469
+ target ids and consent gate as `memory_space_transfer`. Both tool schemas expose
1470
+ `user_approved` and their descriptions carry the security warning.
1471
+ - **`context.requireExplicitConsentForTransfer`** (default **true**, validated
1472
+ boolean, HTTP-editable and exposed in the settings page): the operator's master
1473
+ switch for the engine gate. The settings toggle explains the risk.
1474
+ - **`GET /api/hippocampus/memories`** (`limit`, `space`): bounded recent-memory
1475
+ projection (`eventId`, `day`, `tags`, `snippet`) used by the panel's per-memory
1476
+ detail rows. `Memory.recentMemories()` is read-only and index-snapshot based.
1477
+ - **UI per-memory 分享/转移 button**: the panel now lists the 20 most recent
1478
+ memories with a human-initiated transfer dialog (target space, copy/cut toggle,
1479
+ second confirmation for cut). It calls the transfer route directly — **bypassing
1480
+ the model entirely** — and the browser request is the consenting human.
1481
+
1482
+ ### Fixed / Security
1483
+
1484
+ - `Memory.transferEvents()` now throws
1485
+ **`MEM_E_REQUIRE_USER_CONSENT`** with the fixed message
1486
+ `[系统拦截] 跨空间传递需要用户明确授权。请向用户确认后再试。` when
1487
+ `context.requireExplicitConsentForTransfer` is true and the call does not carry
1488
+ `userApproved === true`. The gate runs **before** space ids are validated, before
1489
+ any store is opened, before content is read and before any pending-delete record
1490
+ is written, so a refused call is provably side-effect free.
1491
+ - `POST /api/hippocampus/transfer` is documented and implemented as the **human
1492
+ channel**: it marks `userApproved: true` itself (same-origin authenticated
1493
+ browser request). The agent half cannot reach HTTP routes, so a UI click needs no
1494
+ model involvement and a model call still hits the gate.
1495
+ - The consent gate is strict: `userApproved` must be the boolean `true`; the
1496
+ config value must be a boolean (a string like `"yes"` fails fast).
1497
+
1498
+ ### Tests
1499
+
1500
+ - New `test/v151.consent.test.js` (9 tests): default-on config + fail-fast type
1501
+ check; engine gate fires before validation/IO (invalid target still answers
1502
+ CONSENT, nothing parked, source untouched); agent tool blocked then succeeds only
1503
+ with `user_approved: true`; `memory_transfer_to_global` same contract; explicit
1504
+ config opt-out; engine-level facade contract; prompt red-line markers; HTTP route
1505
+ marks consent; UI 分享/转移 + direct-API contract.
1506
+ - Intentional contract growth updates: tools 9 → 10, HTTP routes 5 → 6, v150 UI
1507
+ route/transfer assertions extended with `userApproved`, manifest 1.5.1.
1508
+ - Full suite: **263 tests, 263 pass, 0 fail**.
1509
+
1510
+ ## [1.5.0] — 2026-11-02
1511
+
1512
+ Tag-explosion defence, physical multi-space routing, session handoff and the
1513
+ cross-space transfer API. The plugin stays deliberately permission-free: the
1514
+ complex permission choreography belongs to the future Orchestrator plugin, while
1515
+ this engine owns only physical memory. **253 tests green** (was 200).
1516
+
1517
+ ### Added — module 1: tag-explosion defence (P0)
1518
+
1519
+ - **`index.maxPostingsPerTag` (default 500, 1–100000)**: derives the inverted index
1520
+ with a hard physical cap per tag. When a tag exceeds it, the retained pointers are
1521
+ chosen by `salience desc -> eventTime desc -> eventId asc` and re-sorted for
1522
+ retrieval (`eventTime desc`, then id). `eventCount`, `mass` and `lastSeen` are
1523
+ still aggregated over **all** events, so the counts the degradation layer reports
1524
+ are honest; only the in-memory posting pointers are dropped (the JSONL log is
1525
+ untouched and rebuildable). Tags expose `postingsLimit` / `postingsTruncated` /
1526
+ `postingsDropped`; index stats expose `postingsTruncated` / `postingsDropped`.
1527
+ - **Recall degradation for oversized tags**: an EXPLICIT query tag holding more than
1528
+ 50 memories (`TAG_OVERFLOW_THRESHOLD`) is not expanded into the candidate pool.
1529
+ The response carries `oversizedTagHints: [{ tag, total, code:
1530
+ 'MEM_E_TAG_OVERFLOW', hint: '[系统提示] 发现关于 [tag] 的记忆共 N 条,数据量过大。
1531
+ 请提供更精确的 startTime/endTime 或使用 deep_raw 查阅。', window }]` and the
1532
+ course-block fallback is suppressed so the flood cannot re-enter through the back
1533
+ door. If the caller insists (a second recall on the same tag), only the **3 most
1534
+ recent** summaries are returned (`oversizedRecent: true`,
1535
+ `oversized-tag-recent:3`). Graph neighbours of an oversized tag are never woken.
1536
+ - **`deep_raw` super-tag gate**: a query touching a tag with more than 500
1537
+ associations (`SUPER_TAG_THRESHOLD`) without `start_time`/`end_time` now throws
1538
+ **`MEM_E_TIME_RANGE_REQUIRED`** (narrow queries keep the old
1539
+ `MEM_E_INVALID_INPUT` contract). One authority decides: the tool no longer
1540
+ pre-validates the window.
1541
+
1542
+ ### Added — module 2: multi-space routing & session handoff (physical layer)
1543
+
1544
+ - **Config** `context.autoSpaceFollow` (false), `context.autoRolloverEnabled`
1545
+ (true), `context.autoRolloverThreshold` (0.85, 0.5–0.99),
1546
+ `context.nativeTokenLimit` (8000, 512–1000000) — validated fail-fast, editable
1547
+ over HTTP and in the UI.
1548
+ - **`SpaceRouter`** (`src/spaces/spaceRouter.js`): `targetSpaceId` on
1549
+ `remember`/`recall` routes to an isolated physical store
1550
+ (`<dataDir>/spaces/<id>`, `default` = the existing store, so every old path is
1551
+ byte-identical). One FIFO promise chain **per space**: same-space operations are
1552
+ serialised, different spaces run concurrently (a single global lock would
1553
+ reintroduce the cross-space stalls spaces exist to remove). Ids become directory
1554
+ names, so `^[a-z0-9][a-z0-9._-]{0,63}$` is enforced and a typo fails with
1555
+ `MEM_E_INVALID_INPUT` instead of silently writing into the default space.
1556
+ `runMany` acquires in sorted order (no ABBA deadlock).
1557
+ - **Qwen native fidelity**: `ContextEngine.nativeState()` reports
1558
+ `mode: 'native' | 'layered'`; below `nativeTokenLimit` nothing is folded (folding
1559
+ is a layered-mode operation), above it the L1.5 layered fold runs. The legacy
1560
+ `maxTokens` paging threshold is untouched.
1561
+ - **Automatic handoff (转生)**: when the session reaches
1562
+ `autoRolloverThreshold x nativeTokenLimit`, the tail is distilled into ONE durable
1563
+ L1.5 summary (`status:handoff`), `state/handoff.json` is marked active and the
1564
+ `memory-state` prompt appends `[交接标记] … 本插件不能保证一个会话永生不死,只能
1565
+ 保证人格不死。`. A new session consumes the marker. Handoffs are idempotent (one
1566
+ summary per handoff) and self-trigger from the `session/event` stream and from
1567
+ tool boundaries. With `autoRolloverEnabled: false` no marker is written and
1568
+ ContextEngine force-evicts at 95% (`reason: 'native-force'`, down to
1569
+ `target x nativeTokenLimit`).
1570
+ - **Panel/status**: `panel.session` (`mode`, `tokens`, `nativeTokenLimit`,
1571
+ `threshold`, `remainingTokens`, `rolloverEnabled`, `handoffActive`, …) and
1572
+ `panel.spaces` (`current`, `ids`, `open`) are part of the UI contract.
1573
+
1574
+ ### Added — module 3: atomic cross-space transfer
1575
+
1576
+ - **`memory_space_transfer` tool** (`event_ids`, `target_space_id`,
1577
+ `transfer_mode: 'copy' | 'move'` default copy, optional `source_space_id`) and
1578
+ `Memory.transferEvents()`.
1579
+ - **Safety rails enforced by the engine, not the caller**: privacy screening aborts
1580
+ the whole batch with **`MEM_E_PRIVACY_BLOCKED`** (ID cards, CN phones, bank cards,
1581
+ emails, credential assignments, PEM private keys; matched bytes never leave the
1582
+ scanner) before any write; `raw_turn` / `rawTurn` / `raw_*` pointers are stripped
1583
+ from meta at every depth; the TARGET space regenerates `event_id`s
1584
+ (`dedupe:false`, never reuses the source identity) and tags copies
1585
+ `transferred:from:<source>` + `transferred:to:<target>`.
1586
+ - **State difference**: `copy` leaves the source untouched (`state: 'retained'`);
1587
+ `move` parks the source ids in the **two-phase pending_delete queue**
1588
+ (`state: 'pending_delete'`, `dueAt`, cancellable with `restore`) only after every
1589
+ target write succeeded — never a direct physical delete, and a partial target
1590
+ failure leaves the source untouched.
1591
+ - **HTTP**: `POST /api/hippocampus/transfer` (same-origin, validated body) for the
1592
+ UI migration button.
1593
+
1594
+ ### Added — module 4: UI
1595
+
1596
+ - **Space panel**: soft-follow toggle (`context.autoSpaceFollow`), auto-rollover
1597
+ toggle, trigger-ratio slider, native-window field, single-tag index cap control,
1598
+ and a live status bar: `[当前: 原生模式 | 剩余 X Tokens 触发交接]` (also
1599
+ `分层折叠` / `已交接` variants).
1600
+ - **Migration interaction**: copy/cut (复制/剪切) toggle next to the transfer button;
1601
+ choosing 剪切 requires a **second confirmation warning** before any request is
1602
+ sent.
1603
+ - **Philosophy footer** (bold, bottom of the settings page): **本插件不能保证一个
1604
+ 会话永生不死,只能保证人格不死。**
1605
+ - **Subtraction**: the tag search box uses the host-native Enter key only — no
1606
+ debounce, no timer, no effect. `filterGraphByQuery` is pure and testable; the
1607
+ force layout is not re-run by filtering.
1608
+
1609
+ ### Changed
1610
+
1611
+ - `uiConfig` exposes `index`; `Memory.applyLiveConfig()` projects a validated config
1612
+ onto the facade **and every open child space**, including the context engine's
1613
+ native/rollover overrides.
1614
+ - `Memory` opens child spaces lazily with the same policy input; `close()` closes
1615
+ children first; a child failure never blocks the rest.
1616
+ - The `memory-state` prompt only gains the handoff block when a marker is active,
1617
+ so the cache-stable prefix is unchanged in the common case.
1618
+
1619
+ ### Tests
1620
+
1621
+ - New files: `v150.index.test.js` (truncation/degradation/super-tag gate),
1622
+ `v150.space.test.js` (per-space concurrency, native boundary, forced eviction),
1623
+ `v150.transfer.test.js` (copy/move state difference, privacy, raw_turn strip,
1624
+ fresh ids), `v150.ui.test.js` (bundle contract, helpers, no debounce, footer,
1625
+ transfer route), `v150.lifecycle.test.js` (Qwen mode, threshold handoff, marker
1626
+ consumption, `targetSpaceId` isolation, ninth tool surface),
1627
+ `v150.config.test.js` (new groups, ranges, HTTP editability).
1628
+ - Intentional contract updates in old tests: 8 -> 9 tools, 4 -> 5 routes,
1629
+ `panel.session`/`panel.spaces` added to the panel snapshot, manifest 1.5.0.
1630
+ - Full suite: **253 tests, 253 pass, 0 fail** (old 200 cases included unchanged).
1631
+
1632
+ ## [1.4.3] — 2026-11-02
1633
+
1634
+ Two measured blockers from the 2026-11-02 handoff, both fixed and locked by tests.
1635
+
1636
+ ### Added
1637
+
1638
+ - **`raw.maxScanTurns` config (500–50000, default 5000)**: `deep_raw`'s scan budget
1639
+ was a hidden constant and is now a validated, UI-editable knob (`raw.maxScanTurns`).
1640
+ - **`stage()` / `commitMany()`**: remember is now a `stage -> commitMany` composition.
1641
+ `stage()` validates and builds a record (identity + idempotency, no log/index I/O);
1642
+ `commitMany()` performs ONE durable append, ONE ledger checkpoint and ONE index
1643
+ delta for a whole batch. `bulkIngest` uses it, so a 50-item chunk is one write
1644
+ instead of 50.
1645
+ - **`memory-state` prompt is now composed** via `composePrompt`: stable rules →
1646
+ `[Memory Map]` (active tags + counts) → `[Memory Blocks]` (the only per-turn
1647
+ volatile tail). The old single-line `briefing()` is no longer the prompt body
1648
+ (it changed on every write and broke the prefix cache). Full-chain tests lock the
1649
+ prefix to be byte-identical before/after a recall injects a block.
1650
+ - **`scripts/confidence-ab.mjs`**: local A/B benchmark for `context.minInjectConfidence`
1651
+ (100 noise + 10/3 relevant; characters, hits, low-confidence hints, mis-degraded
1652
+ relevant memories). Run it with `node scripts/confidence-ab.mjs`.
1653
+ - **Crash-restart test**: kills the process inside the 200ms checkpoint window
1654
+ (cancelled timer, no `close()`), reopens the same directory, and asserts the fresh
1655
+ instance reports `stale` (`unflushed-bytes`), rebuilds the index and can recall the
1656
+ unflushed tail.
1657
+
1658
+ ### Fixed
1659
+
1660
+ - **`injectRecall()` crashed on any L3 semantic hit**: it used `summary.id` while
1661
+ `rankSemantic()` returns `summaryId`, so a recall with a distilled summary and
1662
+ `context.injectPrompt` failed with `MEM_E_IO: ContextEngine.inject requires an id`.
1663
+ Now it uses `summaryId ?? id` and skips invalid summaries. Found by the new
1664
+ prompt/tag-tree full-chain test.
1665
+ - `logStore.status()` now exposes `unflushedBytes` (shard size minus manifest bytes)
1666
+ so an unclean shutdown cannot hide the uncheckpointed tail behind equal counters.
1667
+
1668
+ ### Changed
1669
+
1670
+ - **`deep_raw` scans NEWEST-FIRST** (per shard, tail to head). The old head-first
1671
+ scan burned its whole budget on the oldest 5000 turns of a day file — in a 10k
1672
+ shard the newest turn could never be found. A hit beyond the window now returns
1673
+ `truncated: true` with a note instead of pretending the turn does not exist.
1674
+ - **Buffered log append**: the hot path keeps one append handle without fsync +
1675
+ manifest rewrite per record. A 200ms checkpoint (and `close()`, and any
1676
+ rewrite/compaction) fsyncs and publishes the manifest; `status().unflushedBytes`
1677
+ plus the boot check make a mid-burst crash visible as stale instead of silently
1678
+ "up to date".
1679
+ - **Identity ledger checkpoint is debounced** (500ms / `close()`): it is a derived
1680
+ startup hint rebuilt from the log, so rewriting it per append was pure O(n²) cost.
1681
+ - **Index appends are lazy**: `applyRecords` records the delta and marks the view
1682
+ dirty; the next `snapshot()` folds it once. N writes cost one index build, and
1683
+ read-your-writes still holds because the fold happens on the read path.
1684
+ - **Briefing is dirty-driven**: a write marks the prompt-state line stale; the next
1685
+ `briefing()` / panel poll rebuilds it once instead of every append.
1686
+
1687
+ ### Measured
1688
+
1689
+ - Sequential `memory.remember` x1000: **119/s -> 9104/s** (8.4s -> 110ms).
1690
+ - 10,000-line raw shard, newest query: **0 hits -> 1 hit** (`deep_raw` now starts at
1691
+ the tail; hash restore and redaction regression-guarded).
1692
+ - **`deep_raw` tail-scan bias documented**: beyond `raw.maxScanTurns` (default 5000)
1693
+ per shard, only the newest N turns are covered; older history needs a larger budget
1694
+ or time-window pagination (`end_time` moved backwards). `truncated: true` + notes
1695
+ always say so.
1696
+ - **Confidence A/B (measured)**: `minInjectConfidence=0.6` cuts the tool payload by
1697
+ **49.7%** (10 relevant / 100 noise) and **75.8%** (3 relevant / 100 noise), with
1698
+ **0 relevant hits mis-degraded**; the prompt window only shrinks when the top-8
1699
+ contains noise (0% vs 59.7% in the two scenarios), so the honest claim is
1700
+ "long-tail payload + anti-hallucination", not "always fewer prompt tokens".
1701
+ - 197 tests green (was 189); after the prompt/tag-tree full-chain wiring and the
1702
+ crash-restart test: **200**.
1703
+
1704
+ ## [1.4.2] — 2026-11-01
1705
+
1706
+ ### Added
1707
+
1708
+ - **L1.5 标签层级树**: hierarchical tags (`tech/frontend/vue3`) now have a
1709
+ three-level lifecycle — immortal roots, leaves that die when their reference
1710
+ count reaches zero, and mids that enter a grace window when they lose their last
1711
+ child. A mid inside that window is a **ghost**: it can be revived by a new leaf,
1712
+ and it is what the UI's history view shows. The tree is a **derived cache**
1713
+ (`state/tag-tree.json`) built by `maintain()` from the converged index; the
1714
+ previous cache is carried forward (`refCount = 0`, orphans dropped) so the
1715
+ lifecycle is observable across maintenance runs. Deleting the file loses only
1716
+ ghost history.
1717
+ - **Bounded prune queue**: dead leaves are queued and consumed one
1718
+ `tagTree.pruneBatchSize` batch per maintenance run; the remaining queue is
1719
+ persisted in the same atomic write, so a 10k-leaf storm drains across runs
1720
+ instead of causing a maintenance storm.
1721
+ - **Anti-hallucination recall degradation**: a `memory_recall` hit reached only
1722
+ through a fading mid is **removed from `hits` entirely** (body, snippet and score
1723
+ never reach the model or the prompt window) and replaced by one metadata hint per
1724
+ mid: path, count, remaining grace days and the exact `deep_raw` time window. A
1725
+ query that names a fading mid with no live episode returns a `count: 0` hint
1726
+ instead of silence.
1727
+ - **`panel.tagTree`**: node/root/mid/leaf/ghost/queue counts for the Web panel, and
1728
+ `GET /api/hippocampus/graph` now returns `tagTree.ghosts` in the same response as
1729
+ the cached graph.
1730
+ - **UI**: `tagTree.*` sliders with numeric boxes and hover tooltips in the settings
1731
+ section; ghost nodes rendered in the force graph as translucent dashed circles
1732
+ hanging under their parent root, with a `仅活跃 / 历史全貌` toggle that cross-fades
1733
+ them via CSS opacity (the force layout does not re-run when toggling).
1734
+ - **Config `tagTree` group** (fail-fast, editable over HTTP and in the UI):
1735
+ `midHalfLifeMultiplier` (1–10), `midGracePeriodDays` (7–180),
1736
+ `pruneBatchSize` (10–500), `leafDecayFloor` (0–1). `midHalfLifeMultiplier` is the
1737
+ only source of the mid half-life — no silent hard-coded lifetime.
1738
+
1739
+ ### Changed
1740
+
1741
+ - `maintain()` now rebuilds/prunes/persists the tag tree after the index
1742
+ generation converges; a tag-tree failure is reported as `report.tagTreeError`
1743
+ and can never fail maintenance or block recall.
1744
+ - `applyConfig` now projects the validated config onto the running `Memory` facade,
1745
+ so live UI edits (raw limits, tagTree lifetimes, …) actually reach the running
1746
+ objects instead of waiting for a reload.
1747
+ - `pruneBatch` re-derives decay against the pass's `now` (a frozen build-time score
1748
+ made grace windows meaningless), rejects `O(mids × nodes)` rescans, and keeps
1749
+ parent child counts truthful when a mid dies.
1750
+
1751
+ ## [1.4.1] — 2026-11-01
1752
+
1753
+ ### Added
1754
+
1755
+ - **Prompt discipline (soft interception)**: a static `memory:policy` section tells
1756
+ the model to prefer `memory_recall` for history/files/system facts, and to treat
1757
+ a `[Slimmed]` response as an invitation to answer from the summary unless the
1758
+ `recovery_hash` must be dereferenced.
1759
+ - **Own-tool output slimming**: `memory_recall`/`memory_admin` responses over the
1760
+ budget (default 2000 tokens) are captured to raw first, then returned as
1761
+ `{slimmed, summary, topics, key_entities, recovery_hash, hint}`; the hint points
1762
+ at `memory_recall(mode="deep_raw", hash=…)`, which restores the exact payload.
1763
+ - **Retrieval confidence**: hits below `context.minInjectConfidence` (default 0.6)
1764
+ carry a short hint instead of their full body, plus a `low-confidence-hints:N` note.
1765
+ - **Write flood guard**: writes above 80% of `storageBudgetMb` throw
1766
+ `MEM_E_WRITE_FLOOD`; `memory.bulkIngest` chunks 50 items per await and ships as
1767
+ `memory_bulk_ingest`.
1768
+ - **raw.captureRatio** (0 | 0.5 | 1): deterministic sampling by content hash;
1769
+ ratio 0 disables capture and `deep_raw` returns an explicit warning.
1770
+
1771
+ ### Changed
1772
+
1773
+ - `memory_recall` gains `hash` (exact raw restore) and confidence fields; deep_raw
1774
+ results honour the token budget before returning.
1775
+ - `promptLayout` composes stable rules → memory map → `[Memory Blocks]` tail.
1776
+
1777
+ ## [1.4.0] — 2026-10-31
1778
+
1779
+ ### Added
1780
+
1781
+ - **Raw-turn forensics (`memory_capture`, `memory_recall mode:"deep_raw"`)**: a
1782
+ separate day-sharded JSONL store (`raw/`) that is never indexed, never loaded at
1783
+ boot, and never touched by normal recall. Gated by `raw.mode` (default
1784
+ `salience`: high-salience, code, stack traces, tool output, or `force`), deduped
1785
+ by content hash, secret-redacted, and capped by `maxTurnKb` (head+tail
1786
+ truncation), `maxBytesPerDay`, `maxTotalMb`, and `retentionDays` (pruned by
1787
+ maintenance; code shards keep 90 days). `deep_raw` scans newest→oldest under a
1788
+ byte/turn budget and reports `truncated: true` instead of pretending it saw
1789
+ everything.
1790
+ - **Spaced repetition**: engine-owned schedule (`1,2,4,7,15,30` days) persisted in
1791
+ `state/reviews.json`; `maintain()` reconciles due items and `reinforce` advances
1792
+ the step. Exposed as `memory_admin action="reviews"`.
1793
+ - **Two-phase delete**: `forget` parks the event for `delete.graceHours`
1794
+ (default 24) in `pending_deletes`; `restore` cancels it, and `maintain()`
1795
+ promotes expired requests into the 4-phase pipeline. Unknown ids now fail
1796
+ immediately, before parking.
1797
+ - **UI data-dir migration**: `dataDir` is editable in the settings page. Saving it
1798
+ takes `.migration.lock`, returns HTTP 202 with `state=migrating`, copies with
1799
+ `fs.promises.cp` in the background, verifies `recordCount` on both sides, and
1800
+ only then switches and reloads the store. A mismatch removes the target and
1801
+ keeps the old store authoritative; the source is never deleted.
1802
+ - New config groups: `raw.*`, `delete.graceHours`, `review.enabled`,
1803
+ `migration.timeoutMs` (all fail-fast validators, UI tooltips included).
1804
+ - **Raw-turn black box (minimal schema)**: each line is exactly
1805
+ `{turn_id, timestamp, role, content}` — no tags, salience, decay, event ids,
1806
+ graph links, session ids or metadata. Addressing is by `(day file, line number)`;
1807
+ append-only keeps lines stable (the one lawful line-pointer exception).
1808
+ Writes are queued and flushed in batches (10 records / 1s), never sync.
1809
+ - **Read-side redaction**: the shard keeps 100% plaintext (forensic integrity);
1810
+ secrets are redacted when `deep_raw` returns snippets, before any text reaches a
1811
+ model prompt. README states local storage is plaintext.
1812
+ - **Tombstones**: a committed purge appends `raw_tombstone {hash, timestamp}`;
1813
+ scans skip tombstoned content hashes (no resurrection).
1814
+ - **deep_raw constraints**: `start_time` and `end_time` are mandatory (missing →
1815
+ `MEM_E_INVALID_INPUT`), results are capped by `raw.maxResultTokens` (default
1816
+ 1000) and carry the truncation notice when cut.
1817
+ - **TTL**: maintenance deletes whole day files strictly older than
1818
+ `today - raw.retentionDays`; today's shard is never touched. Raw bytes are
1819
+ surfaced as `panel.storage.rawBytes` and counted in the dashboard ring.
1820
+ - **Automatic raw capture**: the plugin subscribes to `dsh-session`'s
1821
+ `session/event` and stores every user/assistant surface message verbatim
1822
+ (`raw.autoCapture: true`). The Host-injected `Current runtime context.` block is
1823
+ stripped out of `content` and kept (truncated) in `metadata.runtimeContext`, so
1824
+ `deep_raw` stays signal-clean. Tool output is opt-in (`raw.captureTools: false`),
1825
+ **except failed tool results** (`isError`), which are always captured as
1826
+ `kind: "error"`. Budgets, dedupe and retention still apply.
1827
+
1828
+ ### Changed
1829
+
1830
+ - Panel adds `raw`, `reviews`, and `pendingDeletes`; the settings page renders a
1831
+ migration progress card while `state=migrating`.
1832
+ - `Memory._scheduler` cron now reads `runtime.config` per tick, so a hot config
1833
+ update changes the schedule without a restart.
1834
+
1835
+ ## [1.3.1] — 2026-10-30
1836
+
1837
+ ### Fixed
1838
+
1839
+ - **Cold-start 404 (root cause)**: `webServer` is provided by the web-app row, which
1840
+ activates *after* this plugin's `apply()`. The old code called
1841
+ `ctx.get('webServer')` once and silently skipped registration when it was
1842
+ absent — every cold start had no routes, while a warm reload worked. Route
1843
+ registration now lives in `ctx.inject(['webServer'], child => …)`, so the child
1844
+ fiber activates the moment the service appears and the routes are always
1845
+ mounted. Verified live (404 → 200) and covered by a deferred-inject test.
1846
+ - **Front-end death spiral**: a bodiless 404 used to be synthesized into a JSON
1847
+ error, which the old retry counter treated as a protocol failure and gave up
1848
+ after six attempts. `getJson` now keeps "no JSON" distinct, and the pure
1849
+ `decideRetry` policy retries bodiless 404s with exponential backoff (capped at
1850
+ 5s) for up to 10 minutes before surfacing `MEM_E_BOOT_TIMEOUT` with a manual
1851
+ reconnect button.
1852
+ - **Diagnostics**: `apply()` prints `[Hippocampus] Route registered at <iso>
1853
+ (<paths>) phase=<phase>` when the routes are mounted, and
1854
+ `[Hippocampus] Route registration FAILED: <reason>` if the service never
1855
+ provides one.
1856
+
1857
+ ## [1.3.0] — 2026-10-30
1858
+
1859
+ ### Added
1860
+
1861
+ - **Context folding (推币机)**: blocks evicted from the context window are no longer
1862
+ dropped. A light rule folds the most recent batch into one `folded_summary`
1863
+ episode tagged `status:folded` — extracting names, task statements and core
1864
+ conclusions — and writes it back to the L1 log.
1865
+ - **Graph association (在线联想)**: when a query touches a tag, retrieval reads the
1866
+ cached graph and pulls that tag's three strongest neighbours into the candidate
1867
+ pool with an explicit `penalty: 0.5`; such hits are marked `association.via` and
1868
+ can never outrank a direct hit.
1869
+ - **Monthly memos (月记)**: `maintain()` condenses a finished natural month into one
1870
+ `status:monthly` episode. Memos do not decay (`decay = 1`) and are pulled in
1871
+ first for fuzzy historical queries ("上个月", "2023-10", "去年" …).
1872
+
1873
+ ### Changed
1874
+
1875
+ - HTTP routes are now registered **before** tools, prompts and scheduling inside
1876
+ `apply()`, so a page that wins the boot race hits a live handler answering
1877
+ `state=pending` instead of a 404. The Host-side assumption is documented in the
1878
+ code: `apply()` awaits nothing, and route service is expected once it returns.
1879
+
1880
+ ## [1.2.0] — 2026-10-30
1881
+
1882
+ ### Added
1883
+
1884
+ - **`memory_checkpoint`** (`task_id`, `progress`, `updated_at`): exactly one active
1885
+ heavy task. A new checkpoint demotes the previous one, one not refreshed for
1886
+ seven days is demoted by `maintain()`, and `memory_admin action="active_task"`
1887
+ reads it straight from the index — the active-set cap of 200 does not apply.
1888
+ - **Multimodal pointers**: `memory_remember` accepts `media_url` (absolute path or
1889
+ http(s) URL) plus `media_type` (`image|video|document|audio`). Inline base64 in
1890
+ `content` is rejected with `MEM_E_INVALID_MEDIA` from 256 consecutive base64
1891
+ characters; 200 characters is still ordinary text.
1892
+ - **`decay.halfLifeDays`** (default 30, 7–365) and **`activeSet.cap`** (default 200,
1893
+ 100–1000): both declared in `DEFAULT_CONFIG`, validated fail-fast by
1894
+ `resolveConfig`, projected into `policy`, and editable from the settings page.
1895
+ - **State handshake**: every route response now carries `state`
1896
+ (`pending|in_progress|ready|failed`), and the UI retries on `state` rather than
1897
+ on the HTTP status. A bodiless 404 during boot is treated as `pending` for a
1898
+ 120s grace window (the routes are only mounted once the Host runs `apply()`).
1899
+
1900
+ ### Changed
1901
+
1902
+ - Writes before READY are refused loudly: `POST /api/hippocampus/config` answers
1903
+ `409` with `MEM_E_NOT_READY` and the current state; tools already answered
1904
+ `MEM_E_NOT_READY`, and their error details now include `state` and `retryable`.
1905
+ - The settings page covers the full editable surface (18 keys), with the documented
1906
+ hints for `storageBudgetMb`, `context.maxTokens`, `decay.halfLifeDays` and
1907
+ `activeSet.cap`; saving before READY is disabled in the UI and rejected by the API.
1908
+
1909
+ ## [1.1.0] — 2026-10-29
1910
+
1911
+ ### Added
1912
+
1913
+ - **Graph dragging**: nodes are movable with pointer events. The dragged node is
1914
+ pinned for the duration, coordinates are mutated in a ref and painted straight
1915
+ to the DOM (no `setState` per frame), and release unpins it and runs a short
1916
+ alpha relaxation over its 1-hop neighbourhood. A pointer travel under 4px is
1917
+ still a click, so selecting a label can never move the node by accident.
1918
+ - **`storageBudgetMb`** (integer, default 50, range 10–1000): the storage ring's
1919
+ budget is now configurable instead of hard-coded, and the ring recomputes the
1920
+ moment the value is saved.
1921
+ - **Full settings UI**: every editable config key is in the settings section —
1922
+ switches for booleans, bounded number inputs, a select for
1923
+ `identity.eventTimePolicy`, and a text field for the maintenance cron. Saving
1924
+ posts one dotted-path patch through the same fail-fast validator as startup;
1925
+ a rejected value shows a red banner with the `MEM_E_CONFIG_*` code and nothing
1926
+ is applied. A successful save broadcasts `config-changed` so the panel
1927
+ refetches stats and graph immediately.
1928
+
1929
+ ### Fixed
1930
+
1931
+ - Dotted config paths deeper than one level (`identity.eventTimePolicy`,
1932
+ `retrieval.topK`) now nest correctly instead of producing a literal key.
1933
+
1934
+ ## [1.0.0] — 2026-10-29
1935
+
1936
+ First public release. The package was previously developed under the working
1937
+ names `@local/dsh-memory` / `Layers-Hippocampus`; the data directory is
1938
+ unchanged and legacy folders are migrated automatically.
1939
+
1940
+ ### Added
1941
+
1942
+ - **Layers**: append-only event log, rebuildable tag index (A/B generations),
1943
+ day diaries, independent semantic layer, L2.5 trend quarantine with promotion
1944
+ and burst detection.
1945
+ - **Identity discipline**: canonical `content_hash`, `event_id =
1946
+ hash(content_hash + event_time + occurrence_index)`, separate idempotency
1947
+ index, tombstones that survive log compaction.
1948
+ - **Context paging**: token budget, eviction thresholds, cumulative saved-token
1949
+ accounting persisted in `state/context.json`.
1950
+ - **Maintenance**: one gate for cron and Dream (`runtime.runMaintenance`), no
1951
+ queueing and no backfill; a missed window is skipped, not replayed.
1952
+ - **Config fail-fast**: `enableDream`, `dreamIdleMinutes`, `enableReflection`,
1953
+ `graphMaxEdges` (100–2000, default 500), cron, context and temp ranges are
1954
+ validated by `resolveConfig`; HTTP hot updates go through the same validator.
1955
+ - **Async startup state machine** `pending → in_progress → ready | failed`, with
1956
+ `POST /api/hippocampus/retry` and a UI retry banner.
1957
+ - **Offline knowledge graph**: built at the end of `maintain()` from the index
1958
+ (log minus tombstones), per-node Top-N neighbours, global weight order, cached
1959
+ at `state/graph.json`, hard cap 2000 edges.
1960
+ - **Web UI**: sidebar icon, main panel (SVG storage ring, stats, force-directed
1961
+ graph with progressive reveal), and a settings section.
1962
+ - **HTTP API** (same-origin, behind the Host's browser auth):
1963
+ `GET /api/hippocampus/stats`, `GET|POST /api/hippocampus/config`,
1964
+ `GET /api/hippocampus/graph`, `POST /api/hippocampus/retry`.
1965
+ - **Tests**: 106 in-process cases (Node `node:test`) covering identity,
1966
+ retrieval, L2.5, maintenance, migration, routes, graph and the client bundle
1967
+ contract.
1968
+
1969
+ ### Security
1970
+
1971
+ - The UI never receives credentials and never calls agent tools; every number is
1972
+ read through the Host's authenticated JSON routes.
1973
+ - The graph route returns at most `graphMaxEdges` edges from a cached file — no
1974
+ query language, no path input.
1975
+
1976
+ [1.0.0]: https://github.com/382quaii/dsh-Layers-Hippocampus/releases/tag/v1.0.0