dsh-layers-hippocampus 1.7.2 → 1.7.4

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