dsh-recall-rebuild 0.1.3 → 0.1.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +20 -2
- package/dist/config.d.ts +34 -0
- package/dist/config.js +6 -0
- package/dist/index.d.ts +22 -0
- package/dist/index.js +29 -2
- package/dist/observability.d.ts +69 -0
- package/dist/observability.js +119 -0
- package/dist/recall.d.ts +2 -1
- package/dist/recall.js +31 -4
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -35,6 +35,7 @@
|
|
|
35
35
|
- **生成式重建**:在 `agent/pre-step` 用会话末尾消息召回碎片,LLM 重建为带语境/情绪/时间感的回忆片段,替代生硬原文注入;
|
|
36
36
|
- **与生态共存不错位**:注入消息 `source.kind='plugin:recall-rebuild'`,不会被 prime-memory 当作新用户消息再次捕获/蒸馏;`replace` 策略原位替换对方的原文召回,`append` 策略追加,不重复注入;
|
|
37
37
|
- **永不阻塞对话**:无记忆库/无模型路由/超时/重建失败,一律静默跳过本轮;
|
|
38
|
+
- **重建质量可观测**:每轮在 `~/.dsh/recall-rebuild/logs/recall-YYYY-MM-DD.log` 写一条 JSONL 审计日志,「原始检索碎片 ↔ 重建后片段」同屏对比 + 注入方式/耗时/跳过原因,附带 `stats.json` 统计——零额外注入、零 token 成本,自己判断重建效果;
|
|
38
39
|
- **零部署硬件成本**:不买显卡、不租 GPU,重建调用走宿主已有的 LLM 路由,每轮只消耗百级 token;
|
|
39
40
|
- **零额外运行时依赖**:用 Node 22+ 内置 `node:sqlite` 读库,安装即用。
|
|
40
41
|
|
|
@@ -121,12 +122,27 @@ flowchart LR
|
|
|
121
122
|
| `user.isolation` | `auto` | IM 用户隔离模式:`auto` 剔除「明确属于其他用户」的记忆(无主记忆默认可见,命中后归位);`strict` 只注入「已归属当前用户」的记忆(新用户零记忆起步);`off` 不过滤。桌面直接对话自动不隔离 |
|
|
122
123
|
| `user.isolationDir` | `''` | 归属索引目录;空 = `<DSH_HOME>/recall-rebuild/namespaces` |
|
|
123
124
|
| `user.sourceTagPattern` | `''` | 覆盖内置 `<dsh_im_source>` 解析正则;不同桥接插件字段不同时可自定义(需含一个捕获组取用户 id) |
|
|
125
|
+
| `observability.logEnabled` | `true` | 每轮重建审计日志开关(JSON Lines,按天滚动) |
|
|
126
|
+
| `observability.logDir` | `''` | 日志目录;空 = `<DSH_HOME>/recall-rebuild/logs` |
|
|
127
|
+
| `observability.includeFragments` | `true` | 日志是否记录原始检索碎片(与重建片段同屏对比);`false` 只记重建结果 |
|
|
128
|
+
| `observability.statsEnabled` | `true` | 是否写统计文件 `stats.json`(30s 节流) |
|
|
129
|
+
|
|
130
|
+
## 观测:怎么判断重建是否真的更好
|
|
131
|
+
|
|
132
|
+
每轮运行后,打开日志目录(`~/.dsh/recall-rebuild/logs/`):
|
|
133
|
+
|
|
134
|
+
- **`recall-YYYY-MM-DD.log`**:每轮一行 JSON,同一轮里 `fragments`(原始检索碎片)与 `rebuilt`(重建后片段)并排——直接对比同一份记忆的两种呈现,自己判断哪种更"像人";
|
|
135
|
+
- **`stats.json`**:累计轮数 / 命中轮 / 重建成功 / 注入 / 替换数,看重建的覆盖面和替换率。
|
|
136
|
+
|
|
137
|
+
字段速览:`round` 轮次、`userKey` 当前 IM 用户、`hitCount` 命中数、`memoryIds` 依据记忆 id、`fragments` 原始碎片、`rebuilt` 重建片段、`injection` 注入方式(`replaced` 替换了对方原文召回 / `appended` 追加 / `none` 未注入)、`latencyMs` 耗时、`error` 跳过原因。
|
|
138
|
+
|
|
139
|
+
> 想运行时真·对比(同一轮同时看到原文召回与重建片段),把 `inject.strategy` 设为 `append`;想零成本对比,看日志即可。
|
|
124
140
|
|
|
125
141
|
## Roadmap
|
|
126
142
|
|
|
127
143
|
- [ ] 更多记忆源 adapter(`dsh-memory-vault`、`dsh-auto-memory`、`dsh-memory-gate` 等变体);
|
|
128
144
|
- [x] IM 用户级命名空间隔离(跨 QQ/微信的同一人记忆共享)—— v0.1.3 已实现;
|
|
129
|
-
- [
|
|
145
|
+
- [x] 重建质量可观测(每轮 JSONL 日志 + stats)—— v0.1.4 已实现;
|
|
130
146
|
- [ ] 睡眠巩固 / 联想扩散(更接近人脑的长期记忆子系统的后续阶段)。
|
|
131
147
|
|
|
132
148
|
## 局限(如实声明)
|
|
@@ -136,7 +152,8 @@ flowchart LR
|
|
|
136
152
|
3. **用户识别依赖桥接插件约定**:优先解析 `<dsh_im_source>` JSON(senderId/chatId/threadId/botId),兜底常见字段(senderId/userId/openid/fromUser);不同桥接字段不同时用 `user.sourceTagPattern` 覆盖。识别不到用户(桌面会话)时不做隔离。
|
|
137
153
|
4. **幻觉受控但非零**:重建 prompt 明确禁止编造碎片外事实,但 LLM 仍有漂移概率;注入标注记忆依据 id 便于审计。需要强事实的场景可关掉重建(`rebuild.enabled=false`)。
|
|
138
154
|
5. **token 消耗**:每轮召回命中即产生一次重建调用(通常百级 token),由宿主模型路由计费。
|
|
139
|
-
6.
|
|
155
|
+
6. **日志零成本但非自动诊断**:日志只记录事实(碎片/重建/耗时/跳过原因),不做好坏判定;用户可对比判断,或切换 `inject.strategy=append` 运行时对比。
|
|
156
|
+
7. **未覆盖**:LoRA 权重内化等权重级记忆不在本插件范围(见 Roadmap)。
|
|
140
157
|
|
|
141
158
|
## 开发与验证
|
|
142
159
|
|
|
@@ -165,6 +182,7 @@ This plugin upgrades the **recall/presentation layer**:
|
|
|
165
182
|
- **Per-user memory isolation for IM (QQ/WeChat…)**: it parses the `<dsh_im_source>` block that IM bridge plugins attach to messages, extracts `senderId`/`chatId`, and keeps each user's memories out of other users' recalls via an ownership index it maintains in its **own** directory (`<DSH_HOME>/recall-rebuild/namespaces`) — the underlying memory DB is still never written. Modes: `auto` (drop memories clearly owned by others; ownerless memories are conservatively visible until claimed), `strict` (only inject memories already owned by the current user), `off` (no filtering). Desktop chats with no detectable user are never filtered;
|
|
166
183
|
- 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;
|
|
167
184
|
- **Never blocks a conversation**: missing store, missing model route, timeout or rebuild failure all silently skip the step;
|
|
185
|
+
- **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;
|
|
168
186
|
- **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`.
|
|
169
187
|
|
|
170
188
|
**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.
|
package/dist/config.d.ts
CHANGED
|
@@ -56,6 +56,17 @@ export interface UserIsolationOptions {
|
|
|
56
56
|
/** 覆盖内置 <dsh_im_source> 解析正则(不同桥接插件字段不同时可自定义);空 = 内置。 */
|
|
57
57
|
sourceTagPattern: string;
|
|
58
58
|
}
|
|
59
|
+
/** 重建质量可观测选项。 */
|
|
60
|
+
export interface ObservabilityOptions {
|
|
61
|
+
/** 每轮重建审计日志开关(JSON Lines,按天滚动)。 */
|
|
62
|
+
logEnabled: boolean;
|
|
63
|
+
/** 日志目录;空 = <DSH_HOME>/recall-rebuild/logs。 */
|
|
64
|
+
logDir: string;
|
|
65
|
+
/** 日志是否记录原始检索碎片(与重建片段同屏对比);false 只记重建结果。 */
|
|
66
|
+
includeFragments: boolean;
|
|
67
|
+
/** 是否写统计文件 stats.json(30s 节流)。 */
|
|
68
|
+
statsEnabled: boolean;
|
|
69
|
+
}
|
|
59
70
|
export interface RecallRebuildConfig {
|
|
60
71
|
/** 总开关。 */
|
|
61
72
|
enabled: boolean;
|
|
@@ -73,6 +84,7 @@ export interface RecallRebuildConfig {
|
|
|
73
84
|
inject: InjectOptions;
|
|
74
85
|
query: QueryOptions;
|
|
75
86
|
user: UserIsolationOptions;
|
|
87
|
+
observability: ObservabilityOptions;
|
|
76
88
|
}
|
|
77
89
|
export declare const recallRebuildSchema: Schema<Schemastery.ObjectS<NoInfer<{
|
|
78
90
|
enabled: Schema<boolean, boolean, "defined">;
|
|
@@ -122,6 +134,17 @@ export declare const recallRebuildSchema: Schema<Schemastery.ObjectS<NoInfer<{
|
|
|
122
134
|
isolationDir: Schema<string, string, "defined">;
|
|
123
135
|
sourceTagPattern: Schema<string, string, "defined">;
|
|
124
136
|
}>>, "defined">;
|
|
137
|
+
observability: Schema<Schemastery.ObjectS<NoInfer<{
|
|
138
|
+
logEnabled: Schema<boolean, boolean, "defined">;
|
|
139
|
+
logDir: Schema<string, string, "defined">;
|
|
140
|
+
includeFragments: Schema<boolean, boolean, "defined">;
|
|
141
|
+
statsEnabled: Schema<boolean, boolean, "defined">;
|
|
142
|
+
}>>, Schemastery.ObjectT<NoInfer<{
|
|
143
|
+
logEnabled: Schema<boolean, boolean, "defined">;
|
|
144
|
+
logDir: Schema<string, string, "defined">;
|
|
145
|
+
includeFragments: Schema<boolean, boolean, "defined">;
|
|
146
|
+
statsEnabled: Schema<boolean, boolean, "defined">;
|
|
147
|
+
}>>, "defined">;
|
|
125
148
|
}>>, Schemastery.ObjectT<NoInfer<{
|
|
126
149
|
enabled: Schema<boolean, boolean, "defined">;
|
|
127
150
|
dataDir: Schema<string, string, "defined">;
|
|
@@ -170,4 +193,15 @@ export declare const recallRebuildSchema: Schema<Schemastery.ObjectS<NoInfer<{
|
|
|
170
193
|
isolationDir: Schema<string, string, "defined">;
|
|
171
194
|
sourceTagPattern: Schema<string, string, "defined">;
|
|
172
195
|
}>>, "defined">;
|
|
196
|
+
observability: Schema<Schemastery.ObjectS<NoInfer<{
|
|
197
|
+
logEnabled: Schema<boolean, boolean, "defined">;
|
|
198
|
+
logDir: Schema<string, string, "defined">;
|
|
199
|
+
includeFragments: Schema<boolean, boolean, "defined">;
|
|
200
|
+
statsEnabled: Schema<boolean, boolean, "defined">;
|
|
201
|
+
}>>, Schemastery.ObjectT<NoInfer<{
|
|
202
|
+
logEnabled: Schema<boolean, boolean, "defined">;
|
|
203
|
+
logDir: Schema<string, string, "defined">;
|
|
204
|
+
includeFragments: Schema<boolean, boolean, "defined">;
|
|
205
|
+
statsEnabled: Schema<boolean, boolean, "defined">;
|
|
206
|
+
}>>, "defined">;
|
|
173
207
|
}>>, "defined">;
|
package/dist/config.js
CHANGED
|
@@ -34,4 +34,10 @@ export const recallRebuildSchema = Schema.object({
|
|
|
34
34
|
isolationDir: Schema.string().default(''),
|
|
35
35
|
sourceTagPattern: Schema.string().default(''),
|
|
36
36
|
}).default({}),
|
|
37
|
+
observability: Schema.object({
|
|
38
|
+
logEnabled: Schema.boolean().default(true),
|
|
39
|
+
logDir: Schema.string().default(''),
|
|
40
|
+
includeFragments: Schema.boolean().default(true),
|
|
41
|
+
statsEnabled: Schema.boolean().default(true),
|
|
42
|
+
}).default({}),
|
|
37
43
|
}).default({});
|
package/dist/index.d.ts
CHANGED
|
@@ -50,6 +50,17 @@ export declare const Config: import("@deepseek-ai/schemastery").default<Schemast
|
|
|
50
50
|
isolationDir: import("@deepseek-ai/schemastery").default<string, string, "defined">;
|
|
51
51
|
sourceTagPattern: import("@deepseek-ai/schemastery").default<string, string, "defined">;
|
|
52
52
|
}>>, "defined">;
|
|
53
|
+
observability: import("@deepseek-ai/schemastery").default<Schemastery.ObjectS<NoInfer<{
|
|
54
|
+
logEnabled: import("@deepseek-ai/schemastery").default<boolean, boolean, "defined">;
|
|
55
|
+
logDir: import("@deepseek-ai/schemastery").default<string, string, "defined">;
|
|
56
|
+
includeFragments: import("@deepseek-ai/schemastery").default<boolean, boolean, "defined">;
|
|
57
|
+
statsEnabled: import("@deepseek-ai/schemastery").default<boolean, boolean, "defined">;
|
|
58
|
+
}>>, Schemastery.ObjectT<NoInfer<{
|
|
59
|
+
logEnabled: import("@deepseek-ai/schemastery").default<boolean, boolean, "defined">;
|
|
60
|
+
logDir: import("@deepseek-ai/schemastery").default<string, string, "defined">;
|
|
61
|
+
includeFragments: import("@deepseek-ai/schemastery").default<boolean, boolean, "defined">;
|
|
62
|
+
statsEnabled: import("@deepseek-ai/schemastery").default<boolean, boolean, "defined">;
|
|
63
|
+
}>>, "defined">;
|
|
53
64
|
}>>, Schemastery.ObjectT<NoInfer<{
|
|
54
65
|
enabled: import("@deepseek-ai/schemastery").default<boolean, boolean, "defined">;
|
|
55
66
|
dataDir: import("@deepseek-ai/schemastery").default<string, string, "defined">;
|
|
@@ -98,5 +109,16 @@ export declare const Config: import("@deepseek-ai/schemastery").default<Schemast
|
|
|
98
109
|
isolationDir: import("@deepseek-ai/schemastery").default<string, string, "defined">;
|
|
99
110
|
sourceTagPattern: import("@deepseek-ai/schemastery").default<string, string, "defined">;
|
|
100
111
|
}>>, "defined">;
|
|
112
|
+
observability: import("@deepseek-ai/schemastery").default<Schemastery.ObjectS<NoInfer<{
|
|
113
|
+
logEnabled: import("@deepseek-ai/schemastery").default<boolean, boolean, "defined">;
|
|
114
|
+
logDir: import("@deepseek-ai/schemastery").default<string, string, "defined">;
|
|
115
|
+
includeFragments: import("@deepseek-ai/schemastery").default<boolean, boolean, "defined">;
|
|
116
|
+
statsEnabled: import("@deepseek-ai/schemastery").default<boolean, boolean, "defined">;
|
|
117
|
+
}>>, Schemastery.ObjectT<NoInfer<{
|
|
118
|
+
logEnabled: import("@deepseek-ai/schemastery").default<boolean, boolean, "defined">;
|
|
119
|
+
logDir: import("@deepseek-ai/schemastery").default<string, string, "defined">;
|
|
120
|
+
includeFragments: import("@deepseek-ai/schemastery").default<boolean, boolean, "defined">;
|
|
121
|
+
statsEnabled: import("@deepseek-ai/schemastery").default<boolean, boolean, "defined">;
|
|
122
|
+
}>>, "defined">;
|
|
101
123
|
}>>, "defined">;
|
|
102
124
|
export declare function apply(ctx: Context, config: RecallRebuildConfig): Promise<void>;
|
package/dist/index.js
CHANGED
|
@@ -13,6 +13,7 @@ import { recallRebuildSchema } from './config.js';
|
|
|
13
13
|
import { openMemorySource } from './store.js';
|
|
14
14
|
import { registerRecallRebuild } from './recall.js';
|
|
15
15
|
import { NamespaceStore } from './namespace.js';
|
|
16
|
+
import { RebuildLogger } from './observability.js';
|
|
16
17
|
export const name = 'recall-rebuild';
|
|
17
18
|
export const inject = ['llm'];
|
|
18
19
|
export const Config = recallRebuildSchema;
|
|
@@ -53,6 +54,25 @@ function resolveIsolationDir(config, logger) {
|
|
|
53
54
|
}
|
|
54
55
|
return fallback;
|
|
55
56
|
}
|
|
57
|
+
/** 重建日志目录:<DSH_HOME>/recall-rebuild/logs(缺省 ~/.dsh/recall-rebuild/logs)。 */
|
|
58
|
+
function resolveLogDir(config, logger) {
|
|
59
|
+
if (config.observability.logDir)
|
|
60
|
+
return config.observability.logDir;
|
|
61
|
+
try {
|
|
62
|
+
const home = dshHomePath();
|
|
63
|
+
if (home)
|
|
64
|
+
return path.join(home, 'recall-rebuild', 'logs');
|
|
65
|
+
}
|
|
66
|
+
catch {
|
|
67
|
+
/* 落到兜底 */
|
|
68
|
+
}
|
|
69
|
+
const base = process.env.HOME || process.env.USERPROFILE || '';
|
|
70
|
+
const fallback = base ? path.join(base, '.dsh', 'recall-rebuild', 'logs') : '';
|
|
71
|
+
if (!fallback) {
|
|
72
|
+
logger.warn(`[recall-rebuild] 无法确定日志目录,请在 config.observability.logDir 显式指定`);
|
|
73
|
+
}
|
|
74
|
+
return fallback;
|
|
75
|
+
}
|
|
56
76
|
export async function apply(ctx, config) {
|
|
57
77
|
const logger = ctx.logger;
|
|
58
78
|
const dataDir = resolveDataDir(config, logger);
|
|
@@ -64,6 +84,13 @@ export async function apply(ctx, config) {
|
|
|
64
84
|
// IM 用户级命名空间隔离(自己的目录,绝不写底层记忆库)
|
|
65
85
|
const namespaces = new NamespaceStore(resolveIsolationDir(config, logger), logger);
|
|
66
86
|
namespaces.ensureDir();
|
|
87
|
+
// 重建质量可观测:每轮 JSONL 日志 + 统计(自己的目录)
|
|
88
|
+
const obsLog = new RebuildLogger({
|
|
89
|
+
logDir: resolveLogDir(config, logger),
|
|
90
|
+
enabled: config.observability.logEnabled,
|
|
91
|
+
includeFragments: config.observability.includeFragments,
|
|
92
|
+
logger,
|
|
93
|
+
});
|
|
67
94
|
if (store.ok) {
|
|
68
95
|
logger.info(`[recall-rebuild] 已只读挂载记忆库: ${store.label}`);
|
|
69
96
|
}
|
|
@@ -71,8 +98,8 @@ export async function apply(ctx, config) {
|
|
|
71
98
|
logger.warn(`[recall-rebuild] 记忆库不可用(${store.label}),插件按只观察模式运行(不注入)。` +
|
|
72
99
|
`请先安装并运行 dsh-prime-memory / dsh-memory-palace,或确认 config.dataDir / cwd 正确`);
|
|
73
100
|
}
|
|
74
|
-
registerRecallRebuild(ctx, store, config, logger, namespaces);
|
|
101
|
+
registerRecallRebuild(ctx, store, config, logger, namespaces, obsLog);
|
|
75
102
|
logger.info(`[recall-rebuild] 重建式回忆增强就绪 ` +
|
|
76
103
|
`(rebuild=${config.rebuild.enabled}, inject=${config.inject.strategy}, source=${config.source}, ` +
|
|
77
|
-
`isolation=${config.user.isolation})`);
|
|
104
|
+
`isolation=${config.user.isolation}, log=${config.observability.logEnabled})`);
|
|
78
105
|
}
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
import type { LoggerLike } from './store.js';
|
|
2
|
+
export interface RebuildLogEntry {
|
|
3
|
+
ts: string;
|
|
4
|
+
round: number;
|
|
5
|
+
userKey: string | null;
|
|
6
|
+
isolation: string;
|
|
7
|
+
query: string;
|
|
8
|
+
hitCount: number;
|
|
9
|
+
memoryIds: string[];
|
|
10
|
+
fragments: string[];
|
|
11
|
+
rebuilt: string;
|
|
12
|
+
rebuiltChars: number;
|
|
13
|
+
injection: 'replaced' | 'appended' | 'none';
|
|
14
|
+
latencyMs: number;
|
|
15
|
+
error?: string;
|
|
16
|
+
}
|
|
17
|
+
interface Stats {
|
|
18
|
+
rounds: number;
|
|
19
|
+
hits: number;
|
|
20
|
+
rebuilt: number;
|
|
21
|
+
injected: number;
|
|
22
|
+
replaced: number;
|
|
23
|
+
errors: number;
|
|
24
|
+
lastRoundAt: string;
|
|
25
|
+
}
|
|
26
|
+
export declare class RebuildLogger {
|
|
27
|
+
private readonly logDir;
|
|
28
|
+
private readonly enabled;
|
|
29
|
+
private readonly includeFragments;
|
|
30
|
+
private readonly logger;
|
|
31
|
+
private roundNo;
|
|
32
|
+
private stats;
|
|
33
|
+
private lastStatsWrite;
|
|
34
|
+
private readonly statsIntervalMs;
|
|
35
|
+
constructor(opts: {
|
|
36
|
+
logDir: string;
|
|
37
|
+
enabled: boolean;
|
|
38
|
+
includeFragments: boolean;
|
|
39
|
+
logger: LoggerLike;
|
|
40
|
+
});
|
|
41
|
+
/** 当前轮日志文件名(按天滚动)。 */
|
|
42
|
+
private todayFile;
|
|
43
|
+
/**
|
|
44
|
+
* 记录一轮。
|
|
45
|
+
* @param partial 必填字段之外的内容;fragments 仅 includeFragments 时保留
|
|
46
|
+
*/
|
|
47
|
+
log(partial: {
|
|
48
|
+
userKey: string | null;
|
|
49
|
+
isolation: string;
|
|
50
|
+
query: string;
|
|
51
|
+
hitCount: number;
|
|
52
|
+
memoryIds: string[];
|
|
53
|
+
rebuilt: string;
|
|
54
|
+
injection: 'replaced' | 'appended' | 'none';
|
|
55
|
+
latencyMs: number;
|
|
56
|
+
error?: string;
|
|
57
|
+
fragments?: string[];
|
|
58
|
+
}): void;
|
|
59
|
+
/** 原子写 stats.json(节流外也可主动调用)。 */
|
|
60
|
+
flushStats(): void;
|
|
61
|
+
/** 当前累计统计(读给宿主用)。 */
|
|
62
|
+
snapshot(): Stats;
|
|
63
|
+
}
|
|
64
|
+
/** 给 verify 用的纯函数:从日志条目提取碎片对比段(原文 vs 重建)。 */
|
|
65
|
+
export declare function fragmentSample(entry: RebuildLogEntry): {
|
|
66
|
+
original: string[];
|
|
67
|
+
rebuilt: string;
|
|
68
|
+
};
|
|
69
|
+
export {};
|
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 重建质量可观测:每轮重建的完整审计日志 + 轻量统计。
|
|
3
|
+
*
|
|
4
|
+
* 目的:让用户直接看到「同一批记忆,原文检索碎片 ↔ 重建后片段」的差异,
|
|
5
|
+
* 自己判断重建式回忆是否真的更好(注入效果对比,零额外注入、零 token 成本)。
|
|
6
|
+
*
|
|
7
|
+
* 日志:按天滚动 JSON Lines(<logDir>/recall-YYYY-MM-DD.log),
|
|
8
|
+
* 每轮 pre-step 写一条;目录自动创建,写失败静默(不阻塞对话)。
|
|
9
|
+
* 统计:<logDir>/stats.json,内存累计 + 30s 节流原子写。
|
|
10
|
+
*/
|
|
11
|
+
import * as fs from 'node:fs';
|
|
12
|
+
import * as path from 'node:path';
|
|
13
|
+
function truncate(s, max) {
|
|
14
|
+
if (!s)
|
|
15
|
+
return '';
|
|
16
|
+
return s.length > max ? `${s.slice(0, max)}…` : s;
|
|
17
|
+
}
|
|
18
|
+
export class RebuildLogger {
|
|
19
|
+
logDir;
|
|
20
|
+
enabled;
|
|
21
|
+
includeFragments;
|
|
22
|
+
logger;
|
|
23
|
+
roundNo = 0;
|
|
24
|
+
stats = {
|
|
25
|
+
rounds: 0,
|
|
26
|
+
hits: 0,
|
|
27
|
+
rebuilt: 0,
|
|
28
|
+
injected: 0,
|
|
29
|
+
replaced: 0,
|
|
30
|
+
errors: 0,
|
|
31
|
+
lastRoundAt: '',
|
|
32
|
+
};
|
|
33
|
+
lastStatsWrite = 0;
|
|
34
|
+
statsIntervalMs = 30_000;
|
|
35
|
+
constructor(opts) {
|
|
36
|
+
this.logDir = opts.logDir;
|
|
37
|
+
this.enabled = opts.enabled;
|
|
38
|
+
this.includeFragments = opts.includeFragments;
|
|
39
|
+
this.logger = opts.logger;
|
|
40
|
+
}
|
|
41
|
+
/** 当前轮日志文件名(按天滚动)。 */
|
|
42
|
+
todayFile() {
|
|
43
|
+
const d = new Date();
|
|
44
|
+
const mm = String(d.getMonth() + 1).padStart(2, '0');
|
|
45
|
+
const dd = String(d.getDate()).padStart(2, '0');
|
|
46
|
+
return `recall-${d.getFullYear()}-${mm}-${dd}.log`;
|
|
47
|
+
}
|
|
48
|
+
/**
|
|
49
|
+
* 记录一轮。
|
|
50
|
+
* @param partial 必填字段之外的内容;fragments 仅 includeFragments 时保留
|
|
51
|
+
*/
|
|
52
|
+
log(partial) {
|
|
53
|
+
this.roundNo += 1;
|
|
54
|
+
this.stats.rounds += 1;
|
|
55
|
+
if (partial.hitCount > 0)
|
|
56
|
+
this.stats.hits += 1;
|
|
57
|
+
// rebuilt = 实际发生重建流程且成功的轮数(零命中/报错不计)
|
|
58
|
+
if (!partial.error && partial.hitCount > 0)
|
|
59
|
+
this.stats.rebuilt += 1;
|
|
60
|
+
if (partial.injection !== 'none')
|
|
61
|
+
this.stats.injected += 1;
|
|
62
|
+
if (partial.injection === 'replaced')
|
|
63
|
+
this.stats.replaced += 1;
|
|
64
|
+
if (partial.error)
|
|
65
|
+
this.stats.errors += 1;
|
|
66
|
+
this.stats.lastRoundAt = new Date().toISOString();
|
|
67
|
+
if (!this.enabled)
|
|
68
|
+
return;
|
|
69
|
+
const entry = {
|
|
70
|
+
ts: new Date().toISOString(),
|
|
71
|
+
round: this.roundNo,
|
|
72
|
+
userKey: partial.userKey,
|
|
73
|
+
isolation: partial.isolation,
|
|
74
|
+
query: truncate(partial.query, 300),
|
|
75
|
+
hitCount: partial.hitCount,
|
|
76
|
+
memoryIds: partial.memoryIds.slice(0, 10),
|
|
77
|
+
fragments: this.includeFragments
|
|
78
|
+
? (partial.fragments ?? []).slice(0, 5).map((f) => truncate(f, 200))
|
|
79
|
+
: [],
|
|
80
|
+
rebuilt: truncate(partial.rebuilt, 600),
|
|
81
|
+
rebuiltChars: partial.rebuilt.length,
|
|
82
|
+
injection: partial.injection,
|
|
83
|
+
latencyMs: partial.latencyMs,
|
|
84
|
+
...(partial.error ? { error: truncate(partial.error, 300) } : {}),
|
|
85
|
+
};
|
|
86
|
+
try {
|
|
87
|
+
fs.mkdirSync(this.logDir, { recursive: true });
|
|
88
|
+
fs.appendFileSync(path.join(this.logDir, this.todayFile()), `${JSON.stringify(entry)}\n`, 'utf8');
|
|
89
|
+
}
|
|
90
|
+
catch (err) {
|
|
91
|
+
this.logger.warn(`[recall-rebuild] 写重建日志失败: ${err instanceof Error ? err.message : String(err)}`);
|
|
92
|
+
}
|
|
93
|
+
// 统计节流落盘
|
|
94
|
+
if (Date.now() - this.lastStatsWrite > this.statsIntervalMs)
|
|
95
|
+
this.flushStats();
|
|
96
|
+
}
|
|
97
|
+
/** 原子写 stats.json(节流外也可主动调用)。 */
|
|
98
|
+
flushStats() {
|
|
99
|
+
this.lastStatsWrite = Date.now();
|
|
100
|
+
try {
|
|
101
|
+
fs.mkdirSync(this.logDir, { recursive: true });
|
|
102
|
+
const p = path.join(this.logDir, 'stats.json');
|
|
103
|
+
const tmp = `${p}.tmp`;
|
|
104
|
+
fs.writeFileSync(tmp, JSON.stringify(this.stats, null, 2), 'utf8');
|
|
105
|
+
fs.renameSync(tmp, p);
|
|
106
|
+
}
|
|
107
|
+
catch (err) {
|
|
108
|
+
this.logger.warn(`[recall-rebuild] 写统计文件失败: ${err instanceof Error ? err.message : String(err)}`);
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
/** 当前累计统计(读给宿主用)。 */
|
|
112
|
+
snapshot() {
|
|
113
|
+
return { ...this.stats };
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
/** 给 verify 用的纯函数:从日志条目提取碎片对比段(原文 vs 重建)。 */
|
|
117
|
+
export function fragmentSample(entry) {
|
|
118
|
+
return { original: entry.fragments ?? [], rebuilt: entry.rebuilt };
|
|
119
|
+
}
|
package/dist/recall.d.ts
CHANGED
|
@@ -16,6 +16,7 @@ import type { Context } from '@deepseek-ai/cordis';
|
|
|
16
16
|
import type { RecallRebuildConfig } from './config.js';
|
|
17
17
|
import type { LoggerLike, MemoryStore } from './store.js';
|
|
18
18
|
import { type NamespaceStore } from './namespace.js';
|
|
19
|
+
import type { RebuildLogger } from './observability.js';
|
|
19
20
|
interface MsgLike {
|
|
20
21
|
source?: {
|
|
21
22
|
kind?: string;
|
|
@@ -26,5 +27,5 @@ interface MsgLike {
|
|
|
26
27
|
}
|
|
27
28
|
/** 判断一条消息是否为其它插件(prime-memory 等)注入的原文召回。 */
|
|
28
29
|
export declare function isOtherPluginRecall(m: MsgLike): boolean;
|
|
29
|
-
export declare function registerRecallRebuild(ctx: Context, store: MemoryStore, cfg: RecallRebuildConfig, logger: LoggerLike, namespaces?: NamespaceStore): void;
|
|
30
|
+
export declare function registerRecallRebuild(ctx: Context, store: MemoryStore, cfg: RecallRebuildConfig, logger: LoggerLike, namespaces?: NamespaceStore, obsLog?: RebuildLogger): void;
|
|
30
31
|
export {};
|
package/dist/recall.js
CHANGED
|
@@ -64,7 +64,7 @@ function buildInjectionMessage(text, sourceIds, cfg) {
|
|
|
64
64
|
source,
|
|
65
65
|
});
|
|
66
66
|
}
|
|
67
|
-
export function registerRecallRebuild(ctx, store, cfg, logger, namespaces) {
|
|
67
|
+
export function registerRecallRebuild(ctx, store, cfg, logger, namespaces, obsLog) {
|
|
68
68
|
if (!cfg.enabled)
|
|
69
69
|
return;
|
|
70
70
|
const emitter = ctx;
|
|
@@ -79,6 +79,7 @@ export function registerRecallRebuild(ctx, store, cfg, logger, namespaces) {
|
|
|
79
79
|
if (!hasNewUser)
|
|
80
80
|
return decision;
|
|
81
81
|
try {
|
|
82
|
+
const startedAt = Date.now();
|
|
82
83
|
const query = buildRecallQuery(payload.messages, cfg);
|
|
83
84
|
if (!query)
|
|
84
85
|
return decision;
|
|
@@ -87,28 +88,54 @@ export function registerRecallRebuild(ctx, store, cfg, logger, namespaces) {
|
|
|
87
88
|
? extractUserKey(decision.messages.map(blocksToText), cfg.user.sourceTagPattern)
|
|
88
89
|
: null;
|
|
89
90
|
let memories = store.search(query, cfg.rebuild.maxResults);
|
|
90
|
-
|
|
91
|
+
const logBase = () => ({
|
|
92
|
+
userKey,
|
|
93
|
+
isolation: cfg.user.isolation,
|
|
94
|
+
query,
|
|
95
|
+
hitCount: memories.length,
|
|
96
|
+
memoryIds: memories.map((m) => m.id),
|
|
97
|
+
fragments: memories.map((m) => m.content),
|
|
98
|
+
rebuilt: '',
|
|
99
|
+
injection: 'none',
|
|
100
|
+
latencyMs: Date.now() - startedAt,
|
|
101
|
+
});
|
|
102
|
+
if (memories.length === 0) {
|
|
103
|
+
if (obsLog)
|
|
104
|
+
obsLog.log({ ...logBase() });
|
|
91
105
|
return decision;
|
|
106
|
+
}
|
|
92
107
|
// 用户级命名空间隔离:过滤"明确属于其他用户"的记忆
|
|
93
108
|
if (namespaces) {
|
|
94
109
|
memories = namespaces.filter(memories, userKey, cfg.user.isolation);
|
|
95
|
-
if (memories.length === 0)
|
|
110
|
+
if (memories.length === 0) {
|
|
111
|
+
if (obsLog)
|
|
112
|
+
obsLog.log({ ...logBase(), error: '隔离过滤后无可用记忆' });
|
|
96
113
|
return decision;
|
|
114
|
+
}
|
|
97
115
|
// 只把"本轮实际保留"的候选记为当前用户归属(无主记忆随命中归位)
|
|
98
116
|
namespaces.recordHits(userKey, memories);
|
|
99
117
|
}
|
|
100
118
|
const rebuilt = await rebuildMemory(ctx, memories, query, cfg.rebuild, payload.signal, logger);
|
|
101
|
-
if (!rebuilt || !rebuilt.text)
|
|
119
|
+
if (!rebuilt || !rebuilt.text) {
|
|
120
|
+
if (obsLog)
|
|
121
|
+
obsLog.log({ ...logBase(), error: '重建返回空,跳过注入' });
|
|
102
122
|
return decision;
|
|
123
|
+
}
|
|
103
124
|
const injection = buildInjectionMessage(rebuilt.text, rebuilt.sourceIds, cfg);
|
|
125
|
+
let injectionKind = 'appended';
|
|
104
126
|
if (cfg.inject.strategy === 'replace') {
|
|
105
127
|
const idx = decision.messages.findIndex(isOtherPluginRecall);
|
|
106
128
|
if (idx >= 0) {
|
|
107
129
|
const msgs = [...decision.messages];
|
|
108
130
|
msgs[idx] = injection;
|
|
131
|
+
injectionKind = 'replaced';
|
|
132
|
+
if (obsLog)
|
|
133
|
+
obsLog.log({ ...logBase(), rebuilt: rebuilt.text, injection: injectionKind, latencyMs: Date.now() - startedAt });
|
|
109
134
|
return { kind: 'enter', messages: msgs };
|
|
110
135
|
}
|
|
111
136
|
}
|
|
137
|
+
if (obsLog)
|
|
138
|
+
obsLog.log({ ...logBase(), rebuilt: rebuilt.text, injection: injectionKind, latencyMs: Date.now() - startedAt });
|
|
112
139
|
return { kind: 'enter', messages: [injection, ...decision.messages] };
|
|
113
140
|
}
|
|
114
141
|
catch (err) {
|