dsh-layers-hippocampus 1.6.1 → 1.6.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -4,10 +4,68 @@ All notable changes to `dsh-layers-hippocampus` are documented here.
4
4
  The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
5
5
  and the project adheres to [Semantic Versioning](https://semver.org/).
6
6
 
7
+ ## [1.6.2] — 2026-11-11
8
+
9
+ **补丁版:修复冷数据归档与保留期的时间冲突,并把“打破日志线性增长”的三层机制并入正式记录。**
10
+
11
+ - **Fixed — 设置页卡在“正在启动…”并报 `MEM_E_NETWORK: HTTP 404`**(2026-11-13):
12
+ 1.6.2 的强校验 `archiveAfterDays < retentionDays` 与**旧 profile**(`raw.retentionDays: 30`、
13
+ 从未写过 `archiveAfterDays`)冲突,`apply()` 抛 `MEM_E_CONFIG_OUT_OF_RANGE`,插件根本没加载,
14
+ 所有 `/api/hippocampus/*` 路由缺失 → UI 永远 404。现在:
15
+ - `archiveAfterDays` **未被显式配置**时按 `retentionDays - 1` 派生,并置
16
+ `raw.archiveAfterDaysDerived: true`(旧 profile 可直接启动);
17
+ - **显式**给出越界的 `archiveAfterDays` 仍然 fail-fast(配置错误不该被静默原谅)。
18
+ - **Fixed — 归档文件不受 retention 约束**:`prune()` 原来只删 `.jsonl` 明文分片,`.jsonl.br`
19
+ 归档会永久堆积,等于变相突破保留期。现在整月归档的末日晚于 cutoff 才保留,否则连
20
+ `state/raw-archive.json` 记录一起删除,返回 `removedArchives`。
21
+
22
+ - **修复冷数据归档时间冲突**:冷归档阈值与 TTL 保留期原本互相挤压(`archiveAfterDays` 与
23
+ `retentionDays` 同为 30/90 量级,冷分片常在归档前就被 TTL 删除)。现在默认值上调为
24
+ `archiveAfterDays: 90`、`retentionDays: 365`,并保留 fail-fast 校验
25
+ (`archiveAfterDays` 必须严格小于 `retentionDays`),同时新增 `raw.coldAccessWindowDays: 90`,
26
+ 也就是“近 90 天零访问”才允许归档。
27
+ - **实施多档保留策略(含遗忘性保存与全保存)**:raw 层保留谱系落地为
28
+ `raw.mode: off | salience | all` ——
29
+ `off` 为不保存(遗忘性保存,仅保留 L1 之上的记忆)、`salience` 为默认的高价值保存、
30
+ `all` 为全保存(受 `maxTurnKb` / `maxBytesPerDay` / `maxTotalMb` 预算约束);
31
+ 另加 `raw.distillPrune`(默认 false):蒸馏产物覆盖第 i 天、且该分片已出
32
+ `raw.hotWindowDays` 热窗时,允许物理清理 raw 原文,**必经 Tombstone 防复活**。
33
+ L2 继续走同类项合并(`l2Merge`),L3 增加硬熔断 `semantic.maxEntries`(默认 100)+ LRU 淘汰,
34
+ 语义层随“事件重要性”而非“对话条数”增长。
35
+ - **优化长窗口压缩与高频引用去重**:
36
+ - 冷归档默认改用 **Brotli quality 11**(`.jsonl.br`,极限压缩),`gzip`(9) / `zstd` 仍可选,
37
+ 全部来自 Node 内置 `node:zlib`,零外部依赖;读取按扩展名流式解压、命中即停。
38
+ - 高频重复的超长内容(工具 schema / 系统提示块,≥512 字符且出现 ≥2 次)在建索引时
39
+ 只存一份到 `templates.json`,事件侧改为 `contentRef` 引用(`src/index/templates.js`),
40
+ 索引加载时还原原文;**日志本体不参与替换**,raw 逐行真相、`deep_raw` 与行级游标不受影响。
41
+ - 稀疏行索引(每 64 行采样)继续用于跳过时间窗不重叠的分片并复用 `lineCount`。
42
+
43
+ ### 1.6.2 详细变更
44
+
45
+ - **Breaking the linear log curve — three layers** (`test/v162.nonlinear.test.js`, 9 cases):
46
+ - **Compression layer**: cold classification is now MULTI-dimensional (age >
47
+ `raw.archiveAfterDays` **AND** zero access for `raw.coldAccessWindowDays` **AND** no
48
+ `pinned` / `status:handoff` / hot-tag record). Defaults move to
49
+ `archiveAfterDays=90`, `coldAccessWindowDays=90`, `retentionDays=365`. Cold
50
+ archives default to **Brotli quality 11** (`.jsonl.br`, "极限压缩") instead of
51
+ gzip; `gzip`/`zstd` stay selectable and all three are Node built-ins.
52
+ Recently-read old shards stay PLAINTEXT for O(1) cursor scans.
53
+ - **Encoding layer (referential dedup, NOT columnar)**: repeated long content
54
+ (tool schemas / system prompt blocks, ≥512 chars, ≥2 occurrences) is stored ONCE
55
+ in `templates.json` at the INDEX layer; events carry `contentRef` instead of a
56
+ duplicate copy. Index loads resolve refs, so readers always see exact content —
57
+ the log itself is untouched (`src/index/templates.js`).
58
+ - **Semantic layer**: raw stops being the only home of truth. `raw.distillPrune`
59
+ (opt-in) lets `maintain()` physically clean raw shards that are outside
60
+ `raw.hotWindowDays` **and** already covered by an L3 summary — always through the
61
+ tombstone path, so nothing resurrects. L3 gains a hard capacity breaker
62
+ (`semantic.maxEntries`, default 100) with LRU retirement recorded as append-only
63
+ `semantic_retire` events.
64
+
7
65
  ## [1.6.1] — 2026-11-07
8
66
 
9
67
  **Version fully un-frozen (user directive 2026-11-07): normal semantic versioning
10
- resumes; 1.6.1 is the current release (patch on top of 1.6.0).**
68
+ resumes; 1.6.1 was the release that followed 1.6.0.**
11
69
 
12
70
  - **Archive month detail UI**: the panel's raw section now shows `indexedShards` /
13
71
  `archiveCount` StatCards plus a **collapsible month table** (月份 / 引擎 / 归档大小 /
@@ -80,7 +138,7 @@ resumes; 1.6.1 is the current release (patch on top of 1.6.0).**
80
138
  (`O(K log K)` ordering) but the per-candidate decay/similarity work is skipped
81
139
  for the long low-salience tail.
82
140
  - Regression: pinned decay stays exactly 1 (bypass path), monthly memos unchanged.
83
- - **447 tests green** (64 files).
141
+ - **456 tests green** (64 files).
84
142
 
85
143
  ## [1.6.0] — 2026-11-06
86
144
 
@@ -107,7 +165,7 @@ Cold-start wake-up + user-controlled cold-start injection:
107
165
 
108
166
  > Historical note: 1.5.7 shipped under a temporary version freeze; the 2026-11-07
109
167
  > directive removed ALL freeze language and resumed normal semantic versioning
110
- > (current version: 1.6.1). The sentence below is the historical 1.5.7 statement.
168
+ > (current version: 1.6.2). The sentence below is the historical 1.5.7 statement.
111
169
 
112
170
  **Version freeze (historical, superseded): 1.5.7 was the shipped release.**
113
171
  This release folds in everything added after the 1.5.6 draft — Orchestrator
package/README.md CHANGED
@@ -7,7 +7,7 @@
7
7
 
8
8
  | | |
9
9
  | --- | --- |
10
- | 版本 | **1.6.1** |
10
+ | 版本 | **1.6.2** |
11
11
  | 包名 | `dsh-layers-hippocampus` |
12
12
  | 仓库 | <https://github.com/382quaii/dsh-Layers-Hippocampus> |
13
13
  | 许可证 | MIT |
@@ -80,21 +80,42 @@
80
80
  (`context.coldStartInjectSummary` 默认开、`context.coldStartInjectRecentTurns` 默认关);
81
81
  静态「状态唤醒」策略常驻,两个开关都关时也不会退化成客服腔。
82
82
 
83
- ### raw 冷热分层与按月归档
83
+ ### 打破线性增长:压缩 / 编码 / 语义三层
84
+
85
+ append-only 日志天然是 O(n),只压不改斜率。三层各自掰弯一段曲线:
86
+
87
+ **① 压缩层(冷数据极限压榨)**
84
88
 
85
89
  - 原始回合按天分片(`raw/YYYY-MM-DD.jsonl`);热数据保持明文,供 `deep_raw` **倒序流式扫描**
86
90
  (64 KiB 反向分块,峰值内存 = 一个 chunk + 一行)。
87
- - **冷数据按月归档**:`maintain()` 中月度门控(每月最多一次),把超过 `raw.archiveAfterDays`
88
- (默认 7 天)的分片合并为 `raw-archive-YYYY-MM.jsonl.gz`(或 `.jsonl.zst`)后删除明文。
89
- - 压缩引擎可选 `gzip`(默认)/ `zstd`,均使用 Node 内置 `node:zlib`——**不下载任何依赖**;
90
- 运行时无 zstd 时静默回退并在 `capabilities.compression` 上报。
91
- - 归档**不碰**近 30 天被读过、`pinned`、`status:handoff` 或带高频标签的分片。
92
- - 读取归档时用 `createGunzip()` / `createZstdDecompress()` **流式逐行解压**,命中即停,
93
- 绝不把整个归档读进内存。
91
+ - **多维冷热判定**(严禁只看时间):同时满足 `生成时间 > raw.archiveAfterDays`(默认 **90 天**)、
92
+ 近 `raw.coldAccessWindowDays`(默认 **90 天**)**零访问**、且不含 `pinned` / `status:handoff` /
93
+ 高频标签,才进入归档。
94
+ - **极限分层压缩**:冷数据按月合并为 `raw-archive-YYYY-MM.jsonl.br`,默认 **Brotli quality 11**;
95
+ 可切 `gzip` / `zstd`(全部 Node 内置,**零依赖**)。旧格式历史归档依然可读。
96
+ - 读取归档时用 `createBrotliDecompress()` / `createGunzip()` / `createZstdDecompress()`
97
+ **流式逐行解压**,命中即停,绝不把整个归档读进内存。
94
98
  - **稀疏行索引**:每个分片旁挂 `<day>.jsonl.idx.json`(每 64 行采样),`deep_raw` 据此跳过
95
99
  时间窗不重叠的分片并复用行数,索引缺失/陈旧/损坏时自动降级为顺序扫描。
96
100
 
97
- ### 多维保留策略
101
+ **② 编码层(引用去重,不碰列式存储)**
102
+
103
+ - 明确拒绝 Parquet / 列式:那会摧毁事件溯源的行级读取能力。
104
+ - 重复的超长内容(工具 schema、系统提示块,≥512 字符且出现 ≥2 次)在**索引层**只存一份
105
+ (`templates.json`),事件用 `contentRef` 指向它;索引加载时还原成原文,读者无感。
106
+ - **日志本身一字不改**:raw 仍是逐行原文,`deep_raw`、哈希恢复、行级游标全部不受影响。
107
+
108
+ **③ 语义层(从线性到亚线性)**
109
+
110
+ - 哲学:**无损存记忆、有损存过程**。原始 raw 降级为可选审计层,蒸馏后的 L2/L3 才是长期主体。
111
+ - 热窗口内保留 raw 原文;超出 `raw.hotWindowDays`(默认 30 天)且**已被 L3 摘要覆盖**的 raw
112
+ 分片,可在 `raw.distillPrune: true` 下被物理清理——**必经 Tombstone 路径**,删除即不可复活。
113
+ - **L2 走同类项合并**(`l2Merge`),绝不无限追加。
114
+ - **L3 硬熔断**:`semantic.maxEntries`(默认 **100**),超限按 LRU 淘汰最久未更新的摘要,
115
+ 淘汰以 append-only 的 `semantic_retire` 记录落盘(决策本身可审计)。
116
+ - 结果:L2/L3 随**事件重要性**增长,而不是随对话条数线性膨胀。
117
+
118
+ ### raw 保留三档
98
119
 
99
120
  raw 层提供三档,覆盖从“只留关键”到“全留”:
100
121
 
@@ -104,8 +125,8 @@ raw 层提供三档,覆盖从“只留关键”到“全留”:
104
125
  | `salience` | **默认**。只保留高价值回合:`salience ≥ raw.minSalience`、代码块、栈轨迹、错误类型等形态 |
105
126
  | `all` | 全部保存,受 `maxTurnKb` / `maxBytesPerDay` / `maxTotalMb` 预算约束 |
106
127
 
107
- 配合 `raw.retentionDays`(默认 90 天,必须严格大于 `archiveAfterDays`)与 `pinned` 永不清除,
108
- 形成“高价值永存 / 全量短存 / 按需不存”的完整谱系。
128
+ 配合 `raw.retentionDays`(默认 **365 天**,必须严格大于 `archiveAfterDays`)与 `pinned` 永不清除,
129
+ 形成“高价值永存 / 全量长期存 / 按需不存”的完整谱系。
109
130
 
110
131
  ### 检索、衰减与面板
111
132
 
@@ -125,7 +146,7 @@ raw 层提供三档,覆盖从“只留关键”到“全留”:
125
146
  pnpm add dsh-layers-hippocampus
126
147
 
127
148
  # 或从 GitHub 指定 tag
128
- pnpm add "github:382quaii/dsh-Layers-Hippocampus#v1.6.1"
149
+ pnpm add "github:382quaii/dsh-Layers-Hippocampus#v1.6.2"
129
150
  ```
130
151
 
131
152
  ### 2. 挂到 profile
@@ -161,7 +182,7 @@ node scripts/wait-for-routes.mjs
161
182
  ### 4. 验证
162
183
 
163
184
  ```bash
164
- npm test # 进程内全量用例(447 个)
185
+ npm test # 进程内全量用例(456 个)
165
186
  npm run check # 语法检查 + 全量测试
166
187
  ```
167
188
 
@@ -1,6 +1,6 @@
1
1
  # @local/dsh-memory — 分层长期记忆 Host 插件
2
2
 
3
- > 版本:**1.6.1** | 全量用例:**447/447** | 运行时依赖:**零**
3
+ > 版本:**1.6.2** | 全量用例:**456/456** | 运行时依赖:**零**
4
4
 
5
5
  给 DSH 智能体一份"活得比会话久"的记忆:**追加式原始日志是唯一真相源**,标签索引、日记、活跃集合全部是可丢弃、可重建的读模型,语义摘要独立于原始日志生死。
6
6
 
@@ -82,12 +82,56 @@ flowchart TD
82
82
  HINT --> P
83
83
  DT --> P
84
84
 
85
- R -.->|"月度门控 + 冷热判定"| AR["冷归档<br/>raw-archive-YYYY-MM.jsonl.gz/.zst"]
85
+ R -.->|"月度门控 + 冷热判定(90天+零访问)"| AR["冷归档<br/>raw-archive-YYYY-MM.jsonl.br (brotli 11)"]
86
86
  AR -.->|"流式解压"| SCAN
87
+
88
+ R -.->|"distillPrune: 已蒸馏 + 出热窗"| TB
89
+ IDXA -.->|"重复长文本 → contentRef"| TPL["templates.json<br/>(只存一份)"]
87
90
  ```
88
91
 
89
92
  **读路径与写路径分离**:写入只 append 到 `log/`(加 `ledger` 幂等键),索引/日记/标签树/图谱全部由 `maintain()` 离线重建;**读路径永不修改真相源**,因此任何读模型损坏都只是性能事件,不是数据事件。
90
93
 
94
+ ## 打破线性增长:压缩、编码、语义三层
95
+
96
+ append-only 且逐条存原文 ⇒ 增长 O(n);Zstd 只改变斜率。三层分别作用于不同环节:
97
+
98
+ ### ① 压缩层(冷数据极限压榨)
99
+
100
+ - **多维冷热判定**(`RawStore.archiveCold`,`src/rawStore.js`)——**全满足才归档**:
101
+ 1. 分片日期 > `raw.archiveAfterDays`(默认 **90**);
102
+ 2. 近 `raw.coldAccessWindowDays`(默认 **90**)内 `access_count == 0`(`state/raw-access.json`);
103
+ 3. 无 `pinned` / `status:handoff` / 活跃高频标签。
104
+ 近期被读过的「高龄」分片保持**明文**,O(1) 游标扫描不受影响。
105
+ - **极限压缩**:`src/compression.js` 默认 Brotli **quality 11**(`.jsonl.br`),
106
+ `gzip`(9) / `zstd` 仍可选;三者全为 Node 内置 `node:zlib`,无外部依赖。
107
+ - **月度门控**:`maintain()` 每月最多归档一次;同月已有归档则跳过(避免 deep_raw 重复行)。
108
+ - **写入崩溃安全**:先写 `<target>.tmp`,压缩流完全 flush 后 `rename`。
109
+ - 读取:`scanArchive()` 按扩展名分派解压器(`.br`/`.gz`/`.zst`),流式逐行、命中即停。
110
+
111
+ ### ② 编码层(引用去重,明确拒绝列式)
112
+
113
+ - `src/index/templates.js`:`dedupeTemplates(events)` 把「≥512 字符且出现 ≥2 次」的重复长文本
114
+ 提升为模板,事件侧置空 `content` 并写 `contentRef = tpl_<sha256 前16位>`。
115
+ - 模板随索引代际落盘为 `templates.json`;`IndexStore.current()` 加载时用 `resolveTemplates()`
116
+ 还原原文 —— 读者永远拿到完整内容。
117
+ - **红线**:日志不参与替换。raw 仍是逐行原文,`deep_raw`、`restoreByHash`、行级游标全部不变;
118
+ 数据本身即精确回答 O(n) 问题。
119
+ - 收益记入 `stats.templateRefs / stats.templates / stats.templateSavedChars`。
120
+
121
+ ### ③ 语义层(从线性到亚线性)
122
+
123
+ - **无损存记忆、有损存过程**:raw 降级为可选审计层,L2/L3 才是长期主体。
124
+ - `RawStore.pruneDistilled()`:仅当 `raw.distillPrune === true` **且**调用方给出已蒸馏日集合
125
+ (来自 L3 摘要的 `sourceEvents` → 事件日)时,才删除出热窗分片;删除前先把每条内容哈希写入
126
+ **tombstone**,因此不可能被重建复活。默认关闭 —— raw 仍是绝对真相。
127
+ - **L2 同类项合并**:`src/l2Merge.js`(`status:l2-merged` + `state/l2-merge.json`),不无限追加。
128
+ - **L3 硬熔断 + LRU**:`SemanticStore.enforceCapacity()`,上限 `semantic.maxEntries`(默认 **100**);
129
+ 超限时按 `updatedAt` 最旧优先追认 `semantic_retire`(append-only,可审计、可重放)。
130
+ `semantic.lruOnCap=false` 可关闭。`maintain()` 报告 `report.semanticCapacity`。
131
+
132
+ 效果:日志只在一个**有界热窗**内保持全量原文;冷数据被极限压缩、重复模板只存一份、
133
+ 已被蒸馏的过程数据可安全回收,而 L2/L3 的上界由「事件重要性」决定,不随对话条数线性膨胀。
134
+
91
135
  ## 配置
92
136
 
93
137
  ```yaml
@@ -637,7 +681,7 @@ window.__ModuleLoader__.load({
637
681
 
638
682
  运行器带**看门狗**:默认 **60s**(`MEM_TEST_TIMEOUT_MS` 可调)仍未退出,就打印**卡住时正在导入/执行的文件、最后完成的测试名与完成数、活动资源、尚未触发的定时器**,然后 `process.exit(1)`。它不会用 `process.exit(0)` 掩盖超时——挂起即失败。`MEM_TEST_TRACE=1` 可看文件级进度,`MEM_TEST_ONLY=<子串>` 只跑一组。
639
683
 
640
- 447 个用例(64 个文件)覆盖:
684
+ 456 个用例(64 个文件)覆盖:
641
685
 
642
686
  - 索引与标签:重建 digest 一致、行号漂移防护(eventId 不变、行号变)、同义合并、活跃集 cap 挤出、规则变更不改清单、空活跃集降级、top-k 有界有序去重。
643
687
  - 衰减与删除:30 天半衰期、reinforce 移动锚点(不存字段)、仅文本粗筛、标签过滤、维护代切换且旧代可读、boot 检查、压缩不丢记录、并发维护串行化、四阶段删除、archive 可回滚 vs purge 不可、strict 巩固暂停与恢复、任务重放幂等、错误 id 零变更。
package/index.js CHANGED
@@ -61,7 +61,7 @@ export { resolveConfig, DEFAULT_CONFIG };
61
61
  * of letting a raw 404 reach the user.
62
62
  */
63
63
  export const CAPABILITIES = Object.freeze({
64
- version: '1.6.1',
64
+ version: '1.6.2',
65
65
  spaces: true,
66
66
  memories: true,
67
67
  transferConsent: true,
@@ -1446,6 +1446,8 @@ function uiConfig(config) {
1446
1446
  features: config.features,
1447
1447
  // v1.5.6 L2 multi-merge tunables.
1448
1448
  l2Merge: config.l2Merge,
1449
+ // v1.6.1 L3 capacity breaker (semantic layer must not grow with conversation count).
1450
+ semantic: config.semantic,
1449
1451
  // v1.5.6: offline Dream tunables — SAFE SUBSET ONLY. `dream.llm` is deliberately
1450
1452
  // absent: the endpoint/credential live in the profile or DSH_DREAM_LLM_* env and
1451
1453
  // must never round-trip through the browser.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-layers-hippocampus",
3
- "version": "1.6.1",
3
+ "version": "1.6.2",
4
4
  "private": false,
5
5
  "description": "Layered long-term memory for DeepSeek Harness: append-only event log, rebuildable tag index, day diaries, independent semantic layer, L2.5 trend quarantine, offline knowledge graph and a Web UI panel.",
6
6
  "type": "module",
@@ -1,36 +1,47 @@
1
1
  /**
2
2
  * Compression-engine abstraction for the raw cold tier (v1.6.1, zero dependencies).
3
3
  *
4
- * The DEFAULT engine is `gzip` from Node's built-in `node:zlib`. `zstd` is also
5
- * built into modern Node (22+): when the runtime exposes it, an operator may switch
6
- * `raw.compressionEngine` to `zstd` for a better ratio WITHOUT installing anything.
4
+ * Three engines, all from Node's built-in `node:zlib` — nothing is installed:
7
5
  *
8
- * Older runtimes simply report zstd as unavailable and stay on gzip — the raw tier
9
- * never depends on an external package.
6
+ * - `gzip` : the conservative default-compatible engine (level 6);
7
+ * - `brotli` : the DEFAULT for cold archives — Brotli quality 11 ("极限压缩"),
8
+ * typically the best ratio for JSONL text;
9
+ * - `zstd` : available on Node 22+; faster decode, ratio between the two.
10
+ *
11
+ * An old runtime that lacks an engine falls back to gzip and reports `fallback`,
12
+ * so the raw tier can never hard-depend on an optional codec.
10
13
  */
11
14
 
12
15
  import zlib from 'node:zlib';
13
16
 
14
- export const COMPRESSION_ENGINES = Object.freeze(['gzip', 'zstd']);
17
+ export const COMPRESSION_ENGINES = Object.freeze(['brotli', 'gzip', 'zstd']);
15
18
 
16
19
  /** Extension for a monthly archive produced by the given engine. */
17
- export function archiveExtension(engine = 'gzip') {
18
- return engine === 'zstd' ? '.jsonl.zst' : '.jsonl.gz';
20
+ export function archiveExtension(engine = 'brotli') {
21
+ if (engine === 'zstd') return '.jsonl.zst';
22
+ if (engine === 'brotli') return '.jsonl.br';
23
+ return '.jsonl.gz';
19
24
  }
20
25
 
21
26
  /** Engine that produced an existing archive file (by extension). */
22
27
  export function engineForArchive(name) {
23
- return String(name).endsWith('.jsonl.zst') ? 'zstd' : 'gzip';
28
+ const text = String(name);
29
+ if (text.endsWith('.jsonl.zst')) return 'zstd';
30
+ if (text.endsWith('.jsonl.br')) return 'brotli';
31
+ return 'gzip';
24
32
  }
25
33
 
26
34
  export function isArchiveFile(name) {
27
- return /^raw-archive-\d{4}-\d{2}\.jsonl\.(gz|zst)$/.test(String(name));
35
+ return /^raw-archive-\d{4}-\d{2}\.jsonl\.(gz|zst|br)$/.test(String(name));
28
36
  }
29
37
 
30
38
  /** Runtime capability probe (never throws). */
31
39
  export function probeCompression() {
32
40
  return {
33
41
  gzip: typeof zlib.createGzip === 'function',
42
+ brotli:
43
+ typeof zlib.createBrotliCompress === 'function' &&
44
+ typeof zlib.createBrotliDecompress === 'function',
34
45
  zstd:
35
46
  typeof zlib.createZstdCompress === 'function' &&
36
47
  typeof zlib.createZstdDecompress === 'function',
@@ -40,26 +51,46 @@ export function probeCompression() {
40
51
 
41
52
  /** Resolve the configured engine to a usable one (silent fallback to gzip). */
42
53
  export function resolveEngine(requested, probe = probeCompression()) {
43
- const wanted = String(requested ?? 'gzip');
54
+ const wanted = String(requested ?? 'brotli');
44
55
  if (wanted === 'zstd' && probe.zstd) return { engine: 'zstd', fallback: false, probe };
45
56
  if (wanted === 'zstd' && !probe.zstd) return { engine: 'gzip', fallback: true, probe };
57
+ if (wanted === 'brotli' && probe.brotli) return { engine: 'brotli', fallback: false, probe };
58
+ if (wanted === 'brotli' && !probe.brotli) return { engine: 'gzip', fallback: true, probe };
46
59
  return { engine: 'gzip', fallback: false, probe };
47
60
  }
48
61
 
62
+ /** Maximum quality for each engine (the "极限压缩" setting). */
63
+ export const ENGINE_MAX_LEVEL = Object.freeze({ gzip: 9, brotli: 11, zstd: 22 });
64
+
49
65
  /** Compressor stream for writing one archive. */
50
- export function createCompressStream(engine = 'gzip') {
66
+ export function createCompressStream(engine = 'brotli', { level = null } = {}) {
51
67
  if (engine === 'zstd') {
52
68
  if (typeof zlib.createZstdCompress !== 'function') throw new Error('zstd compression is unavailable in this Node runtime');
53
- return zlib.createZstdCompress({ params: { [zlib.constants.ZSTD_c_compressionLevel]: 6 } });
69
+ const zstdLevel = level ?? 6;
70
+ return zlib.createZstdCompress({ params: { [zlib.constants.ZSTD_c_compressionLevel]: zstdLevel } });
54
71
  }
55
- return zlib.createGzip({ level: 6 });
72
+ if (engine === 'brotli') {
73
+ if (typeof zlib.createBrotliCompress !== 'function') throw new Error('brotli compression is unavailable in this Node runtime');
74
+ // quality 11 is Brotli's maximum: slow but this path only runs once per month.
75
+ return zlib.createBrotliCompress({
76
+ params: {
77
+ [zlib.constants.BROTLI_PARAM_QUALITY]: level ?? zlib.constants.BROTLI_MAX_QUALITY,
78
+ [zlib.constants.BROTLI_PARAM_SIZE_HINT]: 1 << 20,
79
+ },
80
+ });
81
+ }
82
+ return zlib.createGzip({ level: level ?? 9 });
56
83
  }
57
84
 
58
85
  /** Decompressor stream for reading one archive. */
59
- export function createDecompressStream(engine = 'gzip') {
86
+ export function createDecompressStream(engine = 'brotli') {
60
87
  if (engine === 'zstd') {
61
88
  if (typeof zlib.createZstdDecompress !== 'function') throw new Error('zstd decompression is unavailable in this Node runtime');
62
89
  return zlib.createZstdDecompress();
63
90
  }
91
+ if (engine === 'brotli') {
92
+ if (typeof zlib.createBrotliDecompress !== 'function') throw new Error('brotli decompression is unavailable in this Node runtime');
93
+ return zlib.createBrotliDecompress();
94
+ }
64
95
  return zlib.createGunzip();
65
96
  }
package/src/config.js CHANGED
@@ -227,13 +227,22 @@ export const DEFAULT_CONFIG = Object.freeze({
227
227
  maxTurnKb: 64,
228
228
  maxBytesPerDay: 8,
229
229
  maxTotalMb: 256,
230
- retentionDays: 90,
231
- // v1.6.1 cold-tier: shards older than this are candidates for monthly gzip
232
- // archiving (must stay strictly below retentionDays).
233
- archiveAfterDays: 7,
234
- // Monthly archive compressor. `gzip` is the built-in default; `zstd` uses the
235
- // Node runtime's built-in zstd when available and silently falls back otherwise.
236
- compressionEngine: 'gzip',
230
+ retentionDays: 365,
231
+ // v1.6.1 cold-tier: a shard becomes an archive CANDIDATE only when it is older
232
+ // than this AND has had zero access for `coldAccessWindowDays` AND carries no
233
+ // pinned / status:handoff / hot-tag record. Must stay strictly below retentionDays.
234
+ archiveAfterDays: 90,
235
+ // How long "no access" must hold before a cold shard may be archived.
236
+ coldAccessWindowDays: 90,
237
+ // Monthly archive compressor. `brotli` (quality 11) is the default极限压缩;
238
+ // `zstd` / `gzip` remain selectable. All three are Node built-ins — no installs.
239
+ compressionEngine: 'brotli',
240
+ // v1.6.1 semantic-layer evolution: once a shard falls outside the hot window AND
241
+ // its distillation has produced L2/L3 output, the raw bytes may be physically
242
+ // cleaned (always through the tombstone path, so nothing can resurrect).
243
+ // Default OFF: raw stays the absolute truth unless an operator opts in.
244
+ hotWindowDays: 30,
245
+ distillPrune: false,
237
246
  maxScanMb: 16,
238
247
  // Deep-scan turn budget. The scanner walks each shard NEWEST-FIRST, so this is
239
248
  // "how far back from the tail a single deep_raw may look" — a knob, not a
@@ -268,6 +277,10 @@ export const DEFAULT_CONFIG = Object.freeze({
268
277
  // v1.5.6 L2 multi-merge: condense duplicate same-tag episodes into one record,
269
278
  // pinned and ordinary groups strictly separated. Offline (maintain) only.
270
279
  l2Merge: Object.freeze({ enabled: true, minGroupSize: 2, maxGroupsPerRun: 5, maxSummaryChars: 400 }),
280
+ // v1.6.1 L3 capacity breaker: the semantic layer grows with EVENT IMPORTANCE, not
281
+ // with conversation count. At the cap, the least-recently-used summary is retired
282
+ // (LRU), never appended forever.
283
+ semantic: Object.freeze({ maxEntries: 100, lruOnCap: true }),
271
284
  policy: Object.freeze({}),
272
285
  });
273
286
 
@@ -713,22 +726,47 @@ export function resolveConfig(raw = {}, { env = process.env } = {}) {
713
726
  'raw.retentionDays',
714
727
  { min: 1, max: 365 },
715
728
  );
716
- const rawArchiveAfterDays = requireInteger(
717
- rawIn.archiveAfterDays === undefined ? defaults.raw.archiveAfterDays : rawIn.archiveAfterDays,
729
+ // v1.6.2 compat: profiles written before 1.6.2 usually pin `retentionDays: 30`
730
+ // while `archiveAfterDays` did not exist yet. Failing fast there would leave the
731
+ // plugin unloaded (routes 404) for every existing install, so when the caller did
732
+ // NOT state `archiveAfterDays` explicitly we derive a valid one instead of throwing.
733
+ // An EXPLICIT archiveAfterDays that is out of range still fails fast.
734
+ const archiveAfterDaysExplicit = rawIn.archiveAfterDays !== undefined;
735
+ let rawArchiveAfterDays = requireInteger(
736
+ archiveAfterDaysExplicit ? rawIn.archiveAfterDays : defaults.raw.archiveAfterDays,
718
737
  'raw.archiveAfterDays',
719
738
  { min: 1, max: 3650 },
720
739
  );
740
+ let rawArchiveAfterDaysDerived = false;
721
741
  if (rawArchiveAfterDays >= rawRetentionDays) {
722
- throw configError(
723
- ErrorCodes.CONFIG_OUT_OF_RANGE,
724
- `config.raw.archiveAfterDays (${rawArchiveAfterDays}) must be strictly below config.raw.retentionDays (${rawRetentionDays}); otherwise there is nothing to archive`,
725
- { key: 'raw.archiveAfterDays', got: rawArchiveAfterDays, retentionDays: rawRetentionDays },
726
- );
742
+ if (archiveAfterDaysExplicit) {
743
+ throw configError(
744
+ ErrorCodes.CONFIG_OUT_OF_RANGE,
745
+ `config.raw.archiveAfterDays (${rawArchiveAfterDays}) must be strictly below config.raw.retentionDays (${rawRetentionDays}); otherwise there is nothing to archive`,
746
+ { key: 'raw.archiveAfterDays', got: rawArchiveAfterDays, retentionDays: rawRetentionDays },
747
+ );
748
+ }
749
+ rawArchiveAfterDays = Math.max(1, rawRetentionDays - 1);
750
+ rawArchiveAfterDaysDerived = true;
727
751
  }
752
+ const rawColdAccessWindowDays = requireInteger(
753
+ rawIn.coldAccessWindowDays === undefined ? defaults.raw.coldAccessWindowDays : rawIn.coldAccessWindowDays,
754
+ 'raw.coldAccessWindowDays',
755
+ { min: 1, max: 3650 },
756
+ );
728
757
  const rawCompressionEngine = requireEnum(
729
758
  rawIn.compressionEngine === undefined ? defaults.raw.compressionEngine : rawIn.compressionEngine,
730
759
  'raw.compressionEngine',
731
- ['gzip', 'zstd'],
760
+ ['brotli', 'gzip', 'zstd'],
761
+ );
762
+ const rawHotWindowDays = requireInteger(
763
+ rawIn.hotWindowDays === undefined ? defaults.raw.hotWindowDays : rawIn.hotWindowDays,
764
+ 'raw.hotWindowDays',
765
+ { min: 1, max: 3650 },
766
+ );
767
+ const rawDistillPrune = requireBoolean(
768
+ rawIn.distillPrune === undefined ? defaults.raw.distillPrune : rawIn.distillPrune,
769
+ 'raw.distillPrune',
732
770
  );
733
771
  const rawMaxScanMb = requireInteger(
734
772
  rawIn.maxScanMb === undefined ? defaults.raw.maxScanMb : rawIn.maxScanMb,
@@ -941,8 +979,24 @@ export function resolveConfig(raw = {}, { env = process.env } = {}) {
941
979
  ),
942
980
  });
943
981
 
944
- const policyIn = input.policy === undefined ? {} : input.policy;
945
- if (!isPlainObject(policyIn)) {
982
+ // ---- L3 capacity breaker (v1.6.1) --------------------------------------
983
+ const semanticIn = input.semantic === undefined ? {} : input.semantic;
984
+ if (!isPlainObject(semanticIn)) {
985
+ throw configError(ErrorCodes.CONFIG_INVALID_TYPE, 'config.semantic must be an object', { key: 'semantic' });
986
+ }
987
+ const semanticConfig = Object.freeze({
988
+ maxEntries: requireInteger(
989
+ semanticIn.maxEntries === undefined ? defaults.semantic.maxEntries : semanticIn.maxEntries,
990
+ 'semantic.maxEntries',
991
+ { min: 1, max: 100_000 },
992
+ ),
993
+ lruOnCap: requireBoolean(
994
+ semanticIn.lruOnCap === undefined ? defaults.semantic.lruOnCap : semanticIn.lruOnCap,
995
+ 'semantic.lruOnCap',
996
+ ),
997
+ });
998
+
999
+ const policyIn = input.policy === undefined ? {} : input.policy; if (!isPlainObject(policyIn)) {
946
1000
  throw configError(ErrorCodes.CONFIG_INVALID_TYPE, 'config.policy must be an object', { key: 'policy' });
947
1001
  }
948
1002
  const identityIn = input.identity ?? {};
@@ -1119,7 +1173,13 @@ export function resolveConfig(raw = {}, { env = process.env } = {}) {
1119
1173
  maxTotalMb: rawMaxTotalMb,
1120
1174
  retentionDays: rawRetentionDays,
1121
1175
  archiveAfterDays: rawArchiveAfterDays,
1176
+ // True when archiveAfterDays was DERIVED to stay below an older profile's
1177
+ // retentionDays; surfaced so the settings page can explain the value.
1178
+ archiveAfterDaysDerived: rawArchiveAfterDaysDerived,
1179
+ coldAccessWindowDays: rawColdAccessWindowDays,
1122
1180
  compressionEngine: rawCompressionEngine,
1181
+ hotWindowDays: rawHotWindowDays,
1182
+ distillPrune: rawDistillPrune,
1123
1183
  maxScanMb: rawMaxScanMb,
1124
1184
  maxScanTurns: rawMaxScanTurns,
1125
1185
  maxResultTokens: rawMaxResultTokens,
@@ -1133,6 +1193,7 @@ export function resolveConfig(raw = {}, { env = process.env } = {}) {
1133
1193
  tagging: taggingConfig,
1134
1194
  features: featuresConfig,
1135
1195
  l2Merge: l2MergeConfig,
1196
+ semantic: semanticConfig,
1136
1197
  policy: policyIn,
1137
1198
  };
1138
1199
  return resolved;
@@ -20,6 +20,7 @@ import { buildAliasMap, hashPolicy, normalisedScore, normaliseTagToken } from '.
20
20
  import { decayFactor } from '../decay.js';
21
21
  import { clamp01, dayKey, round, sha256, snippet } from '../util.js';
22
22
  import { RECORD_TYPES } from '../log/records.js';
23
+ import { dedupeTemplates } from './templates.js';
23
24
 
24
25
  /**
25
26
  * Fold the log into the three things derivation needs.
@@ -178,9 +179,15 @@ export function buildIndex({
178
179
  // identically across rebuilds, so no insertion-order dependence is allowed.
179
180
  events.sort((a, b) => b.anchorTime - a.anchorTime || a.eventId.localeCompare(b.eventId));
180
181
 
181
- const tags = deriveTagTable(events, { policy, now, maxPostingsPerTag });
182
+ // v1.6.1 referential dedup: the LOG keeps every raw row; the index stores repeated
183
+ // long texts (tool schemas / system prompt blocks) ONCE and points at them.
184
+ const deduped = dedupeTemplates(events);
185
+ const indexedEvents = deduped.events;
186
+ const templates = deduped.templates;
187
+
188
+ const tags = deriveTagTable(indexedEvents, { policy, now, maxPostingsPerTag });
182
189
  const activeSet = deriveActiveSet(tags, { policy, now, previous });
183
- const diary = deriveDiary(events, { policy, now });
190
+ const diary = deriveDiary(indexedEvents, { policy, now });
184
191
 
185
192
  const stats = {
186
193
  // Log-side counters make the boot check a two-counter comparison.
@@ -203,6 +210,11 @@ export function buildIndex({
203
210
  postingsDropped: Object.values(tags).reduce((sum, entry) => sum + entry.postingsDropped, 0),
204
211
  // v1.5.6: how many records are pinned (never decay, never archived).
205
212
  pinnedEvents: events.filter((event) => event.pinned === true).length,
213
+ // v1.6.1 referential dedup accounting: one template row per repeated long text,
214
+ // and how many characters the index no longer duplicates.
215
+ templateRefs: deduped.stats.refs,
216
+ templates: deduped.stats.templates,
217
+ templateSavedChars: deduped.stats.savedChars,
206
218
  };
207
219
 
208
220
  return {
@@ -211,7 +223,8 @@ export function buildIndex({
211
223
  policyHash: hashPolicy(policy),
212
224
  sourceLogGen,
213
225
  aliases: Object.fromEntries([...aliases.entries()].sort(([a], [b]) => a.localeCompare(b))),
214
- events,
226
+ events: indexedEvents,
227
+ templates,
215
228
  tags,
216
229
  activeSet,
217
230
  diary,
@@ -14,6 +14,7 @@
14
14
 
15
15
  import fs from 'node:fs';
16
16
  import path from 'node:path';
17
+ import { resolveTemplates } from './templates.js';
17
18
  import { MemoryError, ErrorCodes } from '../errors.js';
18
19
  import {
19
20
  ensureDir,
@@ -33,6 +34,7 @@ const FILES = {
33
34
  diary: 'diary.json',
34
35
  tombstones: 'tombstones.json',
35
36
  aliases: 'aliases.json',
37
+ templates: 'templates.json',
36
38
  manifest: 'manifest.json',
37
39
  };
38
40
 
@@ -73,13 +75,18 @@ export class IndexStore {
73
75
  if (!manifest) {
74
76
  throw new MemoryError(ErrorCodes.INDEX_MISSING, 'index generation has no manifest', { gen });
75
77
  }
78
+ const templates = readJson(path.join(dir, FILES.templates), {});
79
+ const rawEvents = readJson(path.join(dir, FILES.events), []);
76
80
  const view = {
77
81
  generation: gen,
78
82
  manifest,
79
83
  builtAt: manifest.builtAt,
80
84
  policyHash: manifest.policyHash,
81
85
  sourceLogGen: manifest.sourceLogGen,
82
- events: readJson(path.join(dir, FILES.events), []),
86
+ // v1.6.1: the on-disk index stores repeated long contents ONCE (templates) and
87
+ // events point at them; every reader gets the resolved content back.
88
+ events: resolveTemplates(rawEvents, templates),
89
+ templates,
83
90
  tags: readJson(path.join(dir, FILES.tags), {}),
84
91
  activeSet: readJson(path.join(dir, FILES.activeSet), { cap: 0, entries: [], evicted: [], churn: {} }),
85
92
  diary: readJson(path.join(dir, FILES.diary), { blocks: [] }),
@@ -113,6 +120,7 @@ export class IndexStore {
113
120
  writeJsonAtomic(path.join(tmp, FILES.diary), index.diary);
114
121
  writeJsonAtomic(path.join(tmp, FILES.tombstones), index.tombstones);
115
122
  writeJsonAtomic(path.join(tmp, FILES.aliases), index.aliases);
123
+ writeJsonAtomic(path.join(tmp, FILES.templates), index.templates ?? {});
116
124
 
117
125
  const manifest = {
118
126
  v: 1,
@@ -136,7 +144,8 @@ export class IndexStore {
136
144
  builtAt: index.builtAt,
137
145
  policyHash: index.policyHash,
138
146
  sourceLogGen: manifest.sourceLogGen,
139
- events: index.events,
147
+ events: resolveTemplates(index.events, index.templates ?? {}),
148
+ templates: index.templates ?? {},
140
149
  tags: index.tags,
141
150
  activeSet: index.activeSet,
142
151
  diary: index.diary,
@@ -0,0 +1,84 @@
1
+ /**
2
+ * Referential content dedup for the INDEX layer (v1.6.1, "编码层小改").
3
+ *
4
+ * The log stays raw and row-addressable: every record keeps its own `content`, so
5
+ * `deep_raw`, hash restore and the row-level cursor are untouched. What this module
6
+ * removes is the REPEATED COPY inside the read model: when the same long text (tool
7
+ * schema, system prompt block, role template) appears in `minOccurrences`+ events and
8
+ * is at least `minChars` long, the index stores it ONCE in `templates.json` and each
9
+ * event carries `contentRef` instead of the full text.
10
+ *
11
+ * Contract:
12
+ * - the index is a derived read model, so a rematerialised content is still exact;
13
+ * - `resolveTemplates()` runs on every index load, so readers never see a ref;
14
+ * - a missing template file degrades to "no dedup" (refs stay unresolved → the
15
+ * event content is empty only for events that were stored as refs, which cannot
16
+ * happen without the template file).
17
+ */
18
+
19
+ import { sha256 } from '../util.js';
20
+
21
+ export const TEMPLATE_MIN_CHARS = 512;
22
+ export const TEMPLATE_MIN_OCCURRENCES = 2;
23
+
24
+ export function templateRefFor(content) {
25
+ return `tpl_${sha256(content).slice(0, 16)}`;
26
+ }
27
+
28
+ /**
29
+ * Replace repeated long contents with refs.
30
+ * @param {object[]} events projected index events (each may carry `content`)
31
+ * @param {{minChars?: number, minOccurrences?: number}} [options]
32
+ * @returns {{events: object[], templates: object, stats: {templates: number, refs: number, savedChars: number}}}
33
+ */
34
+ export function dedupeTemplates(events, options = {}) {
35
+ const minChars = Math.max(1, Number(options.minChars ?? TEMPLATE_MIN_CHARS));
36
+ const minOccurrences = Math.max(2, Number(options.minOccurrences ?? TEMPLATE_MIN_OCCURRENCES));
37
+ const counts = new Map();
38
+ for (const event of events) {
39
+ const content = event?.content;
40
+ if (typeof content !== 'string' || content.length < minChars) continue;
41
+ counts.set(content, (counts.get(content) ?? 0) + 1);
42
+ }
43
+ const repeated = new Map();
44
+ for (const [content, count] of counts) {
45
+ if (count >= minOccurrences) repeated.set(content, templateRefFor(content));
46
+ }
47
+ if (repeated.size === 0) {
48
+ return { events, templates: {}, stats: { templates: 0, refs: 0, savedChars: 0 } };
49
+ }
50
+ const templates = {};
51
+ for (const [content, ref] of repeated) templates[ref] = content;
52
+ let refs = 0;
53
+ let savedChars = 0;
54
+ const projected = events.map((event) => {
55
+ const content = event?.content;
56
+ if (typeof content !== 'string') return event;
57
+ const ref = repeated.get(content);
58
+ if (!ref) return event;
59
+ refs += 1;
60
+ // Every copy beyond the single stored template is a saved copy.
61
+ savedChars += content.length;
62
+ return { ...event, content: '', contentRef: ref };
63
+ });
64
+ savedChars -= [...repeated.keys()].reduce((sum, content) => sum + content.length, 0);
65
+ return { events: projected, templates, stats: { templates: repeated.size, refs, savedChars: Math.max(0, savedChars) } };
66
+ }
67
+
68
+ /**
69
+ * Restore every `contentRef` back to its full text. Shallow: returns new objects for
70
+ * ref-carrying events only, so an index without templates costs nothing.
71
+ */
72
+ export function resolveTemplates(events, templates) {
73
+ if (!templates || Object.keys(templates).length === 0) return events;
74
+ let changed = false;
75
+ const resolved = events.map((event) => {
76
+ const ref = event?.contentRef;
77
+ if (!ref) return event;
78
+ const content = templates[ref];
79
+ if (typeof content !== 'string') return event;
80
+ changed = true;
81
+ return { ...event, content };
82
+ });
83
+ return changed ? resolved : events;
84
+ }
package/src/memory.js CHANGED
@@ -2126,6 +2126,38 @@ export class Memory {
2126
2126
  } catch (error) {
2127
2127
  report.tagTreeError = error instanceof Error ? error.message : String(error);
2128
2128
  }
2129
+ // v1.6.1 semantic-layer evolution: "无损存记忆、有损存过程". Only when the
2130
+ // operator opts in (raw.distillPrune) do we clean raw bytes whose day is already
2131
+ // covered by an L3 summary — and always through the tombstone path.
2132
+ try {
2133
+ const events = this.indexManager?.snapshot?.()?.events ?? [];
2134
+ const byId = new Map(events.map((event) => [event.eventId, event]));
2135
+ const distilledDays = new Set();
2136
+ for (const summary of this.semanticStore.list()) {
2137
+ for (const eventId of summary.sourceEvents ?? []) {
2138
+ const event = byId.get(eventId);
2139
+ if (Number.isFinite(event?.eventTime)) distilledDays.add(dayKey(event.eventTime));
2140
+ }
2141
+ }
2142
+ report.rawDistillPrune = await this.raw.pruneDistilled({
2143
+ now: this.clock.now(),
2144
+ hotWindowDays: this.config?.raw?.hotWindowDays ?? 30,
2145
+ distilledDays,
2146
+ });
2147
+ } catch (error) {
2148
+ report.rawDistillPruneError = error instanceof Error ? error.message : String(error);
2149
+ }
2150
+ // v1.6.1 L3 capacity breaker: keep the semantic layer bounded by importance, not
2151
+ // by conversation count. Excess summaries are retired via LRU (append-only retire).
2152
+ try {
2153
+ report.semanticCapacity = this.semanticStore.enforceCapacity({
2154
+ clock: this.clock,
2155
+ maxEntries: this.config?.semantic?.maxEntries ?? 100,
2156
+ lruOnCap: this.config?.semantic?.lruOnCap !== false,
2157
+ });
2158
+ } catch (error) {
2159
+ report.semanticCapacityError = error instanceof Error ? error.message : String(error);
2160
+ }
2129
2161
  this.refreshBriefing();
2130
2162
  return report;
2131
2163
  }
package/src/rawArchive.js CHANGED
@@ -33,7 +33,7 @@ export function archiveMonthOf(day) {
33
33
  return String(day).slice(0, 7); // YYYY-MM
34
34
  }
35
35
 
36
- export function archiveName(month, engine = 'gzip') {
36
+ export function archiveName(month, engine = 'brotli') {
37
37
  return `${ARCHIVE_PREFIX}${month}${archiveExtension(engine)}`;
38
38
  }
39
39
 
@@ -76,6 +76,15 @@ export class RawArchive {
76
76
  return value && typeof value === 'object' ? value : { lastRunAt: null, archives: {} };
77
77
  }
78
78
 
79
+ /** Persist the archive bookkeeping (used by prune when a whole month is dropped). */
80
+ writeState(state) {
81
+ ensureDir(this.stateDir);
82
+ writeJsonAtomic(this.archiveFile, {
83
+ lastRunAt: state?.lastRunAt ?? null,
84
+ archives: state?.archives ?? {},
85
+ });
86
+ }
87
+
79
88
  listArchives() {
80
89
  try {
81
90
  return fs.readdirSync(this.rawDir).filter(isArchiveName).sort();
@@ -92,7 +101,7 @@ export class RawArchive {
92
101
  * Build (or extend) the month archive from eligible shards.
93
102
  * @returns {Promise<{ archived: string[], month: string|null, bytes: number, skipped: string[], reason?: string }>}
94
103
  */
95
- async archive({ shards, eligible, now = this.clock.now(), engine = 'gzip' }) {
104
+ async archive({ shards, eligible, now = this.clock.now(), engine = 'brotli' }) {
96
105
  const state = this.readState();
97
106
  const monthGateMs = Number(state.lastRunAt ?? 0);
98
107
  if (monthGateMs > 0 && now - monthGateMs < MONTH_MS) {
@@ -161,7 +170,7 @@ export class RawArchive {
161
170
  * write is crash-safe: output goes to `<target>.tmp` and is renamed only after the
162
171
  * compressor has fully flushed.
163
172
  */
164
- export async function mergeShardsToArchive({ files, target, engine = 'gzip' }) {
173
+ export async function mergeShardsToArchive({ files, target, engine = 'brotli' }) {
165
174
  ensureDir(path.dirname(target));
166
175
  const tmp = `${target}.tmp`;
167
176
  const out = fs.createWriteStream(tmp);
package/src/rawStore.js CHANGED
@@ -27,6 +27,7 @@ import { createHash } from 'node:crypto';
27
27
  import { MemoryError, ErrorCodes } from './errors.js';
28
28
  import { dayKey, ensureDir, sha256 } from './util.js';
29
29
  import { RawArchive, archiveMonthOf, isArchiveName, scanGzipArchive } from './rawArchive.js';
30
+ import { engineForArchive } from './compression.js';
30
31
  import { buildIndex, indexFileFor, isIndexFile, readIndex, shardOverlapsWindow, writeIndex } from './rawIndex.js';
31
32
 
32
33
  export const RAW_DIR = 'raw';
@@ -500,7 +501,7 @@ export class RawStore {
500
501
  for (let cursor = startTime; cursor <= endTime; cursor += 86_400_000) wantedMonths.add(archiveMonthOf(dayKey(cursor)));
501
502
  const archives = this.archive
502
503
  .listArchives()
503
- .filter((name) => wantedMonths.has(name.replace(/^raw-archive-/, '').replace(/\.jsonl\.(gz|zst)$/, '')));
504
+ .filter((name) => wantedMonths.has(name.replace(/^raw-archive-/, '').replace(/\.jsonl\.(gz|zst|br)$/, '')));
504
505
 
505
506
  const hits = [];
506
507
  const archiveErrors = [];
@@ -713,19 +714,20 @@ export class RawStore {
713
714
 
714
715
  /**
715
716
  * Cold-tier archiving (v1.6.1). Runs at most once per month, merges all eligible
716
- * daily shards of a calendar month into `raw-archive-YYYY-MM.jsonl.gz`.
717
+ * daily shards of a calendar month into `raw-archive-YYYY-MM.jsonl.br` (brotli 11).
717
718
  *
718
- * Eligibility (ALL must hold):
719
- * 1. shard day is older than `raw.archiveAfterDays` (default 30);
720
- * 2. access_count over the last 30 days is 0 (counter in state/raw-access.json);
719
+ * Multi-dimensional eligibility — ALL must hold (never age alone):
720
+ * 1. shard day is older than `raw.archiveAfterDays` (default 90);
721
+ * 2. access_count in `raw.coldAccessWindowDays` (default 90) is 0;
721
722
  * 3. the shard contains no pinned / status:handoff / hot-tag event.
722
723
  */
723
- async archiveCold({ now = this.clock.now(), hotTags = null, archiveAfterDays = null } = {}) {
724
+ async archiveCold({ now = this.clock.now(), hotTags = null, archiveAfterDays = null, coldAccessWindowDays = null } = {}) {
724
725
  const config = this.config();
725
- const afterDays = Math.max(1, Number(archiveAfterDays ?? config.archiveAfterDays ?? 30));
726
+ const afterDays = Math.max(1, Number(archiveAfterDays ?? config.archiveAfterDays ?? 90));
727
+ const accessWindowDays = Math.max(1, Number(coldAccessWindowDays ?? config.coldAccessWindowDays ?? 90));
726
728
  const access = this.archive.readAccess();
727
729
  const cutoff = dayKey(now - afterDays * 86_400_000);
728
- const recentCutoff = now - 30 * 86_400_000;
730
+ const recentCutoff = now - accessWindowDays * 86_400_000;
729
731
  const hot = new Set(Array.isArray(hotTags) ? hotTags : []);
730
732
  const eligible = [];
731
733
  const skipped = [];
@@ -774,7 +776,7 @@ export class RawStore {
774
776
  shards: this.listShards(),
775
777
  eligible,
776
778
  now,
777
- engine: config.compressionEngine ?? 'gzip',
779
+ engine: config.compressionEngine ?? 'brotli',
778
780
  });
779
781
  if (result.archived.length > 0) {
780
782
  this._total = null;
@@ -784,12 +786,78 @@ export class RawStore {
784
786
  return { ...result, eligible: eligible.length, skipped };
785
787
  }
786
788
 
789
+ /**
790
+ * v1.6.1 semantic-layer evolution: "无损存记忆、有损存过程".
791
+ *
792
+ * A shard outside `raw.hotWindowDays` whose distillation already produced L2/L3
793
+ * output may be physically cleaned. Every removed record's content hash is written
794
+ * through the TOMBSTONE path first, so nothing can be resurrected by a later
795
+ * replay/rebuild — the deletion is real, not a hide.
796
+ *
797
+ * Safety: this never runs unless `raw.distillPrune` is on AND the caller passes the
798
+ * distilled day set (coverage proof). Raw remains the absolute truth by default.
799
+ *
800
+ * @param {{now?: number, hotWindowDays?: number, distilledDays?: Iterable<string>, limit?: number}} input
801
+ */
802
+ async pruneDistilled({ now = this.clock.now(), hotWindowDays = null, distilledDays = null, limit = Infinity } = {}) {
803
+ const config = this.config();
804
+ if (config.distillPrune !== true) {
805
+ return { enabled: false, removed: [], freedBytes: 0, tombstoned: 0, reason: 'distillPrune-disabled' };
806
+ }
807
+ const covered = new Set(Array.isArray(distilledDays) ? distilledDays : distilledDays ? [...distilledDays] : []);
808
+ if (covered.size === 0) {
809
+ return { enabled: true, removed: [], freedBytes: 0, tombstoned: 0, reason: 'no-distilled-days' };
810
+ }
811
+ const windowDays = Math.max(1, Number(hotWindowDays ?? config.hotWindowDays ?? 30));
812
+ const today = dayKey(now);
813
+ const cutoff = dayKey(now - windowDays * 86_400_000);
814
+ const removed = [];
815
+ const hashes = new Set();
816
+ let freed = 0;
817
+ for (const name of this.listShards().slice(0, Number.isFinite(limit) ? limit : undefined)) {
818
+ const day = name.replace('.jsonl', '');
819
+ if (day === today) continue; // never touch the shard being written
820
+ if (day >= cutoff) continue; // still hot: keep the verbatim window
821
+ if (!covered.has(day)) continue; // no distillation proof for this day
822
+ const file = path.join(this.dir, name);
823
+ try {
824
+ for await (const line of readLinesForward(file)) {
825
+ if (!line.trim()) continue;
826
+ try {
827
+ const record = JSON.parse(line);
828
+ if (record?.type === 'raw_tombstone' || typeof record?.content !== 'string') continue;
829
+ hashes.add(sha256(record.content));
830
+ } catch {
831
+ /* malformed line: it cannot be hashed, so it cannot be tombstoned */
832
+ }
833
+ }
834
+ const size = fs.statSync(file).size;
835
+ fs.rmSync(file, { force: true });
836
+ fs.rmSync(indexFileFor(file), { force: true });
837
+ freed += size;
838
+ removed.push(day);
839
+ } catch (error) {
840
+ if (error?.code === 'ENOENT') continue;
841
+ throw error;
842
+ }
843
+ }
844
+ if (hashes.size > 0) await this.tombstone([...hashes], { at: now });
845
+ if (removed.length > 0) {
846
+ this._total = null;
847
+ this._hashes.clear();
848
+ this._dayBytes.clear();
849
+ this._tombstones = null;
850
+ }
851
+ return { enabled: true, removed, freedBytes: freed, tombstoned: hashes.size, hotWindowDays: windowDays };
852
+ }
853
+
787
854
  /** TTL: delete whole shards strictly older than `today - retentionDays`. */ async prune({ now = this.clock.now() } = {}) {
788
855
  const config = this.config();
789
856
  const retention = Math.max(1, config.retentionDays ?? 30);
790
857
  const today = dayKey(now);
791
858
  const cutoff = dayKey(now - retention * 86_400_000);
792
859
  const removed = [];
860
+ const removedArchives = [];
793
861
  let freed = 0;
794
862
  for (const name of this.listShards()) {
795
863
  const day = name.replace('.jsonl', '');
@@ -807,13 +875,40 @@ export class RawStore {
807
875
  /* already gone */
808
876
  }
809
877
  }
810
- if (removed.length > 0) {
878
+ // v1.6.2: archives obey the SAME retention. A whole month is dropped only when
879
+ // its last day is already before the cutoff, so a retention of 30 days can no
880
+ // longer turn cold data into unbounded `.br` files that outlive the policy.
881
+ const cutoffMonth = cutoff.slice(0, 7);
882
+ for (const name of this.archive.listArchives()) {
883
+ const month = name.slice('raw-archive-'.length, 'raw-archive-'.length + 7);
884
+ if (month >= cutoffMonth) continue; // month still inside the retention window
885
+ try {
886
+ const file = this.archive.archivePath(name);
887
+ const size = fs.statSync(file).size;
888
+ fs.rmSync(file, { force: true });
889
+ freed += size;
890
+ removedArchives.push(month);
891
+ } catch {
892
+ /* already gone */
893
+ }
894
+ }
895
+ if (removed.length > 0 || removedArchives.length > 0) {
811
896
  this._total = null;
812
897
  this._hashes.clear();
813
898
  this._dayBytes.clear();
814
899
  this._tombstones = null;
900
+ if (removedArchives.length > 0) {
901
+ try {
902
+ const state = this.archive.readState();
903
+ const archives = { ...(state.archives ?? {}) };
904
+ for (const month of removedArchives) delete archives[month];
905
+ if (typeof this.archive.writeState === 'function') this.archive.writeState({ ...state, archives });
906
+ } catch {
907
+ /* bookkeeping only: a stale archive index must not fail pruning */
908
+ }
909
+ }
815
910
  }
816
- return { removed, freedBytes: freed, retentionDays: retention, today };
911
+ return { removed, removedArchives, freedBytes: freed, retentionDays: retention, today };
817
912
  }
818
913
 
819
914
  /**
@@ -860,7 +955,7 @@ export class RawStore {
860
955
  archiveMonths.push({
861
956
  name,
862
957
  month,
863
- engine: name.endsWith('.zst') ? 'zstd' : 'gzip',
958
+ engine: engineForArchive(name),
864
959
  bytes,
865
960
  at: Number.isFinite(record?.at) ? record.at : null,
866
961
  bytesBefore: Number.isFinite(record?.bytesBefore) ? record.bytesBefore : null,
@@ -891,6 +986,7 @@ export class RawStore {
891
986
  totalBytes: plaintextBytes + archivedBytes,
892
987
  archiveMonths: archiveMonths.slice(-12),
893
988
  engines: {
989
+ brotli: archiveMonths.filter((entry) => entry.engine === 'brotli').length,
894
990
  gzip: archiveMonths.filter((entry) => entry.engine === 'gzip').length,
895
991
  zstd: archiveMonths.filter((entry) => entry.engine === 'zstd').length,
896
992
  },
@@ -197,6 +197,29 @@ export class SemanticStore {
197
197
  };
198
198
  }
199
199
 
200
+ /**
201
+ * L3 capacity breaker (v1.6.1): the semantic layer must grow with event
202
+ * IMPORTANCE, never with conversation count. When the folded view exceeds
203
+ * `maxEntries`, the least-recently-updated summaries are retired via the
204
+ * append-only `semantic_retire` record — never deleted from the file, so the
205
+ * decision itself stays auditable and replayable.
206
+ *
207
+ * @param {{clock: object, maxEntries?: number, lruOnCap?: boolean}} input
208
+ * @returns {{kept: number, retired: string[], capped: boolean}}
209
+ */
210
+ enforceCapacity({ clock, maxEntries, lruOnCap = true }) {
211
+ const cap = Number.isFinite(maxEntries) ? Math.max(1, Math.floor(maxEntries)) : Infinity;
212
+ const summaries = this.list();
213
+ if (!lruOnCap || !Number.isFinite(cap) || summaries.length <= cap) {
214
+ return { kept: summaries.length, retired: [], capped: false };
215
+ }
216
+ // `list()` is sorted newest-first by updatedAt, so the tail is the LRU end.
217
+ const excess = summaries.slice(cap);
218
+ const retired = excess.map((summary) => summary.summaryId);
219
+ for (const summaryId of retired) this.retire({ clock, summaryId, reason: 'capacity-lru' });
220
+ return { kept: summaries.length - retired.length, retired, capped: true };
221
+ }
222
+
200
223
  summarise(record) {
201
224
  return {
202
225
  summaryId: record.summary_id,
package/src/webRoutes.js CHANGED
@@ -97,6 +97,9 @@ export const EDITABLE_CONFIG_KEYS = Object.freeze([
97
97
  'l2Merge.minGroupSize',
98
98
  'l2Merge.maxGroupsPerRun',
99
99
  'l2Merge.maxSummaryChars',
100
+ // v1.6.1 L3 capacity breaker.
101
+ 'semantic.maxEntries',
102
+ 'semantic.lruOnCap',
100
103
  // v1.5.6 offline Dream tunables. CREDENTIALS ARE NOT EDITABLE: `dream.llm.*`
101
104
  // (baseUrl/model/apiKey) stays in the profile / DSH_DREAM_LLM_* env.
102
105
  'dream.useLlm',
@@ -124,6 +127,9 @@ export const EDITABLE_CONFIG_KEYS = Object.freeze([
124
127
  'raw.retentionDays',
125
128
  'raw.archiveAfterDays',
126
129
  'raw.compressionEngine',
130
+ 'raw.coldAccessWindowDays',
131
+ 'raw.hotWindowDays',
132
+ 'raw.distillPrune',
127
133
  'raw.maxScanMb',
128
134
  'raw.maxScanTurns',
129
135
  'raw.maxResultTokens',
package/ui/client.js CHANGED
@@ -2244,7 +2244,7 @@
2244
2244
  'tr',
2245
2245
  { key: entry.name },
2246
2246
  h('td', { style: { padding: '4px 8px' } }, entry.month || '—'),
2247
- h('td', { style: { padding: '4px 8px' } }, entry.engine === 'zstd' ? 'zstd' : 'gzip'),
2247
+ h('td', { style: { padding: '4px 8px' } }, entry.engine === 'zstd' ? 'zstd' : entry.engine === 'brotli' ? 'brotli' : 'gzip'),
2248
2248
  h('td', { style: { padding: '4px 8px' } }, fmtBytes(entry.bytes || 0)),
2249
2249
  h('td', { style: { padding: '4px 8px', color: palette.muted } }, fmtTime(entry.at)),
2250
2250
  ),
@@ -2584,7 +2584,9 @@
2584
2584
  rawMaxTotalMb: Number((config.raw && config.raw.maxTotalMb) ?? 256),
2585
2585
  rawRetentionDays: Number((config.raw && config.raw.retentionDays) ?? 90),
2586
2586
  rawArchiveAfterDays: Number((config.raw && config.raw.archiveAfterDays) ?? 7),
2587
- rawCompressionEngine: (config.raw && config.raw.compressionEngine) === 'zstd' ? 'zstd' : 'gzip',
2587
+ rawCompressionEngine: ['brotli', 'zstd', 'gzip'].includes(config.raw && config.raw.compressionEngine)
2588
+ ? config.raw.compressionEngine
2589
+ : 'brotli',
2588
2590
  rawMaxScanTurns: Number((config.raw && config.raw.maxScanTurns) ?? 5000),
2589
2591
  deleteGraceHours: Number((config.delete && config.delete.graceHours) ?? 24),
2590
2592
  reviewEnabled: (config.review && config.review.enabled) !== false,
@@ -3013,7 +3015,9 @@
3013
3015
  'raw.maxTotalMb': Number(draft.rawMaxTotalMb),
3014
3016
  'raw.retentionDays': Number(draft.rawRetentionDays),
3015
3017
  'raw.archiveAfterDays': Number(draft.rawArchiveAfterDays),
3016
- 'raw.compressionEngine': draft.rawCompressionEngine === 'zstd' ? 'zstd' : 'gzip',
3018
+ 'raw.compressionEngine': ['brotli', 'zstd', 'gzip'].includes(draft.rawCompressionEngine)
3019
+ ? draft.rawCompressionEngine
3020
+ : 'brotli',
3017
3021
  'raw.maxScanTurns': Number(draft.rawMaxScanTurns),
3018
3022
  'delete.graceHours': Number(draft.deleteGraceHours),
3019
3023
  'review.enabled': Boolean(draft.reviewEnabled),
@@ -3679,13 +3683,14 @@
3679
3683
  label: '冷压缩引擎(raw.compressionEngine)',
3680
3684
  hint:
3681
3685
  (statsPayload && statsPayload.capabilities && statsPayload.capabilities.compression
3682
- ? `当前运行时 Node ${statsPayload.capabilities.compression.node}:gzip ${statsPayload.capabilities.compression.gzip ? '可用' : '不可用'},zstd ${statsPayload.capabilities.compression.zstd ? '可用' : '不可用'}。`
3686
+ ? `当前运行时 Node ${statsPayload.capabilities.compression.node}:brotli ${statsPayload.capabilities.compression.brotli ? '可用' : '不可用'},gzip ${statsPayload.capabilities.compression.gzip ? '可用' : '不可用'},zstd ${statsPayload.capabilities.compression.zstd ? '可用' : '不可用'}。`
3683
3687
  : '') +
3684
- 'Zstd 使用 Node 内置 zstandard(无需下载或安装外部包)。启用后新归档为 .jsonl.zst,压缩率更高;停用则切回 .jsonl.gz。历史归档保持原格式、两种格式都可流式读取。',
3688
+ '全部为 Node 内置编解码器(无需下载或安装外部包)。Brotli 11 级为冷数据默认的极限压缩;Gzip/Zstd 仍可选。历史归档保持原格式,三种格式都可流式读取。',
3685
3689
  value: draft.rawCompressionEngine,
3686
3690
  options: [
3687
- { value: 'gzip', label: 'Gzip(Node 内置,默认)' },
3688
- { value: 'zstd', label: 'Zstd(Node 内置,压缩率更高)' },
3691
+ { value: 'brotli', label: 'Brotli 11 级(Node 内置,默认,压缩率最高)' },
3692
+ { value: 'gzip', label: 'Gzip(Node 内置,兼容性最好)' },
3693
+ { value: 'zstd', label: 'Zstd(Node 内置,解压更快)' },
3689
3694
  ],
3690
3695
  onChange: (value) => edit('rawCompressionEngine', value),
3691
3696
  disabled,
@@ -3702,17 +3707,17 @@
3702
3707
  onClick: () =>
3703
3708
  edit(
3704
3709
  'rawCompressionEngine',
3705
- draft.rawCompressionEngine === 'zstd' ? 'gzip' : 'zstd',
3710
+ draft.rawCompressionEngine === 'brotli' ? 'gzip' : 'brotli',
3706
3711
  ),
3707
3712
  },
3708
- draft.rawCompressionEngine === 'zstd' ? '停用 Zstd(切回 Gzip)' : '启用 Zstd(内置引擎)',
3713
+ draft.rawCompressionEngine === 'brotli' ? '切回 Gzip(兼容模式)' : '启用 Brotli 11 级(极限压缩)',
3709
3714
  ),
3710
3715
  h(
3711
3716
  'span',
3712
3717
  { style: { ...labelStyle, marginBottom: 0 } },
3713
- draft.rawCompressionEngine === 'zstd'
3714
- ? 'Zstd 已启用:点击“保存全部”后,新归档使用 .jsonl.zst。'
3715
- : '当前使用 Gzip:点击“保存全部”后切换,下个月归档生效。',
3718
+ draft.rawCompressionEngine === 'brotli'
3719
+ ? 'Brotli 11 级已选中:点击“保存全部”后,新归档使用 .jsonl.br。'
3720
+ : '当前未使用极限压缩:点击“保存全部”后切换,下个月归档生效。',
3716
3721
  ),
3717
3722
  ),
3718
3723
  h(Field, {