dsh-recall-rebuild 0.1.4 → 0.1.6
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/README.md +62 -4
- package/dist/commands.d.ts +43 -0
- package/dist/commands.js +177 -0
- package/dist/config.d.ts +116 -0
- package/dist/config.js +20 -0
- package/dist/consolidate.d.ts +32 -0
- package/dist/consolidate.js +144 -0
- package/dist/consolidated.d.ts +108 -0
- package/dist/consolidated.js +270 -0
- package/dist/index.d.ts +76 -0
- package/dist/index.js +50 -3
- package/dist/recall.d.ts +2 -1
- package/dist/recall.js +66 -1
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -36,6 +36,8 @@
|
|
|
36
36
|
- **与生态共存不错位**:注入消息 `source.kind='plugin:recall-rebuild'`,不会被 prime-memory 当作新用户消息再次捕获/蒸馏;`replace` 策略原位替换对方的原文召回,`append` 策略追加,不重复注入;
|
|
37
37
|
- **永不阻塞对话**:无记忆库/无模型路由/超时/重建失败,一律静默跳过本轮;
|
|
38
38
|
- **重建质量可观测**:每轮在 `~/.dsh/recall-rebuild/logs/recall-YYYY-MM-DD.log` 写一条 JSONL 审计日志,「原始检索碎片 ↔ 重建后片段」同屏对比 + 注入方式/耗时/跳过原因,附带 `stats.json` 统计——零额外注入、零 token 成本,自己判断重建效果;
|
|
39
|
+
- **睡眠巩固 + 联想扩散(长期记忆子系统)**:空闲时把累积的碎片「聚类 → LLM 抽象为稳定记忆 → 联想图扩散 → 低频遗忘降权」,巩固层条目在召回时优先注入、命中越用越稳、强关联主题顺带想起——更接近人脑的「夜间回放迁移到新皮层」;产出只存本插件目录,底层记忆库保持只读;
|
|
40
|
+
- **巩固层交互命令**:`/recall-rebuild list | now | edit <id> <内容> | forget <id>`——像管理自己的记忆一样查看长期记忆、立即触发一次巩固、修正记错的、主动忘掉不想留的(操作遵循同一套用户隔离视图);
|
|
39
41
|
- **零部署硬件成本**:不买显卡、不租 GPU,重建调用走宿主已有的 LLM 路由,每轮只消耗百级 token;
|
|
40
42
|
- **零额外运行时依赖**:用 Node 22+ 内置 `node:sqlite` 读库,安装即用。
|
|
41
43
|
|
|
@@ -82,6 +84,9 @@ flowchart LR
|
|
|
82
84
|
P --> Q["构造召回查询<br/>(会话末尾消息)"]
|
|
83
85
|
Q --> S[("记忆库<br/>prime(SQLite)/ dsh-memory(JSON)/ palace(Markdown)")]
|
|
84
86
|
S --> F["用户命名空间过滤<br/>(auto/strict/off)"]
|
|
87
|
+
S -. "碎片累积(pending)" .-> C["睡眠巩固(空闲异步)<br/>聚类 → LLM 抽象 → 联想 → 遗忘"]
|
|
88
|
+
C --> C2[("巩固层<br/>~/.dsh/recall-rebuild/consolidated")]
|
|
89
|
+
C2 -. "active 条目 + 联想扩散" .-> F
|
|
85
90
|
F --> R["LLM 重建式回忆<br/>(碎片 → 带语境的回忆片段)"]
|
|
86
91
|
R --> I["注入回忆片段<br/>source.kind = plugin:recall-rebuild"]
|
|
87
92
|
F --> N[("归属索引<br/>~/.dsh/recall-rebuild/namespaces")]
|
|
@@ -92,7 +97,7 @@ flowchart LR
|
|
|
92
97
|
R -. "失败/超时 → 静默跳过" .-> M
|
|
93
98
|
```
|
|
94
99
|
|
|
95
|
-
一句话流程:**提取用户 → 检索 → 用户隔离过滤 → 重建 → 注入**,而不是**检索 →
|
|
100
|
+
一句话流程:**提取用户 → 检索 → 用户隔离过滤 → 合并巩固层 → 重建 → 注入**,而不是**检索 → 注入**;碎片在空闲时「睡眠巩固」沉淀为稳定记忆,下次召回优先想起。
|
|
96
101
|
|
|
97
102
|
## 与现有插件的错开与共存
|
|
98
103
|
|
|
@@ -126,6 +131,53 @@ flowchart LR
|
|
|
126
131
|
| `observability.logDir` | `''` | 日志目录;空 = `<DSH_HOME>/recall-rebuild/logs` |
|
|
127
132
|
| `observability.includeFragments` | `true` | 日志是否记录原始检索碎片(与重建片段同屏对比);`false` 只记重建结果 |
|
|
128
133
|
| `observability.statsEnabled` | `true` | 是否写统计文件 `stats.json`(30s 节流) |
|
|
134
|
+
| `consolidate.enabled` | `true` | 睡眠巩固总开关 |
|
|
135
|
+
| `consolidate.dir` | `''` | 巩固层目录;空 = `<DSH_HOME>/recall-rebuild/consolidated` |
|
|
136
|
+
| `consolidate.minFragments` | `20` | 待巩固碎片累积多少条触发一次巩固 |
|
|
137
|
+
| `consolidate.minIntervalMs` | `21600000` | 距上次巩固最短间隔(6h) |
|
|
138
|
+
| `consolidate.checkIntervalMs` | `3600000` | 定时检查间隔(1h) |
|
|
139
|
+
| `consolidate.maxFragmentsPerRun` | `50` | 单次巩固最多处理碎片数 |
|
|
140
|
+
| `consolidate.clusterThreshold` | `0.25` | 聚类相似度阈值(同主题碎片 ≥ 阈值归为一簇) |
|
|
141
|
+
| `consolidate.maxCluster` | `8` | 单簇最多碎片数 |
|
|
142
|
+
| `consolidate.maxOutputChars` | `400` | 单条巩固输出字符上限 |
|
|
143
|
+
| `consolidate.temperature` | `0.4` | 巩固调用温度(低于重建,求稳) |
|
|
144
|
+
| `consolidate.maxTokens` | `1024` | 巩固调用输出 token 上限 |
|
|
145
|
+
| `consolidate.timeoutMs` | `20000` | 单簇巩固超时(离线任务可放宽) |
|
|
146
|
+
| `consolidate.confidenceThreshold` | `0.4` | 遗忘阈值:置信度低于它且长期未命中 → dormant(召回降权) |
|
|
147
|
+
| `consolidate.dormantDays` | `30` | 多少天未命中(且低置信)进入 dormant |
|
|
148
|
+
| `commands.enabled` | `true` | 巩固层交互命令总开关 |
|
|
149
|
+
| `commands.name` | `recall-rebuild` | 注册的命令名(不含前导 `/`);与其它插件冲突时改名 |
|
|
150
|
+
|
|
151
|
+
## 长期记忆子系统:睡眠巩固与联想扩散
|
|
152
|
+
|
|
153
|
+
类比人脑:**底层记忆插件 = 海马体**(即时捕获碎片),**本插件的巩固层 = 新皮层**(把碎片沉淀为稳定记忆)。这层只存在本插件自己的目录(`~/.dsh/recall-rebuild/consolidated/`),底层记忆库始终保持只读。
|
|
154
|
+
|
|
155
|
+
**一次巩固(空闲异步,不阻塞对话)做什么**:
|
|
156
|
+
|
|
157
|
+
1. **累积**:每轮检索命中的碎片进入 `pending.json`(去重、限量);
|
|
158
|
+
2. **聚类**:纯本地按 2-gram 相似度把同主题碎片分簇(无需 LLM、零成本);
|
|
159
|
+
3. **LLM 抽象**:每簇交给宿主 LLM,提炼为 1-3 条稳定的长期记忆(`stable-fact / pattern / preference / relationship / mood`),忽略一次性噪音;
|
|
160
|
+
4. **联想扩散**:本轮产出的条目两两建立关联边(`links.json` 权重累加)——召回命中一条时,强关联主题顺带想起;
|
|
161
|
+
5. **遗忘(只读侧)**:低置信 + 30 天未命中的条目进入 `dormant`(召回降权,不删除、不写底层库);
|
|
162
|
+
6. **越用越稳**:每次命中 `touchCount+1`,高置信条目优先注入。
|
|
163
|
+
|
|
164
|
+
触发:启动后空闲 10s 查一次,之后每 `checkIntervalMs` 查一次;pending 达标且距上次巩固超 `minIntervalMs` 才真正执行;失败保留 pending 下次再试。
|
|
165
|
+
|
|
166
|
+
**加固了这一层的定位**:它不替代底层记忆插件,也不重复存储——底层负责「记住」,巩固层负责「把记住的东西变成稳定的自己」。
|
|
167
|
+
|
|
168
|
+
## 管理长期记忆(命令)
|
|
169
|
+
|
|
170
|
+
像管理自己的记忆一样管理巩固层(命令在支持 `/` 命令的 DSH 界面输入;宿主没有命令服务时自动跳过,不影响插件主体):
|
|
171
|
+
|
|
172
|
+
| 命令 | 作用 |
|
|
173
|
+
| --- | --- |
|
|
174
|
+
| `/recall-rebuild list [--all]` | 查看长期记忆:类型 / 置信度 / 命中次数 / 更新时间;dormant(已降权)单独标出。默认只显示当前用户的记忆 + 共享记忆,`--all` 查看全部(含其它 IM 用户) |
|
|
175
|
+
| `/recall-rebuild now` | 立即触发一次睡眠巩固(绕过最短间隔;pending 为空时提示) |
|
|
176
|
+
| `/recall-rebuild edit <id> <新内容>` | 修正一条记忆的内容(人也会记错、改口) |
|
|
177
|
+
| `/recall-rebuild forget <id>` | 主动删除一条记忆及其联想边(与被动遗忘不同,这是显式操作,不写底层库) |
|
|
178
|
+
| `/recall-rebuild help` | 显示用法 |
|
|
179
|
+
|
|
180
|
+
命令的可见范围与召回隔离是同一套规则:当前会话能识别 IM 用户时,只能查看/修改「该用户 + 无主共享」的记忆;桌面会话(识别不到用户)或 `--all` 时不受限。命令名冲突时用 `commands.name` 改名。
|
|
129
181
|
|
|
130
182
|
## 观测:怎么判断重建是否真的更好
|
|
131
183
|
|
|
@@ -143,7 +195,9 @@ flowchart LR
|
|
|
143
195
|
- [ ] 更多记忆源 adapter(`dsh-memory-vault`、`dsh-auto-memory`、`dsh-memory-gate` 等变体);
|
|
144
196
|
- [x] IM 用户级命名空间隔离(跨 QQ/微信的同一人记忆共享)—— v0.1.3 已实现;
|
|
145
197
|
- [x] 重建质量可观测(每轮 JSONL 日志 + stats)—— v0.1.4 已实现;
|
|
146
|
-
- [
|
|
198
|
+
- [x] 睡眠巩固 / 联想扩散(长期记忆子系统:聚类 → LLM 抽象 → 联想 → 遗忘)—— v0.1.5 已实现;
|
|
199
|
+
- [x] 巩固层交互命令(list / now / edit / forget,管理长期记忆)—— v0.1.6 已实现;
|
|
200
|
+
- [ ] 巩固层条目编辑/手动触发、更多记忆源 adapter(欢迎提 issue)。
|
|
147
201
|
|
|
148
202
|
## 局限(如实声明)
|
|
149
203
|
|
|
@@ -151,9 +205,11 @@ flowchart LR
|
|
|
151
205
|
2. **用户隔离是观察式启发式,非底层强隔离**:底层记忆库(prime 等)没有 IM 用户字段,本插件靠「谁在会话中命中过这条记忆,它就归谁」建立归属。因此:`auto` 模式防得住「已明确归属他人」的记忆,防不住「从未被命中过的无主记忆」(它们默认可见,命中后归位);`strict` 模式从零记忆起步,聊过的话题才开始归位。需要强隐私隔离且不介意冷启动时用 `strict`。
|
|
152
206
|
3. **用户识别依赖桥接插件约定**:优先解析 `<dsh_im_source>` JSON(senderId/chatId/threadId/botId),兜底常见字段(senderId/userId/openid/fromUser);不同桥接字段不同时用 `user.sourceTagPattern` 覆盖。识别不到用户(桌面会话)时不做隔离。
|
|
153
207
|
4. **幻觉受控但非零**:重建 prompt 明确禁止编造碎片外事实,但 LLM 仍有漂移概率;注入标注记忆依据 id 便于审计。需要强事实的场景可关掉重建(`rebuild.enabled=false`)。
|
|
154
|
-
5. **token 消耗**:每轮召回命中即产生一次重建调用(通常百级 token)
|
|
208
|
+
5. **token 消耗**:每轮召回命中即产生一次重建调用(通常百级 token),由宿主模型路由计费;巩固只在空闲且碎片达标时发生,每次几十~几百 token。
|
|
155
209
|
6. **日志零成本但非自动诊断**:日志只记录事实(碎片/重建/耗时/跳过原因),不做好坏判定;用户可对比判断,或切换 `inject.strategy=append` 运行时对比。
|
|
156
|
-
7.
|
|
210
|
+
7. **巩固层是启发式蒸馏,非底层改写**:聚类基于 2-gram 相似度(可能把近义不同词的两条碎片分到不同簇);LLM 抽象有轻幻觉风险(已在 prompt 禁止编造);dormant 只是召回降权,不会删底层库、也不会在本插件内物理删除。
|
|
211
|
+
8. **未覆盖**:LoRA 权重内化等权重级记忆不在本插件范围(见 Roadmap)。
|
|
212
|
+
9. **交互命令依赖宿主命令服务**:支持 `/` 命令的界面(桌面/Web UI)都有;无命令服务的组合(如 headless)下命令静默不注册,插件其余功能不受影响。
|
|
157
213
|
|
|
158
214
|
## 开发与验证
|
|
159
215
|
|
|
@@ -183,6 +239,8 @@ This plugin upgrades the **recall/presentation layer**:
|
|
|
183
239
|
- Injects via `agent/pre-step` with `source.kind='plugin:recall-rebuild'`, so it is never re-captured by the underlying memory plugin; `replace` strategy swaps out the other plugin's raw-text recall in place, `append` adds alongside;
|
|
184
240
|
- **Never blocks a conversation**: missing store, missing model route, timeout or rebuild failure all silently skip the step;
|
|
185
241
|
- **Observable rebuild quality**: every round appends one JSONL audit line to `~/.dsh/recall-rebuild/logs/recall-YYYY-MM-DD.log` — raw fragments vs rebuilt snippet side by side, injection mode / latency / skip reason, plus a throttled `stats.json` — zero extra injection, zero token cost, so you can judge for yourself whether rebuilding beats raw recall;
|
|
242
|
+
- **Sleep consolidation + associative spreading (long-term memory layer)**: while idle, accumulated fragments are clustered (local 2-gram similarity), LLM-distilled into stable memories (`stable-fact`/`pattern`/`preference`/`relationship`/`mood`), linked in a spreading-activation graph, and low-confidence long-unused entries decay to `dormant` (recall down-weighting, never deleted, never written to the base store). Consolidated entries are recalled first, get more stable the more they are hit, and strong links make related topics surface too — closer to how the brain consolidates daytime experience overnight. Everything lives under `<DSH_HOME>/recall-rebuild/consolidated/`;
|
|
243
|
+
- **Manage your long-term memories with slash commands**: `/recall-rebuild list [--all]` (view consolidated memories with type/confidence/hit count), `now` (trigger a consolidation immediately), `edit <id> <text>` (fix a misremembered entry) and `forget <id>` (explicitly delete an entry and its links). The command view follows the same per-user isolation rules; it silently skips registration when the host has no command service;
|
|
186
244
|
- **Zero infra cost**: no GPU/VM — rebuild calls go through the host's existing LLM routing, ~hundreds of tokens per hit; uses only Node's built-in `node:sqlite`.
|
|
187
245
|
|
|
188
246
|
**Who it's for**: DSH desktop-pet / virtual-character / companion users who want the bot to "remember like a person" rather than "quote a file", including characters bridged to QQ/WeChat.
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 巩固层交互命令(/recall-rebuild ...)。
|
|
3
|
+
*
|
|
4
|
+
* 让用户能像「管理自己的记忆」一样管理巩固层:
|
|
5
|
+
* - list —— 查看长期记忆(受 IM 用户隔离约束,--all 显示全部);
|
|
6
|
+
* - now —— 立即触发一次睡眠巩固(绕过最短间隔,离线任务语义);
|
|
7
|
+
* - edit <id> <新内容> —— 修正一条记忆的内容(人也会记错、改口);
|
|
8
|
+
* - forget <id> —— 主动删除一条记忆(与被动遗忘不同,这是显式操作);
|
|
9
|
+
* - help —— 用法。
|
|
10
|
+
*
|
|
11
|
+
* 注册方式:DSH 官方 `ctx.commands.register`(inject 可选 'commands?',
|
|
12
|
+
* 无 commands 服务时静默跳过,插件主体功能不受影响)。
|
|
13
|
+
*/
|
|
14
|
+
import type { Context } from '@deepseek-ai/cordis';
|
|
15
|
+
import type { RecallRebuildConfig } from './config.js';
|
|
16
|
+
import type { LoggerLike, MemoryStore } from './store.js';
|
|
17
|
+
import type { ConsolidatedMemory, ConsolidatedStore } from './consolidated.js';
|
|
18
|
+
export type CommandSub = 'now' | 'list' | 'edit' | 'forget' | 'help' | 'unknown';
|
|
19
|
+
/** 解析后的命令参数(纯函数,可测)。 */
|
|
20
|
+
export interface CommandArgs {
|
|
21
|
+
sub: CommandSub;
|
|
22
|
+
/** 子命令之后的剩余参数(token 化)。 */
|
|
23
|
+
args: string[];
|
|
24
|
+
/** 是否带 --all(仅 list 用)。 */
|
|
25
|
+
all: boolean;
|
|
26
|
+
}
|
|
27
|
+
/** 纯函数:解析 /recall-rebuild <sub> 之后的输入。 */
|
|
28
|
+
export declare function parseCommandLine(rawInput: string): CommandArgs;
|
|
29
|
+
/**
|
|
30
|
+
* 可见性过滤(与召回隔离同一套规则,但命令是管理视图):
|
|
31
|
+
* - userKey 为 null(桌面/识别不到)或 isolation=off → 全部可见;
|
|
32
|
+
* - 否则只显示「当前用户 + 无主(null)」的条目;
|
|
33
|
+
* - all=true 时忽略隔离显示全部(带归属标注由 formatList 处理)。
|
|
34
|
+
*/
|
|
35
|
+
export declare function visibleMemories(consolidated: ConsolidatedStore, userKey: string | null, isolation: 'off' | 'auto' | 'strict', all: boolean): ConsolidatedMemory[];
|
|
36
|
+
/** 纯函数:把条目列表格式化为可读文本(命令输出)。 */
|
|
37
|
+
export declare function formatMemoryList(mems: ConsolidatedMemory[], opts: {
|
|
38
|
+
userKey: string | null;
|
|
39
|
+
all: boolean;
|
|
40
|
+
now: number;
|
|
41
|
+
}): string;
|
|
42
|
+
/** 注册巩固层交互命令;宿主没有 commands 服务时静默跳过。 */
|
|
43
|
+
export declare function registerRecallRebuildCommands(ctx: Context, store: MemoryStore, consolidated: ConsolidatedStore, cfg: RecallRebuildConfig, logger: LoggerLike): void;
|
package/dist/commands.js
ADDED
|
@@ -0,0 +1,177 @@
|
|
|
1
|
+
import { runConsolidation } from './consolidate.js';
|
|
2
|
+
import { extractUserKey } from './namespace.js';
|
|
3
|
+
/** 纯函数:解析 /recall-rebuild <sub> 之后的输入。 */
|
|
4
|
+
export function parseCommandLine(rawInput) {
|
|
5
|
+
const trimmed = (rawInput ?? '').trim();
|
|
6
|
+
if (!trimmed)
|
|
7
|
+
return { sub: 'help', args: [], all: false };
|
|
8
|
+
const parts = trimmed.split(/\s+/);
|
|
9
|
+
const head = (parts[0] ?? '').toLowerCase();
|
|
10
|
+
const known = ['now', 'list', 'edit', 'forget', 'help'];
|
|
11
|
+
const sub = known.includes(head) ? head : 'unknown';
|
|
12
|
+
const rest = parts.slice(1);
|
|
13
|
+
return { sub, args: rest, all: rest.includes('--all') };
|
|
14
|
+
}
|
|
15
|
+
/**
|
|
16
|
+
* 可见性过滤(与召回隔离同一套规则,但命令是管理视图):
|
|
17
|
+
* - userKey 为 null(桌面/识别不到)或 isolation=off → 全部可见;
|
|
18
|
+
* - 否则只显示「当前用户 + 无主(null)」的条目;
|
|
19
|
+
* - all=true 时忽略隔离显示全部(带归属标注由 formatList 处理)。
|
|
20
|
+
*/
|
|
21
|
+
export function visibleMemories(consolidated, userKey, isolation, all) {
|
|
22
|
+
const allMems = consolidated.list();
|
|
23
|
+
if (all || userKey === null || isolation === 'off')
|
|
24
|
+
return allMems;
|
|
25
|
+
return allMems.filter((m) => m.userKey === null || m.userKey === userKey);
|
|
26
|
+
}
|
|
27
|
+
const TYPE_LABEL = {
|
|
28
|
+
'stable-fact': '事实',
|
|
29
|
+
pattern: '规律',
|
|
30
|
+
preference: '偏好',
|
|
31
|
+
relationship: '关系',
|
|
32
|
+
mood: '情绪',
|
|
33
|
+
};
|
|
34
|
+
/** 纯函数:把条目列表格式化为可读文本(命令输出)。 */
|
|
35
|
+
export function formatMemoryList(mems, opts) {
|
|
36
|
+
const active = mems
|
|
37
|
+
.filter((m) => m.status === 'active')
|
|
38
|
+
.sort((a, b) => b.confidence - a.confidence || b.touchCount - a.touchCount);
|
|
39
|
+
const dormant = mems.filter((m) => m.status === 'dormant');
|
|
40
|
+
const lines = [];
|
|
41
|
+
lines.push(`长期记忆(巩固层): active ${active.length} / dormant ${dormant.length}`);
|
|
42
|
+
for (const m of active) {
|
|
43
|
+
const owner = m.userKey ? ` [${m.userKey}]` : '';
|
|
44
|
+
lines.push(`• ${m.id}${owner} [${TYPE_LABEL[m.type]}] 置信${(m.confidence * 100).toFixed(0)}% · 命中${m.touchCount} · 更新${new Date(m.updatedAt).toISOString().slice(0, 10)}`);
|
|
45
|
+
lines.push(` ${m.content}`);
|
|
46
|
+
}
|
|
47
|
+
for (const m of dormant) {
|
|
48
|
+
const owner = m.userKey ? ` [${m.userKey}]` : '';
|
|
49
|
+
lines.push(`[dormant 已降权] ${m.id}${owner} [${TYPE_LABEL[m.type]}] ${m.content}`);
|
|
50
|
+
}
|
|
51
|
+
if (mems.length === 0)
|
|
52
|
+
lines.push('(巩固层还没有条目——多聊几轮后,碎片会在空闲时沉淀为长期记忆)');
|
|
53
|
+
if (!opts.all && opts.userKey !== null) {
|
|
54
|
+
lines.push(`(隔离视图:仅显示当前用户${opts.userKey}与共享记忆;--all 查看全部)`);
|
|
55
|
+
}
|
|
56
|
+
return lines.join('\n');
|
|
57
|
+
}
|
|
58
|
+
/** 从 agent 会话最近消息提取文本(用于识别当前 IM 用户;失败返回空数组)。 */
|
|
59
|
+
function recentUserTexts(agent, n) {
|
|
60
|
+
const events = agent?.session?.events;
|
|
61
|
+
if (!Array.isArray(events))
|
|
62
|
+
return [];
|
|
63
|
+
const out = [];
|
|
64
|
+
for (let i = events.length - 1; i >= 0 && out.length < n; i--) {
|
|
65
|
+
const ev = events[i];
|
|
66
|
+
if (!ev || ev.type !== 'user/message')
|
|
67
|
+
continue;
|
|
68
|
+
const blocks = ev.data?.content;
|
|
69
|
+
if (!Array.isArray(blocks))
|
|
70
|
+
continue;
|
|
71
|
+
const text = blocks
|
|
72
|
+
.filter((b) => {
|
|
73
|
+
const blk = b;
|
|
74
|
+
return !!blk && blk.type === 'text' && typeof blk.text === 'string';
|
|
75
|
+
})
|
|
76
|
+
.map((b) => b.text)
|
|
77
|
+
.join(' ');
|
|
78
|
+
if (text)
|
|
79
|
+
out.push(text);
|
|
80
|
+
}
|
|
81
|
+
return out;
|
|
82
|
+
}
|
|
83
|
+
/** 注册巩固层交互命令;宿主没有 commands 服务时静默跳过。 */
|
|
84
|
+
export function registerRecallRebuildCommands(ctx, store, consolidated, cfg, logger) {
|
|
85
|
+
if (!cfg.commands.enabled)
|
|
86
|
+
return;
|
|
87
|
+
const runtime = ctx.commands;
|
|
88
|
+
if (!runtime?.register)
|
|
89
|
+
return;
|
|
90
|
+
const commandName = cfg.commands.name;
|
|
91
|
+
const disposer = runtime.register({
|
|
92
|
+
name: commandName,
|
|
93
|
+
description: '管理长期记忆(巩固层): list / now / edit / forget / help',
|
|
94
|
+
input: { hint: 'list [--all] | now | edit <id> <新内容> | forget <id> | help' },
|
|
95
|
+
handler: async (invocation) => {
|
|
96
|
+
try {
|
|
97
|
+
// 当前会话 IM 用户:从最近 user 消息提取;桌面/识别不到 → null
|
|
98
|
+
const userKey = extractUserKey(recentUserTexts(invocation.agent, 8), cfg.user.sourceTagPattern) ?? null;
|
|
99
|
+
const { sub, args, all } = parseCommandLine(invocation.rawInput);
|
|
100
|
+
switch (sub) {
|
|
101
|
+
case 'now': {
|
|
102
|
+
if (!cfg.consolidate.enabled) {
|
|
103
|
+
return { kind: 'error', text: '巩固已关闭(consolidate.enabled=false)。' };
|
|
104
|
+
}
|
|
105
|
+
const pending = consolidated.pending().length;
|
|
106
|
+
if (pending === 0) {
|
|
107
|
+
return { kind: 'success', text: '没有待巩固碎片(pending 为空)——多聊几轮后碎片会自动累积。' };
|
|
108
|
+
}
|
|
109
|
+
const result = await runConsolidation(ctx, store, consolidated, cfg.consolidate, logger);
|
|
110
|
+
return {
|
|
111
|
+
kind: 'success',
|
|
112
|
+
text: `睡眠巩固已执行:处理 pending ${result.pending} 条,` +
|
|
113
|
+
`产出 ${result.entries} 条新记忆,${result.decayed} 条进入 dormant。`,
|
|
114
|
+
};
|
|
115
|
+
}
|
|
116
|
+
case 'list': {
|
|
117
|
+
const mems = visibleMemories(consolidated, userKey, cfg.user.isolation, all);
|
|
118
|
+
return { kind: 'success', text: formatMemoryList(mems, { userKey, all, now: Date.now() }) };
|
|
119
|
+
}
|
|
120
|
+
case 'edit': {
|
|
121
|
+
const id = args[0];
|
|
122
|
+
const content = args.slice(1).join(' ').trim();
|
|
123
|
+
if (!id || !content) {
|
|
124
|
+
return { kind: 'error', text: `用法: /${commandName} edit <id> <新内容>` };
|
|
125
|
+
}
|
|
126
|
+
const m = consolidated.get(id);
|
|
127
|
+
if (!m)
|
|
128
|
+
return { kind: 'error', text: `找不到记忆 ${id}。` };
|
|
129
|
+
const visible = visibleMemories(consolidated, userKey, cfg.user.isolation, false).some((x) => x.id === id);
|
|
130
|
+
if (!visible)
|
|
131
|
+
return { kind: 'error', text: `记忆 ${id} 不在当前用户的可见范围内。` };
|
|
132
|
+
consolidated.upsert({
|
|
133
|
+
...m,
|
|
134
|
+
content: content.slice(0, cfg.consolidate.maxOutputChars),
|
|
135
|
+
updatedAt: Date.now(),
|
|
136
|
+
});
|
|
137
|
+
return { kind: 'success', text: `已更新记忆 ${id}。` };
|
|
138
|
+
}
|
|
139
|
+
case 'forget': {
|
|
140
|
+
const id = args[0];
|
|
141
|
+
if (!id)
|
|
142
|
+
return { kind: 'error', text: `用法: /${commandName} forget <id>` };
|
|
143
|
+
const m = consolidated.get(id);
|
|
144
|
+
if (!m)
|
|
145
|
+
return { kind: 'error', text: `找不到记忆 ${id}。` };
|
|
146
|
+
const visible = visibleMemories(consolidated, userKey, cfg.user.isolation, false).some((x) => x.id === id);
|
|
147
|
+
if (!visible)
|
|
148
|
+
return { kind: 'error', text: `记忆 ${id} 不在当前用户的可见范围内。` };
|
|
149
|
+
consolidated.remove(id);
|
|
150
|
+
return { kind: 'success', text: `已删除记忆 ${id}(含其联想边)。` };
|
|
151
|
+
}
|
|
152
|
+
case 'help':
|
|
153
|
+
return {
|
|
154
|
+
kind: 'success',
|
|
155
|
+
text: `/${commandName} 用法:\n` +
|
|
156
|
+
` /${commandName} list [--all] 查看长期记忆(默认仅当前用户视角)\n` +
|
|
157
|
+
` /${commandName} now 立即触发一次睡眠巩固\n` +
|
|
158
|
+
` /${commandName} edit <id> <内容> 修正一条记忆\n` +
|
|
159
|
+
` /${commandName} forget <id> 主动删除一条记忆\n` +
|
|
160
|
+
` /${commandName} help 显示本帮助`,
|
|
161
|
+
};
|
|
162
|
+
default:
|
|
163
|
+
return {
|
|
164
|
+
kind: 'error',
|
|
165
|
+
text: `未知子命令 "${args.length > 0 ? args[0] : ''}"。输入 /${commandName} help 查看用法。`,
|
|
166
|
+
};
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
catch (err) {
|
|
170
|
+
logger.warn(`[recall-rebuild] 命令处理失败: ${err instanceof Error ? err.message : String(err)}`);
|
|
171
|
+
return { kind: 'error', text: '命令处理失败,请查看日志。' };
|
|
172
|
+
}
|
|
173
|
+
},
|
|
174
|
+
});
|
|
175
|
+
ctx.effect(() => disposer, `recall-rebuild: command`);
|
|
176
|
+
logger.info(`[recall-rebuild] 已注册命令 /${commandName}(list / now / edit / forget)`);
|
|
177
|
+
}
|
package/dist/config.d.ts
CHANGED
|
@@ -67,6 +67,44 @@ export interface ObservabilityOptions {
|
|
|
67
67
|
/** 是否写统计文件 stats.json(30s 节流)。 */
|
|
68
68
|
statsEnabled: boolean;
|
|
69
69
|
}
|
|
70
|
+
/** 巩固层交互命令选项(/recall-rebuild list | now | edit | forget)。 */
|
|
71
|
+
export interface CommandsOptions {
|
|
72
|
+
/** 命令总开关;false = 不注册任何命令。 */
|
|
73
|
+
enabled: boolean;
|
|
74
|
+
/** 注册的命令名(不含前导 /);与其它插件冲突时改名。 */
|
|
75
|
+
name: string;
|
|
76
|
+
}
|
|
77
|
+
/** 睡眠巩固(长期记忆子系统)选项。 */
|
|
78
|
+
export interface ConsolidateOptions {
|
|
79
|
+
/** 巩固总开关。 */
|
|
80
|
+
enabled: boolean;
|
|
81
|
+
/** 巩固层目录;空 = <DSH_HOME>/recall-rebuild/consolidated。 */
|
|
82
|
+
dir: string;
|
|
83
|
+
/** 待巩固碎片累积达到多少条才触发一次巩固。 */
|
|
84
|
+
minFragments: number;
|
|
85
|
+
/** 距上次巩固的最短间隔(ms);防止巩固过于频繁。 */
|
|
86
|
+
minIntervalMs: number;
|
|
87
|
+
/** 定时检查间隔(ms)。 */
|
|
88
|
+
checkIntervalMs: number;
|
|
89
|
+
/** 单次巩固最多处理的碎片条数。 */
|
|
90
|
+
maxFragmentsPerRun: number;
|
|
91
|
+
/** 聚类相似度阈值(0-1);同主题碎片 ≥ 阈值归为一簇。 */
|
|
92
|
+
clusterThreshold: number;
|
|
93
|
+
/** 单簇最多碎片条数。 */
|
|
94
|
+
maxCluster: number;
|
|
95
|
+
/** 单条巩固输出字符上限。 */
|
|
96
|
+
maxOutputChars: number;
|
|
97
|
+
/** 巩固调用温度(巩固要稳,默认低于重建)。 */
|
|
98
|
+
temperature: number;
|
|
99
|
+
/** 巩固调用输出 token 上限。 */
|
|
100
|
+
maxTokens: number;
|
|
101
|
+
/** 单簇巩固超时(ms);离线任务可放宽。 */
|
|
102
|
+
timeoutMs: number;
|
|
103
|
+
/** 遗忘阈值:置信度低于它且长期未命中 → dormant(召回降权)。 */
|
|
104
|
+
confidenceThreshold: number;
|
|
105
|
+
/** 多少天未命中(且低置信)进入 dormant。 */
|
|
106
|
+
dormantDays: number;
|
|
107
|
+
}
|
|
70
108
|
export interface RecallRebuildConfig {
|
|
71
109
|
/** 总开关。 */
|
|
72
110
|
enabled: boolean;
|
|
@@ -85,6 +123,8 @@ export interface RecallRebuildConfig {
|
|
|
85
123
|
query: QueryOptions;
|
|
86
124
|
user: UserIsolationOptions;
|
|
87
125
|
observability: ObservabilityOptions;
|
|
126
|
+
consolidate: ConsolidateOptions;
|
|
127
|
+
commands: CommandsOptions;
|
|
88
128
|
}
|
|
89
129
|
export declare const recallRebuildSchema: Schema<Schemastery.ObjectS<NoInfer<{
|
|
90
130
|
enabled: Schema<boolean, boolean, "defined">;
|
|
@@ -145,6 +185,44 @@ export declare const recallRebuildSchema: Schema<Schemastery.ObjectS<NoInfer<{
|
|
|
145
185
|
includeFragments: Schema<boolean, boolean, "defined">;
|
|
146
186
|
statsEnabled: Schema<boolean, boolean, "defined">;
|
|
147
187
|
}>>, "defined">;
|
|
188
|
+
consolidate: Schema<Schemastery.ObjectS<NoInfer<{
|
|
189
|
+
enabled: Schema<boolean, boolean, "defined">;
|
|
190
|
+
dir: Schema<string, string, "defined">;
|
|
191
|
+
minFragments: Schema<number, number, "defined">;
|
|
192
|
+
minIntervalMs: Schema<number, number, "defined">;
|
|
193
|
+
checkIntervalMs: Schema<number, number, "defined">;
|
|
194
|
+
maxFragmentsPerRun: Schema<number, number, "defined">;
|
|
195
|
+
clusterThreshold: Schema<number, number, "defined">;
|
|
196
|
+
maxCluster: Schema<number, number, "defined">;
|
|
197
|
+
maxOutputChars: Schema<number, number, "defined">;
|
|
198
|
+
temperature: Schema<number, number, "defined">;
|
|
199
|
+
maxTokens: Schema<number, number, "defined">;
|
|
200
|
+
timeoutMs: Schema<number, number, "defined">;
|
|
201
|
+
confidenceThreshold: Schema<number, number, "defined">;
|
|
202
|
+
dormantDays: Schema<number, number, "defined">;
|
|
203
|
+
}>>, Schemastery.ObjectT<NoInfer<{
|
|
204
|
+
enabled: Schema<boolean, boolean, "defined">;
|
|
205
|
+
dir: Schema<string, string, "defined">;
|
|
206
|
+
minFragments: Schema<number, number, "defined">;
|
|
207
|
+
minIntervalMs: Schema<number, number, "defined">;
|
|
208
|
+
checkIntervalMs: Schema<number, number, "defined">;
|
|
209
|
+
maxFragmentsPerRun: Schema<number, number, "defined">;
|
|
210
|
+
clusterThreshold: Schema<number, number, "defined">;
|
|
211
|
+
maxCluster: Schema<number, number, "defined">;
|
|
212
|
+
maxOutputChars: Schema<number, number, "defined">;
|
|
213
|
+
temperature: Schema<number, number, "defined">;
|
|
214
|
+
maxTokens: Schema<number, number, "defined">;
|
|
215
|
+
timeoutMs: Schema<number, number, "defined">;
|
|
216
|
+
confidenceThreshold: Schema<number, number, "defined">;
|
|
217
|
+
dormantDays: Schema<number, number, "defined">;
|
|
218
|
+
}>>, "defined">;
|
|
219
|
+
commands: Schema<Schemastery.ObjectS<NoInfer<{
|
|
220
|
+
enabled: Schema<boolean, boolean, "defined">;
|
|
221
|
+
name: Schema<string, string, "defined">;
|
|
222
|
+
}>>, Schemastery.ObjectT<NoInfer<{
|
|
223
|
+
enabled: Schema<boolean, boolean, "defined">;
|
|
224
|
+
name: Schema<string, string, "defined">;
|
|
225
|
+
}>>, "defined">;
|
|
148
226
|
}>>, Schemastery.ObjectT<NoInfer<{
|
|
149
227
|
enabled: Schema<boolean, boolean, "defined">;
|
|
150
228
|
dataDir: Schema<string, string, "defined">;
|
|
@@ -204,4 +282,42 @@ export declare const recallRebuildSchema: Schema<Schemastery.ObjectS<NoInfer<{
|
|
|
204
282
|
includeFragments: Schema<boolean, boolean, "defined">;
|
|
205
283
|
statsEnabled: Schema<boolean, boolean, "defined">;
|
|
206
284
|
}>>, "defined">;
|
|
285
|
+
consolidate: Schema<Schemastery.ObjectS<NoInfer<{
|
|
286
|
+
enabled: Schema<boolean, boolean, "defined">;
|
|
287
|
+
dir: Schema<string, string, "defined">;
|
|
288
|
+
minFragments: Schema<number, number, "defined">;
|
|
289
|
+
minIntervalMs: Schema<number, number, "defined">;
|
|
290
|
+
checkIntervalMs: Schema<number, number, "defined">;
|
|
291
|
+
maxFragmentsPerRun: Schema<number, number, "defined">;
|
|
292
|
+
clusterThreshold: Schema<number, number, "defined">;
|
|
293
|
+
maxCluster: Schema<number, number, "defined">;
|
|
294
|
+
maxOutputChars: Schema<number, number, "defined">;
|
|
295
|
+
temperature: Schema<number, number, "defined">;
|
|
296
|
+
maxTokens: Schema<number, number, "defined">;
|
|
297
|
+
timeoutMs: Schema<number, number, "defined">;
|
|
298
|
+
confidenceThreshold: Schema<number, number, "defined">;
|
|
299
|
+
dormantDays: Schema<number, number, "defined">;
|
|
300
|
+
}>>, Schemastery.ObjectT<NoInfer<{
|
|
301
|
+
enabled: Schema<boolean, boolean, "defined">;
|
|
302
|
+
dir: Schema<string, string, "defined">;
|
|
303
|
+
minFragments: Schema<number, number, "defined">;
|
|
304
|
+
minIntervalMs: Schema<number, number, "defined">;
|
|
305
|
+
checkIntervalMs: Schema<number, number, "defined">;
|
|
306
|
+
maxFragmentsPerRun: Schema<number, number, "defined">;
|
|
307
|
+
clusterThreshold: Schema<number, number, "defined">;
|
|
308
|
+
maxCluster: Schema<number, number, "defined">;
|
|
309
|
+
maxOutputChars: Schema<number, number, "defined">;
|
|
310
|
+
temperature: Schema<number, number, "defined">;
|
|
311
|
+
maxTokens: Schema<number, number, "defined">;
|
|
312
|
+
timeoutMs: Schema<number, number, "defined">;
|
|
313
|
+
confidenceThreshold: Schema<number, number, "defined">;
|
|
314
|
+
dormantDays: Schema<number, number, "defined">;
|
|
315
|
+
}>>, "defined">;
|
|
316
|
+
commands: Schema<Schemastery.ObjectS<NoInfer<{
|
|
317
|
+
enabled: Schema<boolean, boolean, "defined">;
|
|
318
|
+
name: Schema<string, string, "defined">;
|
|
319
|
+
}>>, Schemastery.ObjectT<NoInfer<{
|
|
320
|
+
enabled: Schema<boolean, boolean, "defined">;
|
|
321
|
+
name: Schema<string, string, "defined">;
|
|
322
|
+
}>>, "defined">;
|
|
207
323
|
}>>, "defined">;
|
package/dist/config.js
CHANGED
|
@@ -40,4 +40,24 @@ export const recallRebuildSchema = Schema.object({
|
|
|
40
40
|
includeFragments: Schema.boolean().default(true),
|
|
41
41
|
statsEnabled: Schema.boolean().default(true),
|
|
42
42
|
}).default({}),
|
|
43
|
+
consolidate: Schema.object({
|
|
44
|
+
enabled: Schema.boolean().default(true),
|
|
45
|
+
dir: Schema.string().default(''),
|
|
46
|
+
minFragments: Schema.number().min(5).max(200).default(20),
|
|
47
|
+
minIntervalMs: Schema.number().min(60000).max(86400000 * 7).default(21600000),
|
|
48
|
+
checkIntervalMs: Schema.number().min(60000).max(86400000).default(3600000),
|
|
49
|
+
maxFragmentsPerRun: Schema.number().min(10).max(200).default(50),
|
|
50
|
+
clusterThreshold: Schema.number().min(0.05).max(0.9).default(0.25),
|
|
51
|
+
maxCluster: Schema.number().min(2).max(20).default(8),
|
|
52
|
+
maxOutputChars: Schema.number().min(40).max(2000).default(400),
|
|
53
|
+
temperature: Schema.number().min(0).max(1.5).default(0.4),
|
|
54
|
+
maxTokens: Schema.number().min(64).max(4096).default(1024),
|
|
55
|
+
timeoutMs: Schema.number().min(1000).max(120000).default(20000),
|
|
56
|
+
confidenceThreshold: Schema.number().min(0.1).max(0.9).default(0.4),
|
|
57
|
+
dormantDays: Schema.number().min(3).max(365).default(30),
|
|
58
|
+
}).default({}),
|
|
59
|
+
commands: Schema.object({
|
|
60
|
+
enabled: Schema.boolean().default(true),
|
|
61
|
+
name: Schema.string().default('recall-rebuild'),
|
|
62
|
+
}).default({}),
|
|
43
63
|
}).default({});
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 睡眠巩固引擎:把累积的待巩固碎片「聚类 → LLM 抽象 → 联想扩散 → 遗忘降权」。
|
|
3
|
+
*
|
|
4
|
+
* 触发与调度(index.ts 注册):
|
|
5
|
+
* - 定时检查(checkIntervalMs)+ pending 达标(minFragments)且距上次巩固超过
|
|
6
|
+
* minIntervalMs 时才真正执行;
|
|
7
|
+
* - 纯异步、绝不阻塞对话:失败(无模型路由/超时/解析失败)保留 pending 下次再试。
|
|
8
|
+
*
|
|
9
|
+
* 产出只写自己的巩固层目录(consolidated/),底层记忆库保持只读。
|
|
10
|
+
*/
|
|
11
|
+
import type { Context } from '@deepseek-ai/cordis';
|
|
12
|
+
import type { ConsolidateOptions } from './config.js';
|
|
13
|
+
import type { LoggerLike, MemoryStore } from './store.js';
|
|
14
|
+
import { type ConsolidatedStore } from './consolidated.js';
|
|
15
|
+
/** 一次巩固的执行结果(供调度与命令输出)。 */
|
|
16
|
+
export interface ConsolidationResult {
|
|
17
|
+
/** 是否产生了新的巩固条目。 */
|
|
18
|
+
produced: boolean;
|
|
19
|
+
/** 本次处理的簇数。 */
|
|
20
|
+
clusters: number;
|
|
21
|
+
/** 产出的新条目数。 */
|
|
22
|
+
entries: number;
|
|
23
|
+
/** 进入 dormant 的条目数。 */
|
|
24
|
+
decayed: number;
|
|
25
|
+
/** 处理前的 pending 碎片数。 */
|
|
26
|
+
pending: number;
|
|
27
|
+
}
|
|
28
|
+
/**
|
|
29
|
+
* 执行一次巩固。返回执行结果;任何失败都不抛错:
|
|
30
|
+
* 无路由/超时/解析失败 → 保留 pending,由调用方继续调度。
|
|
31
|
+
*/
|
|
32
|
+
export declare function runConsolidation(ctx: Context, _store: MemoryStore, consolidated: ConsolidatedStore, opts: ConsolidateOptions, logger: LoggerLike): Promise<ConsolidationResult>;
|