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/LICENSE +21 -0
- package/README.md +251 -2
- package/client.js +573 -0
- package/cordis.patch.yml +6 -0
- package/index.js +7143 -0
- package/package.json +49 -4
- package/tests/abort-loop.mjs +70 -0
- package/tests/ancestor-lookup.mjs +169 -0
- package/tests/append-race.mjs +90 -0
- package/tests/backlog-state.mjs +274 -0
- package/tests/client-bundle.mjs +256 -0
- package/tests/context-memo.mjs +85 -0
- package/tests/extract-cost.mjs +312 -0
- package/tests/extract-retry.mjs +88 -0
- package/tests/extract-system.mjs +138 -0
- package/tests/extract-window.mjs +236 -0
- package/tests/extract.mjs +126 -0
- package/tests/func.mjs +217 -0
- package/tests/index-budget.mjs +182 -0
- package/tests/index-comments.mjs +92 -0
- package/tests/index-truncate.mjs +237 -0
- package/tests/memory-notes.mjs +90 -0
- package/tests/native-tools-edge.mjs +297 -0
- package/tests/native-tools.mjs +182 -0
- package/tests/prompt-split.mjs +253 -0
- package/tests/recall-score.mjs +225 -0
- package/tests/resume-recovery.mjs +245 -0
- package/tests/sandbox-grants.mjs +494 -0
- package/tests/save-append-edges.mjs +190 -0
- package/tests/sensitive-path.mjs +227 -0
- package/tests/settings-api.mjs +399 -0
- package/tests/settings-disable.mjs +280 -0
- package/tests/smoke.mjs +111 -0
|
@@ -0,0 +1,227 @@
|
|
|
1
|
+
// E(v0.11)敏感段守卫:对齐 zcode.cjs 的 T5a/x5a/k5a。
|
|
2
|
+
// memory_update/delete 的 rel、抽取目标、直写守卫、补戳、reindex 都不得把
|
|
3
|
+
// .git/hooks/node_modules/.zcode/skills 等段下的 .md 当记忆。
|
|
4
|
+
// 用法: node sensitive-path.mjs [index.js 路径]
|
|
5
|
+
import { pathToFileURL } from "node:url";
|
|
6
|
+
import { mkdtempSync, mkdirSync, writeFileSync, readFileSync, existsSync, rmSync } from "node:fs";
|
|
7
|
+
import { createHash } from "node:crypto";
|
|
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 MEM = (name, body) =>
|
|
20
|
+
`---\nname: ${JSON.stringify(name)}\ndescription: "test"\nmetadata:\n type: project\n---\n\n${body}\n`;
|
|
21
|
+
|
|
22
|
+
const root = mkdtempSync(join(tmpdir(), "zcm-sens-"));
|
|
23
|
+
const cwd = mkdtempSync(join(tmpdir(), "zcm-senscwd-"));
|
|
24
|
+
const hash = createHash("sha256").update("sens-identity", "utf8").digest("hex").slice(0, 16);
|
|
25
|
+
const dir = join(root, "projects", `project-${hash}`, "memory");
|
|
26
|
+
mkdirSync(join(dir, "sub"), { recursive: true });
|
|
27
|
+
writeFileSync(join(dir, "MEMORY.md"), "- [Allowed](sub/x.md) — ok\n");
|
|
28
|
+
writeFileSync(join(dir, "sub", "x.md"), MEM("allowed", "合法子目录里的记忆。"));
|
|
29
|
+
for (const seg of [
|
|
30
|
+
"hooks", ".git", "node_modules", ".zcode", "skills", "commands", "agents",
|
|
31
|
+
".cargo", ".yarn", "config", "head", ".husky", ".githooks", ".vscode", ".idea",
|
|
32
|
+
"objects", "refs", ".claude", ".devcontainer", ".mvn",
|
|
33
|
+
]) {
|
|
34
|
+
mkdirSync(join(dir, seg), { recursive: true });
|
|
35
|
+
writeFileSync(join(dir, seg, "x.md"), MEM("trap", `陷阱段 ${seg} 里的文件。`));
|
|
36
|
+
}
|
|
37
|
+
// 嵌套敏感段:sub/config/x.md 也不能被当成记忆。
|
|
38
|
+
mkdirSync(join(dir, "sub", "config"), { recursive: true });
|
|
39
|
+
writeFileSync(join(dir, "sub", "config", "x.md"), MEM("nested-trap", "嵌套敏感段里的文件。"));
|
|
40
|
+
|
|
41
|
+
const reg = { sections: [], tools: [], commands: [], handlers: new Map() };
|
|
42
|
+
const ctx = {
|
|
43
|
+
systemPrompt: { section: (o) => reg.sections.push(o), context: () => {} },
|
|
44
|
+
tools: { register: (d) => reg.tools.push(d) },
|
|
45
|
+
commands: { register: (c) => reg.commands.push(c) },
|
|
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
|
+
const cfg = { memoriesRoot: root, enabled: true, workspaceIdentity: "sens-identity", promptStyle: "native" };
|
|
53
|
+
mod.apply(ctx, cfg);
|
|
54
|
+
|
|
55
|
+
const emit = async (ev, ...args) => {
|
|
56
|
+
const out = [];
|
|
57
|
+
for (const fn of reg.handlers.get(ev) || []) out.push(await fn(...args));
|
|
58
|
+
return out;
|
|
59
|
+
};
|
|
60
|
+
const tool = (n) => reg.tools.find((t) => t.name === n);
|
|
61
|
+
const exec = (extra = {}) => ({ agent: { session: { header: { id: "sess-sens", cwd } } }, ...extra });
|
|
62
|
+
|
|
63
|
+
try {
|
|
64
|
+
// 1. rel 守卫:合法子目录允许,所有敏感段拒绝(含 bidi/尾点/冒号前缀变体)。
|
|
65
|
+
const update = tool("memory_update");
|
|
66
|
+
check(!!update, "memory_update missing");
|
|
67
|
+
const del = tool("memory_delete");
|
|
68
|
+
const allowed = await update.execute({ name: "allowed", rel: "sub/x.md", body: "合法更新。" }, exec());
|
|
69
|
+
check(allowed.ok === true, "allowed sub/x.md must update", allowed);
|
|
70
|
+
|
|
71
|
+
const refuse = [
|
|
72
|
+
".git/x.md",
|
|
73
|
+
"hooks/x.md",
|
|
74
|
+
"node_modules/x.md",
|
|
75
|
+
".zcode/x.md",
|
|
76
|
+
"skills/x.md",
|
|
77
|
+
"commands/x.md",
|
|
78
|
+
"agents/x.md",
|
|
79
|
+
".cargo/x.md",
|
|
80
|
+
".yarn/x.md",
|
|
81
|
+
"config/x.md",
|
|
82
|
+
"head/x.md",
|
|
83
|
+
".husky/x.md",
|
|
84
|
+
".githooks/x.md",
|
|
85
|
+
".vscode/x.md",
|
|
86
|
+
".idea/x.md",
|
|
87
|
+
"objects/x.md",
|
|
88
|
+
"refs/x.md",
|
|
89
|
+
".claude/x.md",
|
|
90
|
+
".devcontainer/x.md",
|
|
91
|
+
".mvn/x.md",
|
|
92
|
+
"sub/config/x.md",
|
|
93
|
+
"sub/hooks/x.md",
|
|
94
|
+
"skills\u200b/x.md",
|
|
95
|
+
"skills\u200e/x.md",
|
|
96
|
+
".git./x.md",
|
|
97
|
+
"skills:stream/x.md",
|
|
98
|
+
".GiT/x.md",
|
|
99
|
+
"C:/x.md",
|
|
100
|
+
"../escape.md",
|
|
101
|
+
"sub/../x.md",
|
|
102
|
+
];
|
|
103
|
+
for (const rel of refuse) {
|
|
104
|
+
const r = await update.execute({ name: "any", rel, body: "不该写进去。" }, exec());
|
|
105
|
+
check(r.ok === false, `update must refuse rel=${JSON.stringify(rel)}`, r);
|
|
106
|
+
check(/敏感段|绝对路径|不能包含/.test(String(r.message)), `refusal reason for=${JSON.stringify(rel)}`, r.message);
|
|
107
|
+
const d = await del.execute({ name: "any", rel }, exec());
|
|
108
|
+
check(d.ok === false, `delete must refuse rel=${JSON.stringify(rel)}`, d);
|
|
109
|
+
}
|
|
110
|
+
// 合法子目录没被误伤
|
|
111
|
+
check(readFileSync(join(dir, "sub", "x.md"), "utf8").includes("合法更新"), "allowed file not updated");
|
|
112
|
+
|
|
113
|
+
// 读侧一致性:敏感段里的既有文件不能「可读可列出、却改不了删不了」。
|
|
114
|
+
// walkMd 已跳过敏感目录,所以 memory_read/list/recall 都看不到它们。
|
|
115
|
+
for (const nm of ["trap", "nested-trap"]) {
|
|
116
|
+
const rd = await tool("memory_read").execute({ name: nm, scope: "project" }, exec());
|
|
117
|
+
check(rd.hit === false, `memory_read must not surface sensitive "${nm}"`, rd);
|
|
118
|
+
}
|
|
119
|
+
const listed = await tool("memory_list").execute({ scope: "project" }, exec());
|
|
120
|
+
check(!JSON.stringify(listed).includes("陷阱段"), "memory_list must not surface sensitive entries", listed);
|
|
121
|
+
|
|
122
|
+
// 2. 直写守卫:主代理 Write 到 hooks/x.md 被拒绝(不是跳过补戳,而是拒绝写)。
|
|
123
|
+
const [deny] = await emit(
|
|
124
|
+
"tools/pre-execute",
|
|
125
|
+
{ name: "write", arguments: JSON.stringify({ file_path: join(dir, "hooks", "x.md") }), agent: { session: { header: { cwd } } } },
|
|
126
|
+
async () => ({ kind: "accept" }),
|
|
127
|
+
);
|
|
128
|
+
check(deny?.kind === "deny", "write guard must deny hooks/x.md", deny);
|
|
129
|
+
check(/敏感段/.test(String(deny?.reason)), "deny reason mentions segment", deny);
|
|
130
|
+
const [allowWrite] = await emit(
|
|
131
|
+
"tools/pre-execute",
|
|
132
|
+
{ name: "write", arguments: JSON.stringify({ file_path: join(dir, "sub", "x.md") }), agent: { session: { header: { cwd } } } },
|
|
133
|
+
async () => ({ kind: "accept" }),
|
|
134
|
+
);
|
|
135
|
+
check(allowWrite?.kind === "accept", "normal memory path must pass", allowWrite);
|
|
136
|
+
|
|
137
|
+
// 3. 补戳:敏感段文件不被盖章,正常文件照常补。
|
|
138
|
+
const trap = join(dir, "node_modules", "x.md");
|
|
139
|
+
// 旧版本测试在上面的 delete 循环里可能已经把夹具删掉:重新放回去再测。
|
|
140
|
+
writeFileSync(trap, MEM("trap", "陷阱段 node_modules 里的文件。"));
|
|
141
|
+
check(!readFileSync(trap, "utf8").includes("node_type"), "trap fixture should lack node_type");
|
|
142
|
+
const legit = join(dir, "sub", "stamp-me.md");
|
|
143
|
+
writeFileSync(legit, MEM("stamp-me", "待补戳。"));
|
|
144
|
+
const [res] = await emit(
|
|
145
|
+
"tools/post-execute",
|
|
146
|
+
{ name: "write", arguments: JSON.stringify({ file_path: trap }), agent: { session: { header: { id: "sess-sens", cwd } } } },
|
|
147
|
+
{ kind: "accept", value: { status: "completed", path: trap } },
|
|
148
|
+
async () => ({ kind: "accept" }),
|
|
149
|
+
);
|
|
150
|
+
check(res?.kind === "accept", "post-execute passthrough");
|
|
151
|
+
check(!readFileSync(trap, "utf8").includes("originSessionId"), "sensitive file must not be stamped");
|
|
152
|
+
await emit(
|
|
153
|
+
"tools/post-execute",
|
|
154
|
+
{ name: "write", arguments: JSON.stringify({ file_path: legit }), agent: { session: { header: { id: "sess-sens", cwd } } } },
|
|
155
|
+
{ kind: "accept", value: { status: "completed", path: legit } },
|
|
156
|
+
async () => ({ kind: "accept" }),
|
|
157
|
+
);
|
|
158
|
+
check(readFileSync(legit, "utf8").includes("originSessionId"), "legit file must be stamped");
|
|
159
|
+
|
|
160
|
+
// 4. reindex:敏感段里的 .md 不补索引行。
|
|
161
|
+
const reindex = tool("memory_reindex");
|
|
162
|
+
check(!!reindex, "memory_reindex missing");
|
|
163
|
+
const r = await reindex.execute({ scope: "project", dryRun: true }, exec());
|
|
164
|
+
const addedRels = (r.added || []).map((x) => x.rel);
|
|
165
|
+
check(!addedRels.some((x) => /(^|\/)(hooks|node_modules|skills|agents|commands|\.git|\.zcode|config|head)\//.test(String(x))), "reindex added sensitive file", addedRels);
|
|
166
|
+
check(String(r.message || "").length > 0, "reindex message");
|
|
167
|
+
|
|
168
|
+
// 5. 抽取落盘:目标只存在于 hooks/ 时按「找不到」跳过,不归档/不改写。
|
|
169
|
+
mkdirSync(join(dir, "hooks"), { recursive: true });
|
|
170
|
+
writeFileSync(join(dir, "hooks", "x.md"), MEM("trap-hook", "陷阱段 hooks 里的文件。"));
|
|
171
|
+
const before = readFileSync(join(dir, "hooks", "x.md"), "utf8");
|
|
172
|
+
const calls = [];
|
|
173
|
+
ctx.llm.stream = async function* (opts) {
|
|
174
|
+
calls.push(opts);
|
|
175
|
+
yield { type: "text-delta", text: JSON.stringify({ writes: [{ op: "update", target: "trap", body: "被污染。" }] }) };
|
|
176
|
+
yield { type: "finish", reason: { kind: "stop" } };
|
|
177
|
+
};
|
|
178
|
+
const session = { header: { id: "sess-extract", cwd, createdAt: "2026-12-05T12:00:00.000Z" } };
|
|
179
|
+
let ran = false;
|
|
180
|
+
const agent = {
|
|
181
|
+
session,
|
|
182
|
+
status: "idle",
|
|
183
|
+
inbox: { nextTurn: [], nextStep: [] },
|
|
184
|
+
model: { current: () => ({ provider: "mock", model: "mock-1" }) },
|
|
185
|
+
whenIdle: () => Promise.resolve(),
|
|
186
|
+
runMaintenance: async (fn) => {
|
|
187
|
+
ran = true;
|
|
188
|
+
return fn(new AbortController().signal);
|
|
189
|
+
},
|
|
190
|
+
};
|
|
191
|
+
await emit("session/event", session, { type: "turn/start", seq: 1, data: { turn: 1 } });
|
|
192
|
+
await emit("session/event", session, {
|
|
193
|
+
type: "user/message",
|
|
194
|
+
seq: 2,
|
|
195
|
+
data: { source: { kind: "user" }, content: [{ type: "text", text: "请记住:这个项目的发布命令是 pnpm release,产物在 dist 目录里。" }] },
|
|
196
|
+
});
|
|
197
|
+
await emit("session/event", session, {
|
|
198
|
+
type: "assistant/message",
|
|
199
|
+
seq: 3,
|
|
200
|
+
data: { turn: 1, message: { content: [{ type: "text", text: "好的,发布命令是 pnpm release,产物在 dist。" }] } },
|
|
201
|
+
});
|
|
202
|
+
await emit("agent/turn-stopping", { agent, turn: 1 });
|
|
203
|
+
for (let i = 0; i < 100 && !ran; i++) await new Promise((r) => setTimeout(r, 20));
|
|
204
|
+
for (let i = 0; i < 100; i++) {
|
|
205
|
+
if (!ran) break;
|
|
206
|
+
const stFile = join(root, "_extract-state.json");
|
|
207
|
+
if (existsSync(stFile)) break;
|
|
208
|
+
await new Promise((r) => setTimeout(r, 20));
|
|
209
|
+
}
|
|
210
|
+
check(ran, "extraction maintenance not started");
|
|
211
|
+
check(calls.length >= 1, "mock llm not called");
|
|
212
|
+
check(readFileSync(join(dir, "hooks", "x.md"), "utf8") === before, "sensitive target must not be modified by extraction");
|
|
213
|
+
} finally {
|
|
214
|
+
try {
|
|
215
|
+
rmSync(root, { recursive: true, force: true });
|
|
216
|
+
rmSync(cwd, { recursive: true, force: true });
|
|
217
|
+
} catch {
|
|
218
|
+
/* noop */
|
|
219
|
+
}
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
if (fails.length) {
|
|
223
|
+
console.error("FAIL sensitive-path");
|
|
224
|
+
for (const f of fails) console.error(" -", f);
|
|
225
|
+
process.exit(1);
|
|
226
|
+
}
|
|
227
|
+
console.log("PASS sensitive-path");
|
|
@@ -0,0 +1,399 @@
|
|
|
1
|
+
// 设置页接口回归:/dsh-zcode-memory-api 的快照、开关落盘与「profile 硬关闭」优先级。
|
|
2
|
+
// 用法: node tests/settings-api.mjs [index.js 路径]
|
|
3
|
+
import { pathToFileURL } from "node:url";
|
|
4
|
+
import { mkdtempSync, mkdirSync, writeFileSync, readFileSync, rmSync, existsSync } 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 fails = [];
|
|
12
|
+
const ok = (cond, msg, extra) => { if (!cond) fails.push(msg + (extra === undefined ? "" : ` (got ${JSON.stringify(extra).slice(0, 300)})`)); };
|
|
13
|
+
const eq = (a, b, msg) => ok(a === b, `${msg}: expected ${JSON.stringify(b)}, got ${JSON.stringify(a)}`);
|
|
14
|
+
|
|
15
|
+
const root = mkdtempSync(join(tmpdir(), "zcm-settings-"));
|
|
16
|
+
|
|
17
|
+
/** 造一份项目 + 全局记忆,来源与 walkMd/listWorkspaces 的约定一致。 */
|
|
18
|
+
function seed(p, mtimeNote) {
|
|
19
|
+
const wsDir = join(p, "projects", "zcode-0123456789abcdef", "memory");
|
|
20
|
+
mkdirSync(wsDir, { recursive: true });
|
|
21
|
+
writeFileSync(join(wsDir, "MEMORY.md"), "- [你好](hello.md) — 项目示例\n", "utf8");
|
|
22
|
+
writeFileSync(join(wsDir, "hello.md"), [
|
|
23
|
+
"---",
|
|
24
|
+
"name: hello",
|
|
25
|
+
"description: 项目示例摘要",
|
|
26
|
+
"metadata:",
|
|
27
|
+
" type: project",
|
|
28
|
+
"---",
|
|
29
|
+
"项目正文。",
|
|
30
|
+
].join("\n"), "utf8");
|
|
31
|
+
// 超长正文:设置页返回的 body 必须截到 SETTINGS_BODY_CAP(1600),而 chars 保留全长。
|
|
32
|
+
writeFileSync(join(wsDir, "long.md"), [
|
|
33
|
+
"---",
|
|
34
|
+
"name: long",
|
|
35
|
+
"description: 超长正文",
|
|
36
|
+
"---",
|
|
37
|
+
"长".repeat(5000) + (mtimeNote || ""),
|
|
38
|
+
].join("\n"), "utf8");
|
|
39
|
+
|
|
40
|
+
const globalDir = join(p, "global", "memory");
|
|
41
|
+
mkdirSync(globalDir, { recursive: true });
|
|
42
|
+
writeFileSync(join(globalDir, "MEMORY.md"), "- [全局条目](g-note.md) — 全局示例\n", "utf8");
|
|
43
|
+
writeFileSync(join(globalDir, "g-note.md"), [
|
|
44
|
+
"---",
|
|
45
|
+
"name: g-note",
|
|
46
|
+
"description: 全局示例摘要",
|
|
47
|
+
"metadata:",
|
|
48
|
+
" type: user",
|
|
49
|
+
"---",
|
|
50
|
+
"全局正文。",
|
|
51
|
+
].join("\n"), "utf8");
|
|
52
|
+
}
|
|
53
|
+
seed(root);
|
|
54
|
+
|
|
55
|
+
/** 最小 ctx:记录 prompt/tools/commands,并替 webServer 捕获路由。 */
|
|
56
|
+
function makeCtx() {
|
|
57
|
+
const reg = { sections: [], contexts: [], tools: [], commands: [], handlers: new Map(), route: null, warns: [] };
|
|
58
|
+
const ctx = {
|
|
59
|
+
systemPrompt: {
|
|
60
|
+
section: (o) => reg.sections.push(o),
|
|
61
|
+
context: (o) => reg.contexts.push(o),
|
|
62
|
+
},
|
|
63
|
+
tools: { register: (d) => reg.tools.push(d) },
|
|
64
|
+
commands: { register: (c) => reg.commands.push(c) },
|
|
65
|
+
on: (ev, fn) => {
|
|
66
|
+
if (!reg.handlers.has(ev)) reg.handlers.set(ev, []);
|
|
67
|
+
reg.handlers.get(ev).push(fn);
|
|
68
|
+
},
|
|
69
|
+
llm: { stream: async function* () {} },
|
|
70
|
+
inject(names, cb) {
|
|
71
|
+
ok(Array.isArray(names) && names.includes("webServer"), "must inject webServer", names);
|
|
72
|
+
const scoped = {
|
|
73
|
+
webServer: { register: (r) => { reg.route = r; return () => {}; } },
|
|
74
|
+
effect: (fn) => fn(),
|
|
75
|
+
logger: { warn: (m) => reg.warns.push(String(m)) },
|
|
76
|
+
};
|
|
77
|
+
cb(scoped);
|
|
78
|
+
},
|
|
79
|
+
logger: { warn: (m) => reg.warns.push(String(m)) },
|
|
80
|
+
};
|
|
81
|
+
return { ctx, reg };
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/** 调路由:GET 同步返回;POST 由 handler 内部异步回包,统一在 end() 时 resolve。 */
|
|
85
|
+
function call(reg, method, body, opts = {}) {
|
|
86
|
+
return new Promise((resolve, reject) => {
|
|
87
|
+
const headers = { host: "127.0.0.1:3210", ...(opts.headers || {}) };
|
|
88
|
+
if (method === "POST") headers["content-type"] = headers["content-type"] || "application/json";
|
|
89
|
+
const req = {
|
|
90
|
+
method,
|
|
91
|
+
url: opts.url || "/dsh-zcode-memory-api",
|
|
92
|
+
headers,
|
|
93
|
+
socket: opts.socket === undefined ? { remoteAddress: "127.0.0.1" } : opts.socket,
|
|
94
|
+
async *[Symbol.asyncIterator]() {
|
|
95
|
+
if (body !== undefined) yield Buffer.from(typeof body === "string" ? body : JSON.stringify(body));
|
|
96
|
+
},
|
|
97
|
+
};
|
|
98
|
+
let status = 0;
|
|
99
|
+
const res = {
|
|
100
|
+
writeHead: (s) => { status = s; },
|
|
101
|
+
end: (chunk) => {
|
|
102
|
+
try {
|
|
103
|
+
resolve({ status, body: JSON.parse(String(chunk || "null")) });
|
|
104
|
+
} catch (e) {
|
|
105
|
+
reject(e);
|
|
106
|
+
}
|
|
107
|
+
},
|
|
108
|
+
};
|
|
109
|
+
reg.route.handler(req, res);
|
|
110
|
+
});
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
// ---- 第一轮:config enabled=true ----
|
|
114
|
+
{
|
|
115
|
+
const { ctx, reg } = makeCtx();
|
|
116
|
+
mod.apply(ctx, { memoriesRoot: root, enabled: true, promptStyle: "native" });
|
|
117
|
+
ok(!!reg.route, "settings route was not registered");
|
|
118
|
+
eq(reg.route.path, "/dsh-zcode-memory-api", "route path");
|
|
119
|
+
|
|
120
|
+
const get = await call(reg, "GET");
|
|
121
|
+
eq(get.status, 200, "GET status");
|
|
122
|
+
eq(get.body.ok, true, "GET ok");
|
|
123
|
+
eq(get.body.enabled, true, "GET enabled");
|
|
124
|
+
eq(get.body.configEnabled, true, "GET configEnabled");
|
|
125
|
+
eq(get.body.stateEnabled, null, "GET stateEnabled before any toggle");
|
|
126
|
+
eq(get.body.counts.total, 3, "GET total count");
|
|
127
|
+
eq(get.body.counts.project, 2, "GET project count");
|
|
128
|
+
eq(get.body.counts.global, 1, "GET global count");
|
|
129
|
+
|
|
130
|
+
const hello = get.body.items.find((it) => it.slug === "hello");
|
|
131
|
+
ok(!!hello, "project memory missing");
|
|
132
|
+
eq(hello.title, "你好", "index title takes precedence");
|
|
133
|
+
eq(hello.scope, "project", "project scope");
|
|
134
|
+
eq(hello.type, "project", "type passthrough");
|
|
135
|
+
ok(hello.workspace === "zcode", "workspace label should drop the hash", hello.workspace);
|
|
136
|
+
|
|
137
|
+
const long = get.body.items.find((it) => it.slug === "long");
|
|
138
|
+
eq(long.chars, 5000, "chars keeps full length");
|
|
139
|
+
eq(long.truncated, true, "long body must be flagged truncated");
|
|
140
|
+
ok(long.body.length === 1600, "body must be capped at 1600", long.body.length);
|
|
141
|
+
|
|
142
|
+
const globalItem = get.body.items.find((it) => it.slug === "g-note");
|
|
143
|
+
eq(globalItem.scope, "global", "global scope");
|
|
144
|
+
|
|
145
|
+
// 非本机请求拒绝
|
|
146
|
+
const denied = await call(reg, "GET", undefined, { headers: { host: "evil.example.com:80" } });
|
|
147
|
+
eq(denied.status, 403, "non-loopback host must be rejected");
|
|
148
|
+
|
|
149
|
+
// 远程 TCP 对端:即使伪造 Host 也必须拒绝(防止非 loopback 部署泄露记忆正文)。
|
|
150
|
+
const remote = await call(reg, "GET", undefined, { socket: { remoteAddress: "10.0.0.5" } });
|
|
151
|
+
eq(remote.status, 403, "remote peer must be rejected");
|
|
152
|
+
// 0.0.0.0 是监听地址,不是可访问目标。
|
|
153
|
+
const wildcard = await call(reg, "GET", undefined, { headers: { host: "0.0.0.0:3210" } });
|
|
154
|
+
eq(wildcard.status, 403, "0.0.0.0 host must be rejected");
|
|
155
|
+
// 内部协议(无 TCP peer)允许空 Host。
|
|
156
|
+
const internal = await call(reg, "GET", undefined, { headers: { host: "" }, socket: null });
|
|
157
|
+
eq(internal.status, 200, "internal empty-host request should pass");
|
|
158
|
+
// 没有 TCP peer 也不能无条件信任:公网 Host/Origin 仍必须拒绝(UDS/宿主适配层场景)。
|
|
159
|
+
const internalBadHost = await call(reg, "GET", undefined, { headers: { host: "memory.example.com" }, socket: null });
|
|
160
|
+
eq(internalBadHost.status, 403, "socketless public Host must be rejected");
|
|
161
|
+
const internalBadOrigin = await call(reg, "POST", { enabled: false }, { headers: { host: "", origin: "https://evil.example" }, socket: null });
|
|
162
|
+
eq(internalBadOrigin.status, 403, "socketless public Origin must be rejected");
|
|
163
|
+
// 有 TCP peer 时空 Host:远端地址已确认是 loopback,空 Host 不构成额外风险(自制客户端)。
|
|
164
|
+
const emptyHostLoopback = await call(reg, "GET", undefined, { headers: { host: "" } });
|
|
165
|
+
eq(emptyHostLoopback.status, 200, "empty host from a loopback peer is allowed");
|
|
166
|
+
// 但同一空 Host 来自远端必须被拒绝(先看 TCP 对端,再看 Host)。
|
|
167
|
+
const emptyHostRemote = await call(reg, "GET", undefined, { headers: { host: "" }, socket: { remoteAddress: "10.0.0.5" } });
|
|
168
|
+
eq(emptyHostRemote.status, 403, "empty host with a remote peer must be rejected");
|
|
169
|
+
|
|
170
|
+
// CSRF:跨站 Origin / Sec-Fetch-Site / text/plain 的 POST 必须拒绝。
|
|
171
|
+
const evilOrigin = await call(reg, "POST", { enabled: false }, { headers: { origin: "https://evil.example" } });
|
|
172
|
+
eq(evilOrigin.status, 403, "cross-origin POST must be rejected");
|
|
173
|
+
const nullOrigin = await call(reg, "POST", { enabled: false }, { headers: { origin: "null" } });
|
|
174
|
+
eq(nullOrigin.status, 403, "null origin POST must be rejected");
|
|
175
|
+
const crossSite = await call(reg, "POST", { enabled: false }, { headers: { "sec-fetch-site": "cross-site" } });
|
|
176
|
+
eq(crossSite.status, 403, "cross-site POST must be rejected");
|
|
177
|
+
const plain = await call(reg, "POST", { enabled: false }, { headers: { "content-type": "text/plain" } });
|
|
178
|
+
eq(plain.status, 415, "non-JSON POST must be 415");
|
|
179
|
+
// 桌面自定义协议来源允许(真实页面走 dsh-app://)。
|
|
180
|
+
const appOrigin = await call(reg, "POST", { enabled: true }, { headers: { origin: "dsh-app://app" } });
|
|
181
|
+
eq(appOrigin.status, 200, "dsh-app origin should be allowed");
|
|
182
|
+
// 同源要 host+port 都对上:本机其他端口的页面不能盲 POST。
|
|
183
|
+
const crossPort = await call(reg, "POST", { enabled: false }, { headers: { origin: "http://127.0.0.1:9999" } });
|
|
184
|
+
eq(crossPort.status, 403, "loopback origin on another port must be rejected");
|
|
185
|
+
const samePort = await call(reg, "POST", { enabled: true }, { headers: { origin: "http://127.0.0.1:3210" } });
|
|
186
|
+
eq(samePort.status, 200, "same host+port origin should be allowed");
|
|
187
|
+
|
|
188
|
+
// 关闭:落盘 + 立即生效(规则段/索引段为空、工具拒绝)
|
|
189
|
+
const post = await call(reg, "POST", { enabled: false });
|
|
190
|
+
eq(post.status, 200, "POST status");
|
|
191
|
+
eq(post.body.enabled, false, "POST effective enabled");
|
|
192
|
+
eq(post.body.stateEnabled, false, "POST stateEnabled");
|
|
193
|
+
const stateFile = join(root, "_settings.json");
|
|
194
|
+
const stateJson = JSON.parse(readFileSync(stateFile, "utf8"));
|
|
195
|
+
eq(stateJson.enabled, false, "state file persisted");
|
|
196
|
+
eq(stateJson.version, 1, "state file version");
|
|
197
|
+
|
|
198
|
+
// 关闭后所有 memory_* 工具都必须拒绝(写工具尤其不能继续落盘)。
|
|
199
|
+
const exec = { agent: { session: { id: "sess-toggle", header: { cwd: root, createdAt: new Date().toISOString() } } } };
|
|
200
|
+
const toolOf = (name) => reg.tools.find((x) => x.name === name);
|
|
201
|
+
const argsOf = {
|
|
202
|
+
memory_save: { title: "关闭期不应写入", body: "即使参数完整也必须被开关拒绝。", scope: "project" },
|
|
203
|
+
memory_update: { name: "hello" },
|
|
204
|
+
memory_delete: { name: "hello" },
|
|
205
|
+
memory_recall: { query: "hello" },
|
|
206
|
+
memory_read: { name: "hello" },
|
|
207
|
+
memory_list: {},
|
|
208
|
+
memory_status: {},
|
|
209
|
+
memory_reindex: {},
|
|
210
|
+
};
|
|
211
|
+
for (const name of ["memory_save", "memory_update", "memory_delete", "memory_list", "memory_status", "memory_reindex", "memory_recall", "memory_read"]) {
|
|
212
|
+
const t = toolOf(name);
|
|
213
|
+
ok(!!t, `${name} missing`);
|
|
214
|
+
if (t) {
|
|
215
|
+
// 用**有效参数**:空参时参数校验本身就会返回 false,测不出 enabled 守卫。
|
|
216
|
+
const r = await t.execute(argsOf[name], exec);
|
|
217
|
+
eq(r?.ok, false, `${name} must be refused while disabled`);
|
|
218
|
+
ok(String(r?.message || "").includes("disabled") || name === "memory_list" || name === "memory_status" || name === "memory_reindex",
|
|
219
|
+
`${name} refusal should say disabled`, r?.message);
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
ok(!existsSync(join(root, "projects", "x")), "disabled save must not create project dirs");
|
|
223
|
+
const cmd = reg.commands.find((c) => c.name === "memory");
|
|
224
|
+
ok(!!cmd, "memory command missing");
|
|
225
|
+
if (cmd) {
|
|
226
|
+
const r = await cmd.handler({ rawInput: "list", agent: exec.agent });
|
|
227
|
+
eq(r?.kind, "error", "/memory must be refused while disabled");
|
|
228
|
+
}
|
|
229
|
+
// 关闭时 save 的 ok:false 已保证不落盘(execute 在写之前返回)。
|
|
230
|
+
|
|
231
|
+
const rules = reg.sections.find((s) => s.name === "zcode-memory-rules");
|
|
232
|
+
ok(!!rules, "rules section missing");
|
|
233
|
+
eq(rules.text({ agent: { session: { header: { cwd: root } } } }), "", "rules must be empty when toggled off");
|
|
234
|
+
const memCtx = reg.contexts.find((c) => c.name === "zcode-memory");
|
|
235
|
+
ok(!!memCtx, "index context missing");
|
|
236
|
+
eq(memCtx.text({ agent: { session: { header: { cwd: root } } } }), "", "index context must be empty when toggled off");
|
|
237
|
+
|
|
238
|
+
// 重新打开
|
|
239
|
+
const on = await call(reg, "POST", { enabled: true });
|
|
240
|
+
eq(on.body.enabled, true, "POST re-enabled");
|
|
241
|
+
ok(JSON.parse(readFileSync(stateFile, "utf8")).enabled === true, "state file re-enabled");
|
|
242
|
+
const savedAfterOn = await toolOf("memory_save").execute(
|
|
243
|
+
{ title: "重新开启后的条目", body: "重新打开后应可写入。", scope: "project" },
|
|
244
|
+
exec,
|
|
245
|
+
);
|
|
246
|
+
eq(savedAfterOn?.ok, true, "memory_save must work again after re-enable");
|
|
247
|
+
|
|
248
|
+
// 参数校验
|
|
249
|
+
const bad = await call(reg, "POST", { enabled: "yes" });
|
|
250
|
+
eq(bad.status, 400, "non-boolean must be 400");
|
|
251
|
+
const nullBody = await call(reg, "POST", "null");
|
|
252
|
+
eq(nullBody.status, 400, "null JSON body must be 400");
|
|
253
|
+
eq(nullBody.body.code, "bad_request", "null body code");
|
|
254
|
+
const badJson = await call(reg, "POST", "{not json");
|
|
255
|
+
eq(badJson.status, 400, "invalid JSON must be 400");
|
|
256
|
+
eq(badJson.body.code, "bad_request", "invalid JSON code");
|
|
257
|
+
const tooLarge = await call(reg, "POST", { enabled: true, pad: "x".repeat(70000) });
|
|
258
|
+
eq(tooLarge.status, 413, "oversized body must be 413");
|
|
259
|
+
const method = await call(reg, "PUT");
|
|
260
|
+
eq(method.status, 405, "unsupported method must be 405");
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
// ---- 第二轮:同一 memoriesRoot 重新 apply,开关从文件恢复 ----
|
|
264
|
+
{
|
|
265
|
+
const { ctx, reg } = makeCtx();
|
|
266
|
+
// 上一轮最后写的是 enabled=true;先手动改成 false 验证恢复。
|
|
267
|
+
writeFileSync(join(root, "_settings.json"), JSON.stringify({ version: 1, enabled: false }), "utf8");
|
|
268
|
+
mod.apply(ctx, { memoriesRoot: root, enabled: true, promptStyle: "native" });
|
|
269
|
+
const get = await call(reg, "GET");
|
|
270
|
+
eq(get.body.enabled, false, "toggle must survive re-apply");
|
|
271
|
+
eq(get.body.stateEnabled, false, "stateEnabled restored");
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
// ---- 第三轮:profile enabled=false 是硬关闭,页面开关不能把它打开 ----
|
|
275
|
+
{
|
|
276
|
+
const { ctx, reg } = makeCtx();
|
|
277
|
+
writeFileSync(join(root, "_settings.json"), JSON.stringify({ version: 1, enabled: true }), "utf8");
|
|
278
|
+
mod.apply(ctx, { memoriesRoot: root, enabled: false, promptStyle: "native" });
|
|
279
|
+
const get = await call(reg, "GET");
|
|
280
|
+
eq(get.body.configEnabled, false, "configEnabled false");
|
|
281
|
+
eq(get.body.enabled, false, "config hard-off wins");
|
|
282
|
+
const post = await call(reg, "POST", { enabled: true });
|
|
283
|
+
eq(post.status, 200, "POST accepted even when config hard-off");
|
|
284
|
+
eq(post.body.enabled, false, "effective stays false");
|
|
285
|
+
eq(post.body.stateEnabled, true, "preference still saved for later");
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
// ---- 缺 webServer:注册失败但不抛(记忆功能照常) ----
|
|
289
|
+
{
|
|
290
|
+
const { ctx, reg } = makeCtx();
|
|
291
|
+
delete ctx.inject;
|
|
292
|
+
let threw = false;
|
|
293
|
+
try {
|
|
294
|
+
mod.apply(ctx, { memoriesRoot: root, enabled: true });
|
|
295
|
+
} catch {
|
|
296
|
+
threw = true;
|
|
297
|
+
}
|
|
298
|
+
ok(!threw, "apply must not throw when webServer is missing");
|
|
299
|
+
ok(reg.route === null, "no route without webServer");
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
// ---- 第四轮:嵌套同名、字段上限、分页、坏状态文件、多实例刷新 ----
|
|
303
|
+
{
|
|
304
|
+
const root2 = mkdtempSync(join(tmpdir(), "zcm-settings2-"));
|
|
305
|
+
const ws = join(root2, "projects", "zcode-0123456789abcdef", "memory");
|
|
306
|
+
mkdirSync(join(ws, "a"), { recursive: true });
|
|
307
|
+
mkdirSync(join(ws, "b"), { recursive: true });
|
|
308
|
+
writeFileSync(join(ws, "MEMORY.md"), "- [A 标题](a/topic.md)\n- [B 标题](b/topic.md)\n", "utf8");
|
|
309
|
+
writeFileSync(join(ws, "a", "topic.md"), "---\nname: topic-a\ndescription: A 版\n---\nA 正文\n", "utf8");
|
|
310
|
+
writeFileSync(join(ws, "b", "topic.md"), "---\nname: topic-b\ndescription: B 版\n---\nB 正文\n", "utf8");
|
|
311
|
+
writeFileSync(join(ws, "n1.md"), "---\nname: n1\ndescription: 一\n---\n一\n", "utf8");
|
|
312
|
+
writeFileSync(join(ws, "n2.md"), "---\nname: n2\ndescription: 二\n---\n二\n", "utf8");
|
|
313
|
+
writeFileSync(join(ws, "n3.md"), "---\nname: n3\ndescription: 三\n---\n三\n", "utf8");
|
|
314
|
+
// 只有 frontmatter、没有正文/摘要的文件:必须仍然占一个分页位,不能被跳过。
|
|
315
|
+
writeFileSync(join(ws, "empty.md"), "---\nname: empty\n---\n", "utf8");
|
|
316
|
+
// description 上限:20,000 字不能原样返回。
|
|
317
|
+
writeFileSync(join(ws, "big.md"), `---\nname: big\ndescription: ${"描".repeat(20000)}\n---\n正文\n`, "utf8");
|
|
318
|
+
|
|
319
|
+
const { ctx: ctx2, reg: reg2 } = makeCtx();
|
|
320
|
+
mod.apply(ctx2, { memoriesRoot: root2, enabled: true, promptStyle: "native" });
|
|
321
|
+
|
|
322
|
+
const page1 = await call(reg2, "GET", undefined, { url: "/dsh-zcode-memory-api?offset=0&limit=2" });
|
|
323
|
+
eq(page1.status, 200, "paged GET status");
|
|
324
|
+
eq(page1.body.page.limit, 2, "page limit");
|
|
325
|
+
eq(page1.body.page.offset, 0, "page offset");
|
|
326
|
+
eq(page1.body.items.length, 2, "page size");
|
|
327
|
+
eq(page1.body.page.hasMore, true, "page hasMore");
|
|
328
|
+
eq(page1.body.counts.total, 7, "total counts all files (including empty body)");
|
|
329
|
+
const ids1 = page1.body.items.map((x) => x.rel);
|
|
330
|
+
eq(page1.body.page.nextOffset, 2, "nextOffset is offset+limit");
|
|
331
|
+
const page2 = await call(reg2, "GET", undefined, { url: `/dsh-zcode-memory-api?offset=${page1.body.page.nextOffset}&limit=2` });
|
|
332
|
+
const ids2 = page2.body.items.map((x) => x.rel);
|
|
333
|
+
ok(ids1.every((x) => !ids2.includes(x)), "pages must not overlap", [ids1, ids2]);
|
|
334
|
+
// 空正文文件在页内时,翻页也不能重复/停滞。
|
|
335
|
+
const seen = [...ids1, ...ids2];
|
|
336
|
+
eq(new Set(seen).size, 4, "two pages must yield four distinct rows");
|
|
337
|
+
const emptyItem = allEmpty(await call(reg2, "GET", undefined, { url: "/dsh-zcode-memory-api?offset=0&limit=500" }));
|
|
338
|
+
ok(emptyItem && emptyItem.body === "", "empty-body file should be listed with an empty body", emptyItem);
|
|
339
|
+
|
|
340
|
+
const all = await call(reg2, "GET", undefined, { url: "/dsh-zcode-memory-api?offset=0&limit=500" });
|
|
341
|
+
const topics = all.body.items.filter((x) => x.slug === "topic");
|
|
342
|
+
eq(topics.length, 2, "nested same-basename files must both be listed");
|
|
343
|
+
eq(new Set(topics.map((x) => x.rel)).size, 2, "nested items must have distinct rel keys");
|
|
344
|
+
ok(topics.every((x) => String(x.rel).includes("/")), "nested rel should include the subdirectory", topics.map((x) => x.rel));
|
|
345
|
+
eq(new Set(topics.map((x) => x.title)).size, 2, "nested titles must come from their own rel links, not the basename map", topics.map((x) => x.title));
|
|
346
|
+
|
|
347
|
+
const big = all.body.items.find((x) => x.slug === "big");
|
|
348
|
+
ok(!!big && big.description.length <= 500, "description must be capped", big && big.description.length);
|
|
349
|
+
|
|
350
|
+
// 坏状态文件:按“无偏好”运行,但必须把错误暴露给页面。
|
|
351
|
+
writeFileSync(join(root2, "_settings.json"), "{broken", "utf8");
|
|
352
|
+
{
|
|
353
|
+
const { ctx: ctxBad, reg: regBad } = makeCtx();
|
|
354
|
+
mod.apply(ctxBad, { memoriesRoot: root2, enabled: true });
|
|
355
|
+
const g = await call(regBad, "GET");
|
|
356
|
+
eq(g.status, 200, "bad state GET still 200");
|
|
357
|
+
eq(g.body.stateError, "invalid", "bad state must be reported");
|
|
358
|
+
// 坏状态文件不能 fail-open:启动时按关闭处理,避免一次损坏把隐私开关打开。
|
|
359
|
+
eq(g.body.enabled, false, "bad state must fail closed at startup");
|
|
360
|
+
}
|
|
361
|
+
|
|
362
|
+
// 多实例:A 关闭后,B 的下一次 GET 必须看到(force refresh),不能永远停在 apply 时的值。
|
|
363
|
+
writeFileSync(join(root2, "_settings.json"), JSON.stringify({ version: 1, enabled: true }), "utf8");
|
|
364
|
+
const { ctx: ctxA, reg: regA } = makeCtx();
|
|
365
|
+
const { ctx: ctxB, reg: regB } = makeCtx();
|
|
366
|
+
mod.apply(ctxA, { memoriesRoot: root2, enabled: true });
|
|
367
|
+
mod.apply(ctxB, { memoriesRoot: root2, enabled: true });
|
|
368
|
+
const bBefore = await call(regB, "GET");
|
|
369
|
+
eq(bBefore.body.enabled, true, "B starts enabled");
|
|
370
|
+
const aOff = await call(regA, "POST", { enabled: false });
|
|
371
|
+
eq(aOff.body.enabled, false, "A toggled off");
|
|
372
|
+
const bAfter = await call(regB, "GET");
|
|
373
|
+
eq(bAfter.body.enabled, false, "B must observe A's toggle on next GET");
|
|
374
|
+
eq(bAfter.body.stateEnabled, false, "B stateEnabled follows file");
|
|
375
|
+
|
|
376
|
+
try { rmSync(root2, { recursive: true, force: true }); } catch {}
|
|
377
|
+
}
|
|
378
|
+
|
|
379
|
+
function allEmpty(all) {
|
|
380
|
+
return (all.body.items || []).find((x) => x.slug === "empty");
|
|
381
|
+
}
|
|
382
|
+
|
|
383
|
+
// 状态文件被目录占用:POST 必须是 write_failed,而不是把 EPERM/路径透给前端。
|
|
384
|
+
{
|
|
385
|
+
const dirRoot = mkdtempSync(join(tmpdir(), "zcm-settings-dir-"));
|
|
386
|
+
mkdirSync(join(dirRoot, "_settings.json"), { recursive: true });
|
|
387
|
+
const { ctx: ctxDir, reg: regDir } = makeCtx();
|
|
388
|
+
mod.apply(ctxDir, { memoriesRoot: dirRoot, enabled: true });
|
|
389
|
+
const getDir = await call(regDir, "GET");
|
|
390
|
+
eq(getDir.body.stateError, "not-file", "directory state file must be reported");
|
|
391
|
+
const postDir = await call(regDir, "POST", { enabled: true });
|
|
392
|
+
eq(postDir.status, 500, "write to directory state file must fail");
|
|
393
|
+
eq(postDir.body.code, "write_failed", "fs errors must normalize to write_failed", postDir.body);
|
|
394
|
+
try { rmSync(dirRoot, { recursive: true, force: true }); } catch {}
|
|
395
|
+
}
|
|
396
|
+
|
|
397
|
+
console.log(fails.length ? `FAIL ${fails.length}:\n - ` + fails.join("\n - ") : "ALL PASS");
|
|
398
|
+
try { rmSync(root, { recursive: true, force: true }); } catch {}
|
|
399
|
+
process.exit(fails.length ? 1 : 0);
|