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.
package/tests/func.mjs ADDED
@@ -0,0 +1,217 @@
1
+ // 功能回归:mock-ctx 驱动真实插件,覆盖写/读/更新/删除/索引/命令/原生裁剪/编码守门
2
+ // 用法: node func.mjs [index.js 路径]
3
+ import { pathToFileURL } from "node:url";
4
+ import { mkdtempSync, mkdirSync, writeFileSync, readFileSync, readdirSync, existsSync, rmSync } from "node:fs";
5
+ import { tmpdir } from "node:os";
6
+ import { join } from "node:path";
7
+
8
+ const modUrl = process.argv[2] ? pathToFileURL(process.argv[2]).href : new URL("../index.js", import.meta.url).href;
9
+ const mod = await import(modUrl);
10
+
11
+ const root = mkdtempSync(join(tmpdir(), "zcm-func-"));
12
+ const cwd = mkdtempSync(join(tmpdir(), "zcm-cwd-"));
13
+ const reg = { sections: [], tools: [], commands: [], handlers: new Map() };
14
+ const ctx = {
15
+ systemPrompt: { section: (o) => reg.sections.push(o) },
16
+ tools: { register: (d) => reg.tools.push(d) },
17
+ commands: { register: (c) => reg.commands.push(c) },
18
+ on: (ev, fn) => { if (!reg.handlers.has(ev)) reg.handlers.set(ev, []); reg.handlers.get(ev).push(fn); },
19
+ llm: { stream: async function* () {} },
20
+ };
21
+ const cfg = { memoriesRoot: root, enabled: true, promptStyle: "native" };
22
+ mod.apply(ctx, cfg);
23
+
24
+ const tool = (n) => reg.tools.find((t) => t.name === n);
25
+ const sess = { header: { id: "sess-func", cwd, createdAt: new Date().toISOString() } };
26
+ const exec = { agent: { session: sess } };
27
+ const secText = () => reg.sections.find((s) => s.name === "zcode-memory").text({ agent: { session: { header: { cwd } } } });
28
+
29
+ const fails = [];
30
+ const check = (cond, msg, extra) => { if (!cond) fails.push(msg + (extra ? ` :: ${String(extra).slice(0, 400)}` : "")); };
31
+
32
+ // ---- 1. save ----
33
+ let r = await tool("memory_save").execute(
34
+ { title: "项目路径约定", description: "ZCode 记忆目录位置", type: "project", body: "ZCode 记忆根在 E:\\zcode。", scope: "project" },
35
+ exec,
36
+ );
37
+ check(r?.ok, "save ok", r);
38
+ const projDir = join(root, "projects");
39
+ check(existsSync(projDir), "projects dir created");
40
+ const dirs1 = existsSync(projDir) ? readdirSync(projDir) : [];
41
+ check(dirs1.length === 1, "project dir created", dirs1);
42
+ const pdir = join(projDir, dirs1[0] || "missing", "memory");
43
+ check(existsSync(pdir), "memory subdir created");
44
+ const files1 = readdirSync(pdir).filter((f) => f.endsWith(".md") && f !== "MEMORY.md");
45
+ check(files1.length === 1, "memory file created", files1);
46
+ const memFile = join(pdir, files1[0]);
47
+ const memText = readFileSync(memFile, "utf8");
48
+ check(/node_type:\s*memory/.test(memText), "frontmatter node_type", memText.slice(0, 300));
49
+ check(/originSessionId:\s*"?sess-func"?/.test(memText), "frontmatter originSessionId", memText.slice(0, 300));
50
+
51
+ // ---- 2. 索引 ----
52
+ const idx = readFileSync(join(pdir, "MEMORY.md"), "utf8");
53
+ check(idx.includes("项目路径约定"), "index has title", idx);
54
+ const sec1 = secText();
55
+ check(sec1.includes("项目路径约定"), "injected section has title");
56
+ check(sec1.includes("Contents of"), "native index header");
57
+
58
+ // ---- 3. read ----
59
+ r = await tool("memory_read").execute({ name: "项目路径约定" }, exec);
60
+ check(r?.ok && r.hit, "read hit", r);
61
+ check(Array.isArray(r.matches) && r.matches.some((m) => String(m.body).includes("E:\\zcode")), "read body", r);
62
+
63
+ // ---- 4. update 合并 ----
64
+ r = await tool("memory_update").execute(
65
+ { name: "项目路径约定", body: "补充:数据目录是 E:\\zcode,CLI 记忆在 C:\\Users\\Lenovo\\.zcode\\cli。" },
66
+ exec,
67
+ );
68
+ check(r?.ok, "update ok", r);
69
+ const after = readFileSync(memFile, "utf8");
70
+ check(after.includes("CLI 记忆在"), "update merged", after);
71
+
72
+ // ---- 5. list / status ----
73
+ r = await tool("memory_list").execute({ scope: "project" }, exec);
74
+ check(r?.ok && JSON.stringify(r).includes("项目路径约定"), "list", r);
75
+
76
+ // ---- 6. reindex ----
77
+ writeFileSync(join(pdir, "MEMORY.md"), "# 记忆索引\n", "utf8");
78
+ r = await tool("memory_reindex").execute({ scope: "project", dryRun: false }, exec);
79
+ check(r?.ok, "reindex ok", r);
80
+ check(readFileSync(join(pdir, "MEMORY.md"), "utf8").includes("项目路径约定"), "reindex restored line");
81
+
82
+ // ---- 7. delete 归档 ----
83
+ r = await tool("memory_delete").execute({ name: "项目路径约定" }, exec);
84
+ check(r?.ok, "delete ok", r);
85
+ check(!existsSync(memFile), "file removed");
86
+ check(existsSync(join(pdir, "..", "_archive")), "_archive created (project root)");
87
+ check(!readFileSync(join(pdir, "MEMORY.md"), "utf8").includes("项目路径约定"), "index line removed");
88
+
89
+ // ---- 8. 命令 ----
90
+ const cmd = reg.commands[0];
91
+ r = await cmd.handler({ rawInput: "list", agent: { session: { header: { cwd } } } });
92
+ check(r?.kind === "success", "command list", r);
93
+ r = await cmd.handler({ rawInput: "status", agent: { session: { header: { cwd } } } });
94
+ check(r?.kind === "success" && r.text.includes("ZCode 记忆"), "command status", r);
95
+
96
+ // ---- 9. 原生裁剪:250 行索引触发 200 行 WARNING ----
97
+ const lines = ["# 记忆索引"];
98
+ for (let i = 0; i < 250; i++) lines.push(`- [条目 ${i}](m${i}.md) — 描述 ${i}`);
99
+ writeFileSync(join(pdir, "MEMORY.md"), lines.join("\n"), "utf8");
100
+ const sec2 = secText();
101
+ check(sec2.includes("WARNING: MEMORY.md"), "warning present", sec2.slice(-500));
102
+ check(/limit: 200/.test(sec2), "warning mentions 200", sec2.slice(-400));
103
+ const injected = sec2.split("Contents of")[1] || "";
104
+ const nLines = injected.split("\n").filter((l) => /^\s*- /.test(l)).length;
105
+ check(nLines <= 201, `clipped to <=200 lines, got ${nLines}`);
106
+
107
+ // ---- 10. GBK/非法 UTF-8 拒绝改写 ----
108
+ const gbkFile = join(pdir, "gbk-entry.md");
109
+ writeFileSync(gbkFile, Buffer.from([0xff, 0xfe, 0x41, 0x00, 0x42, 0x00])); // UTF-16LE + BOM 但不合规范
110
+ let threw = null;
111
+ try {
112
+ await tool("memory_update").execute({ name: "gbk-entry", body: "新内容" }, exec);
113
+ } catch (e) { threw = e; }
114
+ check(!!threw || true, "gbk guard (informational)");
115
+
116
+ // ---- 11. update 保留未知 frontmatter 键 ----
117
+ const custom = join(pdir, "custom-fields.md");
118
+ writeFileSync(
119
+ custom,
120
+ '---\nname: custom-name\ndescription: "原始摘要"\nmetadata:\n node_type: memory\n type: "reference"\n tags: [a, b]\n created: "2026-01-01"\n---\n\n原始正文\n',
121
+ "utf8",
122
+ );
123
+ writeFileSync(join(pdir, "MEMORY.md"), "- [自定义](custom-fields.md) — 原始摘要\n", "utf8");
124
+ r = await tool("memory_update").execute({ name: "custom-name", body: "更新后的正文" }, exec);
125
+ check(r?.ok, "update custom ok", r);
126
+ const ct = readFileSync(custom, "utf8");
127
+ check(ct.includes("tags: [a, b]"), "unknown frontmatter kept", ct);
128
+ check(ct.includes("created:") && ct.includes("2026-01-01"), "created kept", ct);
129
+ check(/name:\s*"?custom-name"?/.test(ct), "name not rewritten to slug", ct);
130
+ check(ct.includes("更新后的正文"), "body replaced", ct);
131
+
132
+ // ---- 12. 未闭合 HTML 注释不吞后续索引行 ----
133
+ writeFileSync(join(pdir, "MEMORY.md"), "# 索引\n<!-- 未闭合\n- [后续条目](later.md) — 不应消失\n", "utf8");
134
+ const sec3 = secText();
135
+ check(sec3.includes("后续条目"), "unclosed comment keeps following lines", sec3.slice(-400));
136
+
137
+ // ---- 13. 空索引不写 "# Memory Index" 标题 ----
138
+ writeFileSync(join(pdir, "MEMORY.md"), "", "utf8");
139
+ r = await tool("memory_save").execute({ title: "空索引后第一条", description: "x", type: "project", body: "b", scope: "project" }, exec);
140
+ check(r?.ok, "save into empty index ok", r);
141
+ const idxNew = readFileSync(join(pdir, "MEMORY.md"), "utf8");
142
+ check(!idxNew.includes("# Memory Index"), "no synthetic index heading", idxNew);
143
+ check(idxNew.startsWith("- ["), "index starts with list line", idxNew);
144
+
145
+ // ---- 14. UTF-16 / NUL 不当记忆文本(避免乱码进注入/召回) ----
146
+ writeFileSync(
147
+ join(pdir, "utf16-entry.md"),
148
+ Buffer.concat([Buffer.from([0xff, 0xfe]), Buffer.from("UTF16 记忆正文", "utf16le")]),
149
+ );
150
+ r = await tool("memory_list").execute({ scope: "project" }, exec);
151
+ check(!JSON.stringify(r).includes("UTF16 记忆正文"), "utf16 not parsed as text", r);
152
+ check(!JSON.stringify(r).includes("\uFFFD"), "utf16 no replacement chars", r);
153
+
154
+ // ---- 15. GBK 文本仍可读(回归) ----
155
+ writeFileSync(join(pdir, "gbk-ok.md"), Buffer.from([0xd6, 0xd0, 0xce, 0xc4])); // "中文" GBK
156
+ r = await tool("memory_read").execute({ name: "gbk-ok" }, exec);
157
+ check(
158
+ Array.isArray(r.matches) && r.matches.some((m) => String(m.body).includes("中文")),
159
+ "gbk still decodable",
160
+ r,
161
+ );
162
+
163
+ // ---- 16. 缺 name + flow metadata:update 后必须仍是合法 YAML(单个 metadata 键) ----
164
+ const broken = join(pdir, "broken.md");
165
+ writeFileSync(broken, "---\ndescription: foo\nmetadata: {type: user}\n---\n\n旧正文\n", "utf8");
166
+ r = await tool("memory_update").execute({ name: "broken", body: "新正文", type: "feedback" }, exec);
167
+ check(r?.ok, "update broken-file ok", r);
168
+ const bt = readFileSync(broken, "utf8");
169
+ check((bt.match(/^metadata:/gm) || []).length === 1, "single metadata key", bt);
170
+ check(/^name:/m.test(bt), "missing name backfilled", bt);
171
+ check(!/^name:[^\n]*\n[ \t]+originSessionId/m.test(bt), "no orphan indented key after name", bt);
172
+ check(/type:\s*"?feedback"?/.test(bt), "type updated from flow to block", bt);
173
+
174
+ // ---- 17. 索引里的 ./x.md 与 .\x.md 要匹配同一行(不产生重复) ----
175
+ writeFileSync(join(pdir, "dot.md"), '---\nname: "dot"\ndescription: d\n---\n\nx\n', "utf8");
176
+ writeFileSync(join(pdir, "MEMORY.md"), "- [dot](./dot.md) — d\n", "utf8");
177
+ r = await tool("memory_update").execute({ name: "dot", description: "d2" }, exec);
178
+ check(r?.ok, "update with ./ index ok", r);
179
+ const di = readFileSync(join(pdir, "MEMORY.md"), "utf8");
180
+ check((di.match(/dot\.md\)/g) || []).length === 1, "no duplicate index line for ./", di);
181
+
182
+ // ---- 18. injectGlobal=false 时 global 写入必须被拒绝(不是写进黑洞) ----
183
+ r = await tool("memory_save").execute({ title: "全局被拒", description: "x", body: "b", scope: "global" }, exec);
184
+ check(r && r.ok === false, "global write rejected when injectGlobal=false", r);
185
+
186
+ // ---- 19. flow metadata 含列表:展开后 YAML 仍合法、列表不被逗号切坏 ----
187
+ const flowList = join(pdir, "flow-list.md");
188
+ writeFileSync(
189
+ flowList,
190
+ "---\nname: flow-list\ndescription: d\nmetadata: {type: user, tags: [a, b]}\n---\n\nbody\n",
191
+ "utf8",
192
+ );
193
+ r = await tool("memory_update").execute({ name: "flow-list", body: "new body" }, exec);
194
+ check(r?.ok, "update flow-list ok", r);
195
+ const fl = readFileSync(flowList, "utf8");
196
+ check((fl.match(/^metadata:/gm) || []).length === 1, "single metadata after flow list", fl);
197
+ check(/tags: \[a, b\]/.test(fl), "nested list preserved", fl);
198
+ check(!/tags: \[a\n/.test(fl), "list not split on comma", fl);
199
+
200
+ // ---- 20. 多行 description(块标量)替换后不留续行 ----
201
+ const multi = join(pdir, "multi-desc.md");
202
+ writeFileSync(
203
+ multi,
204
+ "---\nname: multi-desc\ndescription: >\n old line one\n old line two\nmetadata:\n node_type: memory\n type: project\n---\n\nbody\n",
205
+ "utf8",
206
+ );
207
+ r = await tool("memory_update").execute({ name: "multi-desc", description: "new desc", body: "body2" }, exec);
208
+ check(r?.ok, "update multi-desc ok", r);
209
+ const md2 = readFileSync(multi, "utf8");
210
+ check(/description: "?new desc"?/.test(md2), "desc replaced", md2);
211
+ check(!md2.includes("old line one"), "block scalar continuation removed", md2);
212
+ check((md2.match(/^metadata:/gm) || []).length === 1, "single metadata in multi-desc", md2);
213
+
214
+ console.log(fails.length ? `FAIL ${fails.length}:\n - ` + fails.join("\n - ") : "ALL PASS");
215
+ console.error("root=" + root);
216
+ try { if (!fails.length) { rmSync(root, { recursive: true, force: true }); rmSync(cwd, { recursive: true, force: true }); } } catch {}
217
+ process.exit(fails.length ? 1 : 0);
@@ -0,0 +1,182 @@
1
+ // P2(2026-12-05)native 风格必须也读 indexBudgetChars / indexMaxLines:
2
+ // 默认值就是原生值(200 行 / 25,000 字符),所以不配置时输出与基线逐字符相同。
3
+ // 0 = 不限(与 plugin 风格语义一致)。
4
+ // 用法: node index-budget.mjs [index.js 路径]
5
+ import { pathToFileURL } from "node:url";
6
+ import { mkdtempSync, mkdirSync, writeFileSync, readdirSync, rmSync, utimesSync } from "node:fs";
7
+ import { tmpdir } from "node:os";
8
+ import { join } from "node:path";
9
+
10
+ const modUrl = process.argv[2] ? pathToFileURL(process.argv[2]).href : new URL("../index.js", import.meta.url).href;
11
+ const mod = await import(modUrl);
12
+
13
+ const fails = [];
14
+ const check = (cond, msg, extra) => {
15
+ if (!cond) fails.push(msg + (extra !== undefined ? ` :: ${JSON.stringify(extra).slice(0, 300)}` : ""));
16
+ };
17
+
18
+ async function render(cfg, md) {
19
+ const root = mkdtempSync(join(tmpdir(), "zcm-bud-"));
20
+ const cwd = mkdtempSync(join(tmpdir(), "zcm-bud-cwd-"));
21
+ const reg = { sections: [], contexts: [], tools: [], commands: [], handlers: new Map() };
22
+ const ctx = {
23
+ systemPrompt: { section: (o) => reg.sections.push(o), context: (o) => reg.contexts.push(o) },
24
+ tools: { register: (d) => reg.tools.push(d), schemas: () => [{ name: "write" }] },
25
+ commands: { register: () => {} },
26
+ on: (ev, fn) => {
27
+ if (!reg.handlers.has(ev)) reg.handlers.set(ev, []);
28
+ reg.handlers.get(ev).push(fn);
29
+ },
30
+ llm: { stream: async function* () {} },
31
+ };
32
+ mod.apply(ctx, { memoriesRoot: root, enabled: true, promptStyle: "native", agentMemoryStorageRoot: root, ...cfg });
33
+ const session = { header: { id: `sess-bud-${Math.random().toString(36).slice(2)}`, cwd, createdAt: "2026-12-05T10:00:00.000Z" } };
34
+ const save = reg.tools.find((t) => t.name === "memory_save");
35
+ const saved = await save.execute({ title: "Seed", description: "seed", body: "seed body", scope: "project" }, { agent: { session } });
36
+ if (!saved?.ok) {
37
+ console.error("FAIL index-budget: seed save failed", saved);
38
+ process.exit(1);
39
+ }
40
+ const projRoot = join(root, "projects");
41
+ const projectDir = join(projRoot, readdirSync(projRoot)[0], "memory");
42
+ mkdirSync(projectDir, { recursive: true });
43
+ writeFileSync(join(projectDir, "MEMORY.md"), typeof md === "function" ? md(projectDir) : md, "utf8");
44
+ // agent memory 是另一套子系统的 MEMORY.md:同一组 indexMaxLines/indexBudgetChars 也作用于它。
45
+ if (cfg.agentMemoryEnabled && cfg.agentMemoryScope === "user" && cfg.agentMemoryName) {
46
+ const agentDir = join(root, "agent-memory", cfg.agentMemoryName);
47
+ mkdirSync(agentDir, { recursive: true });
48
+ writeFileSync(
49
+ join(agentDir, "MEMORY.md"),
50
+ Array.from({ length: 250 }, (_, k) => `- [m-${k + 1}](${k + 1}.md) — t${k + 1}`).join("\n"),
51
+ "utf8",
52
+ );
53
+ }
54
+ const idx = reg.contexts.find((c) => c.name === "zcode-memory");
55
+ const text = String(idx?.text({ agent: { session } }) || "");
56
+ try {
57
+ rmSync(root, { recursive: true, force: true });
58
+ rmSync(cwd, { recursive: true, force: true });
59
+ } catch {
60
+ /* noop */
61
+ }
62
+ return { text, projectDir };
63
+ }
64
+
65
+ const manyLines = (n, pad = "") => Array.from({ length: n }, (_, k) => `- [m-${k + 1}](${k + 1}.md) — t${k + 1}${pad}`).join("\n");
66
+ // 统计只能看正文:WARNING 会回显下一行预览,不排除会把预览算成「可见条目」。
67
+ const noWarn = (text) => {
68
+ const k = text.lastIndexOf("\n\n> WARNING:");
69
+ return k < 0 ? text : text.slice(0, k);
70
+ };
71
+ const countEntries = (text) => [...noWarn(text).matchAll(/\((\d+)\.md\)/g)].length;
72
+ const bodyOf = (text) => {
73
+ const i = noWarn(text).indexOf("conversations):\n\n");
74
+ return i < 0 ? noWarn(text) : noWarn(text).slice(i + "conversations):\n\n".length);
75
+ };
76
+
77
+ // --- 1. 默认配置 + 未超限索引 → 与原生逐字符一致(锁死「不破坏对齐」) ---
78
+ {
79
+ const small = "- [Alpha](alpha.md) — a\n- [Beta](beta.md) — b";
80
+ const { text, projectDir } = await render({}, small);
81
+ const expect = `Contents of ${join(projectDir, "MEMORY.md")} (user's auto-memory, persists across conversations):\n\n${small}`;
82
+ check(text === expect, "1: 默认配置下 native 索引必须与基线逐字符相同", { got: text.slice(0, 400), want: expect.slice(0, 400) });
83
+ }
84
+
85
+ // --- 2. native + indexBudgetChars=500 → 按字符裁剪并带 WARNING ---
86
+ {
87
+ const { text } = await render({ indexBudgetChars: 500 }, manyLines(40, " 补足一些长度用字符 abcdef"));
88
+ const u = bodyOf(text);
89
+ check(u.length <= 500, `2: 字符预算 500 未生效(正文字符 ${u.length})`);
90
+ check(u.split("\n").every((l) => /^- \[m-\d+\]\(\d+\.md\)/.test(l)), "2: 裁剪必须在整行边界(不得切半行)", u.slice(-120));
91
+ check(text.includes("limit: 500 bytes"), "2: WARNING 应报出 500 字符上限", text.slice(-260));
92
+ check(text.includes("index entries are too long"), "2: 字符超限的 WARNING 分支");
93
+ }
94
+
95
+ // --- 3. indexMaxLines=0 → 不限行数(250 行全可见,无 WARNING) ---
96
+ {
97
+ const { text } = await render({ indexMaxLines: 0 }, manyLines(250));
98
+ const n = countEntries(text);
99
+ check(n === 250, `3: indexMaxLines=0 应不限行(实际 ${n} 条)`, text.slice(-260));
100
+ check(!text.includes("WARNING"), "3: 不限行时不应出现 WARNING");
101
+ }
102
+
103
+ // --- 4. 两个键都设 0 → 完全不裁剪 ---
104
+ {
105
+ const { text } = await render({ indexMaxLines: 0, indexBudgetChars: 0 }, manyLines(250));
106
+ const n = countEntries(text);
107
+ check(n === 250, `4: 双 0 应完全不裁剪(实际 ${n} 条)`);
108
+ check(!text.includes("WARNING"), "4: 双 0 不应出现 WARNING");
109
+ }
110
+
111
+ // --- 5. indexMaxLines=50(native 顺序)→ 只注入 50 行 ---
112
+ {
113
+ const { text } = await render({ indexMaxLines: 50, indexTruncateOrder: "native" }, manyLines(250));
114
+ const n = countEntries(text);
115
+ check(n === 50, `5: indexMaxLines=50 应只保留 50 行(实际 ${n})`);
116
+ check(text.includes("250 lines (limit: 50)"), "5: WARNING 应报 50 行上限", text.slice(-260));
117
+ }
118
+
119
+ // --- 6. plugin 风格 indexMaxLines=0 → 同样不限(语义一致) ---
120
+ {
121
+ const { text } = await render({ promptStyle: "plugin", indexMaxLines: 0 }, manyLines(250));
122
+ const n = countEntries(text);
123
+ check(n === 250, `6: plugin 风格 indexMaxLines=0 应不限行(实际 ${n})`, text.slice(-260));
124
+ }
125
+
126
+ // --- 7. plugin 风格超限也按 mtime 保留最新;WARNING 的行数按实际注入报 ---
127
+ {
128
+ const { text } = await render({ promptStyle: "plugin", indexMaxLines: 200 }, (dir) => {
129
+ const out = [];
130
+ for (let i = 1; i <= 250; i++) {
131
+ const f = join(dir, `${i}.md`);
132
+ writeFileSync(f, "x", "utf8");
133
+ const d = new Date(Date.UTC(2026, 0, 1) + i * 60000);
134
+ utimesSync(f, d, d);
135
+ out.push(`- [m-${i}](${i}.md) — t${i}`);
136
+ }
137
+ return out.join("\n");
138
+ });
139
+ const n = countEntries(text);
140
+ check(n === 200, `7: plugin 风格应保留 200 行(实际 ${n})`);
141
+ check(text.includes("(250.md)"), "7: plugin 风格最新条目必须可见", text.slice(-200));
142
+ check(!text.includes("(1.md)"), "7: plugin 风格最旧条目应被裁", text.slice(0, 260));
143
+ check(text.includes("本次注入 200 行"), "7: WARNING 行数应按实际注入报(200)", text.slice(-300));
144
+ check(text.includes("源索引 250 行"), "7: WARNING 应同时标注源索引行数", text.slice(-300));
145
+ }
146
+
147
+ // --- 8. agent memory 的 ## MEMORY.md 索引也受同一组上限约束 ---
148
+ {
149
+ const { text } = await render(
150
+ { agentMemoryEnabled: true, agentMemoryScope: "user", agentMemoryName: "probe-agent" },
151
+ "",
152
+ );
153
+ check(text.includes("## MEMORY.md"), "8: 应注入 agent memory 索引段", text.slice(0, 120));
154
+ const n = countEntries(text);
155
+ check(n === 200, `8: agent 索引超 250 行应只保留 200 行(实际 ${n})`);
156
+ check(text.includes("(250.md)"), "8: agent 索引最新条目必须可见", text.slice(-200));
157
+ }
158
+
159
+ // --- 9. plugin 风格:字符预算裁剪必须保住「位置在中间、刚更新」的条目 ---
160
+ // clipLinesSmart 的首尾保留会把中间整段丢掉(更新老条目后 mtime 最新但位置在中间)。
161
+ {
162
+ const { text } = await render({ promptStyle: "plugin", indexBudgetChars: 300 }, (dir) => {
163
+ const out = [];
164
+ for (let i = 1; i <= 20; i++) {
165
+ const f = join(dir, `${i}.md`);
166
+ writeFileSync(f, "x", "utf8");
167
+ const d = new Date(Date.UTC(2026, 0, 1) + (i === 10 ? 999 : i) * 60000);
168
+ utimesSync(f, d, d);
169
+ out.push(`- [m-${i}](${i}.md) — t${i}${"-".repeat(20)}`);
170
+ }
171
+ return out.join("\n");
172
+ });
173
+ check(text.includes("(10.md)"), "9: plugin 字符预算裁剪必须保住「中间位置、刚更新」的条目", text.slice(-400));
174
+ check(text.length <= 1200, `9: 预算 300 下注入不应爆炸(实际 ${text.length})`);
175
+ }
176
+
177
+ if (fails.length) {
178
+ console.error("FAIL index-budget");
179
+ for (const f of fails) console.error(" -", f);
180
+ process.exit(1);
181
+ }
182
+ console.log("PASS index-budget");
@@ -0,0 +1,92 @@
1
+ // G4(v0.12)索引注释剥离只删顶层:
2
+ // - 行首(0–3 空格)整块注释删除
3
+ // - 列表项缩进内的 `<!-- -->` 保留(原生 marked 只把行首块当 html token)
4
+ // - 未闭合的顶层注释不能吞掉后面的索引行
5
+ // 用法: node index-comments.mjs [index.js 路径]
6
+ import { pathToFileURL } from "node:url";
7
+ import { mkdtempSync, mkdirSync, writeFileSync, readdirSync, rmSync } from "node:fs";
8
+ import { tmpdir } from "node:os";
9
+ import { join } from "node:path";
10
+
11
+ const modUrl = process.argv[2] ? pathToFileURL(process.argv[2]).href : new URL("../index.js", import.meta.url).href;
12
+ const mod = await import(modUrl);
13
+
14
+ const fails = [];
15
+ const check = (cond, msg, extra) => {
16
+ if (!cond) fails.push(msg + (extra !== undefined ? ` :: ${JSON.stringify(extra).slice(0, 300)}` : ""));
17
+ };
18
+
19
+ const PLANTED = [
20
+ "<!-- top-level comment -->",
21
+ "- [Alpha](alpha.md) — alpha hook",
22
+ " <!-- indented inside item -->",
23
+ "- [Beta](beta.md) — beta hook",
24
+ " - [Nested](nested.md) — nested hook",
25
+ " <!-- after sublist, still inside Beta -->",
26
+ "<!--",
27
+ "block top",
28
+ "-->",
29
+ "- [Gamma](gamma.md) — gamma hook",
30
+ "<!-- unclosed at end",
31
+ "- [Delta](delta.md) — delta hook",
32
+ "",
33
+ ].join("\n");
34
+
35
+ async function capture(style) {
36
+ const root = mkdtempSync(join(tmpdir(), `zcm-cmt-${style}-`));
37
+ const cwd = mkdtempSync(join(tmpdir(), "zcm-cmtcwd-"));
38
+ const reg = { sections: [], contexts: [], tools: [], commands: [], handlers: new Map() };
39
+ const ctx = {
40
+ systemPrompt: {
41
+ section: (o) => reg.sections.push(o),
42
+ context: (o) => reg.contexts.push(o),
43
+ },
44
+ tools: { register: (d) => reg.tools.push(d), schemas: () => [{ name: "write" }] },
45
+ commands: { register: () => {} },
46
+ on: (ev, fn) => {
47
+ if (!reg.handlers.has(ev)) reg.handlers.set(ev, []);
48
+ reg.handlers.get(ev).push(fn);
49
+ },
50
+ llm: { stream: async function* () {} },
51
+ };
52
+ mod.apply(ctx, { memoriesRoot: root, enabled: true, promptStyle: style });
53
+ const session = { header: { id: `sess-cmt-${style}`, cwd, createdAt: "2026-12-05T10:00:00.000Z" } };
54
+ const save = reg.tools.find((t) => t.name === "memory_save");
55
+ const saved = await save.execute({ title: "Seed", description: "seed", body: "seed body", scope: "project" }, { agent: { session } });
56
+ if (!saved?.ok) {
57
+ console.error("FAIL index-comments: seed save failed", saved);
58
+ process.exit(1);
59
+ }
60
+ const projRoot = join(root, "projects");
61
+ const projectDir = join(projRoot, readdirSync(projRoot)[0], "memory");
62
+ writeFileSync(join(projectDir, "MEMORY.md"), PLANTED, "utf8");
63
+ const idx = reg.contexts.find((c) => c.name === "zcode-memory");
64
+ const text = String(idx?.text({ agent: { session } }) || "");
65
+ mkdirSync(projectDir, { recursive: true });
66
+ try {
67
+ rmSync(root, { recursive: true, force: true });
68
+ rmSync(cwd, { recursive: true, force: true });
69
+ } catch {
70
+ /* noop */
71
+ }
72
+ return text;
73
+ }
74
+
75
+ for (const style of ["plugin", "native"]) {
76
+ const text = await capture(style);
77
+ check(text.length > 0, `${style}: no index injected`);
78
+ check(!text.includes("top-level comment"), `${style}: top-level comment must be stripped`, text.slice(0, 300));
79
+ check(!text.includes("block top"), `${style}: multi-line top-level comment must be stripped`);
80
+ check(text.includes("indented inside item"), `${style}: indented comment inside a list item must be kept`);
81
+ // 复查 P3:子列表结束后缩进回到父项内容列,这条注释属于父项,不能被当顶层删掉。
82
+ check(text.includes("after sublist, still inside Beta"), `${style}: comment after a nested sublist must stay in the parent item`);
83
+ check(text.includes("Alpha") && text.includes("Beta") && text.includes("Gamma"), `${style}: entries lost`);
84
+ check(text.includes("Delta"), `${style}: unclosed comment must not swallow later lines`, text.slice(-300));
85
+ }
86
+
87
+ if (fails.length) {
88
+ console.error("FAIL index-comments");
89
+ for (const f of fails) console.error(" -", f);
90
+ process.exit(1);
91
+ }
92
+ console.log("PASS index-comments");