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,494 @@
1
+ // N3 沙箱授权生命周期:同 session 只注册一次、配置换根撤旧授新、关插件/关写入撤权、
2
+ // 插件卸载撤销全部授权、sandboxPolicy 缺失静默。
3
+ // 用法: node sandbox-grants.mjs [index.js 路径]
4
+ import { pathToFileURL } from "node:url";
5
+ import { mkdtempSync, mkdirSync, writeFileSync, rmSync, existsSync } from "node:fs";
6
+ import { tmpdir } from "node:os";
7
+ import { join } from "node:path";
8
+
9
+ const modUrl = process.argv[2] ? pathToFileURL(process.argv[2]).href : new URL("../index.js", import.meta.url).href;
10
+ const mod = await import(modUrl);
11
+
12
+ const root1 = mkdtempSync(join(tmpdir(), "zcm-grant1-"));
13
+ const root2 = mkdtempSync(join(tmpdir(), "zcm-grant2-"));
14
+ const log = [];
15
+ const cleanups = [];
16
+ const policy = {
17
+ registerWritableRoot(session, dir) {
18
+ log.push(`grant ${dir}`);
19
+ return () => log.push(`dispose ${dir}`);
20
+ },
21
+ };
22
+
23
+ const handlers = new Map();
24
+ const reg = { sections: [], contexts: [], tools: [], commands: [], handlers };
25
+ const ctx = {
26
+ systemPrompt: { section: () => {}, context: () => {} },
27
+ tools: { register: () => {} },
28
+ commands: { register: () => {} },
29
+ get: (name) => {
30
+ if (name === "sandboxPolicy") return policy;
31
+ if (name === "agents") return undefined;
32
+ return undefined;
33
+ },
34
+ effect: (fn) => {
35
+ const d = fn();
36
+ cleanups.push(d);
37
+ return d;
38
+ },
39
+ on: (ev, fn) => {
40
+ if (!handlers.has(ev)) handlers.set(ev, []);
41
+ handlers.get(ev).push(fn);
42
+ },
43
+ llm: { stream: async function* () {} },
44
+ };
45
+ const cfg = { memoriesRoot: root1, enabled: true, writeEnabled: true, grantScope: "root" };
46
+ mod.apply(ctx, cfg);
47
+
48
+ const emit = (ev, ...args) => { for (const fn of handlers.get(ev) || []) fn(...args); };
49
+ const fails = [];
50
+ const check = (cond, msg, extra) => {
51
+ if (!cond) fails.push(msg + (extra !== undefined ? ` :: ${JSON.stringify(extra).slice(0, 300)}` : ""));
52
+ };
53
+ const session = { header: { id: "sess-grant", cwd: process.cwd() }, origin: "user", delegationDepth: 0 };
54
+ const agent = { session, status: "idle", inbox: { nextTurn: [], nextStep: [] } };
55
+
56
+ // 1. created 注册;status 幂等。
57
+ emit("agent/created", { agent, source: "fresh" });
58
+ emit("agent/status", { agent, status: "running" });
59
+ emit("agent/status", { agent, status: "idle" });
60
+ check(log.length === 1 && log[0].startsWith("grant"), "one grant per session", log);
61
+
62
+ // 2. 改 memoriesRoot:撤旧根、授新根。
63
+ cfg.memoriesRoot = root2;
64
+ emit("agent/status", { agent, status: "running" });
65
+ check(log.length === 3 && log[1] === `dispose ${root1}` && log[2] === `grant ${root2}`, "root change revokes old and grants new", log);
66
+
67
+ // 3. enabled=false:撤权且不再授。
68
+ cfg.enabled = false;
69
+ emit("agent/status", { agent, status: "idle" });
70
+ check(log.length === 4 && log[3] === `dispose ${root2}`, "disabling plugin revokes grant", log);
71
+ emit("agent/status", { agent, status: "running" });
72
+ check(log.length === 4, "disabled plugin does not grant", log);
73
+
74
+ // 4. writeEnabled=false:同样不授。
75
+ cfg.enabled = true;
76
+ cfg.writeEnabled = false;
77
+ emit("agent/status", { agent, status: "idle" });
78
+ check(log.length === 4, "writeEnabled=false does not grant", log);
79
+
80
+ // 5. 重新打开:恢复授权。
81
+ cfg.writeEnabled = true;
82
+ emit("agent/status", { agent, status: "running" });
83
+ check(log.length === 5 && log[4] === `grant ${root2}`, "re-enabled session gets grant again", log);
84
+
85
+ // 6. 插件卸载:effect 清理必须撤销仍持有的授权。
86
+ check(cleanups.length === 1, "one plugin cleanup registered", cleanups.length);
87
+ for (const fn of cleanups) fn();
88
+ check(log[log.length - 1] === `dispose ${root2}`, "plugin unload disposes live grants", log);
89
+
90
+ // 7. sandboxPolicy 缺失:apply 与事件都不抛。
91
+ {
92
+ const h2 = new Map();
93
+ const ctx2 = {
94
+ systemPrompt: { section: () => {}, context: () => {} },
95
+ tools: { register: () => {} },
96
+ commands: { register: () => {} },
97
+ on: (ev, fn) => {
98
+ if (!h2.has(ev)) h2.set(ev, []);
99
+ h2.get(ev).push(fn);
100
+ },
101
+ llm: { stream: async function* () {} },
102
+ };
103
+ let threw = false;
104
+ try {
105
+ mod.apply(ctx2, { memoriesRoot: root1, enabled: true });
106
+ for (const fn of h2.get("agent/created") || []) fn({ agent, source: "fresh" });
107
+ for (const fn of h2.get("agent/status") || []) fn({ agent, status: "idle" });
108
+ } catch {
109
+ threw = true;
110
+ }
111
+ check(!threw, "missing sandboxPolicy must be silent");
112
+ }
113
+
114
+ // 8. C(v0.11):agent memory 的多目录授权、scope 切换、关开关、卸载撤权。
115
+ // 以及 restricted preset(没有 Write/Edit)时不再注入「用 Write 直接写」的提示。
116
+ {
117
+ const tempCwd = mkdtempSync(join(tmpdir(), "zcm-agentcwd-"));
118
+ const userStore = mkdtempSync(join(tmpdir(), "zcm-agentstore-"));
119
+ const log3 = [];
120
+ const policy3 = {
121
+ registerWritableRoot(_session, dir) {
122
+ log3.push(`grant ${dir}`);
123
+ return () => log3.push(`dispose ${dir}`);
124
+ },
125
+ };
126
+ const h3 = new Map();
127
+ let promptText = null;
128
+ let rulesText = null;
129
+ let schemas = [];
130
+ const reg3 = { tools: [], handlers: h3 };
131
+ const ctx3 = {
132
+ systemPrompt: {
133
+ // G9:规则在 section(zcode-memory-rules),索引在 context;断言看两段合并文本。
134
+ section: (o) => {
135
+ if (o.name === "zcode-memory-rules") rulesText = o;
136
+ },
137
+ context: (o) => {
138
+ if (o.name === "zcode-memory") promptText = o;
139
+ },
140
+ },
141
+ tools: {
142
+ register: (d) => reg3.tools.push(d),
143
+ schemas: () => schemas,
144
+ },
145
+ commands: { register: () => {} },
146
+ get: (name) => (name === "sandboxPolicy" ? policy3 : undefined),
147
+ effect: (fn) => fn(),
148
+ on: (ev, fn) => {
149
+ if (!h3.has(ev)) h3.set(ev, []);
150
+ h3.get(ev).push(fn);
151
+ },
152
+ llm: { stream: async function* () {} },
153
+ };
154
+ const cfg3 = {
155
+ memoriesRoot: root1,
156
+ enabled: true,
157
+ writeEnabled: true,
158
+ promptStyle: "native",
159
+ grantScope: "root",
160
+ agentMemoryEnabled: true,
161
+ agentMemoryScope: "user",
162
+ agentMemoryStorageRoot: userStore,
163
+ agentMemoryName: "tester",
164
+ };
165
+ mod.apply(ctx3, cfg3);
166
+ const emit3 = (ev, ...args) => {
167
+ for (const fn of h3.get(ev) || []) fn(...args);
168
+ };
169
+ const session3 = { header: { id: "sess-agent", cwd: tempCwd }, origin: "user", delegationDepth: 0 };
170
+ const agent3 = { session: session3, status: "idle", inbox: { nextTurn: [], nextStep: [] } };
171
+ const userAgentDir = join(userStore, "agent-memory", "tester");
172
+
173
+ emit3("agent/created", { agent: agent3, source: "fresh" });
174
+ check(
175
+ log3.length === 2 && log3[0] === `grant ${root1}` && log3[1] === `grant ${userAgentDir}`,
176
+ "agent memory user scope grants memoriesRoot + user root",
177
+ log3,
178
+ );
179
+ emit3("agent/status", { agent: agent3, status: "idle" });
180
+ check(log3.length === 2, "status is idempotent for multi-dir grants", log3);
181
+
182
+ // 换 scope:旧两个目录全部撤权,再授 memoriesRoot + project 根。
183
+ cfg3.agentMemoryScope = "local";
184
+ const localAgentDir = join(tempCwd, ".zcode", "agent-memory-local", "tester");
185
+ emit3("agent/status", { agent: agent3, status: "running" });
186
+ check(
187
+ log3.length === 6 &&
188
+ log3[2] === `dispose ${root1}` &&
189
+ log3[3] === `dispose ${userAgentDir}` &&
190
+ log3[4] === `grant ${root1}` &&
191
+ log3[5] === `grant ${localAgentDir}`,
192
+ "scope switch revokes both old dirs and grants new pair",
193
+ log3,
194
+ );
195
+
196
+ // 关 agent memory:撤掉两个目录,只重授 memoriesRoot(旧的 memoriesRoot 授权不强求复用)。
197
+ cfg3.agentMemoryEnabled = false;
198
+ emit3("agent/status", { agent: agent3, status: "running" });
199
+ check(
200
+ log3.length === 9 &&
201
+ log3[6] === `dispose ${root1}` &&
202
+ log3[7] === `dispose ${localAgentDir}` &&
203
+ log3[8] === `grant ${root1}`,
204
+ "disabling agent memory keeps only the memoriesRoot grant",
205
+ log3,
206
+ );
207
+
208
+ // 工具可达性:没有 Write/Edit 时注入只读说明,而不是「用 Write 直接写」。
209
+ // 注意:上面刚把 agentMemoryEnabled 关掉,这里重新打开(授权已单独验过)。
210
+ cfg3.agentMemoryEnabled = true;
211
+ cfg3.agentMemoryScope = "user";
212
+ schemas = [{ name: "read" }, { name: "glob" }, { name: "grep" }];
213
+ const full = (arg) => `${String(rulesText?.text(arg) ?? "")}\n\n${String(promptText?.text(arg) ?? "")}`;
214
+ const ro = full({ agent: { session: session3 } });
215
+ // 只看 agent memory 段:主 Memory 段的 native header 仍含 Write 指引(本轮不改它)。
216
+ const roStart = ro.indexOf("# Persistent Agent Memory");
217
+ const roEnd = ro.indexOf("\n# Memory\n", roStart);
218
+ const agentPart = ro.slice(roStart, roEnd > roStart ? roEnd : undefined);
219
+ check(/has no Write\/Edit tool/.test(agentPart), "restricted preset should get read-only agent memory note", agentPart.slice(0, 300));
220
+ check(!/write to it directly with the Write tool/i.test(agentPart), "restricted preset must not be told to use Write", agentPart.slice(0, 300));
221
+ // native Memory 段同样要降级:整段文本里不应再出现「用 Write 直接写」。
222
+ check(!/write to it directly with the Write tool/i.test(ro), "restricted preset: native Memory header must degrade too", ro.slice(0, 300));
223
+ check(/no Write\/Edit tool is available/.test(ro), "restricted preset: native header should say no write tool");
224
+
225
+ schemas = [{ name: "read" }, { name: "write" }, { name: "edit" }];
226
+ const rw = full({ agent: { session: { header: { ...session3.header, id: "sess-agent-2" } } } });
227
+ // 同一 cwd/preset 的 200ms memo 可能命中:等一会儿再取,确保按新 schemas 重建。
228
+ await new Promise((r) => setTimeout(r, 250));
229
+ const rw2 = full({ agent: { session: { header: { ...session3.header, id: "sess-agent-2" } } } });
230
+ check(/write to it directly with the Write tool/i.test(rw2), "write-capable preset keeps write guidance", rw2.slice(0, 200));
231
+ check(rw.length > 0, "writable prompt built");
232
+
233
+ try {
234
+ rmSync(tempCwd, { recursive: true, force: true });
235
+ rmSync(userStore, { recursive: true, force: true });
236
+ } catch {
237
+ /* noop */
238
+ }
239
+ }
240
+
241
+ // 9. 多目录授权「部分失败」后,下一次 agent 事件必须重试失败的那个目录
242
+ // (v0.11 第一版会把请求 key 记成已完成,失败目录整个会话都不补授)。
243
+ {
244
+ const failCwd = mkdtempSync(join(tmpdir(), "zcm-failcwd-"));
245
+ const store = mkdtempSync(join(tmpdir(), "zcm-failstore-"));
246
+ const log9 = [];
247
+ const policy9 = {
248
+ registerWritableRoot(_s, dir) {
249
+ if (dir.includes("agent-memory") && !policy9.recovered) {
250
+ policy9.recovered = false;
251
+ throw new Error("ACL transient failure");
252
+ }
253
+ log9.push(`grant ${dir}`);
254
+ return () => log9.push(`dispose ${dir}`);
255
+ },
256
+ recovered: false,
257
+ };
258
+ const h9 = new Map();
259
+ const ctx9 = {
260
+ systemPrompt: { section: () => {}, context: () => {} },
261
+ tools: { register: () => {} },
262
+ commands: { register: () => {} },
263
+ get: (name) => (name === "sandboxPolicy" ? policy9 : undefined),
264
+ on: (ev, fn) => {
265
+ if (!h9.has(ev)) h9.set(ev, []);
266
+ h9.get(ev).push(fn);
267
+ },
268
+ llm: { stream: async function* () {} },
269
+ };
270
+ const cfg9 = {
271
+ memoriesRoot: root1,
272
+ enabled: true,
273
+ grantScope: "root",
274
+ agentMemoryEnabled: true,
275
+ agentMemoryScope: "user",
276
+ agentMemoryStorageRoot: store,
277
+ agentMemoryName: "retry",
278
+ };
279
+ mod.apply(ctx9, cfg9);
280
+ const emit9 = (ev, ...args) => {
281
+ for (const fn of h9.get(ev) || []) fn(...args);
282
+ };
283
+ const session9 = { header: { id: "sess-retry", cwd: failCwd }, origin: "user", delegationDepth: 0 };
284
+ const agent9 = { session: session9, status: "idle", inbox: { nextTurn: [], nextStep: [] } };
285
+ emit9("agent/created", { agent: agent9, source: "fresh" });
286
+ check(log9.length === 1, "partial failure should still grant memoriesRoot", log9);
287
+ policy9.recovered = true;
288
+ emit9("agent/status", { agent: agent9, status: "running" });
289
+ check(
290
+ log9.length === 2 && log9[1] === `grant ${join(store, "agent-memory", "retry")}`,
291
+ "next status event must retry the failed directory",
292
+ log9,
293
+ );
294
+ try {
295
+ rmSync(failCwd, { recursive: true, force: true });
296
+ rmSync(store, { recursive: true, force: true });
297
+ } catch {
298
+ /* noop */
299
+ }
300
+ }
301
+
302
+ // 10. standard preset(且未配 agentMemoryName)永远不会注入 persistent memory:
303
+ // 不得为它创建 .zcode/agent-memory/standard,也不得扩权。
304
+ {
305
+ const stdCwd = mkdtempSync(join(tmpdir(), "zcm-stdcwd-"));
306
+ const log10 = [];
307
+ const policy10 = {
308
+ registerWritableRoot(_s, dir) {
309
+ log10.push(`grant ${dir}`);
310
+ return () => log10.push(`dispose ${dir}`);
311
+ },
312
+ };
313
+ const h10 = new Map();
314
+ const ctx10 = {
315
+ systemPrompt: { section: () => {}, context: () => {} },
316
+ tools: { register: () => {} },
317
+ commands: { register: () => {} },
318
+ get: (name) => (name === "sandboxPolicy" ? policy10 : undefined),
319
+ on: (ev, fn) => {
320
+ if (!h10.has(ev)) h10.set(ev, []);
321
+ h10.get(ev).push(fn);
322
+ },
323
+ llm: { stream: async function* () {} },
324
+ };
325
+ mod.apply(ctx10, {
326
+ memoriesRoot: root2,
327
+ enabled: true,
328
+ promptStyle: "native",
329
+ grantScope: "root",
330
+ agentMemoryEnabled: true,
331
+ agentMemoryScope: "project",
332
+ });
333
+ const emit10 = (ev, ...args) => {
334
+ for (const fn of h10.get(ev) || []) fn(...args);
335
+ };
336
+ const session10 = { header: { id: "sess-std", cwd: stdCwd, agentPreset: "standard" }, origin: "user", delegationDepth: 0 };
337
+ const agent10 = { session: session10, status: "idle", inbox: { nextTurn: [], nextStep: [] } };
338
+ emit10("agent/created", { agent: agent10, source: "fresh" });
339
+ check(log10.length === 1 && log10[0] === `grant ${root2}`, "standard preset should only grant memoriesRoot", log10);
340
+ check(!existsSync(join(stdCwd, ".zcode", "agent-memory", "standard")), "standard preset must not create agent-memory dir");
341
+ try {
342
+ rmSync(stdCwd, { recursive: true, force: true });
343
+ } catch {
344
+ /* noop */
345
+ }
346
+ }
347
+
348
+ // 11. G7(v0.12):默认收窄授权——只授实际 memory 目录,不授整个 memoriesRoot。
349
+ {
350
+ const cwd11 = mkdtempSync(join(tmpdir(), "zcm-narrowcwd-"));
351
+ const log11 = [];
352
+ const policy11 = {
353
+ registerWritableRoot(_s, dir) {
354
+ log11.push(`grant ${dir}`);
355
+ return () => log11.push(`dispose ${dir}`);
356
+ },
357
+ };
358
+ const h11 = new Map();
359
+ const tools11 = [];
360
+ const ctx11 = {
361
+ systemPrompt: { section: () => {}, context: () => {} },
362
+ tools: { register: (d) => tools11.push(d) },
363
+ commands: { register: () => {} },
364
+ get: (name) => (name === "sandboxPolicy" ? policy11 : undefined),
365
+ effect: (fn) => fn(),
366
+ on: (ev, fn) => {
367
+ if (!h11.has(ev)) h11.set(ev, []);
368
+ h11.get(ev).push(fn);
369
+ },
370
+ llm: { stream: async function* () {} },
371
+ };
372
+ mod.apply(ctx11, { memoriesRoot: root1, enabled: true, writeEnabled: true });
373
+ const emit11 = (ev, ...args) => {
374
+ for (const fn of h11.get(ev) || []) fn(...args);
375
+ };
376
+ const session11 = {
377
+ header: { id: "sess-narrow", cwd: cwd11, createdAt: "2026-12-05T10:00:00.000Z" },
378
+ origin: "user",
379
+ delegationDepth: 0,
380
+ };
381
+ const save11 = tools11.find((t) => t.name === "memory_save");
382
+ const r11 = await save11.execute(
383
+ { title: "Narrow", description: "d", body: "b", scope: "project" },
384
+ { agent: { session: session11 } },
385
+ );
386
+ check(r11?.ok, "narrow seed save ok", r11);
387
+ const projectDir11 = String(r11.file).slice(0, Math.max(String(r11.file).lastIndexOf("/"), String(r11.file).lastIndexOf("\\")));
388
+ const agent11 = { session: session11, status: "idle", inbox: { nextTurn: [], nextStep: [] } };
389
+ emit11("agent/created", { agent: agent11, source: "fresh" });
390
+ check(log11.length === 1 && log11[0] === `grant ${projectDir11}`, "narrow default grants only the project memory dir", log11);
391
+ check(!log11.includes(`grant ${root1}`), "narrow default must not grant the whole memoriesRoot", log11);
392
+
393
+ // injectGlobal:true 时 global memory 目录也要授;仍然不授整根。
394
+ const gdir = join(root1, "global", "memory");
395
+ mkdirSync(gdir, { recursive: true });
396
+ writeFileSync(join(gdir, "MEMORY.md"), "- [G](g.md) — g\n");
397
+ const cwd12 = mkdtempSync(join(tmpdir(), "zcm-narrowcwd2-"));
398
+ const log12 = [];
399
+ const policy12 = {
400
+ registerWritableRoot(_s, dir) {
401
+ log12.push(`grant ${dir}`);
402
+ return () => log12.push(`dispose ${dir}`);
403
+ },
404
+ };
405
+ const h12 = new Map();
406
+ const ctx12 = {
407
+ systemPrompt: { section: () => {}, context: () => {} },
408
+ tools: { register: () => {} },
409
+ commands: { register: () => {} },
410
+ get: (name) => (name === "sandboxPolicy" ? policy12 : undefined),
411
+ effect: (fn) => fn(),
412
+ on: (ev, fn) => {
413
+ if (!h12.has(ev)) h12.set(ev, []);
414
+ h12.get(ev).push(fn);
415
+ },
416
+ llm: { stream: async function* () {} },
417
+ };
418
+ mod.apply(ctx12, { memoriesRoot: root1, enabled: true, writeEnabled: true, injectGlobal: true });
419
+ const session12 = { header: { id: "sess-narrow2", cwd: cwd12 }, origin: "user", delegationDepth: 0 };
420
+ for (const fn of h12.get("agent/created") || []) fn({ agent: { session: session12 }, source: "fresh" });
421
+ check(log12.includes(`grant ${gdir}`), "narrow + injectGlobal grants the global dir", log12);
422
+ check(!log12.includes(`grant ${root1}`), "narrow + injectGlobal still must not grant the root", log12);
423
+ try {
424
+ rmSync(cwd11, { recursive: true, force: true });
425
+ rmSync(cwd12, { recursive: true, force: true });
426
+ } catch {
427
+ /* noop */
428
+ }
429
+ }
430
+
431
+ // 12. P2-3(v0.12):新项目目录还不存在 → 先不授;memory_save 建出目录后必须立即补授,
432
+ // 不能等到下一个 agent/status(规则段提示「save 后即可直写」必须是真的)。
433
+ {
434
+ const cwd13 = mkdtempSync(join(tmpdir(), "zcm-fresh-"));
435
+ const log13 = [];
436
+ const policy13 = {
437
+ registerWritableRoot(_s, dir) {
438
+ log13.push(`grant ${dir}`);
439
+ return () => log13.push(`dispose ${dir}`);
440
+ },
441
+ };
442
+ const h13 = new Map();
443
+ const tools13 = [];
444
+ const ctx13 = {
445
+ systemPrompt: { section: () => {}, context: () => {} },
446
+ tools: { register: (d) => tools13.push(d), schemas: () => [{ name: "write" }] },
447
+ commands: { register: () => {} },
448
+ get: (name) => (name === "sandboxPolicy" ? policy13 : undefined),
449
+ effect: (fn) => fn(),
450
+ on: (ev, fn) => {
451
+ if (!h13.has(ev)) h13.set(ev, []);
452
+ h13.get(ev).push(fn);
453
+ },
454
+ llm: { stream: async function* () {} },
455
+ };
456
+ // grantScope 默认 dirs。
457
+ mod.apply(ctx13, { memoriesRoot: root2, enabled: true, writeEnabled: true });
458
+ const session13 = {
459
+ header: { id: "sess-fresh", cwd: cwd13, createdAt: "2026-12-05T10:00:00.000Z" },
460
+ origin: "user",
461
+ delegationDepth: 0,
462
+ };
463
+ const agent13 = { session: session13, status: "idle", inbox: { nextTurn: [], nextStep: [] } };
464
+ for (const fn of h13.get("agent/created") || []) fn({ agent: agent13, source: "fresh" });
465
+ check(log13.length === 0, "fresh project dir: nothing to grant before the dir exists", log13);
466
+
467
+ const save13 = tools13.find((t) => t.name === "memory_save");
468
+ const r13 = await save13.execute(
469
+ { title: "Fresh", description: "d", body: "b", scope: "project" },
470
+ { agent: { session: session13 } },
471
+ );
472
+ check(r13?.ok, "fresh project save ok", r13);
473
+ const projectDir13 = String(r13.file).slice(0, Math.max(String(r13.file).lastIndexOf("/"), String(r13.file).lastIndexOf("\\")));
474
+ check(
475
+ log13.includes(`grant ${projectDir13}`),
476
+ "memory_save must grant the new project dir immediately (no agent event needed)",
477
+ log13,
478
+ );
479
+ check(!log13.includes(`grant ${root2}`), "save-time grant must stay narrow", log13);
480
+ try {
481
+ rmSync(cwd13, { recursive: true, force: true });
482
+ } catch {
483
+ /* noop */
484
+ }
485
+ }
486
+
487
+ console.log(fails.length ? `FAIL ${fails.length}:\n - ` + fails.join("\n - ") : "ALL PASS");
488
+ if (!fails.length) {
489
+ try {
490
+ rmSync(root1, { recursive: true, force: true });
491
+ rmSync(root2, { recursive: true, force: true });
492
+ } catch {}
493
+ }
494
+ process.exit(fails.length ? 1 : 0);
@@ -0,0 +1,190 @@
1
+ // N1 边界:memory_save 的 O_APPEND 追加与永久失败回滚。
2
+ // 覆盖:末尾无换行、CRLF 保持、GBK/BOM 索引回滚、同名 rel 回 upsert 不重复、
3
+ // MEMORY.md 为 symlink 时拒绝写入且回滚正文(无 symlink 权限则 skip)。
4
+ // 用法: node save-append-edges.mjs [index.js 路径]
5
+ import { pathToFileURL } from "node:url";
6
+ import {
7
+ mkdtempSync, mkdirSync, writeFileSync, readFileSync, existsSync, rmSync, symlinkSync, unlinkSync,
8
+ } 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 root = mkdtempSync(join(tmpdir(), "zcm-append-"));
16
+ const cwd = mkdtempSync(join(tmpdir(), "zcm-appendcwd-"));
17
+ const reg = { sections: [], contexts: [], tools: [], commands: [], handlers: new Map() };
18
+ const ctx = {
19
+ systemPrompt: { section: (o) => reg.sections.push(o), context: (o) => reg.contexts.push(o) },
20
+ tools: { register: (d) => reg.tools.push(d) },
21
+ commands: { register: (c) => reg.commands.push(c) },
22
+ on: (ev, fn) => { if (!reg.handlers.has(ev)) reg.handlers.set(ev, []); reg.handlers.get(ev).push(fn); },
23
+ llm: { stream: async function* () {} },
24
+ };
25
+ mod.apply(ctx, { memoriesRoot: root, enabled: true, promptStyle: "native" });
26
+
27
+ const save = reg.tools.find((t) => t.name === "memory_save");
28
+ const exec = { agent: { session: { id: "sess-append", header: { cwd, createdAt: "2026-12-05T10:00:00.000Z" } } } };
29
+ const fails = [];
30
+ const check = (cond, msg, extra) => {
31
+ if (!cond) fails.push(msg + (extra !== undefined ? ` :: ${JSON.stringify(extra).slice(0, 300)}` : ""));
32
+ };
33
+
34
+ const seed = await save.execute({ title: "Seed", description: "seed", body: "seed body", scope: "project" }, exec);
35
+ check(seed.ok, "seed save", seed);
36
+ function dirnameOf(p) {
37
+ const i = Math.max(String(p).lastIndexOf("/"), String(p).lastIndexOf("\\"));
38
+ return String(p).slice(0, i);
39
+ }
40
+ const projectDir = dirnameOf(seed.file);
41
+ const mem = join(projectDir, "MEMORY.md");
42
+ check(existsSync(projectDir), "project dir", projectDir);
43
+
44
+ // 工具函数:重置索引为给定内容(直接覆盖,绕过插件)。
45
+ function setIndex(content) {
46
+ writeFileSync(mem, content, { encoding: "utf8" });
47
+ }
48
+ function readIndex() {
49
+ return readFileSync(mem, "utf8");
50
+ }
51
+
52
+ // ---------- 1. 末尾无换行:追加行不能并进上一行 ----------
53
+ {
54
+ setIndex("- [A](a.md) — a");
55
+ writeFileSync(join(projectDir, "a.md"), "---\nname: a\n---\n\nA\n");
56
+ const r = await save.execute({ title: "NoTrail", description: "d", body: "b", scope: "project" }, exec);
57
+ const lines = readIndex().split(/\r?\n/).filter((l) => l !== "");
58
+ check(r.ok, "no-trailing-newline save ok", r);
59
+ check(lines.length === 2 && lines[0].startsWith("- [A]") && lines[1].startsWith("- [NoTrail]"), "no-trailing-newline appended as own line", lines);
60
+ }
61
+
62
+ // ---------- 2. CRLF 索引:追加行沿用 CRLF ----------
63
+ {
64
+ setIndex("- [A](a.md)\r\n");
65
+ const r = await save.execute({ title: "Crlf", description: "d", body: "b", scope: "project" }, exec);
66
+ const bytes = readFileSync(mem, "utf8");
67
+ const crlf = (bytes.match(/\r\n/g) || []).length;
68
+ const bareLf = (bytes.match(/(?<!\r)\n/g) || []).length;
69
+ check(r.ok, "crlf save ok", r);
70
+ check(crlf === 2 && bareLf === 0, "appended line keeps CRLF", { crlf, bareLf, text: JSON.stringify(bytes) });
71
+ }
72
+
73
+ // ---------- 3. GBK 索引:拒绝写入并回滚正文 ----------
74
+ {
75
+ const gbk = Buffer.from([0x2d, 0x20, 0xb2, 0xe2, 0xca, 0xd4, 0x0a]); // "- 测试\n" (GBK)
76
+ writeFileSync(mem, gbk);
77
+ const r = await save.execute({ title: "GbkDenied", description: "d", body: "b", scope: "project" }, exec);
78
+ check(r.ok === false && /UTF-8/.test(r.message), "GBK index rejected", r);
79
+ check(readFileSync(mem).equals(gbk), "GBK index bytes untouched");
80
+ check(!existsSync(join(projectDir, "GbkDenied.md")), "body rolled back after permanent index failure");
81
+ }
82
+
83
+ // ---------- 4. BOM 索引:同上 ----------
84
+ {
85
+ const withBom = Buffer.concat([Buffer.from([0xef, 0xbb, 0xbf]), Buffer.from("- [A](a.md)\n")]);
86
+ writeFileSync(mem, withBom);
87
+ const r = await save.execute({ title: "BomDenied", description: "d", body: "b", scope: "project" }, exec);
88
+ check(r.ok === false && /UTF-8/.test(r.message), "BOM index rejected", r);
89
+ check(readFileSync(mem).equals(withBom), "BOM index bytes untouched");
90
+ check(!existsSync(join(projectDir, "BomDenied.md")), "body rolled back on BOM index");
91
+ }
92
+
93
+ // ---------- 5. 索引已有同名 rel(正文不存在):回退 upsert,不产生重复行 ----------
94
+ {
95
+ setIndex("- [Dup](dup.md) — old hook\n");
96
+ const r = await save.execute({ title: "Dup", description: "fresh hook", body: "b", scope: "project" }, exec);
97
+ const lines = readIndex().split(/\r?\n/).filter((l) => l.trim());
98
+ check(r.ok, "upsert fallback save ok", r);
99
+ check(lines.filter((l) => l.includes("(dup.md)")).length === 1, "existing rel upserted without duplicate", lines);
100
+ check(lines[0].includes("fresh hook"), "upsert refreshes hook", lines);
101
+ }
102
+
103
+ // ---------- 6. MEMORY.md 为 symlink:拒绝写入并回滚正文 ----------
104
+ {
105
+ const sentinel = join(root, "sentinel.txt");
106
+ writeFileSync(sentinel, "SENTINEL\n");
107
+ unlinkSync(mem);
108
+ let linked = false;
109
+ try {
110
+ symlinkSync(sentinel, mem, "file");
111
+ linked = true;
112
+ } catch {
113
+ // Windows 无开发者模式/管理员:无权限建 symlink,跳过这一项。
114
+ }
115
+ if (linked) {
116
+ const r = await save.execute({ title: "SymDenied", description: "d", body: "b", scope: "project" }, exec);
117
+ check(r.ok === false && /symlink/i.test(r.message), "symlink index rejected", r);
118
+ check(readFileSync(sentinel, "utf8") === "SENTINEL\n", "symlink target untouched");
119
+ check(!existsSync(join(projectDir, "SymDenied.md")), "body rolled back on symlink index");
120
+ } else {
121
+ writeFileSync(mem, "- [A](a.md)\n");
122
+ console.log("skip: symlink capability unavailable");
123
+ }
124
+ }
125
+
126
+ // ---------- 7. G5:flow-map frontmatter 补戳(单行标量支持;嵌套/多行仍跳过) ----------
127
+ {
128
+ const sess = { header: { id: "sess-append", cwd, createdAt: "2026-12-05T10:00:00.000Z" } };
129
+ // 多个插件钩子都挂在 tools/post-execute(autoRemember 在补戳之前注册),逐个跑。
130
+ const handlers = reg.handlers.get("tools/post-execute") || [];
131
+ check(handlers.length > 0, "post-execute hook missing");
132
+ const runStamp = async (file) => {
133
+ const exec = { name: "write", arguments: { file_path: file }, agent: { session: sess } };
134
+ for (const h of handlers) await h(exec, { isError: false }, async () => ({ kind: "accept" }));
135
+ return readFileSync(file, "utf8");
136
+ };
137
+
138
+ const flow = join(projectDir, "flowmap.md");
139
+ writeFileSync(flow, "---\nname: flowmap\ndescription: d\nmetadata: {type: user}\n---\n\nbody\n");
140
+ const out = await runStamp(flow);
141
+ check(/node_type:\s*memory/.test(out), "flow-map should be stamped with node_type", out.slice(0, 300));
142
+ check(/originSessionId:\s*"?sess-append"?/.test(out), "flow-map should be stamped with originSessionId", out.slice(0, 300));
143
+ check(/type:\s*user/.test(out), "flow-map existing key must be preserved", out.slice(0, 300));
144
+ check(/^metadata:\s*$/m.test(out), "flow map should be expanded to a block map", out.slice(0, 300));
145
+
146
+ const nested = join(projectDir, "nestedflow.md");
147
+ const nestedSrc = "---\nname: nested\ndescription: d\nmetadata: {type: user, tags: [a, b]}\n---\n\nbody\n";
148
+ writeFileSync(nested, nestedSrc);
149
+ check((await runStamp(nested)) === nestedSrc, "nested flow-map must be left untouched");
150
+
151
+ const multiline = join(projectDir, "multiflow.md");
152
+ const multiSrc = "---\nname: multi\ndescription: d\nmetadata: {type: user,\n tags: x}\n---\n\nbody\n";
153
+ writeFileSync(multiline, multiSrc);
154
+ check((await runStamp(multiline)) === multiSrc, "multi-line flow-map must be left untouched");
155
+
156
+ const already = join(projectDir, "alreadystamped.md");
157
+ const alreadySrc = "---\nname: done\ndescription: d\nmetadata:\n node_type: memory\n type: user\n originSessionId: \"sess-append\"\n---\n\nbody\n";
158
+ writeFileSync(already, alreadySrc);
159
+ check((await runStamp(already)) === alreadySrc, "already-stamped file must not be rewritten");
160
+
161
+ // 复查 P1:plain scalar 里的撇号不是引号——不能把两个键合并成一行写坏 YAML。
162
+ const apos = join(projectDir, "apostrophe.md");
163
+ writeFileSync(apos, "---\nname: apos\ndescription: d\nmetadata: {author: O'Neil, type: project}\n---\n\nbody\n");
164
+ const aposOut = await runStamp(apos);
165
+ check(/node_type:\s*memory/.test(aposOut), "apostrophe flow-map should be stamped", aposOut.slice(0, 300));
166
+ check(/^ {2}author: O'Neil$/m.test(aposOut), "apostrophe value must stay on its own line", aposOut.slice(0, 300));
167
+ check(/^ {2}type: project$/m.test(aposOut), "second key must not be merged into the first", aposOut.slice(0, 300));
168
+
169
+ // 复查 P3:行尾注释的 flow map 也支持(注释不进入展开结果)。
170
+ const tailNote = join(projectDir, "tailnote.md");
171
+ writeFileSync(tailNote, "---\nname: tn\ndescription: d\nmetadata: {type: user} # note\n---\n\nbody\n");
172
+ const tnOut = await runStamp(tailNote);
173
+ check(/node_type:\s*memory/.test(tnOut), "flow-map with trailing comment should be stamped", tnOut.slice(0, 300));
174
+ check(!tnOut.includes("# note"), "trailing comment must not leak into the expanded block");
175
+
176
+ // 复查 P3:重复键本来就非法,整文件跳过(不猜保留哪个)。
177
+ const dupKey = join(projectDir, "dupkey.md");
178
+ const dupSrc = "---\nname: dup\ndescription: d\nmetadata: {a: 1, a: 2}\n---\n\nbody\n";
179
+ writeFileSync(dupKey, dupSrc);
180
+ check((await runStamp(dupKey)) === dupSrc, "duplicate-key flow-map must be left untouched");
181
+ }
182
+
183
+ console.log(fails.length ? `FAIL ${fails.length}:\n - ` + fails.join("\n - ") : "ALL PASS");
184
+ if (!fails.length) {
185
+ try {
186
+ rmSync(root, { recursive: true, force: true });
187
+ rmSync(cwd, { recursive: true, force: true });
188
+ } catch {}
189
+ }
190
+ process.exit(fails.length ? 1 : 0);