dsh-zcode-memory 0.0.0-stage → 1.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,182 @@
1
+ // N5 验收:真 tool-calling 抽取代理。
2
+ // mock llm 第 1 轮返回 memory_list(重复两次) + 不在白名单的 bash;断言:
3
+ // - 请求里声明的工具只含 memory_list/recall/read(bash 被过滤)
4
+ // - 同参数重复调用只执行一次,bash 不执行
5
+ // - 每个 tool-call 都有 tool_result 回灌(跳过的带错误原因)
6
+ // - 最后一轮不再声明 tools,模型给最终 JSON → 落盘 + 游标推进
7
+ // 用法: node native-tools.mjs [index.js 路径]
8
+ import { pathToFileURL } from "node:url";
9
+ import { mkdtempSync, readdirSync, readFileSync, existsSync, rmSync } from "node:fs";
10
+ import { tmpdir } from "node:os";
11
+ import { join } from "node:path";
12
+
13
+ const modUrl = process.argv[2] ? pathToFileURL(process.argv[2]).href : new URL("../index.js", import.meta.url).href;
14
+ const mod = await import(modUrl);
15
+
16
+ const root = mkdtempSync(join(tmpdir(), "zcm-nt-"));
17
+ const cwd = mkdtempSync(join(tmpdir(), "zcm-ntcwd-"));
18
+ const state = { rounds: [], executed: [] };
19
+
20
+ const tools = {
21
+ register: () => {},
22
+ schemas: () => [
23
+ { name: "memory_list", description: "list", parameters: { type: "object" } },
24
+ { name: "memory_recall", description: "recall", parameters: { type: "object" } },
25
+ { name: "memory_read", description: "read", parameters: { type: "object" } },
26
+ // 主模型工具集里的破坏性工具:不得出现在抽取请求的 tools 里,也不得被执行。
27
+ { name: "bash", description: "shell", parameters: { type: "object" } },
28
+ ],
29
+ execute: async ({ calls }) => {
30
+ state.executed.push(...calls.map((c) => c.name));
31
+ return {
32
+ results: calls.map((c) => ({
33
+ callId: c.id,
34
+ result: { isError: false, value: null, content: [{ type: "text", text: `RESULT:${c.name}` }] },
35
+ })),
36
+ additionalContexts: [],
37
+ concluded: false,
38
+ };
39
+ },
40
+ };
41
+
42
+ const reg = { sections: [], contexts: [], tools: [], commands: [], handlers: new Map() };
43
+ const ctx = {
44
+ systemPrompt: { section: (o) => reg.sections.push(o), context: (o) => reg.contexts.push(o) },
45
+ tools,
46
+ commands: { register: (c) => reg.commands.push(c) },
47
+ get: (name) => (name === "sandboxPolicy" ? undefined : undefined),
48
+ on: (ev, fn) => { if (!reg.handlers.has(ev)) reg.handlers.set(ev, []); reg.handlers.get(ev).push(fn); },
49
+ llm: {
50
+ stream: async function* (opts) {
51
+ state.rounds.push({ tools: (opts.tools || []).map((t) => t.name), messages: opts.messages });
52
+ if (state.rounds.length === 1) {
53
+ const call = (id, name, args) => ({
54
+ type: "block-end",
55
+ index: 0,
56
+ block: { type: "tool-call", id, name, arguments: args },
57
+ });
58
+ yield call("c1", "memory_list", "{}");
59
+ yield call("c2", "memory_list", "{}"); // 同参数重复
60
+ yield call("c3", "bash", '{"command":"rm -rf /"}'); // 白名单外
61
+ yield { type: "finish", reason: { kind: "tool-calls" } };
62
+ return;
63
+ }
64
+ yield { type: "finish", reason: { kind: "stop" } };
65
+ yield {
66
+ type: "block-end",
67
+ index: 0,
68
+ block: {
69
+ type: "text",
70
+ text: JSON.stringify({
71
+ writes: [
72
+ {
73
+ op: "create",
74
+ title: "原生工具抽取条目",
75
+ description: "tool-calling 抽取写入",
76
+ type: "project",
77
+ body: "这是 native tool agent 写入的正文。",
78
+ },
79
+ ],
80
+ }),
81
+ },
82
+ };
83
+ },
84
+ },
85
+ };
86
+
87
+ const cfg = { memoriesRoot: root, enabled: true, promptStyle: "native", autoExtractAgentRounds: 2 };
88
+ mod.apply(ctx, cfg);
89
+
90
+ const emit = (ev, ...args) => { for (const fn of reg.handlers.get(ev) || []) fn(...args); };
91
+ const fails = [];
92
+ const check = (cond, msg, extra) => { if (!cond) fails.push(msg + (extra ? ` :: ${String(extra).slice(0, 300)}` : "")); };
93
+
94
+ const session = { header: { id: "sess-nt", cwd, createdAt: "2026-12-05T10:00:00.000Z" } };
95
+ const agent = {
96
+ session, status: "idle", inbox: { nextTurn: [], nextStep: [] },
97
+ model: { current: () => ({ provider: "mock", model: "mock-1" }) },
98
+ whenIdle: () => Promise.resolve(),
99
+ runMaintenance: async (fn) => fn(new AbortController().signal),
100
+ };
101
+
102
+ emit("session/event", session, { type: "turn/start", seq: 1, data: { turn: 1 } });
103
+ emit("session/event", session, {
104
+ type: "user/message", seq: 2,
105
+ data: { source: { kind: "user" }, content: [{ type: "text", text: "这个项目的部署脚本路径是 scripts/deploy.ps1,记一下。" }] },
106
+ });
107
+ emit("session/event", session, {
108
+ type: "assistant/message", seq: 3,
109
+ data: { turn: 1, message: { content: [{ type: "text", text: "已确认部署脚本是 scripts/deploy.ps1。" }] } },
110
+ });
111
+ const memDirGuess = () => {
112
+ const p = join(root, "projects");
113
+ if (!existsSync(p)) return "";
114
+ for (const d of readdirSync(p)) {
115
+ const m = join(p, d, "memory");
116
+ if (existsSync(m)) return m;
117
+ }
118
+ return "";
119
+ };
120
+ emit("agent/turn-stopping", { agent, turn: 1 });
121
+
122
+ for (let i = 0; i < 120; i++) {
123
+ if (memDirGuess() && existsSync(join(memDirGuess(), "MEMORY.md"))) {
124
+ const files = readdirSync(memDirGuess()).filter((f) => f.endsWith(".md") && f !== "MEMORY.md");
125
+ if (files.length) break;
126
+ }
127
+ await new Promise((r) => setTimeout(r, 50));
128
+ }
129
+
130
+ check(state.rounds.length === 2, `llm rounds=${state.rounds.length}`);
131
+ const r1 = state.rounds[0] || { tools: [], messages: [] };
132
+ const r2 = state.rounds[1] || { tools: [], messages: [] };
133
+ check(
134
+ JSON.stringify(r1.tools) === JSON.stringify(["memory_list", "memory_recall", "memory_read"]),
135
+ "round1 declared tools must be the read-only allowlist",
136
+ r1.tools,
137
+ );
138
+ check(r2.tools.length === 0, "last round must not declare tools", r2.tools);
139
+
140
+ check(state.executed.length === 1 && state.executed[0] === "memory_list", "only the fresh whitelisted call executes", state.executed);
141
+ const toolMsgs = (r2.messages || []).filter((m) => m.role === "tool");
142
+ check(toolMsgs.length === 3, `every call needs a tool result (got ${toolMsgs.length})`);
143
+ const errMsgs = toolMsgs.filter((m) => m.isError === true);
144
+ check(errMsgs.length === 2, "duplicate + non-whitelisted calls must come back as errors", errMsgs.map((m) => m.content));
145
+ check(
146
+ toolMsgs.some((m) => JSON.stringify(m.content).includes("RESULT:memory_list")),
147
+ "executed result must be fed back",
148
+ toolMsgs,
149
+ );
150
+ check(
151
+ toolMsgs.some((m) => JSON.stringify(m.content).includes("重复")),
152
+ "duplicate call must be short-circuited",
153
+ toolMsgs,
154
+ );
155
+ const assistantMsgs = (r2.messages || []).filter((m) => m.role === "assistant");
156
+ check(assistantMsgs.length === 1, "one assistant tool-call message", assistantMsgs.length);
157
+ check(
158
+ (assistantMsgs[0]?.content || []).filter((b) => b.type === "tool-call").length === 3,
159
+ "assistant message carries all three calls",
160
+ assistantMsgs[0]?.content,
161
+ );
162
+
163
+ const memDir = memDirGuess();
164
+ const files = memDir ? readdirSync(memDir).filter((f) => f.endsWith(".md") && f !== "MEMORY.md") : [];
165
+ check(files.length === 1, "memory file written", files);
166
+ if (files.length) {
167
+ const body = readFileSync(join(memDir, files[0]), "utf8");
168
+ check(body.includes("native tool agent 写入的正文"), "written body", body);
169
+ check(readFileSync(join(memDir, "MEMORY.md"), "utf8").includes("原生工具抽取条目"), "index synced");
170
+ }
171
+ const stFile = join(root, "_extract-state.json");
172
+ const st = existsSync(stFile) ? JSON.parse(readFileSync(stFile, "utf8")) : {};
173
+ check(st.cursorBySession?.["sess-nt"]?.seq === 3, "cursor advanced only after final writes", st.cursorBySession);
174
+
175
+ console.log(fails.length ? `FAIL ${fails.length}:\n - ` + fails.join("\n - ") : "ALL PASS");
176
+ if (!fails.length) {
177
+ try {
178
+ rmSync(root, { recursive: true, force: true });
179
+ rmSync(cwd, { recursive: true, force: true });
180
+ } catch {}
181
+ }
182
+ process.exit(fails.length ? 1 : 0);
@@ -0,0 +1,253 @@
1
+ // G9(v0.12)规则进 system、索引留 context:
2
+ // - `zcode-memory-rules` 走 systemPrompt.section;`zcode-memory` 走 context(索引)
3
+ // - 规则段只依赖配置/cwd/preset/工具集:索引文件增删不改变规则段文本(前缀缓存稳定)
4
+ // - agent memory 提示体在规则段、`## MEMORY.md` 索引在上下文段
5
+ // - writeEnabled=false:规则段只有只读 header(无 Notes),索引仍可读
6
+ // 用法: node prompt-split.mjs [index.js 路径]
7
+ import { pathToFileURL } from "node:url";
8
+ import { mkdtempSync, mkdirSync, writeFileSync, appendFileSync, rmSync } from "node:fs";
9
+ import { tmpdir } from "node:os";
10
+ import { join } from "node:path";
11
+
12
+ const modUrl = process.argv[2] ? pathToFileURL(process.argv[2]).href : new URL("../index.js", import.meta.url).href;
13
+ const mod = await import(modUrl);
14
+
15
+ const fails = [];
16
+ const check = (cond, msg, extra) => {
17
+ if (!cond) fails.push(msg + (extra !== undefined ? ` :: ${JSON.stringify(extra).slice(0, 300)}` : ""));
18
+ };
19
+
20
+ const root = mkdtempSync(join(tmpdir(), "zcm-split-"));
21
+ const cwd = mkdtempSync(join(tmpdir(), "zcm-splitcwd-"));
22
+
23
+ function makeCtx() {
24
+ const reg = { sections: [], contexts: [], tools: [], commands: [], handlers: new Map() };
25
+ const ctx = {
26
+ systemPrompt: {
27
+ section: (o) => reg.sections.push(o),
28
+ context: (o) => reg.contexts.push(o),
29
+ },
30
+ tools: {
31
+ register: (d) => reg.tools.push(d),
32
+ schemas: () => [{ name: "write" }, { name: "edit" }, { name: "read" }],
33
+ },
34
+ commands: { register: () => {} },
35
+ on: (ev, fn) => {
36
+ if (!reg.handlers.has(ev)) reg.handlers.set(ev, []);
37
+ reg.handlers.get(ev).push(fn);
38
+ },
39
+ llm: { stream: async function* () {} },
40
+ };
41
+ return { reg, ctx };
42
+ }
43
+
44
+ const cfg = { memoriesRoot: root, enabled: true, promptStyle: "native", writeEnabled: true };
45
+ const { reg, ctx } = makeCtx();
46
+ mod.apply(ctx, cfg);
47
+
48
+ const rulesSec = reg.sections.find((s) => s.name === "zcode-memory-rules");
49
+ const indexCtx = reg.contexts.find((c) => c.name === "zcode-memory");
50
+ check(!!rulesSec, "rules must be registered on the system channel (section)");
51
+ check(!!indexCtx, "index must be registered on the context channel");
52
+ check(!reg.contexts.some((c) => c.name === "zcode-memory-rules"), "rules must NOT be a user context snapshot");
53
+ // 基线(v0.11)只有一个注册,上面两条会失败:直接报错退出,别在 undefined 上崩。
54
+ if (!rulesSec || !indexCtx) {
55
+ console.error("FAIL prompt-split");
56
+ for (const f of fails) console.error(" -", f);
57
+ process.exit(1);
58
+ }
59
+
60
+ const session = { header: { id: "sess-split", cwd, createdAt: "2026-12-05T09:00:00.000Z", agentPreset: "standard" } };
61
+ const arg = () => ({ agent: { session } });
62
+ const rules = () => String(rulesSec.text(arg()));
63
+ const index = () => String(indexCtx.text(arg()));
64
+
65
+ // 1. 空库:规则段有 header + Notes,索引段为空(原生不注入空 Contents 块)。
66
+ {
67
+ const r = rules();
68
+ check(r.includes("# Memory\n"), "rules must carry the # Memory header", r.slice(0, 200));
69
+ check(r.includes("# Memory, notes and feedback"), "rules must carry the notes section");
70
+ check(!r.includes("Contents of "), "rules must not contain the index block");
71
+ check(index() === "", "empty index must not inject a context snapshot", index().slice(0, 200));
72
+ }
73
+
74
+ // 2. 写入后索引进 context,规则段文本保持逐字符不变(前缀缓存)。
75
+ const save = reg.tools.find((t) => t.name === "memory_save");
76
+ const exec = { agent: { session } };
77
+ const saved = await save.execute(
78
+ { title: "SplitFact", description: "split hook", type: "project", body: "split body", scope: "project" },
79
+ exec,
80
+ );
81
+ check(saved?.ok, "seed save failed", saved);
82
+ {
83
+ const rBefore = rules();
84
+ const iBefore = index();
85
+ check(iBefore.includes("Contents of "), "index context must contain the Contents block", iBefore.slice(0, 300));
86
+ check(iBefore.includes("SplitFact"), "index context must contain the saved entry");
87
+ check(!iBefore.includes("# Memory, notes and feedback"), "notes must not leak into the index context");
88
+ const idxFile = iBefore.match(/Contents of (.+?) \(/);
89
+ check(!!idxFile, "cannot locate MEMORY.md path in index block", iBefore.slice(0, 200));
90
+ if (idxFile) {
91
+ appendFileSync(idxFile[1], "- [AppendedFact](appended.md) — appended\n");
92
+ await new Promise((res) => setTimeout(res, 260));
93
+ const rAfter = rules();
94
+ const iAfter = index();
95
+ check(iAfter.includes("AppendedFact"), "index context must refresh after MEMORY.md change");
96
+ check(rAfter === rBefore, "rules text must stay byte-identical when the index changes");
97
+ check(rBefore.length > 500, "rules text unexpectedly short", rBefore.length);
98
+ }
99
+ }
100
+
101
+ // 3. agent memory:提示体在规则段,`## MEMORY.md` 在索引段。
102
+ {
103
+ const cwd2 = mkdtempSync(join(tmpdir(), "zcm-splitagent-"));
104
+ const agentDir = join(cwd2, ".zcode", "agent-memory", "reviewer");
105
+ mkdirSync(agentDir, { recursive: true });
106
+ writeFileSync(join(agentDir, "MEMORY.md"), "- [AgentFact](a.md) — agent hook\n");
107
+ const { reg: reg3, ctx: ctx3 } = makeCtx();
108
+ mod.apply(ctx3, {
109
+ memoriesRoot: root,
110
+ enabled: true,
111
+ promptStyle: "native",
112
+ agentMemoryEnabled: true,
113
+ agentMemoryScope: "project",
114
+ agentMemoryName: "reviewer",
115
+ });
116
+ const r3 = reg3.sections.find((s) => s.name === "zcode-memory-rules");
117
+ const i3 = reg3.contexts.find((c) => c.name === "zcode-memory");
118
+ const arg3 = { agent: { session: { header: { cwd: cwd2, agentPreset: "reviewer" } } } };
119
+ const rt = String(r3?.text(arg3));
120
+ const it = String(i3?.text(arg3));
121
+ check(rt.includes("# Persistent Agent Memory"), "agent prompt must be in the rules section");
122
+ check(!rt.includes("## MEMORY.md"), "agent index must not be in the rules section", rt.slice(-300));
123
+ check(it.includes("## MEMORY.md"), "agent index belongs to the context section");
124
+ check(it.includes("AgentFact"), "agent index must list the entry");
125
+ rmSync(cwd2, { recursive: true, force: true });
126
+ }
127
+
128
+ // 4. writeEnabled=false:规则只读,Notes 不注入;索引仍注入。
129
+ {
130
+ const { reg: reg4, ctx: ctx4 } = makeCtx();
131
+ mod.apply(ctx4, { memoriesRoot: root, enabled: true, promptStyle: "native", writeEnabled: false });
132
+ const r4 = String(reg4.sections.find((s) => s.name === "zcode-memory-rules")?.text(arg()));
133
+ const i4 = String(reg4.contexts.find((c) => c.name === "zcode-memory")?.text(arg()));
134
+ check(/Memory is read-only in this session/.test(r4), "read-only header missing", r4.slice(0, 200));
135
+ check(!r4.includes("# Memory, notes and feedback"), "notes must not appear when writeEnabled=false");
136
+ check(i4.includes("SplitFact"), "index should still be readable when write is disabled");
137
+ }
138
+
139
+ // 5. plugin 风格:中文指引在规则段,索引 + 日期在上下文段。
140
+ {
141
+ const { reg: reg5, ctx: ctx5 } = makeCtx();
142
+ mod.apply(ctx5, { memoriesRoot: root, enabled: true, promptStyle: "plugin" });
143
+ const r5 = String(reg5.sections.find((s) => s.name === "zcode-memory-rules")?.text(arg()));
144
+ const i5 = String(reg5.contexts.find((c) => c.name === "zcode-memory")?.text(arg()));
145
+ check(r5.includes("[ZCode 记忆]"), "plugin rules missing");
146
+ check(!r5.includes("### 项目记忆索引"), "plugin index must not be in the rules section");
147
+ check(!/今天是 \d{4}-\d{2}-\d{2}/.test(r5), "volatile date must not be in the system rules section");
148
+ check(i5.includes("### 项目记忆索引"), "plugin index missing from context");
149
+ check(/今天是 \d{4}-\d{2}-\d{2}/.test(i5), "plugin date belongs to the context section");
150
+ }
151
+
152
+ // 6. G8:无 cwd + user scope agent memory 仍要注入(规则与索引都不依赖 workspaceRoot);
153
+ // project/local 没有 cwd 则整段跳过(agentMemoryRoot 会回落到 process.cwd())。
154
+ {
155
+ const store = mkdtempSync(join(tmpdir(), "zcm-splitstore-"));
156
+ const agentDir = join(store, "agent-memory", "reviewer");
157
+ mkdirSync(agentDir, { recursive: true });
158
+ writeFileSync(join(agentDir, "MEMORY.md"), "- [UserScopeFact](u.md) — user scope hook\n");
159
+ const { reg: reg6, ctx: ctx6 } = makeCtx();
160
+ mod.apply(ctx6, {
161
+ memoriesRoot: root,
162
+ enabled: true,
163
+ promptStyle: "native",
164
+ agentMemoryEnabled: true,
165
+ agentMemoryScope: "user",
166
+ agentMemoryStorageRoot: store,
167
+ agentMemoryName: "reviewer",
168
+ });
169
+ const r6 = reg6.sections.find((s) => s.name === "zcode-memory-rules");
170
+ const i6 = reg6.contexts.find((c) => c.name === "zcode-memory");
171
+ const arg6 = { agent: { session: { header: { agentPreset: "reviewer" } } } };
172
+ const rt6 = String(r6?.text(arg6));
173
+ const it6 = String(i6?.text(arg6));
174
+ check(rt6.includes("# Persistent Agent Memory"), "no-cwd user scope must still get agent memory rules", rt6.slice(0, 200));
175
+ check(it6.includes("## MEMORY.md"), "no-cwd user scope must still get the agent memory index");
176
+ check(it6.includes("UserScopeFact"), "no-cwd user scope index must list entries");
177
+ check(!rt6.includes("# Memory\n"), "no-cwd must not inject a project Memory header", rt6.slice(0, 200));
178
+ check(!it6.includes("Contents of "), "no-cwd must not inject a project index block");
179
+
180
+ // project scope 无 cwd:整段跳过。
181
+ const { reg: reg7, ctx: ctx7 } = makeCtx();
182
+ mod.apply(ctx7, {
183
+ memoriesRoot: root,
184
+ enabled: true,
185
+ promptStyle: "native",
186
+ agentMemoryEnabled: true,
187
+ agentMemoryScope: "project",
188
+ agentMemoryName: "reviewer",
189
+ });
190
+ const rt7 = String(reg7.sections.find((s) => s.name === "zcode-memory-rules")?.text(arg6));
191
+ const it7 = String(reg7.contexts.find((c) => c.name === "zcode-memory")?.text(arg6));
192
+ check(!rt7.includes("# Persistent Agent Memory"), "project scope without cwd must be skipped");
193
+ check(!it7.includes("## MEMORY.md"), "project scope without cwd must not get an agent index");
194
+ rmSync(store, { recursive: true, force: true });
195
+ }
196
+
197
+ // 7. G6:native + injectGlobal:true 时 global 索引也要可见(并标注 global);
198
+ // injectGlobal:false(默认)时仍不注入,避免把 ZCode 永不加载的全局记忆当项目事实。
199
+ {
200
+ const globalDir = join(root, "global", "memory");
201
+ mkdirSync(globalDir, { recursive: true });
202
+ writeFileSync(join(globalDir, "MEMORY.md"), "- [GlobalFact](g.md) — global hook\n");
203
+ const { reg: reg8, ctx: ctx8 } = makeCtx();
204
+ mod.apply(ctx8, { memoriesRoot: root, enabled: true, promptStyle: "native", injectGlobal: true });
205
+ const i8 = String(reg8.contexts.find((c) => c.name === "zcode-memory")?.text(arg()));
206
+ check(i8.includes("GlobalFact"), "injectGlobal:true must expose the global index in native style", i8.slice(0, 400));
207
+ check(/scope="global"|global memory/i.test(i8), "global index must be labeled", i8.slice(0, 400));
208
+
209
+ const { reg: reg9, ctx: ctx9 } = makeCtx();
210
+ mod.apply(ctx9, { memoriesRoot: root, enabled: true, promptStyle: "native" });
211
+ const i9 = String(reg9.contexts.find((c) => c.name === "zcode-memory")?.text(arg()));
212
+ check(!i9.includes("GlobalFact"), "injectGlobal:false must not inject the global index", i9.slice(0, 400));
213
+ }
214
+
215
+ // 8. 复查 P2-A:plugin 规则段在「项目目录从无到有」时必须逐字符不变(目录行归索引段)。
216
+ {
217
+ const cwd8 = mkdtempSync(join(tmpdir(), "zcm-splitplugin-"));
218
+ const { reg: reg8p, ctx: ctx8p } = makeCtx();
219
+ mod.apply(ctx8p, { memoriesRoot: root, enabled: true, promptStyle: "plugin" });
220
+ const r8 = reg8p.sections.find((s) => s.name === "zcode-memory-rules");
221
+ const i8 = reg8p.contexts.find((c) => c.name === "zcode-memory");
222
+ const sess8 = { header: { id: "sess-plugin-stable", cwd: cwd8, createdAt: "2026-12-05T09:00:00.000Z" } };
223
+ const arg8 = { agent: { session: sess8 } };
224
+ const before = String(r8?.text(arg8));
225
+ const idxBefore = String(i8?.text(arg8));
226
+ check(!idxBefore.includes("项目记忆目录:"), "plugin index must not announce a project dir before it exists", idxBefore.slice(0, 300));
227
+ const save8 = reg8p.tools.find((t) => t.name === "memory_save");
228
+ const saved8 = await save8.execute(
229
+ { title: "PluginStable", description: "d", body: "b", scope: "project" },
230
+ { agent: { session: sess8 } },
231
+ );
232
+ check(saved8?.ok, "plugin seed save failed", saved8);
233
+ await new Promise((res) => setTimeout(res, 260));
234
+ const after = String(r8?.text(arg8));
235
+ const idxAfter = String(i8?.text(arg8));
236
+ check(after === before, "plugin rules must stay byte-identical when the project dir appears");
237
+ check(idxAfter.includes("项目记忆目录:"), "plugin index should now announce the project dir", idxAfter.slice(0, 300));
238
+ rmSync(cwd8, { recursive: true, force: true });
239
+ }
240
+
241
+ try {
242
+ rmSync(root, { recursive: true, force: true });
243
+ rmSync(cwd, { recursive: true, force: true });
244
+ } catch {
245
+ /* noop */
246
+ }
247
+
248
+ if (fails.length) {
249
+ console.error("FAIL prompt-split");
250
+ for (const f of fails) console.error(" -", f);
251
+ process.exit(1);
252
+ }
253
+ console.log("PASS prompt-split");
@@ -0,0 +1,225 @@
1
+ // P3(2026-12-05)召回归一化:
2
+ // 1. 单字段命中两字词必须召回(旧版绝对阈值 minScore=3 + 2-gram 0.45 → 必漏)。
3
+ // 2. 门槛按**相对匹配率**判定:字段权重/分词权重调整不再需要重算阈值。
4
+ // 3. 正文重复同一个词不加分:噪声条目不得压过精确标题命中。
5
+ // 4. 同义词单字键不再误扩(「判断」不该扩出 timeout/断网)。
6
+ // 5. 只靠扩展词命中的条目排序打折,真正含原词的记忆排前面。
7
+ // 6. 无关查询仍返回 0(不能为了召回率全放行)。
8
+ // 用法: node recall-score.mjs [index.js 路径]
9
+ import { pathToFileURL } from "node:url";
10
+ import { mkdtempSync, rmSync } from "node:fs";
11
+ import { tmpdir } from "node:os";
12
+ import { join } from "node:path";
13
+
14
+ const modUrl = process.argv[2] ? pathToFileURL(process.argv[2]).href : new URL("../index.js", import.meta.url).href;
15
+ const mod = await import(modUrl);
16
+
17
+ const fails = [];
18
+ const check = (cond, msg, extra) => {
19
+ if (!cond) fails.push(msg + (extra !== undefined ? ` :: ${JSON.stringify(extra).slice(0, 400)}` : ""));
20
+ };
21
+
22
+ function harness(extra = {}) {
23
+ const root = mkdtempSync(join(tmpdir(), "zcm-score-"));
24
+ const cwd = mkdtempSync(join(tmpdir(), "zcm-score-cwd-"));
25
+ const reg = { tools: [] };
26
+ const ctx = {
27
+ systemPrompt: { section: () => {}, context: () => {} },
28
+ tools: { register: (d) => reg.tools.push(d), schemas: () => [{ name: "write" }] },
29
+ commands: { register: () => {} },
30
+ on: () => {},
31
+ llm: { stream: async function* () {} },
32
+ };
33
+ mod.apply(ctx, { memoriesRoot: root, enabled: true, promptStyle: "native", ...extra });
34
+ const session = { header: { id: "sess-score", cwd, createdAt: "2026-12-05T11:00:00.000Z" } };
35
+ const exec = { agent: { session } };
36
+ const tool = (n) => reg.tools.find((t) => t.name === n);
37
+ return {
38
+ save: (a) => tool("memory_save").execute({ scope: "project", ...a }, exec),
39
+ recall: (q, topK = 3) => tool("memory_recall").execute({ query: q, topK }, exec),
40
+ cleanup: () => {
41
+ try {
42
+ rmSync(root, { recursive: true, force: true });
43
+ rmSync(cwd, { recursive: true, force: true });
44
+ } catch {
45
+ /* noop */
46
+ }
47
+ },
48
+ };
49
+ }
50
+
51
+ const blank = { title: "无关条目", name: "unrelated", description: "无关", body: "无关正文" };
52
+
53
+ // --- 1. 两字词只命中单一字段:四种字段都必须召回 ---
54
+ for (const field of ["title", "body", "name", "description"]) {
55
+ const h = harness();
56
+ const args = { ...blank };
57
+ if (field === "title") args.title = "掉线问题";
58
+ if (field === "body") args.body = "电脑掉线了怎么处理";
59
+ if (field === "name") args.name = "掉线";
60
+ if (field === "description") args.description = "掉线";
61
+ await h.save(args);
62
+ const r = await h.recall("掉线");
63
+ check((r?.matches || []).length === 1, `1: 仅 ${field} 含两字词「掉线」也必须召回`, r);
64
+ h.cleanup();
65
+ }
66
+
67
+ // --- 2. 英文单字段命中不回归 ---
68
+ for (const field of ["title", "body"]) {
69
+ const h = harness();
70
+ const args = { ...blank };
71
+ if (field === "title") args.title = "pnpm release";
72
+ if (field === "body") args.body = "发布用 pnpm release";
73
+ await h.save(args);
74
+ const r = await h.recall("pnpm");
75
+ check((r?.matches || []).length === 1, `2: 仅 ${field} 含英文词也必须召回`, r);
76
+ h.cleanup();
77
+ }
78
+
79
+ // --- 3. 噪声压精确:正文刷 8 次的条目不得排在精确标题命中之前 ---
80
+ {
81
+ const h = harness();
82
+ // 关键构型:精确条目的 pnpm **只在标题**,噪声条目从头到尾只在正文刷 8 次。
83
+ // (若精确条目的正文也含 pnpm,基线本来就能排第一,这条断言就没有判别力。)
84
+ await h.save({ title: "发布命令 pnpm 用法", name: "release-cmd", description: "发布用", body: "发布命令见上文。" });
85
+ await h.save({
86
+ title: "杂项日志",
87
+ name: "noise-log",
88
+ description: "杂项",
89
+ body: Array.from({ length: 8 }, (_, i) => `第 ${i + 1} 次尝试 pnpm 安装都失败了`).join("\n") + "\n" + "填充".repeat(200),
90
+ });
91
+ const r = await h.recall("pnpm");
92
+ const names = (r?.matches || []).map((m) => m.name);
93
+ check(names[0] === "release-cmd", "3: 正文刷 8 次的噪声条目不得压过精确标题命中", names);
94
+ h.cleanup();
95
+ }
96
+
97
+ // --- 4. 同义词单字键不再误扩:判断/逻辑 不得召回断网记忆 ---
98
+ {
99
+ const h = harness();
100
+ await h.save({ title: "Oppo 互联断网", name: "oppo-net", description: "断网", body: "断网排查:timeout、掉线、disconnect。" });
101
+ await h.save({ title: "代理 2080", name: "proxy-2080", description: "网络代理", body: "代理端口 2080,连不上时检查。" });
102
+ const r = await h.recall("判断一下这个逻辑对不对");
103
+ check((r?.matches || []).length === 0, "4: 「判断一下这个逻辑对不对」不得召回断网/网络记忆", r?.matches?.map((m) => m.name));
104
+ h.cleanup();
105
+ }
106
+
107
+ // --- 5. 只靠扩展词命中的条目排序打折:含原词的记忆排第一;同时扩展仍能召回 ---
108
+ {
109
+ const h = harness();
110
+ await h.save({ title: "TUN 断网根因", name: "tun-net", description: "断网根因", body: "断网是 vgate0 导致的。" });
111
+ await h.save({
112
+ title: "USB 驱动杂记",
113
+ name: "usb-note",
114
+ description: "adb 掉线多为绑错 INF",
115
+ body: "fastboot 掉线、timeout 重连都可以先查驱动。",
116
+ });
117
+ const r = await h.recall("断网");
118
+ const names = (r?.matches || []).map((m) => m.name);
119
+ check(names[0] === "tun-net", "5: 真正含「断网」的记忆必须排第一(扩展命中不打折会把它挤下去)", names);
120
+ check(names.includes("usb-note"), "5: 扩展词仍需保证召回(掉线/timeout 命中的条目不能丢)", names);
121
+ h.cleanup();
122
+ }
123
+
124
+ // --- 6. 无关查询返回 0 ---
125
+ {
126
+ const h = harness();
127
+ await h.save({ title: "发布命令", name: "rel", description: "发布", body: "pnpm release" });
128
+ const r = await h.recall("zzzqqq");
129
+ check((r?.matches || []).length === 0, "6: 无关查询不得召回任何记忆", r?.matches?.map((m) => m.name));
130
+ h.cleanup();
131
+ }
132
+
133
+ // --- 7. 中文口语 6 例:不低于基线的 3/6 ---
134
+ {
135
+ const h = harness();
136
+ await h.save({ title: "笔记本变慢卡顿", name: "laptop-slow", description: "电脑用久了卡", body: "电脑用久了变慢卡顿,先看后台进程和温度。" });
137
+ await h.save({ title: "手机连不上电脑", name: "phone-usb", description: "传文件失败", body: "USB 驱动绑错 INF 会导致 adb 掉线,删设备节点重扫。" });
138
+ await h.save({ title: "微信输入框方块", name: "wechat-box", description: "中文变方块", body: "输入框里 ASCII 变方块,长报告改发 txt。" });
139
+ const queries = [
140
+ "电脑用久了变慢卡顿怎么办",
141
+ "手机连不上电脑传不了文件",
142
+ "微信输入框里英文变成方块",
143
+ "怎么把项目发布出去",
144
+ "记忆文件存在哪个目录",
145
+ "装插件以后工具变少了",
146
+ ];
147
+ let hit = 0;
148
+ for (const q of queries) {
149
+ const r = await h.recall(q);
150
+ if ((r?.matches || []).length > 0) hit++;
151
+ }
152
+ check(hit >= 3, `7: 中文口语命中数不得低于基线的 3/6(实际 ${hit})`);
153
+ h.cleanup();
154
+ }
155
+
156
+ // --- 8. 门槛语义:minScore 是绝对分下限;minMatchRatio 是「字段覆盖率」 ---
157
+ // 覆盖率的分母只累加命中 token,所以单字段命中最低就是 3/5=0.6:默认 0.5 等价于
158
+ // 「至少一个字段命中」,调到 0.61 才会把纯正文命中过滤掉(这是它的实际语义)。
159
+ {
160
+ const h = harness({ minScore: 100 });
161
+ await h.save({ title: "门槛探针", name: "gate", description: "门槛", body: "门槛探针正文" });
162
+ const r = await h.recall("门槛探针");
163
+ check((r?.matches || []).length === 0, "8a: minScore=100 时任何结果都不该返回", r?.matches?.map((m) => m.name));
164
+ h.cleanup();
165
+ }
166
+ {
167
+ const h = harness({ minMatchRatio: 0.61 });
168
+ await h.save({ title: "无关条目", name: "body-only", description: "无关", body: "只有正文提到掉线" });
169
+ const r = await h.recall("掉线");
170
+ check((r?.matches || []).length === 0, "8b: 覆盖率 0.61 应过滤掉「仅正文命中」", r?.matches?.map((m) => m.name));
171
+ h.cleanup();
172
+ }
173
+ {
174
+ const h = harness({ minMatchRatio: 0.55 });
175
+ await h.save({ title: "无关条目", name: "body-only", description: "无关", body: "只有正文提到掉线" });
176
+ const r = await h.recall("掉线");
177
+ check((r?.matches || []).length === 1, "8c: 覆盖率 0.55 应保留「仅正文命中」(0.6≥0.55)", r?.matches?.map((m) => m.name));
178
+ h.cleanup();
179
+ }
180
+
181
+ // --- 9. 口语里被夹在汉字中间的单字(变慢/很卡/太卡了)仍要能召回 ---
182
+ // 单字键只在独立出现时扩展,这些说法靠双字键覆盖;缺一个就会比 v0.12 更难召回。
183
+ {
184
+ const h = harness();
185
+ await h.save({ title: "电脑卡顿排查", name: "lagfix", description: "性能问题", body: "先看后台进程和温度。" });
186
+ for (const q of ["变慢", "很慢", "太慢", "很卡", "太卡了"]) {
187
+ const r = await h.recall(q);
188
+ check((r?.matches || []).length > 0, `9: 「${q}」必须能召回卡顿记忆`, r?.matches?.map((m) => m.name));
189
+ }
190
+ h.cleanup();
191
+ }
192
+
193
+ // --- 10. 反向假阳性:查询「掉线」不得召回只在讲「判断」的记忆 ---
194
+ {
195
+ const h = harness();
196
+ await h.save({ title: "判断逻辑说明", name: "judge-logic", description: "代码评审", body: "先判断这个逻辑对不对,再看边界。" });
197
+ await h.save({ title: "掉线排查", name: "drop-line", description: "网络", body: "掉线先看 timeout 和网线。" });
198
+ const r = await h.recall("掉线");
199
+ const names = (r?.matches || []).map((m) => m.name);
200
+ check(!names.includes("judge-logic"), "10: 「掉线」不得召回「判断」记忆(单字扩展值已移除)", names);
201
+ check(names.includes("drop-line"), "10: 真正讲掉线的记忆仍要召回", names);
202
+ h.cleanup();
203
+ }
204
+
205
+ // --- 11. 正文窗口:长正文要「头 + 尾」两段(单窗只给开头会把结尾的结论切掉) ---
206
+ // 注意:n=2500 覆盖不了 5000 字正文的全部,中段仍要靠 memory_read;这里锁的是
207
+ // 「命中在开头、结论在结尾」这个最常见的组合。
208
+ {
209
+ const h = harness();
210
+ const body = "pnpm 是包管理器。" + "F".repeat(4000) + "\nANSWER-TAIL 产物在 dist 目录。";
211
+ await h.save({ title: "窗口探针 pnpm", name: "window-probe", description: "w", body });
212
+ const r = await h.recall("pnpm");
213
+ const kept = r?.matches?.[0]?.body || "";
214
+ check(kept.includes("pnpm"), "11: 头段必须保留命中词", kept.slice(0, 120));
215
+ check(kept.includes("ANSWER-TAIL"), "11: 长正文尾部的结论不能被窗口切掉", kept.slice(-200));
216
+ check(kept.includes("略去中段"), "11: 应标注中段省略", kept.slice(0, 200));
217
+ h.cleanup();
218
+ }
219
+
220
+ if (fails.length) {
221
+ console.error("FAIL recall-score");
222
+ for (const f of fails) console.error(" -", f);
223
+ process.exit(1);
224
+ }
225
+ console.log("PASS recall-score");