dsh-layers-hippocampus 1.6.6 → 1.6.8
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 +127 -0
- package/README.md +31 -5
- package/docs/ARCHITECTURE.zh.md +2 -2
- package/index.js +135 -6
- package/package.json +1 -1
- package/src/config.js +33 -0
- package/src/context/contextEngine.js +105 -7
- package/src/entropy.js +120 -0
- package/src/errors.js +72 -0
- package/src/hostBridge.js +51 -0
- package/src/memory.js +35 -10
- package/src/rawStore.js +14 -0
- package/src/webRoutes.js +3 -0
- package/ui/client.js +35 -1
package/CHANGELOG.md
CHANGED
|
@@ -4,6 +4,129 @@ 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.8] — 2026-11-20
|
|
8
|
+
|
|
9
|
+
**写侧护栏:拒绝高熵密文 / 加密载荷。** raw 日志与 L1 事件日志是本插件承诺「永远保留」
|
|
10
|
+
的两样东西,而密文块恰恰是唯一无法被召回(没有可搜索的子串)、无法被蒸馏(没有可说的
|
|
11
|
+
语义)、也无法被打标的载荷——它只会永久占用保留期与存储预算。这是审计项 A4,自
|
|
12
|
+
1.5.7 起挂着「文档已规划但代码未实现」,本版补上。
|
|
13
|
+
|
|
14
|
+
- **Added — `src/entropy.js`**:纯函数检测器,零依赖。
|
|
15
|
+
- `shannonEntropy(text)`:香农熵(保留 3 位小数)。
|
|
16
|
+
- `detectCiphertext(text, { minRunChars })` → `null` 或
|
|
17
|
+
`{ reason: 'pem'|'base64'|'hex', runLength, entropy, at, sample }`。
|
|
18
|
+
- 三条判据各自有下限:base64 连续 ≥512 字符且熵 ≥4.5;hex 连续 ≥512 字符且熵 ≥3.5;
|
|
19
|
+
PEM 甲壳(`-----BEGIN PGP MESSAGE-----` 等 5 种标记)**即使很短**也拒绝。
|
|
20
|
+
- 保守优先:散文、源码、URL、Windows 路径、低熵长串、短 base64 data URI 全部放行。
|
|
21
|
+
- **Added — `MEM_E_ENCRYPTED_RAW_REJECTED`**(`src/errors.js`),details 带
|
|
22
|
+
`{ reason, runLength, entropy, at }`,调用方不必解析消息文本。
|
|
23
|
+
- **Changed — 三条写路径统一护栏**:
|
|
24
|
+
- `src/rawStore.js#capture`:在非空校验之后、门槛判定之前检测,**拒绝且零落盘**
|
|
25
|
+
(不入队、不刷盘、分片里不会出现该载荷)。
|
|
26
|
+
- `src/memory.js#remember`:同规则,且**先于**旧的 base64-media 守卫——对一个密文块,
|
|
27
|
+
叫调用方「改用 media_url」是错误建议,正确诊断是「这是密文」。
|
|
28
|
+
- `src/memory.js#captureSessionEvent`:auto-capture 遇到密文时返回
|
|
29
|
+
`{ stored: false, skipped: 'encrypted-blob', reason }`,**不作为 capture 失败刷警告**
|
|
30
|
+
(会话里粘一段密钥不该让日志被 warn 淹没),其他错误仍照旧上抛。
|
|
31
|
+
- **Tests**:新增 `test/v168.encrypted.test.js`(8 例):熵函数基准、7 类正常内容零误判、
|
|
32
|
+
base64/hex/PEM 三判据各自的拒绝理由、raw store 拒绝且磁盘无残留、auto-capture 的 skip
|
|
33
|
+
语义、`remember()` 同规则且普通写入不受影响。全量 **534/534**(84 个测试文件)。
|
|
34
|
+
- **Docs**:`记忆插件-未完成表.md` 从「2026-11-05 待办审计」重写为「当前状态表」——
|
|
35
|
+
A1–A21 逐项给出关闭依据,13 项关闭、2 项 superseded、2 项并入 M3/M6、4 项明确不做
|
|
36
|
+
(并写明为什么不做),另列仍需外部动作的四项(npm 账号封控等)。
|
|
37
|
+
|
|
38
|
+
## [1.6.7] — 2026-11-17
|
|
39
|
+
|
|
40
|
+
**发布链完整性修正 + 索引式提示注入(M1)。1.6.6 在 npm 上的制品(`gitHead 99a07cb`)
|
|
41
|
+
是从一份**旧 checkout** 发布的,只带来 Live Compact 修复,**不含** M3(测试跨包解耦)
|
|
42
|
+
与 M5(错误码边界)。1.6.7 把这两项送往 npm,并让仓库历史与已发布标签不再分叉;
|
|
43
|
+
M1 则是本版的主线功能——每轮 Prompt 不再为记忆**正文**付费。**
|
|
44
|
+
|
|
45
|
+
- **Added — 外部价格 / 通知接缝(M2)**。`dsh-price-tip` / `dsh-peak-runner` /
|
|
46
|
+
`dsh-notify-plugin` 在本机**并不存在**,因此没有「接线真实 API」可做——凭空猜服务名
|
|
47
|
+
等于发明接口。本版只做**可验证的可选接缝**:
|
|
48
|
+
- `HostBridge.setNotifier(sink)` + `notify({title,text,kind,at})`:没有 sink 时返回
|
|
49
|
+
`{delivered:false, reason:'no-notifier'}` 并只记计数,**绝不发明投递通道、绝不抛错**;
|
|
50
|
+
sink 抛错也只记 `sink-error`,不会污染维护流程。
|
|
51
|
+
- `index.js` 探测一组**约定键**(`priceTip` / `notifier` / `peakRunner`,或 `notify` / `peak`),
|
|
52
|
+
并接受多种方法形状(`isLowValley|lowValley|isLow|price`、`notify|send|post`、
|
|
53
|
+
`isPeak|peak|isHigh`)。外部价格服务优先于内置时间窗;`DSH_DREAM_PRICE` 仍可强制覆盖。
|
|
54
|
+
- `capabilities.externalSeams` 报告**哪条接缝真的接上了**(`{wired, source}`),
|
|
55
|
+
所以「没装」是可见事实而不是静默降级。
|
|
56
|
+
- 一旦通知接缝可用,「Dream 因高峰被推迟」会通过它播报(内含 `dueAt`);没有接缝时
|
|
57
|
+
这件事仍由持久化队列与 `dream-deferred` 事件表达,行为不变。
|
|
58
|
+
- **排队本来就是实装的**:`index.js` 的 `tick()` 在高峰把 LLM 蒸馏写入 `dreamQueue`
|
|
59
|
+
并在谷时唤醒(`reason: 'peak-hour'`),不是丢弃,本次未改动该逻辑。
|
|
60
|
+
- **Changed — 多空间开关的语义澄清(M6)**。`features.multiSpace` 默认 `true`,但只有注入了
|
|
61
|
+
能创建空间适配器的 `orchestrator` 服务时才真正生效——以前这个差异是**静默**的:
|
|
62
|
+
用户以为开了多空间,实际在跑单空间。现在新增 `multiSpaceReason()`,返回
|
|
63
|
+
`'active'` / `'disabled-by-config'` / `'orchestrator-missing'` 三态,
|
|
64
|
+
通过 `capabilities.multiSpaceReason` + `capabilities.multiSpaceRequested` 与
|
|
65
|
+
`panel.spaces.{requested,reason}` 同时暴露,设置页在多空间卡片里直接写明
|
|
66
|
+
「当前被配置关闭:features.multiSpace=false」,不再把「没装适配器」和「你关了它」
|
|
67
|
+
混成一个 `spaces:false`。**开关本身没有改默认值**(改默认会静默改变已部署 profile 的行为),
|
|
68
|
+
改的是可观测性与文档;并有用例锁住「布尔值与理由不可能互相矛盾」。
|
|
69
|
+
- **Changed — 索引式提示注入(M1)**。`context.injectMode` 新增两个取值:
|
|
70
|
+
- `index`(**新默认**):每个记忆块只注入一行指针
|
|
71
|
+
`- [memory <eventId>] 标签 · 标签 · 标题`。正文不进 Prompt,需要细节时用
|
|
72
|
+
`memory_recall` 按 eventId / 标签取。`[Memory Blocks]` 标记名保持不变,因此缓存前缀
|
|
73
|
+
语义不变;规则段多一行「这些是索引指针,正文须调 recall」,**只在 index 模式下出现**。
|
|
74
|
+
- `full`:沿用旧版渲染(正文前 200 字)与旧版计费(整段正文),一行代码即可回退。
|
|
75
|
+
- **窗口计费随渲染形态走**:`ContextEngine.tokensOf()` 在 index 模式下只计指针行,
|
|
76
|
+
在 full 模式下仍计整段正文(旧口径,不动既有调优);调用方**显式传入的 `tokens`
|
|
77
|
+
永远优先**,折叠与驱逐的排序不变。
|
|
78
|
+
- `index` 模式下 `tokens()` 的实测差异是数量级的:8,000 字符的正文约 2,000 tokens,
|
|
79
|
+
指针行通常 < 60 tokens。
|
|
80
|
+
- `briefing` 块(运营方钉死的策略)**永不降级为指针**,始终整段渲染。
|
|
81
|
+
- 可编辑键新增 `context.injectMode`(`index` / `full`,非法值 fail-fast),设置页
|
|
82
|
+
「上下文窗口」卡片新增下拉;简洁模式下同样可见可存。
|
|
83
|
+
- **Changed — 测试与兄弟包解耦(M3)**。`test/orchestrator.js` 先按包名 `dsh-layers-orchestrator/src/*`
|
|
84
|
+
解析、失败再退回同级 checkout(`via: 'package' | 'sibling'`);22 个真正依赖多空间的用例改走
|
|
85
|
+
`orchestratorTest()`,缺包时注册为 **skipped 并带原因**而不是 import 阶段崩掉整套测试。
|
|
86
|
+
`makeMemory()` 的 `multiSpace` 默认值改为 `MULTI_SPACE_AVAILABLE`,杜绝 `new null()`。
|
|
87
|
+
实测:两包在位 **510/510**(skipped 0);单独 checkout 时 **454 pass / 0 fail / 56 skipped**。
|
|
88
|
+
- **Changed — 错误码边界(M5)**。`dsh-orchestrator` 内两套命名空间是**故意**并存的:
|
|
89
|
+
`MEM_E_*`(从核心搬出去的引擎沿用,客户端 HTTP 映射依赖它)与 `ORCH_E_*`(路由器/去重/联邦/授权)。
|
|
90
|
+
海马体侧新增单一边界 `src/errors.js#fromOrchestratorError()` + `ORCHESTRATOR_CODE_MAP`:
|
|
91
|
+
`ORCH_E_CONSENT_*` → `MEM_E_REQUIRE_USER_CONSENT`(三个都映射到同一处,因为修法是去问人而不是重试)、
|
|
92
|
+
`ORCH_E_SPACE_INVALID` → `MEM_E_SPACE_INVALID`、`ORCH_E_INVALID_INPUT` → `MEM_E_INVALID_INPUT`、
|
|
93
|
+
`ORCH_E_NOT_READY` → `MEM_E_NOT_READY`、`ORCH_E_FEDERATION_CONFLICT` → `MEM_E_FEDERATION_FAILED`;
|
|
94
|
+
**未列入的 `ORCH_E_*` 不会被拍平成 `MEM_E_IO`**,原始码保留在 `details.orchestratorCode` 里可审计。
|
|
95
|
+
映射表同步写进 `dsh-orchestrator/README.md` 的「错误码边界」一节。
|
|
96
|
+
- **Tests**:新增 `test/v166.errorContract.test.js`(7 例)与 `test/v167.m1.test.js`(9 例:
|
|
97
|
+
默认 index、指针行构成、index 计费 = 渲染行、full 保留旧渲染与旧计费、显式权重优先、
|
|
98
|
+
briefing 不降级、标题截断与回退、`injectMode` 校验与可编辑、规则段只在 index 出现、
|
|
99
|
+
recall 命中把标签与标题带进窗口且正文尾巴不出现);
|
|
100
|
+
`test/v156.features.test.js` 新增 M6 用例(`multiSpaceReason` 三态 + 显式关闭优先于
|
|
101
|
+
缺适配器 + 「布尔值与理由不可能矛盾」的交叉断言);
|
|
102
|
+
`test/v167.m2.test.js`(6 例)锁住 M2 接缝:无 sink 时为 `no-notifier` 的记账型空操作、
|
|
103
|
+
sink 收到 payload 且被计数、sink 抛错只记 `sink-error` 不外溢、`externalSeams()` 如实报告
|
|
104
|
+
「通知与高峰缺席、价格回退本地时间窗」、注入 `notifier` 服务后被自动发现并可用、
|
|
105
|
+
注入 `priceTip` 后外部价格**优先于**本地时钟窗口。
|
|
106
|
+
全量 **526/526**(84 个测试文件)。
|
|
107
|
+
|
|
108
|
+
## [1.6.6] — 2026-11-16
|
|
109
|
+
|
|
110
|
+
**发布修正版:1.6.5 在 npm 上发布的是「每轮请求都裁剪工具结果」的版本——那个把上下文
|
|
111
|
+
从 10% 悄悄缩到 7% 的缺陷没有随任何已发布制品走出去。1.6.6 补上这条修复。**
|
|
112
|
+
|
|
113
|
+
> **发布实况(事后核对)**:1.6.6 的 npm 制品 `gitHead 99a07cb` 来自旧 checkout,
|
|
114
|
+
> **只含**下面的 Live Compact 修复——M3 与 M5 当时已在主线上、但没有进这个 tarball。
|
|
115
|
+
> 那两项随 **1.6.7** 发出。本地 `v1.6.6` tag 已指向 `99a07cb`,与 npm/GitHub 一致;
|
|
116
|
+
> `99a07cb` 也已并入 `main` 历史,发布可追溯。
|
|
117
|
+
> 1.6.5 同理不可覆盖(`gitHead 28776c7`),其 tag 亦指向该提交。
|
|
118
|
+
|
|
119
|
+
- **Fixed — 上下文在每轮请求里被悄悄缩水("从 10% 直接掉到 7%")**。
|
|
120
|
+
`guardRequest` 曾在**每一次** `agent/request` 上调用宿主的 `toolResultPruner.pruneSession()`。
|
|
121
|
+
宿主的 `pruneContent()` 用的是**预设预算**(ptc 预设 `thresholdChars: 8192` → 4k 头 + 1k 尾),
|
|
122
|
+
而且它**只在 `compaction-basic` 的 `context-overflow` 分支里**才被调用——我们把「溢出时裁剪」
|
|
123
|
+
变成了「每轮都裁剪」,一次 pass 就能掉约 80k tokens。
|
|
124
|
+
现在 Live Compact **只跑本插件自己的保守策略**(`context.liveCompact`,默认 200,000 字符阈值 /
|
|
125
|
+
4,000 头 / 2,000 尾 / 每请求最多 4 个节点),不再委托宿主 pruner;
|
|
126
|
+
回归用例 `the guard never rewrites an ordinary tool result on a healthy request`
|
|
127
|
+
断言宿主 pruner 在健康请求上**一次都不被调用**。
|
|
128
|
+
- **Tests**:`test/v164.windowGuard.test.js` 增加上述回归用例(12 例)。全量 **503/503**(79 个测试文件)。
|
|
129
|
+
|
|
7
130
|
## [1.6.5] — 2026-11-15
|
|
8
131
|
|
|
9
132
|
**回归微内核:引擎只负责存储、检索与蒸馏,绝不驱动对话;蒸馏只有一个总调度器;
|
|
@@ -60,6 +183,10 @@ and the project adheres to [Semantic Versioning](https://semver.org/).
|
|
|
60
183
|
`test/flow.test.js` 与 `test/v156.federation.test.js` 的月记断言随调度器迁移改为
|
|
61
184
|
`executeDream()`。全量 **502/502**(80 个测试文件)。
|
|
62
185
|
|
|
186
|
+
> **发布说明**:1.6.5 发布到 npm 的制品(`gitHead 28776c7`)**不包含**上面那条 Live Compact
|
|
187
|
+
> 修复——它是在 1.6.5 发布之后才提交的。该修复进入 **1.6.6**;M3 与 M5 实际进入 **1.6.7**
|
|
188
|
+
> (1.6.6 的制品同样来自旧 checkout,只含 Live Compact)。
|
|
189
|
+
|
|
63
190
|
## [1.6.4] — 2026-11-14
|
|
64
191
|
|
|
65
192
|
**修复 1M 上下文溢出(`CONTEXT_WINDOW_EXCEEDED`):交接判定的分母、分子与状态机三处
|
package/README.md
CHANGED
|
@@ -7,7 +7,7 @@
|
|
|
7
7
|
|
|
8
8
|
| | |
|
|
9
9
|
| --- | --- |
|
|
10
|
-
| 版本 | **1.6.
|
|
10
|
+
| 版本 | **1.6.8** |
|
|
11
11
|
| 包名 | `dsh-layers-hippocampus` |
|
|
12
12
|
| 仓库 | <https://github.com/382quaii/dsh-Layers-Hippocampus> |
|
|
13
13
|
| 许可证 | MIT |
|
|
@@ -96,7 +96,33 @@
|
|
|
96
96
|
- **单轮超大工具输出熔断(Live Compact)**:单个 `tool/result` 超过
|
|
97
97
|
`context.liveCompact.thresholdChars`(默认 200,000 字符)时,保留头 4000 / 尾 2000 字符,
|
|
98
98
|
中间压成一行指向 raw 日志的指针(带 `seq` / `call` / `tool` 坐标),原文仍可用
|
|
99
|
-
`deep_raw`
|
|
99
|
+
`deep_raw` 取回。**只跑本插件自己的保守策略**,不委托宿主的 `toolResultPruner`
|
|
100
|
+
(1.6.6:宿主的预算是预设自己的 8k 级阈值,每轮委托等于每轮偷偷掉几十 k tokens)。
|
|
101
|
+
- **密文不写入(1.6.8)**:写侧(`raw` 捕获、`remember`、auto-capture)会检测高熵载荷,
|
|
102
|
+
命中 base64/hex 长串或 PEM 甲壳时抛 `MEM_E_ENCRYPTED_RAW_REJECTED` 并**零落盘**;
|
|
103
|
+
auto-capture 只降级成 `skipped: 'encrypted-blob'`,不刷警告。密文块永远无法被 recall、
|
|
104
|
+
蒸馏或打标,却会永久占用保留期与预算——所以在入口就拒绝,而不是留着当垃圾。
|
|
105
|
+
散文、源码、URL、路径与短 base64 片段不受影响。
|
|
106
|
+
- **索引式注入(1.6.7,默认)**:`context.injectMode = 'index'` 时,每个记忆块只往 Prompt
|
|
107
|
+
里放一行指针 `- [memory <eventId>] 标签 · 标题`,正文按需用 `recall` 取;
|
|
108
|
+
8,000 字符的正文(≈2,000 tokens)变成通常不到 60 tokens 的指针行。
|
|
109
|
+
`context.injectMode = 'full'` 是旧行为的一键回退(正文直接进 Prompt,按整段计费)。
|
|
110
|
+
`[Memory Blocks]` 标记名与缓存前缀语义保持不变;`briefing` 块(运营方钉死的策略)
|
|
111
|
+
永不降级为指针。
|
|
112
|
+
- **多空间开关会说明自己为什么没生效(1.6.7,M6)**:`features.multiSpace` 默认 `true`,
|
|
113
|
+
但只有注入了能创建空间适配器的 `orchestrator` 服务时才真正运行。以前两者的差异是静默的
|
|
114
|
+
——「我开了多空间」和「我实际在单空间」可以同时为真。现在
|
|
115
|
+
`capabilities.multiSpaceRequested`(配置意图)与 `capabilities.multiSpaceReason`
|
|
116
|
+
(`active` / `disabled-by-config` / `orchestrator-missing`)一起返回,
|
|
117
|
+
`panel.spaces.{requested,reason}` 同样如此,设置页会直接写明是哪一种。
|
|
118
|
+
**默认值没有改动**:改默认会静默改变已部署 profile 的行为。
|
|
119
|
+
- **外部价格 / 通知是可插接的,但不会假装接了(1.6.7,M2)**:
|
|
120
|
+
`dsh-price-tip` / `dsh-peak-runner` / `dsh-notify-plugin` 这类兄弟插件**不是依赖**。
|
|
121
|
+
引擎只探测约定服务键(`priceTip` / `notifier` / `peakRunner`,或 `notify` / `peak`),
|
|
122
|
+
探测不到就用本地时间窗(价格)或记账型空操作(通知):`notify()` 返回
|
|
123
|
+
`{delivered:false, reason:'no-notifier'}`,既不发明投递通道,也不会因缺插件抛错。
|
|
124
|
+
`capabilities.externalSeams` 会如实报告 `{wired, source}`,所以「没装」是可见事实。
|
|
125
|
+
**高峰期不丢任务**:LLM 蒸馏在高峰只被写入持久化队列并在谷时唤醒,不是跳过。
|
|
100
126
|
|
|
101
127
|
### `/memory` 指令集(0 Token)
|
|
102
128
|
|
|
@@ -186,7 +212,7 @@ raw 层提供三档,覆盖从“只留关键”到“全留”:
|
|
|
186
212
|
pnpm add dsh-layers-hippocampus
|
|
187
213
|
|
|
188
214
|
# 或从 GitHub 指定 tag
|
|
189
|
-
pnpm add "github:382quaii/dsh-Layers-Hippocampus#v1.6.
|
|
215
|
+
pnpm add "github:382quaii/dsh-Layers-Hippocampus#v1.6.8"
|
|
190
216
|
```
|
|
191
217
|
|
|
192
218
|
### 2. 挂到 profile
|
|
@@ -247,7 +273,7 @@ node scripts/wait-for-routes.mjs
|
|
|
247
273
|
设置 → 海马体记忆 顶部可切换 **简洁模式 / 专业模式**:
|
|
248
274
|
|
|
249
275
|
- **简洁模式**只显示四块:**身份**(事件时间策略)、**上下文窗口**(预算 / 注入上限 /
|
|
250
|
-
淘汰阈值 / 收敛目标 /
|
|
276
|
+
淘汰阈值 / 收敛目标 / 是否注入 / 注入形态)、**系统级存储位置迁移**、**原始回合留存**
|
|
251
277
|
(只留 `raw.mode`、总量上限、冷压缩引擎三项)。
|
|
252
278
|
- 它是**纯显示层**:隐藏项不渲染,也不参与保存——POST 只携带可见键,文件里其余配置
|
|
253
279
|
保持原值(新装即默认值,专业模式下调过的不会被覆盖)。
|
|
@@ -257,7 +283,7 @@ node scripts/wait-for-routes.mjs
|
|
|
257
283
|
### 6. 验证
|
|
258
284
|
|
|
259
285
|
```bash
|
|
260
|
-
npm test # 进程内全量用例(
|
|
286
|
+
npm test # 进程内全量用例(534 个)
|
|
261
287
|
npm run check # 语法检查 + 全量测试
|
|
262
288
|
```
|
|
263
289
|
|
package/docs/ARCHITECTURE.zh.md
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
# @local/dsh-memory — 分层长期记忆 Host 插件
|
|
2
2
|
|
|
3
|
-
> 版本:**1.6.
|
|
3
|
+
> 版本:**1.6.8** | 全量用例:**534/534** | 运行时依赖:**零**
|
|
4
4
|
|
|
5
5
|
给 DSH 智能体一份"活得比会话久"的记忆:**追加式原始日志是唯一真相源**,标签索引、日记、活跃集合全部是可丢弃、可重建的读模型,语义摘要独立于原始日志生死。
|
|
6
6
|
|
|
@@ -681,7 +681,7 @@ window.__ModuleLoader__.load({
|
|
|
681
681
|
|
|
682
682
|
运行器带**看门狗**:默认 **60s**(`MEM_TEST_TIMEOUT_MS` 可调)仍未退出,就打印**卡住时正在导入/执行的文件、最后完成的测试名与完成数、活动资源、尚未触发的定时器**,然后 `process.exit(1)`。它不会用 `process.exit(0)` 掩盖超时——挂起即失败。`MEM_TEST_TRACE=1` 可看文件级进度,`MEM_TEST_ONLY=<子串>` 只跑一组。
|
|
683
683
|
|
|
684
|
-
|
|
684
|
+
534 个用例(84 个文件)覆盖:
|
|
685
685
|
|
|
686
686
|
- 索引与标签:重建 digest 一致、行号漂移防护(eventId 不变、行号变)、同义合并、活跃集 cap 挤出、规则变更不改清单、空活跃集降级、top-k 有界有序去重。
|
|
687
687
|
- 衰减与删除:30 天半衰期、reinforce 移动锚点(不存字段)、仅文本粗筛、标签过滤、维护代切换且旧代可读、boot 检查、压缩不丢记录、并发维护串行化、四阶段删除、archive 可回滚 vs purge 不可、strict 巩固暂停与恢复、任务重放幂等、错误 id 零变更。
|
package/index.js
CHANGED
|
@@ -28,7 +28,7 @@
|
|
|
28
28
|
*/
|
|
29
29
|
|
|
30
30
|
import path from 'node:path';
|
|
31
|
-
import { resolveConfig, toMemoryOptions, DEFAULT_CONFIG, multiSpaceActive } from './src/config.js';
|
|
31
|
+
import { resolveConfig, toMemoryOptions, DEFAULT_CONFIG, multiSpaceActive, multiSpaceReason } from './src/config.js';
|
|
32
32
|
import { extractEntities } from './src/utils/RegexExtractor.js';
|
|
33
33
|
import { migrateDataDir } from './src/migration.js';
|
|
34
34
|
import { MigrationRunner } from './src/migrationRunner.js';
|
|
@@ -42,6 +42,7 @@ import { isLowValley, nextLowValleyStart, windowInfo } from './src/priceWindow.j
|
|
|
42
42
|
import { DreamTimer } from './src/dreamTimer.js';
|
|
43
43
|
import { probeCompression, resolveEngine } from './src/compression.js';
|
|
44
44
|
import { LIVE_COMPACT_DEFAULTS, liveCompactSession } from './src/context/liveCompact.js';
|
|
45
|
+
import { snippet } from './src/util.js';
|
|
45
46
|
import { MEMORY_API, registerMemoryRoutes } from './src/webRoutes.js';
|
|
46
47
|
|
|
47
48
|
export const name = 'memory';
|
|
@@ -62,7 +63,7 @@ export { resolveConfig, DEFAULT_CONFIG };
|
|
|
62
63
|
* of letting a raw 404 reach the user.
|
|
63
64
|
*/
|
|
64
65
|
export const CAPABILITIES = Object.freeze({
|
|
65
|
-
version: '1.6.
|
|
66
|
+
version: '1.6.8',
|
|
66
67
|
spaces: true,
|
|
67
68
|
memories: true,
|
|
68
69
|
transferConsent: true,
|
|
@@ -135,6 +136,18 @@ export const PROMPT_STATE_RULES = [
|
|
|
135
136
|
'When a detail is missing, call the memory tools instead of guessing.',
|
|
136
137
|
].join('\n');
|
|
137
138
|
|
|
139
|
+
/**
|
|
140
|
+
* v1.6.7 M1 — the `index` mode needs ONE extra sentence, or the model will treat a
|
|
141
|
+
* pointer line as if it were the memory itself. This is the only difference between
|
|
142
|
+
* the two rule sets; everything else stays byte-identical so the prefix cache is
|
|
143
|
+
* unaffected by a mode that does not change it.
|
|
144
|
+
*/
|
|
145
|
+
export const PROMPT_STATE_RULES_INDEX = [
|
|
146
|
+
PROMPT_STATE_RULES,
|
|
147
|
+
'Each block below is an INDEX POINTER: eventId, tags and a title. The full text is NOT here —',
|
|
148
|
+
'call the recall tool with that eventId (or its tags) when you actually need the detail.',
|
|
149
|
+
].join('\n');
|
|
150
|
+
|
|
138
151
|
function errorJson(error) {
|
|
139
152
|
// Failures are values, never thrown across the tool boundary: {ok:false,error}
|
|
140
153
|
// mirrors the {ok:true,...} success shape.
|
|
@@ -764,8 +777,11 @@ export function createRuntime({ ctx = null, config, options, clock, raw = null,
|
|
|
764
777
|
sessionId: usage?.sessionId ?? null,
|
|
765
778
|
agentId: assemblyContext?.agent?.id ?? null,
|
|
766
779
|
});
|
|
780
|
+
// v1.6.7 M1: in `index` mode the window renders pointer lines, so the rules
|
|
781
|
+
// must say so — otherwise the model reads a title as if it were the memory.
|
|
782
|
+
const rules = memory.context.injectMode === 'full' ? PROMPT_STATE_RULES : PROMPT_STATE_RULES_INDEX;
|
|
767
783
|
return (
|
|
768
|
-
composePrompt({ rules
|
|
784
|
+
composePrompt({ rules, activeTask: activeTaskBlock, blocks, hints }) +
|
|
769
785
|
marker +
|
|
770
786
|
(coldStart ? `\n${coldStart}` : '')
|
|
771
787
|
);
|
|
@@ -798,7 +814,7 @@ export function createRuntime({ ctx = null, config, options, clock, raw = null,
|
|
|
798
814
|
// ---- 1. Live Compact ---------------------------------------------------
|
|
799
815
|
// ONLY our own conservative pass, on OUR threshold (200k chars by default).
|
|
800
816
|
//
|
|
801
|
-
// v1.6.
|
|
817
|
+
// v1.6.6: this used to delegate to the host's `toolResultPruner` on EVERY
|
|
802
818
|
// request, which was wrong twice over:
|
|
803
819
|
// - the host prunes with the PRESET's budget (ptc: 8192 chars -> 4k head +
|
|
804
820
|
// 1k tail), so an ordinary 20 KB file read was silently cut down on the
|
|
@@ -983,6 +999,14 @@ export function createRuntime({ ctx = null, config, options, clock, raw = null,
|
|
|
983
999
|
runtime.dreamTimer?.schedule(now);
|
|
984
1000
|
results.push({ ran: false, skipped: true, reason: 'peak-hour', dueAt, source: 'dream' });
|
|
985
1001
|
emit({ type: 'dream-deferred', dueAt, window: windowInfo(now) });
|
|
1002
|
+
// M2: if an external notifier is wired, say why the dream was postponed. Without
|
|
1003
|
+
// one this is a recorded no-op — the queue still holds the work either way.
|
|
1004
|
+
runtime.hostBridge.notify({
|
|
1005
|
+
title: '海马体:整理任务推迟到谷时',
|
|
1006
|
+
text: `LLM 蒸馏在高峰期不做,已排队到 ${new Date(dueAt).toISOString()}(窗口:${windowInfo(now).window ?? 'unknown'})。`,
|
|
1007
|
+
kind: 'dream-deferred',
|
|
1008
|
+
at: now,
|
|
1009
|
+
});
|
|
986
1010
|
return results;
|
|
987
1011
|
}
|
|
988
1012
|
results.push(await runtime.runMaintenance('dream'));
|
|
@@ -1181,7 +1205,18 @@ export function createRuntime({ ctx = null, config, options, clock, raw = null,
|
|
|
1181
1205
|
// v1.6.3: cold-start injection observability. Without it the only way to tell
|
|
1182
1206
|
// "armed but never assembled" from "already injected" is to read the prompt.
|
|
1183
1207
|
coldStart: runtime.coldStartView?.() ?? null,
|
|
1184
|
-
panel: {
|
|
1208
|
+
panel: {
|
|
1209
|
+
...status.panel,
|
|
1210
|
+
// v1.6.7 (M6): the panel's `spaces` block is what the UI renders, so the
|
|
1211
|
+
// configured intent and the reason travel with it instead of only living in
|
|
1212
|
+
// the capability handshake (which the panel does not read).
|
|
1213
|
+
spaces: {
|
|
1214
|
+
...(status.panel.spaces ?? {}),
|
|
1215
|
+
requested: runtime.config.features.multiSpace !== false,
|
|
1216
|
+
reason: runtime.multiSpaceReason(),
|
|
1217
|
+
},
|
|
1218
|
+
migration: runtime.migrationStatus(),
|
|
1219
|
+
},
|
|
1185
1220
|
briefing: memory.briefing(),
|
|
1186
1221
|
config: uiConfig(runtime.config),
|
|
1187
1222
|
};
|
|
@@ -1260,6 +1295,16 @@ export function createRuntime({ ctx = null, config, options, clock, raw = null,
|
|
|
1260
1295
|
return multiSpaceActive(runtime.config, typeof orchestrator?.createSpaceAdapter === 'function');
|
|
1261
1296
|
};
|
|
1262
1297
|
|
|
1298
|
+
/**
|
|
1299
|
+
* v1.6.7 (M6): the same answer as `multiSpaceAvailable()`, plus WHY. Exposed as a
|
|
1300
|
+
* capability so a client/user can tell "I turned it off" from "the adapter is not
|
|
1301
|
+
* installed" instead of seeing an unexplained `spaces:false`.
|
|
1302
|
+
*/
|
|
1303
|
+
runtime.multiSpaceReason = () => {
|
|
1304
|
+
const orchestrator = orchestratorService();
|
|
1305
|
+
return multiSpaceReason(runtime.config, typeof orchestrator?.createSpaceAdapter === 'function');
|
|
1306
|
+
};
|
|
1307
|
+
|
|
1263
1308
|
/**
|
|
1264
1309
|
* Capability handshake read by the client bundle (old host → new UI safety).
|
|
1265
1310
|
* v1.5.6: function, not a constant — the feature flags can change live and the
|
|
@@ -1269,6 +1314,14 @@ export function createRuntime({ ctx = null, config, options, clock, raw = null,
|
|
|
1269
1314
|
...CAPABILITIES,
|
|
1270
1315
|
spaces: runtime.multiSpaceAvailable(),
|
|
1271
1316
|
multiSpace: runtime.multiSpaceAvailable(),
|
|
1317
|
+
// v1.6.7 (M6): the CONFIGURED intent and the reason the effective answer may
|
|
1318
|
+
// differ. `multiSpaceRequested` mirrors `features.multiSpace`; `multiSpaceReason`
|
|
1319
|
+
// is 'active' | 'disabled-by-config' | 'orchestrator-missing'.
|
|
1320
|
+
multiSpaceRequested: runtime.config.features.multiSpace !== false,
|
|
1321
|
+
multiSpaceReason: runtime.multiSpaceReason(),
|
|
1322
|
+
// M2: which optional external seams answered. Absence is reported, not hidden:
|
|
1323
|
+
// `wired:false` means this engine fell back to its own local behaviour.
|
|
1324
|
+
externalSeams: runtime.externalSeams?.() ?? null,
|
|
1272
1325
|
crossSpaceTransfer: runtime.multiSpaceAvailable() && runtime.config.features.crossSpaceTransfer !== false,
|
|
1273
1326
|
// v1.5.6: opt-in cross-space recall aggregation (default false).
|
|
1274
1327
|
crossSpaceRecall: runtime.multiSpaceAvailable() && runtime.config.features.crossSpaceRecall === true,
|
|
@@ -1733,10 +1786,72 @@ export function createRuntime({ ctx = null, config, options, clock, raw = null,
|
|
|
1733
1786
|
});
|
|
1734
1787
|
runtime.hostBridge.attach();
|
|
1735
1788
|
runtime.hostStatus = () => runtime.hostBridge.status();
|
|
1789
|
+
/**
|
|
1790
|
+
* M2: optional external seams.
|
|
1791
|
+
*
|
|
1792
|
+
* The architecture note lists `dsh-price-tip` / `dsh-peak-runner` /
|
|
1793
|
+
* `dsh-notify-plugin` as the plugins this engine should DELEGATE to — but none of
|
|
1794
|
+
* them is installed here, and inventing their service names would be fiction. So we
|
|
1795
|
+
* probe a small set of CONVENTIONAL keys, accept several plausible method shapes, and
|
|
1796
|
+
* degrade to the local implementation (or a recorded no-op) when nothing answers.
|
|
1797
|
+
* `runtime.externalSeams()` reports exactly what was found, so absence is visible
|
|
1798
|
+
* instead of silently pretending.
|
|
1799
|
+
*/
|
|
1800
|
+
const pickMethod = (service, names) => {
|
|
1801
|
+
if (!service || typeof service !== 'object') return null;
|
|
1802
|
+
for (const name of names) {
|
|
1803
|
+
if (typeof service[name] === 'function') return service[name].bind(service);
|
|
1804
|
+
}
|
|
1805
|
+
return null;
|
|
1806
|
+
};
|
|
1807
|
+
const probeExternalSeams = () => {
|
|
1808
|
+
const seams = { price: { wired: false, source: 'local-window' }, notifier: { wired: false, source: null }, peak: { wired: false, source: null } };
|
|
1809
|
+
// Price: an external tip service wins over the built-in clock window.
|
|
1810
|
+
try {
|
|
1811
|
+
const priceService = ctx?.get?.('priceTip') ?? ctx?.get?.('priceTipService') ?? null;
|
|
1812
|
+
const lowValley = pickMethod(priceService, ['isLowValley', 'lowValley', 'isLow', 'price']);
|
|
1813
|
+
if (lowValley) {
|
|
1814
|
+
seams.price = { wired: true, source: 'priceTip' };
|
|
1815
|
+
if (!process.env.DSH_DREAM_PRICE) runtime.hostBridge.setPriceProbe((now) => lowValley(now));
|
|
1816
|
+
}
|
|
1817
|
+
} catch (error) {
|
|
1818
|
+
runtime.logger?.warn?.(`hippocampus: price tip seam failed: ${error?.message ?? error}`);
|
|
1819
|
+
}
|
|
1820
|
+
// Notifications: no sink ⇒ every notify() is a recorded no-op.
|
|
1821
|
+
try {
|
|
1822
|
+
const notifyService = ctx?.get?.('notifier') ?? ctx?.get?.('notify') ?? null;
|
|
1823
|
+
const send = pickMethod(notifyService, ['notify', 'send', 'post']);
|
|
1824
|
+
if (send) {
|
|
1825
|
+
seams.notifier = { wired: true, source: 'notifier' };
|
|
1826
|
+
runtime.hostBridge.setNotifier(send);
|
|
1827
|
+
}
|
|
1828
|
+
} catch (error) {
|
|
1829
|
+
runtime.logger?.warn?.(`hippocampus: notifier seam failed: ${error?.message ?? error}`);
|
|
1830
|
+
}
|
|
1831
|
+
// Peak runner: only used for reporting; the scheduler stays local.
|
|
1832
|
+
try {
|
|
1833
|
+
const peakService = ctx?.get?.('peakRunner') ?? ctx?.get?.('peak') ?? null;
|
|
1834
|
+
const isPeak = pickMethod(peakService, ['isPeak', 'peak', 'isHigh']);
|
|
1835
|
+
if (isPeak) seams.peak = { wired: true, source: 'peakRunner' };
|
|
1836
|
+
} catch {
|
|
1837
|
+
/* reporting-only seam */
|
|
1838
|
+
}
|
|
1839
|
+
return seams;
|
|
1840
|
+
};
|
|
1841
|
+
const externalSeamReport = probeExternalSeams();
|
|
1842
|
+
// Snapshot, not a re-probe: calling the probes twice would re-register the sinks.
|
|
1843
|
+
runtime.externalSeams = () => ({
|
|
1844
|
+
price: {
|
|
1845
|
+
wired: runtime.hostBridge._priceProbe !== null,
|
|
1846
|
+
source: runtime.hostBridge._priceProbe !== null ? externalSeamReport.price.source : 'local-window',
|
|
1847
|
+
},
|
|
1848
|
+
notifier: { wired: runtime.hostBridge.notifierAttached, source: externalSeamReport.notifier.source },
|
|
1849
|
+
peak: { wired: externalSeamReport.peak.wired, source: externalSeamReport.peak.source },
|
|
1850
|
+
});
|
|
1736
1851
|
// v1.5.6 local scheduler: the price window is computed from the clock, so a
|
|
1737
1852
|
// compensating Dream obeys peak hours without any external price plugin. An
|
|
1738
1853
|
// explicit DSH_DREAM_PRICE override wins (hostBridge reads it when no probe).
|
|
1739
|
-
if (!process.env.DSH_DREAM_PRICE) {
|
|
1854
|
+
if (!process.env.DSH_DREAM_PRICE && runtime.hostBridge._priceProbe === null) {
|
|
1740
1855
|
runtime.hostBridge.setPriceProbe((now) => isLowValley(now ?? memory.clock.now()));
|
|
1741
1856
|
}
|
|
1742
1857
|
runtime.dreamWindow = () => windowInfo(memory.clock.now());
|
|
@@ -2927,12 +3042,24 @@ export async function apply(ctx, rawConfig = {}) {
|
|
|
2927
3042
|
function injectRecall(runtime, result) {
|
|
2928
3043
|
const { memory, config } = runtime;
|
|
2929
3044
|
const now = memory.clock.now();
|
|
3045
|
+
/** First line of a snippet is the most informative thing a pointer can carry. */
|
|
3046
|
+
const pointerTitle = (hit) => {
|
|
3047
|
+
const first = String(hit?.snippet ?? '')
|
|
3048
|
+
.split('\n')
|
|
3049
|
+
.map((line) => line.trim())
|
|
3050
|
+
.find((line) => line.length > 0);
|
|
3051
|
+
return first ? snippet(first, 96) : null;
|
|
3052
|
+
};
|
|
2930
3053
|
for (const hit of (result.hits ?? []).slice(0, memory.policy.context.blockTopK)) {
|
|
2931
3054
|
if (!hit?.eventId) continue;
|
|
2932
3055
|
memory.context.inject({
|
|
2933
3056
|
id: hit.eventId,
|
|
2934
3057
|
kind: 'recall',
|
|
3058
|
+
// v1.6.7 M1: the body is kept (folding and `full` mode still need it) but in
|
|
3059
|
+
// `index` mode only the pointer line reaches the prompt.
|
|
2935
3060
|
text: `${hit.day ?? ''} ${hit.snippet ?? ''}`.trim(),
|
|
3061
|
+
title: pointerTitle(hit),
|
|
3062
|
+
tags: Array.isArray(hit.tags) ? hit.tags : null,
|
|
2936
3063
|
salience: hit.salience,
|
|
2937
3064
|
at: hit.eventTime,
|
|
2938
3065
|
now,
|
|
@@ -2948,6 +3075,8 @@ function injectRecall(runtime, result) {
|
|
|
2948
3075
|
id,
|
|
2949
3076
|
kind: 'semantic',
|
|
2950
3077
|
text: summary.text,
|
|
3078
|
+
title: summary.title ?? null,
|
|
3079
|
+
tags: summary.tags ?? null,
|
|
2951
3080
|
salience: summary.confidence,
|
|
2952
3081
|
at: summary.updatedAt,
|
|
2953
3082
|
now,
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "dsh-layers-hippocampus",
|
|
3
|
-
"version": "1.6.
|
|
3
|
+
"version": "1.6.8",
|
|
4
4
|
"private": false,
|
|
5
5
|
"description": "Layered long-term memory for DeepSeek Harness: append-only event log, rebuildable tag index, day diaries, independent semantic layer, L2.5 trend quarantine, offline knowledge graph and a Web UI panel.",
|
|
6
6
|
"type": "module",
|
package/src/config.js
CHANGED
|
@@ -198,6 +198,11 @@ export const DEFAULT_CONFIG = Object.freeze({
|
|
|
198
198
|
threshold: 0.85,
|
|
199
199
|
target: 0.7,
|
|
200
200
|
injectPrompt: true,
|
|
201
|
+
// v1.6.7 M1 `index` (default) emits ONE pointer line per memory block —
|
|
202
|
+
// `- [memory <eventId>] tag · tag · title` — instead of the block body; the body
|
|
203
|
+
// is fetched on demand with the recall tool. `full` restores the legacy rendering
|
|
204
|
+
// for anyone who wants the old prompt shape back.
|
|
205
|
+
injectMode: 'index',
|
|
201
206
|
// v1.6.3 REMOVED: `autoNewSession` / `autoNewSessionPoll` /
|
|
202
207
|
// `autoNewSessionIntervalSeconds`. Handing off is an in-conversation event; the
|
|
203
208
|
// host now CONTINUES the same conversation after the marker instead of opening a
|
|
@@ -531,6 +536,26 @@ export function multiSpaceActive(config, hasOrchestrator) {
|
|
|
531
536
|
return hasOrchestrator === true && config?.features?.multiSpace !== false;
|
|
532
537
|
}
|
|
533
538
|
|
|
539
|
+
/**
|
|
540
|
+
* v1.6.7 (M6): WHY multi-space is on or off, so a caller never has to guess whether
|
|
541
|
+
* `features.multiSpace: true` was honoured.
|
|
542
|
+
*
|
|
543
|
+
* Before this, the default `features.multiSpace: true` combined with
|
|
544
|
+
* `multiSpaceActive()` returning false whenever no adapter was injected meant a user
|
|
545
|
+
* who explicitly enabled the feature silently got single-space behaviour with no
|
|
546
|
+
* explanation. The flag now reports one of three states instead of a bare boolean.
|
|
547
|
+
*
|
|
548
|
+
* @param {object} config resolved config
|
|
549
|
+
* @param {boolean} hasOrchestrator true when an injected `orchestrator` service can
|
|
550
|
+
* actually create a space adapter
|
|
551
|
+
* @returns {'active'|'disabled-by-config'|'orchestrator-missing'}
|
|
552
|
+
*/
|
|
553
|
+
export function multiSpaceReason(config, hasOrchestrator) {
|
|
554
|
+
if (config?.features?.multiSpace === false) return 'disabled-by-config';
|
|
555
|
+
if (hasOrchestrator !== true) return 'orchestrator-missing';
|
|
556
|
+
return 'active';
|
|
557
|
+
}
|
|
558
|
+
|
|
534
559
|
/**
|
|
535
560
|
* Migrate a config object from any older schema to the current one.
|
|
536
561
|
*
|
|
@@ -789,6 +814,13 @@ function buildResolvedConfig(raw = {}, { env = process.env } = {}) {
|
|
|
789
814
|
}
|
|
790
815
|
const contextInjectPrompt =
|
|
791
816
|
contextIn.injectPrompt === undefined ? defaults.context.injectPrompt : requireBoolean(contextIn.injectPrompt, 'context.injectPrompt');
|
|
817
|
+
// v1.6.7 M1: an enum, not a boolean — `index` is the new default, `full` is the
|
|
818
|
+
// legacy body rendering, and a typo must fail fast rather than silently pick one.
|
|
819
|
+
const contextInjectMode = requireEnum(
|
|
820
|
+
contextIn.injectMode === undefined ? defaults.context.injectMode : contextIn.injectMode,
|
|
821
|
+
'context.injectMode',
|
|
822
|
+
['index', 'full'],
|
|
823
|
+
);
|
|
792
824
|
const contextColdStartInjectSummary = requireBoolean(
|
|
793
825
|
contextIn.coldStartInjectSummary === undefined
|
|
794
826
|
? defaults.context.coldStartInjectSummary
|
|
@@ -1385,6 +1417,7 @@ function buildResolvedConfig(raw = {}, { env = process.env } = {}) {
|
|
|
1385
1417
|
threshold: contextThreshold,
|
|
1386
1418
|
target: contextTarget,
|
|
1387
1419
|
injectPrompt: contextInjectPrompt,
|
|
1420
|
+
injectMode: contextInjectMode,
|
|
1388
1421
|
// v1.6.3 cold-start injection switches (independent booleans).
|
|
1389
1422
|
coldStartInjectSummary: contextColdStartInjectSummary,
|
|
1390
1423
|
coldStartInjectRecentTurns: contextColdStartInjectRecentTurns,
|
|
@@ -21,6 +21,43 @@ export function estimateTokens(text) {
|
|
|
21
21
|
return Math.max(1, Math.ceil(String(text ?? '').length / 4));
|
|
22
22
|
}
|
|
23
23
|
|
|
24
|
+
/**
|
|
25
|
+
* v1.6.7 M1 — how a block reaches the prompt.
|
|
26
|
+
*
|
|
27
|
+
* index one pointer line: `- [memory <eventId>] tag1 · tag2 · <title>`
|
|
28
|
+
* full the legacy behaviour: `- [memory <eventId>] <first 200 chars of body>`
|
|
29
|
+
*
|
|
30
|
+
* `index` is the default because the pointer is enough to decide whether to call the
|
|
31
|
+
* recall tool, and the body costs prompt budget on every single turn.
|
|
32
|
+
*/
|
|
33
|
+
export const INDEX_MODE = 'index';
|
|
34
|
+
export const FULL_MODE = 'full';
|
|
35
|
+
export const INJECT_MODES = Object.freeze([INDEX_MODE, FULL_MODE]);
|
|
36
|
+
/** Characters of the block body kept as its "title" in index mode. */
|
|
37
|
+
export const INDEX_TITLE_CHARS = 80;
|
|
38
|
+
/** Tags shown on one pointer line; the rest are implied by the recall result. */
|
|
39
|
+
export const INDEX_TAG_LIMIT = 3;
|
|
40
|
+
|
|
41
|
+
/**
|
|
42
|
+
* The ONE place a block becomes prompt text. `render()` and the token accounting
|
|
43
|
+
* both call it, so what the engine measures is exactly what it emits — the previous
|
|
44
|
+
* split (measure the body, emit a 200-char snippet) understated the window and is
|
|
45
|
+
* the bug this whole feature is about.
|
|
46
|
+
*/
|
|
47
|
+
export function renderBlockLine(block, { mode = INDEX_MODE } = {}) {
|
|
48
|
+
// A briefing block IS its own body: it is the pinned operator policy that must be
|
|
49
|
+
// read verbatim, so it never degrades to a pointer.
|
|
50
|
+
if (block.kind === 'briefing') return String(block.text ?? '');
|
|
51
|
+
if (mode === FULL_MODE) return `- [memory ${block.id}] ${snippet(block.text, 200)}`;
|
|
52
|
+
const tags = Array.isArray(block.tags) ? block.tags.filter(Boolean).slice(0, INDEX_TAG_LIMIT) : [];
|
|
53
|
+
const rawTitle = String(block.title ?? '').replace(/\s+/g, ' ').trim();
|
|
54
|
+
// The cap applies HERE, not only in inject(): renderBlockLine is exported and any
|
|
55
|
+
// caller (or a block restored from an older shape) may hand it an oversized title.
|
|
56
|
+
const title = rawTitle ? snippet(rawTitle, INDEX_TITLE_CHARS) : snippet(block.text, INDEX_TITLE_CHARS);
|
|
57
|
+
const head = tags.length > 0 ? tags.join(' · ') : block.kind;
|
|
58
|
+
return `- [memory ${block.id}] ${head}${title ? ` · ${title}` : ''}`;
|
|
59
|
+
}
|
|
60
|
+
|
|
24
61
|
export class ContextEngine {
|
|
25
62
|
/**
|
|
26
63
|
* @param {object} options
|
|
@@ -48,6 +85,7 @@ export class ContextEngine {
|
|
|
48
85
|
getHostWindow = null,
|
|
49
86
|
getHostUsedTokens = null,
|
|
50
87
|
getReservedTokens = null,
|
|
88
|
+
injectMode = null,
|
|
51
89
|
} = {}) {
|
|
52
90
|
this.clock = clock;
|
|
53
91
|
this.getPolicy = getPolicy;
|
|
@@ -71,6 +109,12 @@ export class ContextEngine {
|
|
|
71
109
|
this.getHostWindow = typeof getHostWindow === 'function' ? getHostWindow : null;
|
|
72
110
|
this.getHostUsedTokens = typeof getHostUsedTokens === 'function' ? getHostUsedTokens : null;
|
|
73
111
|
this.getReservedTokens = typeof getReservedTokens === 'function' ? getReservedTokens : null;
|
|
112
|
+
// v1.6.7 M1: `index` renders one pointer line per block (eventId + tags +
|
|
113
|
+
// title) instead of the block body. The body is NOT lost — it is fetched on
|
|
114
|
+
// demand with the recall tool. This is a prompt-budget decision: a full block is
|
|
115
|
+
// ~200 chars of context the model usually does not need yet, and it is paid for
|
|
116
|
+
// on EVERY turn while the block lives.
|
|
117
|
+
this.injectModeOverride = injectMode === INDEX_MODE || injectMode === FULL_MODE ? injectMode : null;
|
|
74
118
|
this.statsFile = statsFile;
|
|
75
119
|
/** @type {Array<object>} insertion-ordered block table */
|
|
76
120
|
this.blocks = [];
|
|
@@ -106,6 +150,13 @@ export class ContextEngine {
|
|
|
106
150
|
};
|
|
107
151
|
}
|
|
108
152
|
|
|
153
|
+
/** v1.6.7 M1: constructor override > policy > `index` (the documented default). */
|
|
154
|
+
get injectMode() {
|
|
155
|
+
const pol = this.getPolicy?.()?.context ?? {};
|
|
156
|
+
const mode = this.injectModeOverride ?? pol.injectMode;
|
|
157
|
+
return mode === FULL_MODE ? FULL_MODE : INDEX_MODE;
|
|
158
|
+
}
|
|
159
|
+
|
|
109
160
|
/**
|
|
110
161
|
* v1.6.3: the model's REAL context window, resolved host-first.
|
|
111
162
|
*
|
|
@@ -259,6 +310,10 @@ export class ContextEngine {
|
|
|
259
310
|
salience = 0.5,
|
|
260
311
|
at,
|
|
261
312
|
pinned = false,
|
|
313
|
+
// v1.6.7 M1 pointer metadata. Both are optional: a caller that supplies neither
|
|
314
|
+
// still gets a usable pointer (the title falls back to the head of the body).
|
|
315
|
+
title = null,
|
|
316
|
+
tags = null,
|
|
262
317
|
now = this.clock.now(),
|
|
263
318
|
}) {
|
|
264
319
|
if (!id) throw new Error('ContextEngine.inject requires an id');
|
|
@@ -268,7 +323,15 @@ export class ContextEngine {
|
|
|
268
323
|
id,
|
|
269
324
|
kind,
|
|
270
325
|
text: body,
|
|
271
|
-
|
|
326
|
+
title: title === null ? null : String(title).replace(/\s+/g, ' ').trim().slice(0, INDEX_TITLE_CHARS) || null,
|
|
327
|
+
tags: Array.isArray(tags) ? tags.filter((tag) => typeof tag === 'string' && tag.length > 0).slice(0, 12) : null,
|
|
328
|
+
// A caller that states a weight keeps it (tests and `[Active Task]` accounting
|
|
329
|
+
// depend on that); otherwise the weight is derived from the block, and
|
|
330
|
+
// `tokensOf()` re-derives it if `injectMode` later flips.
|
|
331
|
+
tokens: Number.isFinite(tokens)
|
|
332
|
+
? Math.max(1, Math.round(tokens))
|
|
333
|
+
: estimateTokens(this.injectMode === FULL_MODE ? body : renderBlockLine({ id, kind, text: body, title, tags }, { mode: INDEX_MODE })),
|
|
334
|
+
explicitTokens: Number.isFinite(tokens) ? Math.max(1, Math.round(tokens)) : null,
|
|
272
335
|
salience: Number.isFinite(salience) ? Math.max(0, Math.min(1, salience)) : 0.5,
|
|
273
336
|
at: Number.isFinite(at) ? at : now,
|
|
274
337
|
pinned: pinned === true,
|
|
@@ -286,8 +349,31 @@ export class ContextEngine {
|
|
|
286
349
|
return block;
|
|
287
350
|
}
|
|
288
351
|
|
|
352
|
+
/**
|
|
353
|
+
* Tokens this block costs in the prompt RIGHT NOW.
|
|
354
|
+
*
|
|
355
|
+
* `full` keeps the LEGACY weight (the whole body, even though `render()` shows a
|
|
356
|
+
* 200-char snippet): that accounting is the one every existing operator and test
|
|
357
|
+
* calibrated against, and silently shrinking it would make the window admit far
|
|
358
|
+
* more blocks than the old tuning expected.
|
|
359
|
+
*
|
|
360
|
+
* `index` charges the pointer LINE, because that is all it emits — charging for a
|
|
361
|
+
* body that never enters the prompt is exactly the waste M1 removes.
|
|
362
|
+
*
|
|
363
|
+
* Recomputed rather than stored: `injectMode` is live config, so a block injected
|
|
364
|
+
* while `full` was on must be re-measured the moment the mode flips. An explicit
|
|
365
|
+
* weight from the caller always wins — that is a contract, not an estimate.
|
|
366
|
+
*/
|
|
367
|
+
tokensOf(block) {
|
|
368
|
+
if (block.explicitTokens !== null) return block.explicitTokens;
|
|
369
|
+
if (this.injectMode === FULL_MODE) return estimateTokens(block.text);
|
|
370
|
+
return estimateTokens(renderBlockLine(block, { mode: INDEX_MODE }));
|
|
371
|
+
}
|
|
372
|
+
|
|
289
373
|
tokens() {
|
|
290
|
-
|
|
374
|
+
let sum = 0;
|
|
375
|
+
for (const block of this.blocks) sum += this.tokensOf(block);
|
|
376
|
+
return sum;
|
|
291
377
|
}
|
|
292
378
|
|
|
293
379
|
usage({ now = this.clock.now() } = {}) {
|
|
@@ -365,11 +451,19 @@ export class ContextEngine {
|
|
|
365
451
|
}
|
|
366
452
|
}
|
|
367
453
|
if (!victim) break; // everything left is pinned: report, never force
|
|
454
|
+
const victimTokens = this.tokensOf(victim);
|
|
368
455
|
this.blocks = this.blocks.filter((b) => b.id !== victim.id);
|
|
369
|
-
current -=
|
|
456
|
+
current -= victimTokens;
|
|
370
457
|
// Keep the TEXT of the victim: folding ("推币机") needs what was evicted,
|
|
371
458
|
// not just its id — the block is gone from the window either way.
|
|
372
|
-
const record = {
|
|
459
|
+
const record = {
|
|
460
|
+
id: victim.id,
|
|
461
|
+
kind: victim.kind,
|
|
462
|
+
tokens: victimTokens,
|
|
463
|
+
score: round(victimScore, 6),
|
|
464
|
+
text: victim.text,
|
|
465
|
+
at: victim.at,
|
|
466
|
+
};
|
|
373
467
|
evictedNow.push(record);
|
|
374
468
|
this.evicted.push({ ...record, at: now });
|
|
375
469
|
}
|
|
@@ -399,11 +493,12 @@ export class ContextEngine {
|
|
|
399
493
|
* Render the surviving blocks. v1.5.6: `excludeIds` lets prompt assembly drop
|
|
400
494
|
* blocks already injected earlier in the SAME session (dedup by block id).
|
|
401
495
|
*/
|
|
402
|
-
render({ excludeIds = null } = {}) {
|
|
496
|
+
render({ excludeIds = null, mode = null } = {}) {
|
|
403
497
|
const excluded = excludeIds instanceof Set ? excludeIds : null;
|
|
498
|
+
const renderMode = mode === FULL_MODE || mode === INDEX_MODE ? mode : this.injectMode;
|
|
404
499
|
return this.blocks
|
|
405
500
|
.filter((block) => !(excluded && excluded.has(block.id)))
|
|
406
|
-
.map((block) => (block
|
|
501
|
+
.map((block) => renderBlockLine(block, { mode: renderMode }))
|
|
407
502
|
.join('\n');
|
|
408
503
|
}
|
|
409
504
|
|
|
@@ -412,17 +507,20 @@ export class ContextEngine {
|
|
|
412
507
|
return {
|
|
413
508
|
...this.usage({ now }),
|
|
414
509
|
maxTokens,
|
|
510
|
+
injectMode: this.injectMode,
|
|
415
511
|
// Native/layered measurement rides along with the panel snapshot so status
|
|
416
512
|
// readers never have to reconstruct it from the block table.
|
|
417
513
|
native: this.nativeState({ now }),
|
|
418
514
|
blocks: this.blocks.map((block) => ({
|
|
419
515
|
id: block.id,
|
|
420
516
|
kind: block.kind,
|
|
421
|
-
tokens: block
|
|
517
|
+
tokens: this.tokensOf(block),
|
|
422
518
|
salience: block.salience,
|
|
423
519
|
score: round(this.score(block, now), 6),
|
|
424
520
|
pinned: block.pinned,
|
|
425
521
|
at: block.at,
|
|
522
|
+
tags: block.tags,
|
|
523
|
+
title: block.title,
|
|
426
524
|
})),
|
|
427
525
|
recentlyEvicted: this.evicted.slice(-10),
|
|
428
526
|
savedTokens: this.savedTokens,
|
package/src/entropy.js
ADDED
|
@@ -0,0 +1,120 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* High-entropy / ciphertext detection for the WRITE side (audit item A4).
|
|
3
|
+
*
|
|
4
|
+
* The original audit found that the engine only redacts secrets on the READ path and
|
|
5
|
+
* rejects inline base64 in `remember()`, but nothing stopped a captured turn from
|
|
6
|
+
* carrying a ciphertext or an opaque encrypted blob into the append-only log. That
|
|
7
|
+
* log is the one thing this plugin promises never to lose, so a blob that can never
|
|
8
|
+
* be searched, summarised or distilled is worse than a rejection.
|
|
9
|
+
*
|
|
10
|
+
* Design constraints, in order:
|
|
11
|
+
* 1. **No false positives on prose or code.** Detection requires a SINGLE
|
|
12
|
+
* whitespace-free token of at least `MIN_RUN_CHARS` characters drawn from a
|
|
13
|
+
* narrow alphabet, so normal sentences, URLs, file paths and identifiers pass.
|
|
14
|
+
* 2. **Explainable.** Every verdict reports which signal fired (`pem`, `base64`,
|
|
15
|
+
* `hex`) plus the measured entropy, so a caller can log or display the reason.
|
|
16
|
+
* 3. **Cheap.** The scan is linear and bounded to the first `MAX_SCAN_CHARS`
|
|
17
|
+
* characters; capture happens on every surface message.
|
|
18
|
+
*/
|
|
19
|
+
|
|
20
|
+
export const ENCRYPTED_REJECT_CODE = 'MEM_E_ENCRYPTED_RAW_REJECTED';
|
|
21
|
+
|
|
22
|
+
/** A run shorter than this is ordinary text, not a payload. */
|
|
23
|
+
export const MIN_RUN_CHARS = 512;
|
|
24
|
+
/** Entropy floor for base64-ish payloads (bits per character, max 6 for base64). */
|
|
25
|
+
export const BASE64_ENTROPY_FLOOR = 4.5;
|
|
26
|
+
/** Entropy floor for hex payloads (max 4 bits per character). */
|
|
27
|
+
export const HEX_ENTROPY_FLOOR = 3.5;
|
|
28
|
+
/** Only the head of a turn is scanned: capture must stay O(1)-ish. */
|
|
29
|
+
export const MAX_SCAN_CHARS = 2_000_000;
|
|
30
|
+
|
|
31
|
+
const PEM_MARKERS = [
|
|
32
|
+
'-----BEGIN PGP MESSAGE-----',
|
|
33
|
+
'-----BEGIN PGP ARMORED FILE-----',
|
|
34
|
+
'-----BEGIN ENCRYPTED PRIVATE KEY-----',
|
|
35
|
+
'-----BEGIN ENCRYPTED MESSAGE-----',
|
|
36
|
+
'-----BEGIN AGE ENCRYPTED FILE-----',
|
|
37
|
+
];
|
|
38
|
+
|
|
39
|
+
const BASE64_TOKEN = /[A-Za-z0-9+/_-]{512,}={0,2}/;
|
|
40
|
+
const HEX_TOKEN = /\b[0-9a-fA-F]{512,}\b/;
|
|
41
|
+
|
|
42
|
+
/** Shannon entropy in bits per character over the token's own alphabet. */
|
|
43
|
+
export function shannonEntropy(text) {
|
|
44
|
+
if (typeof text !== 'string' || text.length === 0) return 0;
|
|
45
|
+
const counts = new Map();
|
|
46
|
+
for (const char of text) counts.set(char, (counts.get(char) ?? 0) + 1);
|
|
47
|
+
let entropy = 0;
|
|
48
|
+
for (const count of counts.values()) {
|
|
49
|
+
const p = count / text.length;
|
|
50
|
+
entropy -= p * Math.log2(p);
|
|
51
|
+
}
|
|
52
|
+
return Math.round(entropy * 1000) / 1000;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/**
|
|
56
|
+
* Decide whether `text` carries a ciphertext / high-entropy blob.
|
|
57
|
+
*
|
|
58
|
+
* Returns `null` when the content is safe to store, otherwise
|
|
59
|
+
* `{ reject: true, reason, runLength, entropy, sample }`.
|
|
60
|
+
*/
|
|
61
|
+
export function detectCiphertext(text, options = {}) {
|
|
62
|
+
if (typeof text !== 'string' || text.length === 0) return null;
|
|
63
|
+
const minRun = Number.isFinite(options.minRunChars) ? options.minRunChars : MIN_RUN_CHARS;
|
|
64
|
+
const scanned = text.length > MAX_SCAN_CHARS ? text.slice(0, MAX_SCAN_CHARS) : text;
|
|
65
|
+
|
|
66
|
+
// 1. Explicit armour is unambiguous — never a false positive.
|
|
67
|
+
for (const marker of PEM_MARKERS) {
|
|
68
|
+
const at = scanned.indexOf(marker);
|
|
69
|
+
if (at !== -1) {
|
|
70
|
+
return { reject: true, reason: 'pem', runLength: marker.length, entropy: null, at, sample: marker.slice(0, 40) };
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
// 2. A long single-token base64 run that is ALSO high entropy. The entropy floor is
|
|
75
|
+
// what separates an encrypted blob from a repetitive identifier or a data URL of
|
|
76
|
+
// a highly compressible payload.
|
|
77
|
+
const base64 = BASE64_TOKEN.exec(scanned);
|
|
78
|
+
if (base64 && base64[0].length >= minRun) {
|
|
79
|
+
const entropy = shannonEntropy(base64[0]);
|
|
80
|
+
if (entropy >= BASE64_ENTROPY_FLOOR) {
|
|
81
|
+
return {
|
|
82
|
+
reject: true,
|
|
83
|
+
reason: 'base64',
|
|
84
|
+
runLength: base64[0].length,
|
|
85
|
+
entropy,
|
|
86
|
+
at: base64.index,
|
|
87
|
+
sample: base64[0].slice(0, 32),
|
|
88
|
+
};
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
// 3. Long hex blobs (raw ciphertext, keys, digests concatenated).
|
|
93
|
+
const hex = HEX_TOKEN.exec(scanned);
|
|
94
|
+
if (hex && hex[0].length >= minRun) {
|
|
95
|
+
const entropy = shannonEntropy(hex[0]);
|
|
96
|
+
if (entropy >= HEX_ENTROPY_FLOOR) {
|
|
97
|
+
return {
|
|
98
|
+
reject: true,
|
|
99
|
+
reason: 'hex',
|
|
100
|
+
runLength: hex[0].length,
|
|
101
|
+
entropy,
|
|
102
|
+
at: hex.index,
|
|
103
|
+
sample: hex[0].slice(0, 32),
|
|
104
|
+
};
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
return null;
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
/**
|
|
111
|
+
* Throw `MEM_E_ENCRYPTED_RAW_REJECTED` when `text` carries a ciphertext blob.
|
|
112
|
+
*
|
|
113
|
+
* Kept separate from the detector so callers that only need a boolean (tests, the
|
|
114
|
+
* status surface) can use `detectCiphertext` without importing the error type.
|
|
115
|
+
*/
|
|
116
|
+
export function assertNoCiphertext(text, makeError, options = {}) {
|
|
117
|
+
const verdict = detectCiphertext(text, options);
|
|
118
|
+
if (!verdict) return null;
|
|
119
|
+
throw makeError(verdict);
|
|
120
|
+
}
|
package/src/errors.js
CHANGED
|
@@ -33,6 +33,12 @@ export const ErrorCodes = Object.freeze({
|
|
|
33
33
|
FEDERATION_FAILED: 'MEM_E_FEDERATION_FAILED',
|
|
34
34
|
/** A cold raw archive could not be decompressed; the shard is skipped. */
|
|
35
35
|
CORRUPTED_ARCHIVE: 'MEM_E_CORRUPTED_ARCHIVE',
|
|
36
|
+
/**
|
|
37
|
+
* The write carried a ciphertext / high-entropy blob (A4). Rejecting it keeps the
|
|
38
|
+
* append-only log searchable: an encrypted blob could never be recalled, summarised
|
|
39
|
+
* or distilled, yet it would be retained forever.
|
|
40
|
+
*/
|
|
41
|
+
ENCRYPTED_RAW_REJECTED: 'MEM_E_ENCRYPTED_RAW_REJECTED',
|
|
36
42
|
|
|
37
43
|
// ---- configuration (fail-fast at boot; never silently downgraded) ---------
|
|
38
44
|
CONFIG_DEPRECATED: 'MEM_E_CONFIG_DEPRECATED',
|
|
@@ -167,6 +173,9 @@ export class MemoryError extends Error {
|
|
|
167
173
|
/** Wrap an unknown thrown value as a MemoryError with the given fallback code. */
|
|
168
174
|
export function asMemoryError(err, code = ErrorCodes.IO) {
|
|
169
175
|
if (err instanceof MemoryError) return err;
|
|
176
|
+
// v1.6.6 (M5): an orchestrator-namespace failure that reached our boundary is
|
|
177
|
+
// translated, never flattened to MEM_E_IO (see ORCHESTRATOR_CODE_MAP below).
|
|
178
|
+
if (isOrchestratorCode(err?.code)) return fromOrchestratorError(err, code);
|
|
170
179
|
const message = err instanceof Error ? err.message : String(err);
|
|
171
180
|
// A plain Error may already carry a MEM_E_* code (node http handlers, stream
|
|
172
181
|
// helpers). Keep it: downgrading a CONFIG_* failure to MEM_E_IO would make the
|
|
@@ -177,6 +186,69 @@ export function asMemoryError(err, code = ErrorCodes.IO) {
|
|
|
177
186
|
return wrapped;
|
|
178
187
|
}
|
|
179
188
|
|
|
189
|
+
/**
|
|
190
|
+
* v1.6.6 (M5): the two packages share a boundary, not an error namespace.
|
|
191
|
+
*
|
|
192
|
+
* `dsh-orchestrator` owns two contracts on purpose:
|
|
193
|
+
* - `MEM_E_*` for the code MOVED OUT of this core (router/transfer/space), so a
|
|
194
|
+
* tool or HTTP result keeps the exact code a client already branches on — see
|
|
195
|
+
* `dsh-orchestrator/src/compat.js`;
|
|
196
|
+
* - `ORCH_E_*` for the orchestrator's OWN surfaces (consent broker, federation
|
|
197
|
+
* map, claim registry) — see `dsh-orchestrator/src/errors.js`.
|
|
198
|
+
*
|
|
199
|
+
* Anything that reaches THIS package's tool/HTTP result must therefore speak
|
|
200
|
+
* `MEM_E_*`. Rather than rewrite the orchestrator's internal codes (which would
|
|
201
|
+
* break its own tests and its documented API), the translation happens here, at the
|
|
202
|
+
* single boundary every failure crosses. The mapping is total and one-way:
|
|
203
|
+
*
|
|
204
|
+
* | orchestrator code | memory code | why |
|
|
205
|
+
* |---------------------------|----------------------------|---------------------------|
|
|
206
|
+
* | ORCH_E_CONSENT_REQUIRED | MEM_E_REQUIRE_USER_CONSENT | the agent must ask a human |
|
|
207
|
+
* | ORCH_E_CONSENT_INVALID | MEM_E_REQUIRE_USER_CONSENT | a bad token is no consent |
|
|
208
|
+
* | ORCH_E_CONSENT_CONSUMED | MEM_E_REQUIRE_USER_CONSENT | single-use: ask again |
|
|
209
|
+
* | ORCH_E_SPACE_INVALID | MEM_E_SPACE_INVALID | same payload, same verdict |
|
|
210
|
+
* | ORCH_E_INVALID_INPUT | MEM_E_INVALID_INPUT | same payload, same verdict |
|
|
211
|
+
* | ORCH_E_NOT_READY | MEM_E_NOT_READY | same payload, same verdict |
|
|
212
|
+
* | ORCH_E_FEDERATION_CONFLICT| MEM_E_FEDERATION_FAILED | bookkeeping, not the write |
|
|
213
|
+
*
|
|
214
|
+
* A code that is not listed is NOT silently flattened to MEM_E_IO: it keeps the
|
|
215
|
+
* caller's fallback, and the original code stays available on `details.orchestratorCode`.
|
|
216
|
+
*/
|
|
217
|
+
export const ORCHESTRATOR_CODE_MAP = Object.freeze({
|
|
218
|
+
ORCH_E_CONSENT_REQUIRED: 'MEM_E_REQUIRE_USER_CONSENT',
|
|
219
|
+
ORCH_E_CONSENT_INVALID: 'MEM_E_REQUIRE_USER_CONSENT',
|
|
220
|
+
ORCH_E_CONSENT_CONSUMED: 'MEM_E_REQUIRE_USER_CONSENT',
|
|
221
|
+
ORCH_E_SPACE_INVALID: 'MEM_E_SPACE_INVALID',
|
|
222
|
+
ORCH_E_INVALID_INPUT: 'MEM_E_INVALID_INPUT',
|
|
223
|
+
ORCH_E_NOT_READY: 'MEM_E_NOT_READY',
|
|
224
|
+
ORCH_E_FEDERATION_CONFLICT: 'MEM_E_FEDERATION_FAILED',
|
|
225
|
+
});
|
|
226
|
+
|
|
227
|
+
/** True when the code belongs to the orchestrator's own namespace. */
|
|
228
|
+
export function isOrchestratorCode(code) {
|
|
229
|
+
return typeof code === 'string' && code.startsWith('ORCH_E_');
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
/**
|
|
233
|
+
* Translate an orchestrator-namespace error into this package's namespace.
|
|
234
|
+
* Returns the ORIGINAL error unchanged when it is not an ORCH_E_* failure (so a
|
|
235
|
+
* MEM_E_* passthrough is never rewrapped), and otherwise wraps it with the mapped
|
|
236
|
+
* code, keeping `details.orchestratorCode` for forensics.
|
|
237
|
+
*/
|
|
238
|
+
export function fromOrchestratorError(err, code = ErrorCodes.IO) {
|
|
239
|
+
const orchestratorCode = typeof err?.code === 'string' ? err.code : null;
|
|
240
|
+
if (!isOrchestratorCode(orchestratorCode)) return asMemoryError(err, code);
|
|
241
|
+
const mapped = ORCHESTRATOR_CODE_MAP[orchestratorCode] ?? code;
|
|
242
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
243
|
+
const wrapped = new MemoryError(
|
|
244
|
+
mapped,
|
|
245
|
+
message,
|
|
246
|
+
{ orchestratorCode, ...(err?.details && typeof err.details === 'object' ? err.details : {}) },
|
|
247
|
+
);
|
|
248
|
+
wrapped.cause = err;
|
|
249
|
+
return wrapped;
|
|
250
|
+
}
|
|
251
|
+
|
|
180
252
|
export function invalidInput(message, details) {
|
|
181
253
|
return new MemoryError(ErrorCodes.INVALID_INPUT, message, details);
|
|
182
254
|
}
|
package/src/hostBridge.js
CHANGED
|
@@ -19,6 +19,11 @@
|
|
|
19
19
|
* - unknown + an LLM-backed Dream ⇒ SKIP ("price-unknown"). Unknown + a local-only
|
|
20
20
|
* Dream ⇒ allowed (local recompute is cheap and the compensation is the point).
|
|
21
21
|
*
|
|
22
|
+
* M2: notifications are injected the same way. `setNotifier(fn)` accepts an external
|
|
23
|
+
* `dsh-notify-plugin`-style sink; without one every notification is a recorded no-op
|
|
24
|
+
* (`{delivered: false, reason: 'no-notifier'}`), so the plugin never invents a
|
|
25
|
+
* delivery channel and never throws when nothing is wired.
|
|
26
|
+
*
|
|
22
27
|
* Zero dependencies; the bus is a plain `{on, off}` seam so tests can mock the Host.
|
|
23
28
|
*/
|
|
24
29
|
|
|
@@ -66,6 +71,9 @@ export class HostBridge {
|
|
|
66
71
|
this.onAgentPresetSelected = typeof onAgentPresetSelected === 'function' ? onAgentPresetSelected : null;
|
|
67
72
|
this.env = env ?? {};
|
|
68
73
|
this._priceProbe = null;
|
|
74
|
+
// M2: an INJECTED notification sink. Null means "nothing is wired", which is a
|
|
75
|
+
// normal state, not an error — every notify() then answers no-notifier.
|
|
76
|
+
this._notifier = null;
|
|
69
77
|
this._bound = null;
|
|
70
78
|
this._compensating = false;
|
|
71
79
|
this.stats = {
|
|
@@ -76,6 +84,10 @@ export class HostBridge {
|
|
|
76
84
|
skipped: 0,
|
|
77
85
|
lastSkipReason: null,
|
|
78
86
|
presetSelections: 0,
|
|
87
|
+
notifications: 0,
|
|
88
|
+
lastNotificationAt: null,
|
|
89
|
+
notifySkipped: 0,
|
|
90
|
+
lastNotifySkipReason: null,
|
|
79
91
|
};
|
|
80
92
|
}
|
|
81
93
|
|
|
@@ -138,6 +150,44 @@ export class HostBridge {
|
|
|
138
150
|
return this;
|
|
139
151
|
}
|
|
140
152
|
|
|
153
|
+
/**
|
|
154
|
+
* M2: inject a notification sink (`dsh-notify-plugin` style). Passing null clears it.
|
|
155
|
+
*
|
|
156
|
+
* The sink receives `{ title, text, kind, at }`. It may return anything; only a
|
|
157
|
+
* thrown error matters (it is caught, counted and never propagates).
|
|
158
|
+
*/
|
|
159
|
+
setNotifier(sink) {
|
|
160
|
+
this._notifier = typeof sink === 'function' ? sink : null;
|
|
161
|
+
return this;
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
/** True when an external notification channel is wired. */
|
|
165
|
+
get notifierAttached() {
|
|
166
|
+
return this._notifier !== null;
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
/**
|
|
170
|
+
* Deliver one notification through the injected sink. NEVER throws and NEVER
|
|
171
|
+
* invents a channel: without a sink the call is a recorded no-op.
|
|
172
|
+
*/
|
|
173
|
+
notify({ title, text, kind = 'info', at = this.clock() } = {}) {
|
|
174
|
+
const noop = (reason) => {
|
|
175
|
+
this.stats.notifySkipped += 1;
|
|
176
|
+
this.stats.lastNotifySkipReason = reason;
|
|
177
|
+
return { delivered: false, reason };
|
|
178
|
+
};
|
|
179
|
+
if (!this._notifier) return noop('no-notifier');
|
|
180
|
+
try {
|
|
181
|
+
const outcome = this._notifier({ title, text, kind, at });
|
|
182
|
+
this.stats.notifications += 1;
|
|
183
|
+
this.stats.lastNotificationAt = at;
|
|
184
|
+
return { delivered: true, outcome: outcome ?? null };
|
|
185
|
+
} catch (error) {
|
|
186
|
+
this.logger?.warn?.(`hippocampus: notification sink failed: ${error?.message ?? error}`);
|
|
187
|
+
return noop('sink-error');
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
|
|
141
191
|
/** `{known, low}` for one instant. Never guesses: unknown is reported as such. */
|
|
142
192
|
lowValley(now = this.clock()) {
|
|
143
193
|
if (this._priceProbe) {
|
|
@@ -216,6 +266,7 @@ export class HostBridge {
|
|
|
216
266
|
dreamDue: this.dreamDue(),
|
|
217
267
|
compensateAfterHours: this.dreamPolicy().compensateAfterHours,
|
|
218
268
|
attached: this._bound !== null,
|
|
269
|
+
notifierAttached: this.notifierAttached,
|
|
219
270
|
};
|
|
220
271
|
}
|
|
221
272
|
}
|
package/src/memory.js
CHANGED
|
@@ -112,6 +112,7 @@ function validateRoutedNewSpaceId(value) {
|
|
|
112
112
|
return id;
|
|
113
113
|
}
|
|
114
114
|
import { ensureDir, dayKey, genNumber, sha256, readJson, writeJsonAtomic, snippet } from './util.js';
|
|
115
|
+
import { detectCiphertext } from './entropy.js';
|
|
115
116
|
|
|
116
117
|
/** Recursive byte size of a directory tree (symlinks count as their target size). */
|
|
117
118
|
function diskUsage(dir) {
|
|
@@ -466,6 +467,8 @@ export class Memory {
|
|
|
466
467
|
getHostWindow: typeof config.getHostWindow === 'function' ? config.getHostWindow : null,
|
|
467
468
|
getHostUsedTokens: typeof config.getHostUsedTokens === 'function' ? config.getHostUsedTokens : null,
|
|
468
469
|
getReservedTokens: typeof config.getReservedTokens === 'function' ? config.getReservedTokens : null,
|
|
470
|
+
// v1.6.7 M1: `index` (default) emits pointer lines instead of block bodies.
|
|
471
|
+
injectMode: config.context?.injectMode,
|
|
469
472
|
statsFile: path.join(this.paths.state, 'context.json'),
|
|
470
473
|
});
|
|
471
474
|
this.deletePipeline = new DeletePipeline({
|
|
@@ -729,6 +732,18 @@ export class Memory {
|
|
|
729
732
|
mediaType = null,
|
|
730
733
|
} = {}) {
|
|
731
734
|
this.assertOpen();
|
|
735
|
+
// A4: ciphertext is checked FIRST, before the generic base64-media guard, because
|
|
736
|
+
// "this looks like ciphertext" is the more useful diagnosis: the media guard would
|
|
737
|
+
// tell the caller to pass media_url, which is exactly wrong for a secret blob.
|
|
738
|
+
const cipher = detectCiphertext(content);
|
|
739
|
+
if (cipher) {
|
|
740
|
+
throw new MemoryError(
|
|
741
|
+
ErrorCodes.ENCRYPTED_RAW_REJECTED,
|
|
742
|
+
`content carries a ${cipher.reason} blob (${cipher.runLength} chars, entropy ${cipher.entropy ?? 'n/a'}); ` +
|
|
743
|
+
'ciphertext/high-entropy payloads are not stored as memories',
|
|
744
|
+
{ reason: cipher.reason, runLength: cipher.runLength, entropy: cipher.entropy, at: cipher.at },
|
|
745
|
+
);
|
|
746
|
+
}
|
|
732
747
|
ensureNoEmbeddedBase64(content);
|
|
733
748
|
const media = validateMedia(mediaUrl, mediaType);
|
|
734
749
|
const requestedTags = [
|
|
@@ -1588,16 +1603,26 @@ export class Memory {
|
|
|
1588
1603
|
const bucket = parseInt(sha256(turnId + ':' + turn.text).slice(0, 8), 16) % 2;
|
|
1589
1604
|
if (bucket !== 0) return { skipped: 'capture-ratio-sample' };
|
|
1590
1605
|
}
|
|
1591
|
-
|
|
1592
|
-
|
|
1593
|
-
|
|
1594
|
-
|
|
1595
|
-
|
|
1596
|
-
|
|
1597
|
-
|
|
1598
|
-
|
|
1599
|
-
|
|
1600
|
-
|
|
1606
|
+
try {
|
|
1607
|
+
return await this.raw.capture({
|
|
1608
|
+
content: turn.text,
|
|
1609
|
+
role: turn.role,
|
|
1610
|
+
kind: event?.type === 'tool/result' && isError ? 'error' : turn.kind,
|
|
1611
|
+
sessionId: session?.id ?? session?.sessionId ?? null,
|
|
1612
|
+
turnId: `turn_${event?.seq ?? 'x'}_${turn.role}`,
|
|
1613
|
+
at: Number.isFinite(event?.time) ? event.time : undefined,
|
|
1614
|
+
salience: 1,
|
|
1615
|
+
force: true,
|
|
1616
|
+
});
|
|
1617
|
+
} catch (error) {
|
|
1618
|
+
// A4: a ciphertext blob is a normal, expected refusal — not a capture failure.
|
|
1619
|
+
// Returning it as a skip keeps the listener quiet while still leaving a trace in
|
|
1620
|
+
// the turn's own result (and never writes the blob anywhere).
|
|
1621
|
+
if (error?.code === ErrorCodes.ENCRYPTED_RAW_REJECTED) {
|
|
1622
|
+
return { stored: false, skipped: 'encrypted-blob', reason: error?.details?.reason ?? 'ciphertext' };
|
|
1623
|
+
}
|
|
1624
|
+
throw error;
|
|
1625
|
+
}
|
|
1601
1626
|
}
|
|
1602
1627
|
|
|
1603
1628
|
/**
|
package/src/rawStore.js
CHANGED
|
@@ -29,6 +29,7 @@ import { dayKey, ensureDir, sha256 } from './util.js';
|
|
|
29
29
|
import { RawArchive, archiveMonthOf, isArchiveName, scanGzipArchive } from './rawArchive.js';
|
|
30
30
|
import { engineForArchive } from './compression.js';
|
|
31
31
|
import { buildIndex, indexFileFor, isIndexFile, readIndex, shardOverlapsWindow, writeIndex } from './rawIndex.js';
|
|
32
|
+
import { detectCiphertext } from './entropy.js';
|
|
32
33
|
|
|
33
34
|
export const RAW_DIR = 'raw';
|
|
34
35
|
/** Records queued before a forced flush. */
|
|
@@ -296,6 +297,19 @@ export class RawStore {
|
|
|
296
297
|
const config = this.config();
|
|
297
298
|
const text = typeof turn.content === 'string' ? turn.content : '';
|
|
298
299
|
if (!text.trim()) throw new MemoryError(ErrorCodes.INVALID_INPUT, 'raw turn content must be a non-empty string');
|
|
300
|
+
// A4: refuse ciphertext / high-entropy blobs BEFORE they reach the black box. The
|
|
301
|
+
// raw log is the one artefact promised to survive forever; a blob that can never be
|
|
302
|
+
// searched, summarised or distilled would be a permanent liability, so the write is
|
|
303
|
+
// rejected with an explicit code instead of being stored and forgotten.
|
|
304
|
+
const cipher = detectCiphertext(text);
|
|
305
|
+
if (cipher) {
|
|
306
|
+
throw new MemoryError(
|
|
307
|
+
ErrorCodes.ENCRYPTED_RAW_REJECTED,
|
|
308
|
+
`raw turn carries a ${cipher.reason} blob (${cipher.runLength} chars, entropy ${cipher.entropy ?? 'n/a'}); ` +
|
|
309
|
+
'ciphertext/high-entropy payloads are not stored in the append-only log',
|
|
310
|
+
{ reason: cipher.reason, runLength: cipher.runLength, entropy: cipher.entropy, at: cipher.at },
|
|
311
|
+
);
|
|
312
|
+
}
|
|
299
313
|
const decision = this.gate({ mode: config.mode, salience: turn.salience, kind: turn.kind, text, force: turn.force });
|
|
300
314
|
if (!decision.store) return { stored: false, reason: decision.reason };
|
|
301
315
|
|
package/src/webRoutes.js
CHANGED
|
@@ -62,6 +62,9 @@ export const EDITABLE_CONFIG_KEYS = Object.freeze([
|
|
|
62
62
|
'context.threshold',
|
|
63
63
|
'context.target',
|
|
64
64
|
'context.injectPrompt',
|
|
65
|
+
// v1.6.7 M1: `index` (pointer lines) vs `full` (legacy bodies). Editable so an
|
|
66
|
+
// operator can fall back without editing the profile by hand.
|
|
67
|
+
'context.injectMode',
|
|
65
68
|
// REMOVED v1.5.3: 'context.minInjectConfidence' (dead token knob). It is no
|
|
66
69
|
// longer editable — the config validator rejects it loudly on profile load.
|
|
67
70
|
// v1.5.0 multi-space routing + session handoff. Pure physical layer: these
|
package/ui/client.js
CHANGED
|
@@ -2528,6 +2528,9 @@
|
|
|
2528
2528
|
'context.threshold',
|
|
2529
2529
|
'context.target',
|
|
2530
2530
|
'context.injectPrompt',
|
|
2531
|
+
// v1.6.7 M1: visible in the 上下文窗口 card in both modes, so it must also be
|
|
2532
|
+
// in the simple-mode allowlist — a control that renders but never saves is a lie.
|
|
2533
|
+
'context.injectMode',
|
|
2531
2534
|
'raw.mode',
|
|
2532
2535
|
'raw.maxTotalMb',
|
|
2533
2536
|
'raw.compressionEngine',
|
|
@@ -2639,6 +2642,7 @@
|
|
|
2639
2642
|
threshold: Number(config.context.threshold),
|
|
2640
2643
|
target: Number(config.context.target),
|
|
2641
2644
|
injectPrompt: Boolean(config.context.injectPrompt),
|
|
2645
|
+
injectMode: config.context && config.context.injectMode === 'full' ? 'full' : 'index',
|
|
2642
2646
|
// v1.5.0 physical routing + session handoff. Read with defaults so an
|
|
2643
2647
|
// older Host half that has not learned these keys yet still renders.
|
|
2644
2648
|
autoSpaceFollow: Boolean((config.context && config.context.autoSpaceFollow) ?? false),
|
|
@@ -2823,7 +2827,7 @@
|
|
|
2823
2827
|
* here; the server ALSO refuses without confirm so a stray request cannot
|
|
2824
2828
|
* mutate the profile.
|
|
2825
2829
|
*/
|
|
2826
|
-
function OrchestratorInstallCard({ installed }) {
|
|
2830
|
+
function OrchestratorInstallCard({ installed, reason = null }) {
|
|
2827
2831
|
const [busy, setBusy] = React.useState(false);
|
|
2828
2832
|
const [result, setResult] = React.useState(null);
|
|
2829
2833
|
const install = async () => {
|
|
@@ -2873,6 +2877,15 @@
|
|
|
2873
2877
|
{ type: 'button', style: smallButtonStyle, onClick: install, disabled: busy },
|
|
2874
2878
|
busy ? '安装中…' : '从 GitHub 安装 dsh-orchestrator',
|
|
2875
2879
|
),
|
|
2880
|
+
// v1.6.7 (M6): the three reasons are not the same problem, and only one of
|
|
2881
|
+
// them is fixable by installing something.
|
|
2882
|
+
!installed && reason === 'disabled-by-config'
|
|
2883
|
+
? h(
|
|
2884
|
+
'span',
|
|
2885
|
+
{ style: { ...labelStyle, marginBottom: 0, color: palette.muted } },
|
|
2886
|
+
'当前被配置关闭:features.multiSpace=false(引擎按严格单空间运行)',
|
|
2887
|
+
)
|
|
2888
|
+
: null,
|
|
2876
2889
|
h(
|
|
2877
2890
|
'a',
|
|
2878
2891
|
{
|
|
@@ -3020,6 +3033,7 @@
|
|
|
3020
3033
|
'context.threshold': Number(draft.context.threshold),
|
|
3021
3034
|
'context.target': Number(draft.context.target),
|
|
3022
3035
|
'context.injectPrompt': Boolean(draft.context.injectPrompt),
|
|
3036
|
+
'context.injectMode': draft.context.injectMode === 'full' ? 'full' : 'index',
|
|
3023
3037
|
'context.autoSpaceFollow': Boolean(draft.context.autoSpaceFollow),
|
|
3024
3038
|
'context.autoRolloverEnabled': Boolean(draft.context.autoRolloverEnabled),
|
|
3025
3039
|
'context.coldStartInjectSummary': Boolean(draft.context.coldStartInjectSummary),
|
|
@@ -3331,6 +3345,13 @@
|
|
|
3331
3345
|
? null
|
|
3332
3346
|
: h(OrchestratorInstallCard, {
|
|
3333
3347
|
installed: Boolean(state.payload && state.payload.capabilities && state.payload.capabilities.spaces === true),
|
|
3348
|
+
// v1.6.7 (M6): render WHY it is off, so "I enabled multiSpace but nothing
|
|
3349
|
+
// happened" is answered right here instead of looking like a silent bug.
|
|
3350
|
+
reason:
|
|
3351
|
+
(state.payload && state.payload.capabilities && state.payload.capabilities.multiSpaceReason) ||
|
|
3352
|
+
(state.payload && state.payload.capabilities && state.payload.capabilities.spaces === true
|
|
3353
|
+
? 'active'
|
|
3354
|
+
: 'orchestrator-missing'),
|
|
3334
3355
|
}),
|
|
3335
3356
|
h(
|
|
3336
3357
|
Section,
|
|
@@ -3568,6 +3589,19 @@
|
|
|
3568
3589
|
onChange: (value) => edit('context.injectPrompt', value),
|
|
3569
3590
|
disabled,
|
|
3570
3591
|
}),
|
|
3592
|
+
// v1.6.7 M1: pointer lines by default. `full` is kept as the escape hatch
|
|
3593
|
+
// for anyone who wants the old body rendering back.
|
|
3594
|
+
h(Select, {
|
|
3595
|
+
label: '记忆块注入形态(context.injectMode)',
|
|
3596
|
+
hint: '索引(推荐):每块只注入 eventId + 标签 + 标题,正文按需用 recall 取;占用已用窗口的 1/10 不到。全文:沿用旧版渲染,正文直接进 Prompt(更费 Token)。',
|
|
3597
|
+
value: draft.context.injectMode === 'full' ? 'full' : 'index',
|
|
3598
|
+
options: [
|
|
3599
|
+
{ value: 'index', label: '索引(eventId + 标签 + 标题)' },
|
|
3600
|
+
{ value: 'full', label: '全文(旧版渲染)' },
|
|
3601
|
+
],
|
|
3602
|
+
onChange: (value) => edit('context.injectMode', value),
|
|
3603
|
+
disabled,
|
|
3604
|
+
}),
|
|
3571
3605
|
),
|
|
3572
3606
|
h(
|
|
3573
3607
|
Section,
|