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,280 @@
|
|
|
1
|
+
// 总开关的运行期语义:关闭期间不缓冲/不补抽、在途抽取不落盘、开关即时撤/补授权。
|
|
2
|
+
// 用法: node tests/settings-disable.mjs [index.js 路径]
|
|
3
|
+
import { pathToFileURL } from "node:url";
|
|
4
|
+
import { mkdtempSync, mkdirSync, writeFileSync, readdirSync, readFileSync, rmSync } from "node:fs";
|
|
5
|
+
import { tmpdir } from "node:os";
|
|
6
|
+
import { join, resolve, basename } from "node:path";
|
|
7
|
+
import { createHash } from "node:crypto";
|
|
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 root = mkdtempSync(join(tmpdir(), "zcm-off-"));
|
|
13
|
+
const cwd = mkdtempSync(join(tmpdir(), "zcm-offc-"));
|
|
14
|
+
const fails = [];
|
|
15
|
+
const ok = (c, m, e) => { if (!c) fails.push(m + (e === undefined ? "" : ` :: ${String(e).slice(0, 300)}`)); };
|
|
16
|
+
|
|
17
|
+
function mdFiles(dir, out = []) {
|
|
18
|
+
for (const ent of readdirSync(dir, { withFileTypes: true })) {
|
|
19
|
+
const full = join(dir, ent.name);
|
|
20
|
+
if (ent.isDirectory()) mdFiles(full, out);
|
|
21
|
+
else if (ent.name.endsWith(".md")) out.push(full);
|
|
22
|
+
}
|
|
23
|
+
return out;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/** 记录 sections/tools/handlers,并把设置路由抓出来。 */
|
|
27
|
+
function makeCtx({ agents, policy, llm } = {}) {
|
|
28
|
+
const reg = { sections: [], contexts: [], tools: [], commands: [], handlers: new Map(), route: null, prompt: [] };
|
|
29
|
+
const ctx = {
|
|
30
|
+
systemPrompt: { section: (o) => reg.sections.push(o), context: (o) => reg.contexts.push(o) },
|
|
31
|
+
tools: { register: (d) => reg.tools.push(d) },
|
|
32
|
+
commands: { register: (c) => reg.commands.push(c) },
|
|
33
|
+
get: (name) => (name === "sandboxPolicy" ? policy : name === "agents" ? agents : undefined),
|
|
34
|
+
effect: (fn) => { fn(); },
|
|
35
|
+
on: (ev, fn) => { if (!reg.handlers.has(ev)) reg.handlers.set(ev, []); reg.handlers.get(ev).push(fn); },
|
|
36
|
+
inject: (names, cb) => cb({
|
|
37
|
+
webServer: { register: (r) => { reg.route = r; return () => {}; } },
|
|
38
|
+
effect: (fn) => fn(),
|
|
39
|
+
logger: { warn: () => {} },
|
|
40
|
+
}),
|
|
41
|
+
llm: { stream: llm || (async function* () {}) },
|
|
42
|
+
logger: { warn: () => {} },
|
|
43
|
+
};
|
|
44
|
+
const emit = (ev, ...args) => { for (const fn of reg.handlers.get(ev) || []) fn(...args); };
|
|
45
|
+
const call = (method, body) => new Promise((resolve) => {
|
|
46
|
+
const req = {
|
|
47
|
+
method,
|
|
48
|
+
url: "/dsh-zcode-memory-api",
|
|
49
|
+
headers: { host: "127.0.0.1:3210", "content-type": "application/json" },
|
|
50
|
+
socket: { remoteAddress: "127.0.0.1" },
|
|
51
|
+
async *[Symbol.asyncIterator]() { if (body !== undefined) yield Buffer.from(JSON.stringify(body)); },
|
|
52
|
+
};
|
|
53
|
+
const res = {
|
|
54
|
+
writeHead(s) { this.status = s; },
|
|
55
|
+
end(c) { resolve({ status: this.status, body: JSON.parse(String(c || "null")) }); },
|
|
56
|
+
};
|
|
57
|
+
reg.route.handler(req, res);
|
|
58
|
+
});
|
|
59
|
+
return { ctx, reg, emit, call };
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
function sessionOf(id, dir = cwd) {
|
|
63
|
+
return { header: { id, cwd: dir, createdAt: "2026-12-05T12:00:00.000Z", origin: "user", delegationDepth: 0 } };
|
|
64
|
+
}
|
|
65
|
+
function agentOf(session, overrides = {}) {
|
|
66
|
+
return {
|
|
67
|
+
session, status: "idle", inbox: { nextTurn: [], nextStep: [] },
|
|
68
|
+
model: { current: () => ({ provider: "mock", model: "mock-1" }) },
|
|
69
|
+
whenIdle: () => Promise.resolve(),
|
|
70
|
+
runMaintenance: async (fn) => fn(new AbortController().signal),
|
|
71
|
+
...overrides,
|
|
72
|
+
};
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
// ---- A. 关闭期间的对话不缓冲、重开后不补抽 ----
|
|
76
|
+
{
|
|
77
|
+
const regPrompts = [];
|
|
78
|
+
const { ctx, reg, emit, call } = makeCtx({
|
|
79
|
+
llm: async function* (options) {
|
|
80
|
+
regPrompts.push(JSON.stringify(options));
|
|
81
|
+
yield { type: "text-delta", text: '{"writes":[]}' };
|
|
82
|
+
yield { type: "finish", reason: { kind: "stop" } };
|
|
83
|
+
},
|
|
84
|
+
});
|
|
85
|
+
mod.apply(ctx, { memoriesRoot: root, enabled: true, autoExtractMinIntervalMs: 0 });
|
|
86
|
+
const session = sessionOf("sess-off");
|
|
87
|
+
const agent = agentOf(session);
|
|
88
|
+
|
|
89
|
+
// 先走一个开启状态的回合:证明抽取链路确实会调用模型,避免“关闭期没出现”只是因为整条链路坏了。
|
|
90
|
+
emit("session/event", session, { type: "turn/start", seq: 1, data: { turn: 1 } });
|
|
91
|
+
emit("session/event", session, {
|
|
92
|
+
type: "user/message", seq: 2,
|
|
93
|
+
data: { source: { kind: "user" }, content: [{ type: "text", text: "ON_PERIOD_ALLOWED 开启期间这条应该进入抽取 prompt。" }] },
|
|
94
|
+
});
|
|
95
|
+
emit("agent/turn-stopping", { agent, turn: 1 });
|
|
96
|
+
await new Promise((r) => setTimeout(r, 80));
|
|
97
|
+
ok(regPrompts.length > 0, "on-period extraction should call the model", regPrompts.length);
|
|
98
|
+
ok(regPrompts.some((p) => p.includes("ON_PERIOD_ALLOWED")), "on-period message should reach extraction", regPrompts);
|
|
99
|
+
|
|
100
|
+
const off = await call("POST", { enabled: false });
|
|
101
|
+
ok(off.body.enabled === false, "disable via API", off.body);
|
|
102
|
+
|
|
103
|
+
// 关闭期间产生完整回合:内容不能被缓冲。
|
|
104
|
+
emit("session/event", session, { type: "turn/start", seq: 10, data: { turn: 2 } });
|
|
105
|
+
emit("session/event", session, {
|
|
106
|
+
type: "user/message", seq: 11,
|
|
107
|
+
data: { source: { kind: "user" }, content: [{ type: "text", text: "OFF_PERIOD_SECRET 这是一段关闭期间产生、绝不该被抽取的私密内容。" }] },
|
|
108
|
+
});
|
|
109
|
+
emit("session/event", session, {
|
|
110
|
+
type: "assistant/message", seq: 12,
|
|
111
|
+
data: { turn: 2, message: { content: [{ type: "text", text: "OFF_PERIOD_REPLY 关闭期间的回复。" }] } },
|
|
112
|
+
});
|
|
113
|
+
emit("agent/turn-stopping", { agent, turn: 2 });
|
|
114
|
+
|
|
115
|
+
// 状态文件损坏不能让关闭开关 fail-open:1s 内重读后仍必须保持关闭。
|
|
116
|
+
writeFileSync(join(root, "_settings.json"), "{broken", "utf8");
|
|
117
|
+
await new Promise((r) => setTimeout(r, 1200));
|
|
118
|
+
const rules = reg.sections.find((x) => x.name === "zcode-memory-rules");
|
|
119
|
+
ok(!!rules, "rules section missing");
|
|
120
|
+
ok(rules.text({ agent: { session: { header: { cwd } } } }) === "", "corrupt state file must not re-enable memory");
|
|
121
|
+
|
|
122
|
+
const on = await call("POST", { enabled: true });
|
|
123
|
+
ok(on.body.enabled === true, "re-enable via API");
|
|
124
|
+
|
|
125
|
+
// 重开后再走一个回合:不应把关闭期间的 10–12 补抽进去。
|
|
126
|
+
emit("session/event", session, { type: "turn/start", seq: 13, data: { turn: 3 } });
|
|
127
|
+
emit("session/event", session, {
|
|
128
|
+
type: "user/message", seq: 14,
|
|
129
|
+
data: { source: { kind: "user" }, content: [{ type: "text", text: "这是重开后的正常消息,长度足够触发抽取判断。" }] },
|
|
130
|
+
});
|
|
131
|
+
emit("agent/turn-stopping", { agent, turn: 3 });
|
|
132
|
+
await new Promise((r) => setTimeout(r, 80));
|
|
133
|
+
|
|
134
|
+
ok(regPrompts.some((p) => p.includes("ON_PERIOD_ALLOWED")), "on-period extraction must have run", regPrompts.length);
|
|
135
|
+
ok(regPrompts.every((p) => !p.includes("OFF_PERIOD_SECRET")), "off-period content must not reach extraction", regPrompts);
|
|
136
|
+
ok(mdFiles(root).length === 0, "off-period turn must not write memory files", mdFiles(root));
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
// ---- B. 在途抽取遇到关闭:不落盘 ----
|
|
140
|
+
{
|
|
141
|
+
let started = null;
|
|
142
|
+
let release = null;
|
|
143
|
+
const startedP = new Promise((r) => { started = r; });
|
|
144
|
+
const gate = new Promise((r) => { release = r; });
|
|
145
|
+
const { ctx, reg, emit, call } = makeCtx({
|
|
146
|
+
llm: async function* () {
|
|
147
|
+
started();
|
|
148
|
+
await gate;
|
|
149
|
+
yield {
|
|
150
|
+
type: "text-delta",
|
|
151
|
+
text: JSON.stringify({ writes: [{ op: "create", title: "关闭中抽取的条目", description: "不该落盘", body: "关闭后仍被写入了。" }] }),
|
|
152
|
+
};
|
|
153
|
+
yield { type: "finish", reason: { kind: "stop" } };
|
|
154
|
+
},
|
|
155
|
+
});
|
|
156
|
+
mod.apply(ctx, { memoriesRoot: root, enabled: true, autoExtractMinIntervalMs: 0, autoExtractToolAgent: false });
|
|
157
|
+
const session = sessionOf("sess-inflight");
|
|
158
|
+
const agent = agentOf(session);
|
|
159
|
+
|
|
160
|
+
emit("session/event", session, { type: "turn/start", seq: 20, data: { turn: 1 } });
|
|
161
|
+
emit("session/event", session, {
|
|
162
|
+
type: "user/message", seq: 21,
|
|
163
|
+
data: { source: { kind: "user" }, content: [{ type: "text", text: "这是一段足够长的消息,用来启动一次后台抽取,然后在中途关闭开关。" }] },
|
|
164
|
+
});
|
|
165
|
+
emit("agent/turn-stopping", { agent, turn: 1 });
|
|
166
|
+
await started; // 抽取已经发出模型请求
|
|
167
|
+
const off = await call("POST", { enabled: false });
|
|
168
|
+
ok(off.body.enabled === false, "disable while extraction is in flight");
|
|
169
|
+
release(); // 模型在关闭后才返回
|
|
170
|
+
await new Promise((r) => setTimeout(r, 120));
|
|
171
|
+
|
|
172
|
+
ok(mdFiles(root).length === 0, "in-flight extraction must not write after disable", mdFiles(root));
|
|
173
|
+
const state = JSON.parse(readFileSync(join(root, "_extract-state.json"), "utf8"));
|
|
174
|
+
ok(!String(state.lastOutcome || "").includes("ok") || Number(state.written) === 0,
|
|
175
|
+
"state must not report a successful write after disable", state);
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
// ---- C. 开关即时撤/补 sandbox 授权(不等 agent/status) ----
|
|
179
|
+
{
|
|
180
|
+
const log = [];
|
|
181
|
+
const policy = {
|
|
182
|
+
registerWritableRoot(_s, dir) { log.push(`grant ${dir}`); return () => log.push(`dispose ${dir}`); },
|
|
183
|
+
};
|
|
184
|
+
const session = sessionOf("sess-grant");
|
|
185
|
+
const agent = agentOf(session);
|
|
186
|
+
const agents = { list: () => [agent] };
|
|
187
|
+
const { ctx, reg, emit, call } = makeCtx({ agents, policy });
|
|
188
|
+
// 前两个场景可能把共享状态文件留在关闭态;这里先恢复,避免 grant 被开关拦住。
|
|
189
|
+
writeFileSync(join(root, "_settings.json"), JSON.stringify({ version: 1, enabled: true }), "utf8");
|
|
190
|
+
mod.apply(ctx, { memoriesRoot: root, enabled: true, grantScope: "root" });
|
|
191
|
+
emit("agent/created", { agent });
|
|
192
|
+
ok(log.length === 1 && log[0].startsWith("grant"), "initial grant", log);
|
|
193
|
+
const off = await call("POST", { enabled: false });
|
|
194
|
+
ok(off.body.enabled === false, "disable");
|
|
195
|
+
ok(log[log.length - 1].startsWith("dispose"), "disable must revoke immediately", log);
|
|
196
|
+
const on = await call("POST", { enabled: true });
|
|
197
|
+
ok(on.body.enabled === true, "enable");
|
|
198
|
+
ok(log[log.length - 1].startsWith("grant"), "enable must re-grant immediately", log);
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
// ---- D. 直写守卫:开关状态文件永远拒绝;记忆 .md 在关闭时拒绝 ----
|
|
202
|
+
{
|
|
203
|
+
const { ctx, reg, call } = makeCtx();
|
|
204
|
+
mod.apply(ctx, { memoriesRoot: root, enabled: true });
|
|
205
|
+
const handler = reg.handlers.get("tools/pre-execute")[0];
|
|
206
|
+
ok(typeof handler === "function", "pre-execute guard missing");
|
|
207
|
+
const session = sessionOf("sess-guard");
|
|
208
|
+
const execOf = (p) => ({ name: "write", arguments: { path: p }, agent: { session } });
|
|
209
|
+
const next = async () => undefined;
|
|
210
|
+
|
|
211
|
+
const settingsPath = join(root, "_settings.json");
|
|
212
|
+
const denySettings = await handler(execOf(settingsPath), next);
|
|
213
|
+
ok(denySettings && denySettings.kind === "deny", "direct write to _settings.json must be denied", denySettings);
|
|
214
|
+
|
|
215
|
+
const memPath = join(root, "projects", "x", "memory", "note.md");
|
|
216
|
+
const allowed = await handler(execOf(memPath), next);
|
|
217
|
+
ok(!allowed || allowed.kind !== "deny", "memory write should be allowed while enabled", allowed);
|
|
218
|
+
|
|
219
|
+
await call("POST", { enabled: false });
|
|
220
|
+
const deniedOff = await handler(execOf(memPath), next);
|
|
221
|
+
ok(deniedOff && deniedOff.kind === "deny", "memory write must be denied while disabled", deniedOff);
|
|
222
|
+
await call("POST", { enabled: true });
|
|
223
|
+
|
|
224
|
+
// shell 不能改控制面文件(best-effort);普通命令不受影响。
|
|
225
|
+
const bashDeny = await handler({ name: "bash", arguments: { command: "echo x > _settings.json" }, agent: { session } }, next);
|
|
226
|
+
ok(bashDeny && bashDeny.kind === "deny", "shell write to _settings.json must be denied", bashDeny);
|
|
227
|
+
const bashAllow = await handler({ name: "bash", arguments: { command: "echo hello" }, agent: { session } }, next);
|
|
228
|
+
ok(!bashAllow || bashAllow.kind !== "deny", "unrelated shell command should pass", bashAllow);
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
// ---- E. 锁等待期间关闭:拿到锁后复查,不落盘 ----
|
|
232
|
+
{
|
|
233
|
+
const rootE = mkdtempSync(join(tmpdir(), "zcm-off-lock-"));
|
|
234
|
+
const cwdE = mkdtempSync(join(tmpdir(), "zcm-off-lockc-"));
|
|
235
|
+
const norm = process.platform === "win32"
|
|
236
|
+
? resolve(cwdE).replace(/\//g, "\\").toLowerCase()
|
|
237
|
+
: resolve(cwdE);
|
|
238
|
+
const hash = createHash("sha256").update(norm, "utf8").digest("hex").slice(0, 16);
|
|
239
|
+
const dir = join(rootE, "projects", `${basename(cwdE)}-${hash}`, "memory");
|
|
240
|
+
mkdirSync(dir, { recursive: true });
|
|
241
|
+
// 预置一把未过期的锁:让 applyExtraction 在“检查开关之后、真正写盘之前”卡住。
|
|
242
|
+
writeFileSync(join(dir, ".dsh-memory.lock"), `999999-${Date.now()}`, "utf8");
|
|
243
|
+
|
|
244
|
+
let started = null;
|
|
245
|
+
const startedP = new Promise((r) => { started = r; });
|
|
246
|
+
const { ctx, reg, emit, call } = makeCtx({
|
|
247
|
+
llm: async function* () {
|
|
248
|
+
started();
|
|
249
|
+
yield {
|
|
250
|
+
type: "text-delta",
|
|
251
|
+
text: JSON.stringify({ writes: [{ op: "create", title: "TOCTOU", description: "锁等待期间关闭", body: "不该落盘。" }] }),
|
|
252
|
+
};
|
|
253
|
+
yield { type: "finish", reason: { kind: "stop" } };
|
|
254
|
+
},
|
|
255
|
+
});
|
|
256
|
+
mod.apply(ctx, { memoriesRoot: rootE, enabled: true, autoExtractMinIntervalMs: 0, autoExtractToolAgent: false });
|
|
257
|
+
const session = sessionOf("sess-lock", cwdE);
|
|
258
|
+
const agent = agentOf(session);
|
|
259
|
+
|
|
260
|
+
emit("session/event", session, { type: "turn/start", seq: 1, data: { turn: 1 } });
|
|
261
|
+
emit("session/event", session, {
|
|
262
|
+
type: "user/message", seq: 2,
|
|
263
|
+
data: { source: { kind: "user" }, content: [{ type: "text", text: "这条消息会触发抽取,并在锁等待期间被关闭开关。" }] },
|
|
264
|
+
});
|
|
265
|
+
emit("agent/turn-stopping", { agent, turn: 1 });
|
|
266
|
+
await started;
|
|
267
|
+
await new Promise((r) => setTimeout(r, 200)); // 让它进入 withLock 等待
|
|
268
|
+
const off = await call("POST", { enabled: false });
|
|
269
|
+
ok(off.body.enabled === false, "disable while waiting on lock");
|
|
270
|
+
rmSync(join(dir, ".dsh-memory.lock"), { force: true });
|
|
271
|
+
await new Promise((r) => setTimeout(r, 600));
|
|
272
|
+
ok(mdFiles(rootE).length === 0, "close during lock wait must not write", mdFiles(rootE));
|
|
273
|
+
try { rmSync(rootE, { recursive: true, force: true }); rmSync(cwdE, { recursive: true, force: true }); } catch {}
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
console.log(fails.length ? `FAIL ${fails.length}:\n - ` + fails.join("\n - ") : "ALL PASS");
|
|
277
|
+
if (!fails.length) {
|
|
278
|
+
try { rmSync(root, { recursive: true, force: true }); rmSync(cwd, { recursive: true, force: true }); } catch {}
|
|
279
|
+
}
|
|
280
|
+
process.exit(fails.length ? 1 : 0);
|
package/tests/smoke.mjs
ADDED
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
// 插件 mock-ctx 冒烟:确认 apply 能在无 DSH 环境下注册 section/tools/commands
|
|
2
|
+
// 用法: node smoke.mjs [index.js 路径]
|
|
3
|
+
import { pathToFileURL } from "node:url";
|
|
4
|
+
import { mkdtempSync, mkdirSync, writeFileSync, readFileSync, rmSync } from "node:fs";
|
|
5
|
+
import { tmpdir } from "node:os";
|
|
6
|
+
import { join } from "node:path";
|
|
7
|
+
|
|
8
|
+
const modUrl = process.argv[2] ? pathToFileURL(process.argv[2]).href : new URL("../index.js", import.meta.url).href;
|
|
9
|
+
const mod = await import(modUrl);
|
|
10
|
+
|
|
11
|
+
const reg = { sections: [], contexts: [], tools: [], commands: [], handlers: new Map() };
|
|
12
|
+
const ctx = {
|
|
13
|
+
systemPrompt: { section: (o) => reg.sections.push(o) },
|
|
14
|
+
tools: { register: (d) => reg.tools.push(d) },
|
|
15
|
+
commands: { register: (c) => reg.commands.push(c) },
|
|
16
|
+
on: (ev, fn) => { if (!reg.handlers.has(ev)) reg.handlers.set(ev, []); reg.handlers.get(ev).push(fn); },
|
|
17
|
+
llm: { stream: async function* () {} },
|
|
18
|
+
};
|
|
19
|
+
|
|
20
|
+
const root = mkdtempSync(join(tmpdir(), "zcm-smoke-"));
|
|
21
|
+
const cfg = { memoriesRoot: root, enabled: true, promptStyle: "native" };
|
|
22
|
+
mod.apply(ctx, cfg);
|
|
23
|
+
|
|
24
|
+
const fails = [];
|
|
25
|
+
const ok = (cond, msg) => { if (!cond) fails.push(msg); };
|
|
26
|
+
|
|
27
|
+
ok(reg.sections.length === 3, `sections=${reg.sections.length}`);
|
|
28
|
+
const sec = reg.sections.find((s) => s.name === "zcode-memory");
|
|
29
|
+
const rulesSec = reg.sections.find((s) => s.name === "zcode-memory-rules");
|
|
30
|
+
const dateSec = reg.sections.find((s) => s.name === "current-date");
|
|
31
|
+
ok(!!sec, "memory section missing");
|
|
32
|
+
ok(!!rulesSec, "memory rules section missing");
|
|
33
|
+
ok(!!dateSec, "current-date section missing");
|
|
34
|
+
ok(sec.order === 8900, "section order");
|
|
35
|
+
ok(rulesSec.order === 8890, "rules section order");
|
|
36
|
+
ok(sec.interpolate === false && rulesSec.interpolate === false, "interpolate false");
|
|
37
|
+
// injectDate 默认关:DSH standard preset 的 dsh-time-context 已注入带日期的时间快照。
|
|
38
|
+
ok(dateSec.text({}) === "", "date section must be empty by default", dateSec.text({}));
|
|
39
|
+
|
|
40
|
+
// context 通道:systemPrompt.context 存在时应注册为 required 快照,不再注册 section。
|
|
41
|
+
const reg2 = { sections: [], contexts: [], tools: [], commands: [], handlers: new Map() };
|
|
42
|
+
const ctx2 = {
|
|
43
|
+
systemPrompt: {
|
|
44
|
+
section: (o) => reg2.sections.push(o),
|
|
45
|
+
context: (o) => reg2.contexts.push(o),
|
|
46
|
+
},
|
|
47
|
+
tools: { register: (d) => reg2.tools.push(d) },
|
|
48
|
+
commands: { register: (c) => reg2.commands.push(c) },
|
|
49
|
+
on: (ev, fn) => { if (!reg2.handlers.has(ev)) reg2.handlers.set(ev, []); reg2.handlers.get(ev).push(fn); },
|
|
50
|
+
llm: { stream: async function* () {} },
|
|
51
|
+
};
|
|
52
|
+
const root2 = mkdtempSync(join(tmpdir(), "zcm-smoke2-"));
|
|
53
|
+
mod.apply(ctx2, { memoriesRoot: root2, enabled: true, injectDate: true });
|
|
54
|
+
// G9:规则段永远走 system section;只有索引随通道变化。
|
|
55
|
+
ok(reg2.sections.length === 1, `context mode should register only the rules section (got ${reg2.sections.length})`);
|
|
56
|
+
ok(reg2.sections[0]?.name === "zcode-memory-rules", "rules section must stay on the system channel");
|
|
57
|
+
ok(reg2.contexts.length === 2, `contexts=${reg2.contexts.length}`);
|
|
58
|
+
const memCtx = reg2.contexts.find((c) => c.name === "zcode-memory");
|
|
59
|
+
const dateCtx = reg2.contexts.find((c) => c.name === "current-date");
|
|
60
|
+
ok(!!memCtx && !!dateCtx, "context entries missing");
|
|
61
|
+
ok(memCtx.order === 155 && dateCtx.order === 150, "context order");
|
|
62
|
+
ok(memCtx.required === true && dateCtx.required === true, "context required");
|
|
63
|
+
ok(memCtx.interpolate === false && dateCtx.interpolate === false, "context interpolate false");
|
|
64
|
+
ok(/^Today's date is \d{4}-\d{2}-\d{2}\.$/.test(String(dateCtx.text({}))), "date context text", dateCtx.text({}));
|
|
65
|
+
// memo:同一 step 的第二次求值命中缓存,返回同一文本。
|
|
66
|
+
const c1 = memCtx.text({ agent: { session: { header: { cwd: process.cwd() } } } });
|
|
67
|
+
const c2 = memCtx.text({ agent: { session: { header: { cwd: process.cwd() } } } });
|
|
68
|
+
ok(c1 === c2, "context memo mismatch");
|
|
69
|
+
try { rmSync(root2, { recursive: true, force: true }); } catch {}
|
|
70
|
+
|
|
71
|
+
// 空库:规则段仍在 system(指令文本),索引段为空(原生不注入空 Contents 块)。
|
|
72
|
+
const emptyRules = rulesSec.text({ agent: { session: { header: { cwd: process.cwd() } } } });
|
|
73
|
+
const emptyText = sec.text({ agent: { session: { header: { cwd: process.cwd() } } } });
|
|
74
|
+
ok(typeof emptyRules === "string" && emptyRules.length > 200, "rules text too short");
|
|
75
|
+
ok(emptyText === "", "empty library must not inject an index block");
|
|
76
|
+
|
|
77
|
+
// 工具与命令清单
|
|
78
|
+
const toolNames = reg.tools.map((t) => t.name).sort();
|
|
79
|
+
const cmdNames = reg.commands.map((c) => c.name);
|
|
80
|
+
console.log("tools:", toolNames.join(", "));
|
|
81
|
+
console.log("commands:", cmdNames.join(", "));
|
|
82
|
+
console.log("events:", [...reg.handlers.keys()].join(", "));
|
|
83
|
+
ok(toolNames.includes("memory_save") && toolNames.includes("memory_read"), "core tools");
|
|
84
|
+
|
|
85
|
+
// 只读工具标记并发安全;写工具不标记(默认排他)。
|
|
86
|
+
for (const n of ["memory_recall", "memory_read", "memory_list", "memory_status"]) {
|
|
87
|
+
const t = reg.tools.find((x) => x.name === n);
|
|
88
|
+
ok(!!t && t.isConcurrencySafe?.() === true, `${n}: isConcurrencySafe`);
|
|
89
|
+
}
|
|
90
|
+
for (const n of ["memory_save", "memory_update", "memory_delete", "memory_reindex"]) {
|
|
91
|
+
const t = reg.tools.find((x) => x.name === n);
|
|
92
|
+
ok(!!t && t.isConcurrencySafe === undefined, `${n}: must stay exclusive`);
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
// 每个工具必须有 output schema 与 execute
|
|
96
|
+
for (const t of reg.tools) {
|
|
97
|
+
ok(t.output && t.output.schema, `${t.name}: missing output.schema`);
|
|
98
|
+
ok(typeof t.execute === "function", `${t.name}: missing execute`);
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
// 写入后索引与正文
|
|
102
|
+
const save = reg.tools.find((t) => t.name === "memory_save");
|
|
103
|
+
const exec = { agent: { session: { id: "sess-test", header: { cwd: process.cwd(), createdAt: new Date().toISOString() } } } };
|
|
104
|
+
const r = await save.execute({ title: "冒烟测试条目", description: "smoke", type: "project", body: "这是一条冒烟测试记忆。", scope: "project" }, exec);
|
|
105
|
+
ok(r && r.ok, "memory_save failed: " + JSON.stringify(r).slice(0, 300));
|
|
106
|
+
const txt = sec.text({ agent: { session: { header: { cwd: process.cwd() } } } });
|
|
107
|
+
ok(txt.includes("冒烟测试条目"), "index not injected after save");
|
|
108
|
+
|
|
109
|
+
console.log(fails.length ? `FAIL ${fails.length}:\n - ` + fails.join("\n - ") : "ALL PASS");
|
|
110
|
+
try { rmSync(root, { recursive: true, force: true }); } catch {}
|
|
111
|
+
process.exit(fails.length ? 1 : 0);
|