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,237 @@
1
+ // P1(2026-12-05)索引超限时保留哪一段:
2
+ // indexTruncateOrder="newest"(默认)→ 按记忆文件 mtime 从新到旧保留,结构行不裁,
3
+ // 保留行仍按原文件顺序输出(追加写的最新条目不会掉出注入)。
4
+ // indexTruncateOrder="native" → 保留前 N 行(zcode.cjs 行为,逐字符对齐,可回退)。
5
+ // 用法: node index-truncate.mjs [index.js 路径]
6
+ import { pathToFileURL } from "node:url";
7
+ import { mkdtempSync, mkdirSync, writeFileSync, readdirSync, rmSync, utimesSync } 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 BASE_MS = Date.UTC(2026, 0, 1, 0, 0, 0);
20
+ const at = (i) => {
21
+ const d = new Date(BASE_MS + i * 60000);
22
+ return d;
23
+ };
24
+
25
+ // 走真实注入路径:apply → memory_save 建项目目录 → 覆写 MEMORY.md → 取 context 段文本。
26
+ async function render(cfg, build) {
27
+ const root = mkdtempSync(join(tmpdir(), "zcm-trunc-"));
28
+ const cwd = mkdtempSync(join(tmpdir(), "zcm-trunc-cwd-"));
29
+ const reg = { sections: [], contexts: [], tools: [], commands: [], handlers: new Map() };
30
+ const ctx = {
31
+ systemPrompt: {
32
+ section: (o) => reg.sections.push(o),
33
+ context: (o) => reg.contexts.push(o),
34
+ },
35
+ tools: { register: (d) => reg.tools.push(d), schemas: () => [{ name: "write" }] },
36
+ commands: { register: () => {} },
37
+ on: (ev, fn) => {
38
+ if (!reg.handlers.has(ev)) reg.handlers.set(ev, []);
39
+ reg.handlers.get(ev).push(fn);
40
+ },
41
+ llm: { stream: async function* () {} },
42
+ };
43
+ mod.apply(ctx, { memoriesRoot: root, enabled: true, promptStyle: "native", ...cfg });
44
+ const session = { header: { id: `sess-trunc-${Math.random().toString(36).slice(2)}`, cwd, createdAt: "2026-12-05T10:00:00.000Z" } };
45
+ const save = reg.tools.find((t) => t.name === "memory_save");
46
+ const saved = await save.execute({ title: "Seed", description: "seed", body: "seed body", scope: "project" }, { agent: { session } });
47
+ if (!saved?.ok) {
48
+ console.error("FAIL index-truncate: seed save failed", saved);
49
+ process.exit(1);
50
+ }
51
+ const projRoot = join(root, "projects");
52
+ const projectDir = join(projRoot, readdirSync(projRoot)[0], "memory");
53
+ mkdirSync(projectDir, { recursive: true });
54
+ writeFileSync(join(projectDir, "MEMORY.md"), build(projectDir), "utf8");
55
+ const idx = reg.contexts.find((c) => c.name === "zcode-memory");
56
+ const text = String(idx?.text({ agent: { session } }) || "");
57
+ try {
58
+ rmSync(root, { recursive: true, force: true });
59
+ rmSync(cwd, { recursive: true, force: true });
60
+ } catch {
61
+ /* noop */
62
+ }
63
+ return text;
64
+ }
65
+
66
+ // 250 条链接行,mtime 随行号递增(越靠后越新)。
67
+ const build250 = (dir) => {
68
+ const lines = [];
69
+ for (let i = 1; i <= 250; i++) {
70
+ const f = join(dir, `mem-${i}.md`);
71
+ writeFileSync(f, `body ${i}`, "utf8");
72
+ utimesSync(f, at(i), at(i));
73
+ lines.push(`- [mem-${i}](mem-${i}.md) — hook ${i}`);
74
+ }
75
+ return lines.join("\n");
76
+ };
77
+ // 统计只能看正文:WARNING 会回显下一行预览(基线里那「可见的 1 条」就是这么来的)。
78
+ const noWarn = (text) => {
79
+ const k = text.lastIndexOf("\n\n> WARNING:");
80
+ return k < 0 ? text : text.slice(0, k);
81
+ };
82
+ const entryNos = (text) => [...noWarn(text).matchAll(/\(mem-(\d+)\.md\)/g)].map((m) => Number(m[1]));
83
+ // 去掉 `Contents of …` 头,只留真正进索引的正文。
84
+ const bodyOf = (text) => {
85
+ const i = noWarn(text).indexOf("conversations):\n\n");
86
+ return i < 0 ? noWarn(text) : noWarn(text).slice(i + "conversations):\n\n".length);
87
+ };
88
+
89
+ // --- A: 默认(newest):250 行 → 保留最新 200 行,最新 50 条必须全部可见 ---
90
+ const A = await render({}, build250);
91
+ const aNos = entryNos(A);
92
+ check(aNos.length === 200, `A: 应保留 200 行,实际 ${aNos.length}`);
93
+ // 「正好是 mtime 最新的 200 条」,不是「首尾拼凑到 200 条」。
94
+ check(aNos[0] === 51, `A: 必须正好保留最新 200 条(首条应是 mem-51,实际 ${aNos[0]})`);
95
+ const aNew = aNos.filter((n) => n >= 201);
96
+ check(aNew.length === 50, `A: 最新 50 条应全部可见,实际 ${aNew.length}`, aNew.slice(0, 5));
97
+ check(
98
+ aNos.every((n, k) => k === 0 || n > aNos[k - 1]),
99
+ "A: 保留行必须保持原文件顺序(不得重排)",
100
+ aNos.slice(0, 12),
101
+ );
102
+ check(bodyOf(A).length <= 25000, `A: 正文字符超预算 (${bodyOf(A).length})`);
103
+ check(A.includes("250 lines (limit: 200)"), "A: WARNING 应报总行数与上限", A.slice(-260));
104
+ check(A.includes("50 of 250 lines were cut off"), "A: WARNING 应报被裁行数", A.slice(-260));
105
+
106
+ // --- B: 结构行 + 悬空链接行在裁剪时的处理(配额只数链接行,结构行不占) ---
107
+ const B = await render({ indexMaxLines: 2 }, (dir) => {
108
+ for (const i of [1, 2, 3, 4]) {
109
+ const f = join(dir, `mem-${i}.md`);
110
+ writeFileSync(f, "x", "utf8");
111
+ utimesSync(f, at(i), at(i));
112
+ }
113
+ return [
114
+ "# 记忆索引",
115
+ "",
116
+ "- [mem-1](mem-1.md) — a",
117
+ "- [mem-2](mem-2.md) — b",
118
+ "- [ghost](ghost.md) — 悬空目标",
119
+ "- [mem-3](mem-3.md) — c",
120
+ "- [mem-4](mem-4.md) — d",
121
+ ].join("\n");
122
+ });
123
+ check(noWarn(B).includes("# 记忆索引"), "B: 标题行不能被裁", B.slice(0, 200));
124
+ check(noWarn(B).includes("(mem-4.md)") && noWarn(B).includes("(mem-3.md)"), "B: mtime 最新的两条应保留", B.slice(0, 300));
125
+ check(!noWarn(B).includes("(mem-1.md)") && !noWarn(B).includes("(mem-2.md)"), "B: 最旧两条应被裁", B.slice(0, 300));
126
+ check(!noWarn(B).includes("(ghost.md)"), "B: stat 失败的悬空行按最旧处理(不得崩溃)", B.slice(0, 300));
127
+ check(B.indexOf("(mem-3.md)") < B.indexOf("(mem-4.md)"), "B: 保留行顺序不变");
128
+ check(B.includes("WARNING"), "B: 超限应有 WARNING");
129
+
130
+ // --- C: native 顺序 → 与 zcode.cjs 一致:保留前 200 行(可回退性) ---
131
+ const C = await render({ indexTruncateOrder: "native" }, build250);
132
+ const cNos = entryNos(C);
133
+ check(cNos.length === 200, `C: native 顺序应保留 200 行,实际 ${cNos.length}`);
134
+ check(cNos[0] === 1 && cNos[cNos.length - 1] === 200, "C: native 顺序应保留前 200 行", [cNos[0], cNos.at(-1)]);
135
+ check(!noWarn(C).includes("(mem-201.md)"), "C: native 顺序丢弃最新条目(回退到原生行为)");
136
+ check(C.includes("50 of 250 lines were cut off, starting at line 201"), "C: WARNING 起始行号与基线一致", C.slice(-260));
137
+ // 字节级锁定:native 顺序的正文必须逐字等于前 200 行(不含 WARNING)。
138
+ const cExpect = Array.from({ length: 200 }, (_, k) => `- [mem-${k + 1}](mem-${k + 1}.md) — hook ${k + 1}`).join("\n");
139
+ check(bodyOf(C) === cExpect, "C: native 顺序正文必须逐字符等于前 200 行(不可重排/丢行)");
140
+
141
+ // --- D: keepIndexLinks=false 时也要按 mtime 选行(去掉链接后就没有文件名可 stat,
142
+ // 所以选择必须在去链接之前完成) ---
143
+ const D = await render({ keepIndexLinks: false }, build250);
144
+ const dLines = noWarn(D).split("\n").filter((l) => /^- mem-\d+ — hook \d+$/.test(l));
145
+ const dNos = dLines.map((l) => Number(/^- mem-(\d+) —/.exec(l)[1]));
146
+ check(!noWarn(D).includes("]("), "D: keepIndexLinks=false 应去掉链接", noWarn(D).slice(0, 200));
147
+ check(dNos.length === 200, `D: 去链接后仍应保留 200 行,实际 ${dNos.length}`);
148
+ check(dNos[0] === 51, `D: 去链接后也必须正好保留最新 200 条(首条应是 mem-51,实际 ${dNos[0]})`);
149
+ check(dNos.filter((n) => n >= 201).length === 50, "D: 去链接后最新 50 条仍应全部可见", dNos.slice(-5));
150
+ check(dNos.every((n, k) => k === 0 || n > dNos[k - 1]), "D: 保留行顺序不变");
151
+
152
+ // --- E: 只超字符预算(行数未超)时也要按 mtime 保留最新 ---
153
+ // 150 行 × 约 220 字符 ≈ 33k > 25k:旧实现在这条路径上按前缀硬切,最新条目会消失。
154
+ const E = await render({}, (dir) => {
155
+ const a = [];
156
+ for (let i = 1; i <= 150; i++) {
157
+ const f = join(dir, `mem-${i}.md`);
158
+ writeFileSync(f, "x", "utf8");
159
+ utimesSync(f, at(i), at(i));
160
+ a.push(`- [mem-${i}](mem-${i}.md) — ${"y".repeat(180)}${i}`);
161
+ }
162
+ return a.join("\n");
163
+ });
164
+ const eNos = entryNos(E);
165
+ check(eNos.includes(150), "E: 最终超过字符预算时,最新一条(mem-150)必须仍可见", eNos.slice(-5));
166
+ check(!eNos.includes(1), "E: 字符预算裁剪应先丢最旧的(mem-1 应被裁)", eNos.slice(0, 5));
167
+ check(eNos.length > 0 && eNos.length < 150, `E: 应裁掉一部分(实际保留 ${eNos.length} 行)`);
168
+ check(eNos.every((n, k) => k === 0 || n > eNos[k - 1]), "E: 保留行顺序不变");
169
+ check(bodyOf(E).length <= 25000, `E: 正文字符不得超预算(实际 ${bodyOf(E).length})`);
170
+ check(E.includes("index entries are too long"), "E: 应走字符超限的 WARNING 分支", E.slice(-260));
171
+
172
+ // --- F: 全是结构行(无链接可裁)→ 整段保留且不打自相矛盾的 WARNING ---
173
+ const F = await render({ indexMaxLines: 5 }, () =>
174
+ Array.from({ length: 12 }, (_, k) => (k % 3 === 0 ? `# 段 ${k}` : `手写说明 ${k}`)).join("\n"),
175
+ );
176
+ const fBody = bodyOf(F);
177
+ check(fBody.split("\n").length === 12, `F: 无链接行时整段保留(实际 ${fBody.split("\n").length} 行)`, fBody.slice(0, 200));
178
+ check(!F.includes("WARNING"), "F: 没东西可裁时不得打「裁掉 0 行」的假 WARNING", F.slice(-200));
179
+ check(!/line 0\b/.test(F), "F: 不得出现 starting at line 0", F.slice(-200));
180
+
181
+ // --- G: 行数与字符同时超限 → newest 先留 200 行,再按字符预算从最旧丢整条 ---
182
+ const G = await render({}, (dir) => {
183
+ const a = [];
184
+ for (let i = 1; i <= 250; i++) {
185
+ const f = join(dir, `mem-${i}.md`);
186
+ writeFileSync(f, "x", "utf8");
187
+ utimesSync(f, at(i), at(i));
188
+ a.push(`- [mem-${i}](mem-${i}.md) — ${"z".repeat(180)}${i}`);
189
+ }
190
+ return a.join("\n");
191
+ });
192
+ const gNos = entryNos(G);
193
+ check(gNos.length > 0 && gNos.length < 200, `G: 双超限应在 200 行基础上继续按字符裁(实际 ${gNos.length})`);
194
+ check(gNos.includes(250), "G: 双超限时最新条目仍必须可见", gNos.slice(-3));
195
+ check(gNos.every((n, k) => k === 0 || n > gNos[k - 1]), "G: 保留行顺序不变");
196
+ check(bodyOf(G).length <= 25000, `G: 正文不得超字符预算(实际 ${bodyOf(G).length})`);
197
+ check(/\d+ of 250 lines were cut off, starting at line [1-9]\d*/.test(G), "G: WARNING 必须给出有效起始行(不能是 line 0)", G.slice(-260));
198
+
199
+ // --- H: 松散列表(每条后一个空行)→ 空行不占 200 条配额,条目不能被挤掉 ---
200
+ const H = await render({}, (dir) => {
201
+ const a = [];
202
+ for (let i = 1; i <= 200; i++) {
203
+ const f = join(dir, `mem-${i}.md`);
204
+ writeFileSync(f, "x", "utf8");
205
+ utimesSync(f, at(i), at(i));
206
+ a.push(`- [mem-${i}](mem-${i}.md) — hook ${i}`, "");
207
+ }
208
+ return a.join("\n");
209
+ });
210
+ const hNos = entryNos(H);
211
+ check(hNos.length === 200, `H: 松散列表里 200 条记忆不能被空行挤出配额(实际 ${hNos.length})`);
212
+ check(hNos.includes(200) && hNos.includes(1), "H: 条目没超配额时应全部保留", [hNos[0], hNos.at(-1)]);
213
+ check(!noWarn(H).includes("WARNING"), "H: 条目未超配额时不该有 WARNING", H.slice(-200));
214
+
215
+ // --- I: `#fragment` / 文件名带括号的链接也要能 stat 到(否则被当悬空、优先裁掉) ---
216
+ const I = await render({ indexMaxLines: 2 }, (dir) => {
217
+ const mk = (name, i) => {
218
+ const f = join(dir, name);
219
+ writeFileSync(f, "x", "utf8");
220
+ utimesSync(f, at(i), at(i));
221
+ };
222
+ mk("a.md", 3); // 最新,但索引里带 #fragment
223
+ mk("b.md", 1); // 最旧
224
+ mk("c(d).md", 2); // 文件名带括号
225
+ return ["- [a](a.md#sec) — a", "- [b](b.md) — b", "- [c](c(d).md) — c"].join("\n");
226
+ });
227
+ const iBody = noWarn(I);
228
+ check(iBody.includes("(a.md#sec)"), "I: 带 #fragment 的最新条目不能被裁(要先剥 fragment 再 stat)", iBody.slice(0, 260));
229
+ check(iBody.includes("(c(d).md)"), "I: 文件名带括号的最新条目不能被裁", iBody.slice(0, 260));
230
+ check(!iBody.includes("(b.md)"), "I: 真正最旧的条目才该被裁", iBody.slice(0, 260));
231
+
232
+ if (fails.length) {
233
+ console.error("FAIL index-truncate");
234
+ for (const f of fails) console.error(" -", f);
235
+ process.exit(1);
236
+ }
237
+ console.log("PASS index-truncate");
@@ -0,0 +1,90 @@
1
+ // A(v0.11)Memory Notes 段:native 风格逐字符注入 `# Memory, notes and feedback`,
2
+ // 位置在 Memory 段之后、索引块之前;writeEnabled=false 不注入;plugin 风格不重复英文 Notes。
3
+ // 用法: node memory-notes.mjs [index.js 路径]
4
+ import { pathToFileURL } from "node:url";
5
+ import { mkdtempSync, mkdirSync, writeFileSync, rmSync } from "node:fs";
6
+ import { createHash } from "node:crypto";
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
+ // G9 起规则在 system 段(zcode-memory-rules)、索引在 context 段(zcode-memory);
19
+ // 这里按注册顺序拼回完整注入文本再断言(规则在前、索引在后)。
20
+ function runText(cfg, sessionHeader = { cwd: process.cwd() }) {
21
+ const grabbed = [];
22
+ const grab = (o) => {
23
+ if (o.name === "zcode-memory" || o.name === "zcode-memory-rules") grabbed.push(o);
24
+ };
25
+ const ctx = {
26
+ systemPrompt: { section: grab, context: grab },
27
+ tools: { register: () => {} },
28
+ commands: { register: () => {} },
29
+ on: () => {},
30
+ llm: { stream: async function* () {} },
31
+ };
32
+ mod.apply(ctx, cfg);
33
+ const arg = { agent: { session: { header: sessionHeader } } };
34
+ return grabbed.map((o) => String(o.text(arg))).join("\n\n");
35
+ }
36
+
37
+ const root = mkdtempSync(join(tmpdir(), "zcm-notes-"));
38
+ try {
39
+ // 造一个带索引的项目目录:验证 Notes 排在 Memory 段之后、Contents 块之前。
40
+ const hash = createHash("sha256").update("notes-identity", "utf8").digest("hex").slice(0, 16);
41
+ const dir = join(root, "projects", `project-${hash}`, "memory");
42
+ mkdirSync(dir, { recursive: true });
43
+ writeFileSync(join(dir, "MEMORY.md"), "- [项目事实](fact.md) — 一条索引\n");
44
+
45
+ const base = { memoriesRoot: root, enabled: true, promptStyle: "native", workspaceIdentity: "notes-identity" };
46
+
47
+ const text = runText(base);
48
+ for (const needle of ["# Memory, notes and feedback", "applicable", "durable", "completed work", "planning"]) {
49
+ check(text.includes(needle), `native notes missing: ${needle}`);
50
+ }
51
+ // 概念都在;段落本身只注入一次(原生文本里 applicable/durable 自然会出现多次)。
52
+ const count = (s, n) => text.split(n).length - 1;
53
+ check(count(text, "applicable") >= 1, "applicable missing");
54
+ check(count(text, "durable") >= 1, "durable missing");
55
+ check(count(text, "# Memory, notes and feedback") === 1, "notes header duplicated");
56
+
57
+ const notesAt = text.indexOf("# Memory, notes and feedback");
58
+ const memoryAt = text.indexOf("# Memory\n");
59
+ const contentsAt = text.indexOf("Contents of ");
60
+ check(memoryAt >= 0, "missing # Memory header");
61
+ check(notesAt > memoryAt, "notes must come after Memory header");
62
+ check(contentsAt > notesAt, "notes must come before the index block");
63
+
64
+ // 逐字符抽查:原文用 em dash(U+2014),不是 " - "。
65
+ check(text.includes("unless the user asks for them \u2014 work from the context"), "em dash text mismatch");
66
+
67
+ // 只读模式:不教保存规则。
68
+ const readonly = runText({ ...base, writeEnabled: false });
69
+ check(!readonly.includes("# Memory, notes and feedback"), "notes must not appear when writeEnabled=false");
70
+ check(!readonly.includes("Save only what is applicable and durable"), "saving rules leaked in read-only");
71
+
72
+ // plugin 风格:已有中文等价提示,不重复英文 Notes。
73
+ const plugin = runText({ ...base, promptStyle: "plugin" });
74
+ check(!plugin.includes("# Memory, notes and feedback"), "plugin style must not include English notes");
75
+ check(!plugin.includes("applicable: it would directly change"), "plugin style leaked English notes body");
76
+ check(plugin.includes("只保存 applicable 且 durable"), "plugin style lost its Chinese equivalent");
77
+ } finally {
78
+ try {
79
+ rmSync(root, { recursive: true, force: true });
80
+ } catch {
81
+ /* noop */
82
+ }
83
+ }
84
+
85
+ if (fails.length) {
86
+ console.error("FAIL memory-notes");
87
+ for (const f of fails) console.error(" -", f);
88
+ process.exit(1);
89
+ }
90
+ console.log("PASS memory-notes");
@@ -0,0 +1,297 @@
1
+ // N5 边界:真 tool-calling 抽取的异常流契约。
2
+ // 覆盖:重复 callId 改写、部分结果缺失、execute 抛错、finish=tool-calls 无 block、
3
+ // 预置 aborted 不发请求、单轮 >6 调用截断。
4
+ // 用法: node native-tools-edge.mjs [index.js 路径]
5
+ import { pathToFileURL } from "node:url";
6
+ import { mkdtempSync, readFileSync, existsSync, rmSync } 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 BASE = { enabled: true, promptStyle: "native", autoExtractAgentRounds: 2 };
14
+ const fails = [];
15
+ const check = (cond, msg, extra) => {
16
+ if (!cond) fails.push(msg + (extra !== undefined ? ` :: ${JSON.stringify(extra).slice(0, 400)}` : ""));
17
+ };
18
+ const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
19
+
20
+ function toolCall(id, name, args) {
21
+ return { type: "block-end", index: 0, block: { type: "tool-call", id, name, arguments: args } };
22
+ }
23
+ function textBlock(text) {
24
+ return { type: "block-end", index: 0, block: { type: "text", text } };
25
+ }
26
+ function finish(kind) {
27
+ return { type: "finish", reason: { kind } };
28
+ }
29
+ const writesEmpty = () => [textBlock('{"writes":[]}'), finish("stop")];
30
+
31
+ // 跑一个场景:返回 { state, root, memDir, rounds };rounds 记录每次 llm 请求的 options。
32
+ async function scenario({ llm, tools, signal, cfg = {} }) {
33
+ const root = mkdtempSync(join(tmpdir(), "zcm-edge-"));
34
+ const cwd = mkdtempSync(join(tmpdir(), "zcm-edgecwd-"));
35
+ const rounds = [];
36
+ const reg = { sections: [], contexts: [], tools: [], commands: [], handlers: new Map() };
37
+ const defTools = {
38
+ register: (d) => reg.tools.push(d),
39
+ schemas: () => [
40
+ { name: "memory_list", description: "l", parameters: { type: "object" } },
41
+ { name: "memory_read", description: "r", parameters: { type: "object" } },
42
+ ],
43
+ execute:
44
+ tools?.execute ||
45
+ (async ({ calls }) => ({
46
+ results: calls.map((c) => ({
47
+ callId: c.id,
48
+ result: { isError: false, value: null, content: [{ type: "text", text: `R:${c.id}:${c.arguments}` }] },
49
+ })),
50
+ additionalContexts: [],
51
+ concluded: false,
52
+ })),
53
+ };
54
+ const ctx = {
55
+ systemPrompt: { section: (o) => reg.sections.push(o), context: (o) => reg.contexts.push(o) },
56
+ tools: defTools,
57
+ commands: { register: (c) => reg.commands.push(c) },
58
+ get: () => undefined,
59
+ on: (ev, fn) => {
60
+ if (!reg.handlers.has(ev)) reg.handlers.set(ev, []);
61
+ reg.handlers.get(ev).push(fn);
62
+ },
63
+ llm: {
64
+ stream: async function* (opts) {
65
+ rounds.push({ tools: (opts.tools || []).map((t) => t.name), messages: opts.messages });
66
+ for (const ch of llm(rounds.length)) yield ch;
67
+ },
68
+ },
69
+ };
70
+ mod.apply(ctx, { ...BASE, ...cfg, memoriesRoot: root });
71
+
72
+ const emit = (ev, ...args) => {
73
+ for (const fn of reg.handlers.get(ev) || []) fn(...args);
74
+ };
75
+ const session = { header: { id: `sess-edge-${Math.random().toString(36).slice(2, 8)}`, cwd, createdAt: "2026-12-05T10:00:00.000Z" } };
76
+ const agent = {
77
+ session,
78
+ status: "idle",
79
+ inbox: { nextTurn: [], nextStep: [] },
80
+ model: { current: () => ({ provider: "mock", model: "mock-1" }) },
81
+ whenIdle: () => Promise.resolve(),
82
+ runMaintenance: async (fn) => fn(signal || new AbortController().signal),
83
+ };
84
+ emit("session/event", session, { type: "turn/start", seq: 1, data: { turn: 1 } });
85
+ emit("session/event", session, {
86
+ type: "user/message",
87
+ seq: 2,
88
+ data: { source: { kind: "user" }, content: [{ type: "text", text: "这个项目的部署脚本路径是 scripts/deploy.ps1,请记住。" }] },
89
+ });
90
+ emit("session/event", session, {
91
+ type: "assistant/message",
92
+ seq: 3,
93
+ data: { turn: 1, message: { content: [{ type: "text", text: "已确认部署脚本是 scripts/deploy.ps1。" }] } },
94
+ });
95
+ emit("agent/turn-stopping", { agent, turn: 1 });
96
+
97
+ const stFile = join(root, "_extract-state.json");
98
+ let st = null;
99
+ for (let i = 0; i < 100; i++) {
100
+ if (existsSync(stFile)) {
101
+ try {
102
+ st = JSON.parse(readFileSync(stFile, "utf8"));
103
+ if (st.lastRunAt) break;
104
+ } catch {
105
+ /* mid-write */
106
+ }
107
+ }
108
+ await sleep(30);
109
+ }
110
+ await sleep(50);
111
+ if (existsSync(stFile)) st = JSON.parse(readFileSync(stFile, "utf8"));
112
+ const cursor = st?.cursorBySession?.[session.header.id]?.seq ?? 0;
113
+ return { st, cursor, rounds, root };
114
+ }
115
+
116
+ function toolMsgs(round, n) {
117
+ const msgs = round?.messages || [];
118
+ const assistant = msgs.find((m) => m.role === "assistant" && m.content?.some((b) => b.type === "tool-call"));
119
+ return {
120
+ assistant,
121
+ calls: assistant?.content.filter((b) => b.type === "tool-call") || [],
122
+ tools: msgs.filter((m) => m.role === "tool"),
123
+ };
124
+ }
125
+
126
+ // ---------- 1. 重复 callId:必须改写为唯一 id,结果不能错配 ----------
127
+ {
128
+ const executed = [];
129
+ const r = await scenario({
130
+ tools: {
131
+ execute: async ({ calls }) => {
132
+ executed.push(...calls.map((c) => `${c.id}|${c.arguments}`));
133
+ return {
134
+ results: calls.map((c) => ({
135
+ callId: c.id,
136
+ result: { isError: false, value: null, content: [{ type: "text", text: `R:${c.arguments}` }] },
137
+ })),
138
+ additionalContexts: [],
139
+ concluded: false,
140
+ };
141
+ },
142
+ },
143
+ llm: (round) =>
144
+ round === 1
145
+ ? [
146
+ toolCall("dupA", "memory_list", '{"q":"same"}'),
147
+ toolCall("dupA", "memory_list", '{"q":"same"}'),
148
+ toolCall("dupB", "memory_list", '{"q":"one"}'),
149
+ toolCall("dupB", "memory_list", '{"q":"two"}'),
150
+ finish("tool-calls"),
151
+ ]
152
+ : writesEmpty(),
153
+ });
154
+ const { calls, tools } = toolMsgs(r.rounds[1], 4);
155
+ const callIds = calls.map((c) => c.id);
156
+ const toolIds = tools.map((m) => m.toolCallId);
157
+ check(new Set(callIds).size === callIds.length, "duplicate callId must be rewritten in assistant message", callIds);
158
+ check(new Set(toolIds).size === toolIds.length, "tool results must use unique ids", toolIds);
159
+ check(calls.length === 4 && tools.length === 4, "all four calls keep a paired result", { calls: calls.length, tools: tools.length });
160
+ check(executed.length === 3, "same-args duplicate executes once; different args execute separately", executed);
161
+ // 第二个 dupA(同参数)必须是错误结果;两个 dupB 各自拿到自己的结果。
162
+ const texts = tools.map((m) => ({ err: m.isError, t: m.content?.[0]?.text }));
163
+ check(texts.filter((x) => x.err === true).length === 1, "only the same-args duplicate is an error", texts);
164
+ check(texts.some((x) => x.t?.includes('"one"')), "dupB first result delivered", texts);
165
+ check(texts.some((x) => x.t?.includes('"two"')), "dupB second result delivered", texts);
166
+ try { rmSync(r.root, { recursive: true, force: true }); } catch {}
167
+ }
168
+
169
+ // ---------- 2. execute 只返回部分结果:缺失的调用必须补错误结果 ----------
170
+ {
171
+ const r = await scenario({
172
+ tools: {
173
+ execute: async ({ calls }) => ({
174
+ results: [
175
+ {
176
+ callId: calls[0].id,
177
+ result: { isError: false, value: null, content: [{ type: "text", text: "OK-FIRST" }] },
178
+ },
179
+ ],
180
+ additionalContexts: [],
181
+ concluded: false,
182
+ }),
183
+ },
184
+ llm: (round) =>
185
+ round === 1
186
+ ? [toolCall("p1", "memory_list", "{}"), toolCall("p2", "memory_read", '{"name":"x"}'), finish("tool-calls")]
187
+ : writesEmpty(),
188
+ });
189
+ const { tools } = toolMsgs(r.rounds[1], 2);
190
+ check(tools.length === 2, "both calls have results", tools.length);
191
+ const second = tools.find((m) => m.toolCallId === "p2");
192
+ check(second?.isError === true && String(second.content?.[0]?.text).includes("没有返回结果"), "missing result becomes isError", second);
193
+ try { rmSync(r.root, { recursive: true, force: true }); } catch {}
194
+ }
195
+
196
+ // ---------- 3. execute 抛错:所有 fresh 调用得到错误结果,抽取仍可完成 ----------
197
+ {
198
+ const r = await scenario({
199
+ tools: {
200
+ execute: async () => {
201
+ throw new Error("mock execute boom");
202
+ },
203
+ },
204
+ llm: (round) => (round === 1 ? [toolCall("e1", "memory_list", "{}"), toolCall("e2", "memory_read", '{"name":"y"}'), finish("tool-calls")] : writesEmpty()),
205
+ });
206
+ const { tools } = toolMsgs(r.rounds[1], 2);
207
+ check(tools.length === 2 && tools.every((m) => m.isError === true), "execute throw marks every fresh call isError", tools.map((m) => m.isError));
208
+ check(String(tools[0]?.content?.[0]?.text).includes("execute boom"), "failure reason fed back", tools[0]?.content);
209
+ check(r.st.lastOutcome === "empty" && r.cursor === 3, "extraction completes after tool failure", { out: r.st.lastOutcome, cursor: r.cursor });
210
+ try { rmSync(r.root, { recursive: true, force: true }); } catch {}
211
+ }
212
+
213
+ // ---------- 4. finish=tool-calls 但无 block:抛错、不推进游标 ----------
214
+ {
215
+ const r = await scenario({ llm: () => [finish("tool-calls")] });
216
+ check(r.rounds.length === 1, "only one request attempted", r.rounds.length);
217
+ check(r.st.lastOutcome === "failed", "failed outcome recorded", r.st.lastOutcome);
218
+ check(/no tool-call block/.test(String(r.st.lastError)), "protocol error surfaced", r.st.lastError);
219
+ check(r.cursor === 0, "cursor must not advance", r.cursor);
220
+ try { rmSync(r.root, { recursive: true, force: true }); } catch {}
221
+ }
222
+
223
+ // ---------- 5. 预置 aborted signal:不发起 LLM 请求 ----------
224
+ {
225
+ const ac = new AbortController();
226
+ ac.abort();
227
+ const r = await scenario({ signal: ac.signal, llm: (n) => (n === 1 ? [finish("stop")] : writesEmpty()) });
228
+ check(r.rounds.length === 0, "no llm request when signal already aborted", r.rounds.length);
229
+ check(r.st.lastOutcome === "aborted", "aborted outcome recorded", r.st.lastOutcome);
230
+ check(r.cursor === 0, "cursor must not advance on abort", r.cursor);
231
+ try { rmSync(r.root, { recursive: true, force: true }); } catch {}
232
+ }
233
+
234
+ // ---------- 6. 单轮 8 个调用:全配对,前 6 个执行,后 2 个标为跳过 ----------
235
+ {
236
+ const r = await scenario({
237
+ llm: (round) =>
238
+ round === 1
239
+ ? [
240
+ ...Array.from({ length: 8 }, (_, i) => toolCall(`m${i + 1}`, "memory_list", `{"i":${i + 1}}`)),
241
+ finish("tool-calls"),
242
+ ]
243
+ : writesEmpty(),
244
+ });
245
+ const { calls, tools } = toolMsgs(r.rounds[1], 8);
246
+ check(calls.length === 8 && tools.length === 8, "all eight calls keep a paired result", { calls: calls.length, tools: tools.length });
247
+ check(calls.every((c, i) => c.id === `m${i + 1}`), "call order preserved", calls.map((c) => c.id));
248
+ const overCap = tools.filter((m) => String(m.content?.[0]?.text).includes("超过 6"));
249
+ check(overCap.length === 2 && overCap.every((m) => m.isError === true), "calls beyond six are skipped with an error result", overCap.length);
250
+ check(tools.slice(0, 6).every((m) => m.isError === false), "first six execute", tools.slice(0, 6).map((m) => m.isError));
251
+ try { rmSync(r.root, { recursive: true, force: true }); } catch {}
252
+ }
253
+
254
+ // ---------- 7. 旧版单调用 execute(无 batch.results):自动退回 JSON 动作模式 ----------
255
+ // 注意:这条会置位模块级 nativeToolsUnsupported,必须放在最后。
256
+ {
257
+ const r = await scenario({
258
+ tools: {
259
+ // dsh < 0.2.2-rc.3 的形状:单个 result,没有 results 数组。
260
+ execute: async ({ calls }) => ({ callId: calls[0]?.id, result: { isError: true, content: [{ type: "text", text: "UNKNOWN_TOOL" }] } }),
261
+ },
262
+ llm: (round) =>
263
+ round === 1
264
+ ? [toolCall("l1", "memory_list", "{}"), finish("tool-calls")]
265
+ : [
266
+ textBlock(
267
+ JSON.stringify({
268
+ writes: [
269
+ {
270
+ op: "create",
271
+ title: "Legacy Fallback",
272
+ description: "legacy path",
273
+ type: "project",
274
+ body: "fallback wrote this",
275
+ },
276
+ ],
277
+ }),
278
+ ),
279
+ finish("stop"),
280
+ ],
281
+ });
282
+ const { readdirSync } = await import("node:fs");
283
+ const proj = join(r.root, "projects");
284
+ let files = [];
285
+ if (existsSync(proj)) {
286
+ for (const d of readdirSync(proj)) {
287
+ const m = join(proj, d, "memory");
288
+ if (existsSync(m)) files = readdirSync(m).filter((f) => f.endsWith(".md") && f !== "MEMORY.md");
289
+ }
290
+ }
291
+ check(r.rounds.length === 2, "legacy fallback runs one JSON-agent round", r.rounds.length);
292
+ check(files.length === 1 && readFileSync(join(proj, readdirSync(proj)[0], "memory", files[0]), "utf8").includes("fallback wrote this"), "legacy fallback still writes memory", files);
293
+ try { rmSync(r.root, { recursive: true, force: true }); } catch {}
294
+ }
295
+
296
+ console.log(fails.length ? `FAIL ${fails.length}:\n - ` + fails.join("\n - ") : "ALL PASS");
297
+ process.exit(fails.length ? 1 : 0);