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,256 @@
|
|
|
1
|
+
// Client bundle 冒烟:确认 client.js 能被 __ModuleLoader__ 加载、不 require 宿主私有包、
|
|
2
|
+
// 并在 apply 时注册 settings.section。用法: node tests/client-bundle.mjs [client.js 路径]
|
|
3
|
+
import { readFileSync } from "node:fs";
|
|
4
|
+
import vm from "node:vm";
|
|
5
|
+
import { dirname, join } from "node:path";
|
|
6
|
+
import { fileURLToPath } from "node:url";
|
|
7
|
+
|
|
8
|
+
const here = dirname(fileURLToPath(import.meta.url));
|
|
9
|
+
const clientPath = process.argv[2] || join(here, "../client.js");
|
|
10
|
+
const pkg = JSON.parse(readFileSync(join(here, "../package.json"), "utf8"));
|
|
11
|
+
const code = readFileSync(clientPath, "utf8");
|
|
12
|
+
|
|
13
|
+
const fails = [];
|
|
14
|
+
const ok = (cond, msg, extra) => { if (!cond) fails.push(msg + (extra === undefined ? "" : ` (got ${JSON.stringify(extra).slice(0, 200)})`)); };
|
|
15
|
+
const eq = (a, b, msg) => ok(a === b, `${msg}: expected ${JSON.stringify(b)}, got ${JSON.stringify(a)}`);
|
|
16
|
+
|
|
17
|
+
// ---- 1) package.json 的 client 声明 ----
|
|
18
|
+
ok(pkg.exports && pkg.exports["./client"] === "./client.js", "exports['./client'] must point at client.js", pkg.exports);
|
|
19
|
+
ok(pkg.files && pkg.files.includes("client.js"), "files must ship client.js", pkg.files);
|
|
20
|
+
ok(pkg.dsh && pkg.dsh.client && pkg.dsh.client.platform === "web", "dsh.client.platform must be web", pkg.dsh);
|
|
21
|
+
ok(Array.isArray(pkg.dsh?.client?.inject) && pkg.dsh.client.inject.includes("@deepseek-ai/dsh-client-ui-slots"),
|
|
22
|
+
"dsh.client.inject must list ui-slots", pkg.dsh?.client?.inject);
|
|
23
|
+
ok(pkg.dsh.client.inject.includes("@deepseek-ai/dsh-client-locale"),
|
|
24
|
+
"dsh.client.inject must list locale", pkg.dsh?.client?.inject);
|
|
25
|
+
|
|
26
|
+
// ---- 2) 在 vm 里跑 bundle:document/window 全部桩 ----
|
|
27
|
+
let captured = null;
|
|
28
|
+
const styleEl = { setAttribute() {}, textContent: "", remove() {} };
|
|
29
|
+
const documentStub = {
|
|
30
|
+
head: { appendChild() {} },
|
|
31
|
+
createElement: () => styleEl,
|
|
32
|
+
querySelectorAll: () => [],
|
|
33
|
+
currentScript: null,
|
|
34
|
+
baseURI: "http://127.0.0.1/",
|
|
35
|
+
};
|
|
36
|
+
const sandbox = {
|
|
37
|
+
window: { __ModuleLoader__: { load: (m) => { captured = m } } },
|
|
38
|
+
document: documentStub,
|
|
39
|
+
location: { href: "http://127.0.0.1/" },
|
|
40
|
+
URL,
|
|
41
|
+
console,
|
|
42
|
+
fetch: async () => ({ json: async () => ({ ok: true }) }),
|
|
43
|
+
};
|
|
44
|
+
vm.createContext(sandbox);
|
|
45
|
+
try {
|
|
46
|
+
vm.runInContext(code, sandbox, { filename: clientPath });
|
|
47
|
+
} catch (e) {
|
|
48
|
+
fails.push(`bundle threw: ${e && e.message}`);
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
ok(!!captured, "bundle did not call __ModuleLoader__.load");
|
|
52
|
+
if (captured) {
|
|
53
|
+
ok(captured.id === pkg.name, "loader id must equal package name", captured.id);
|
|
54
|
+
ok(typeof captured.factory === "function", "loader factory missing");
|
|
55
|
+
|
|
56
|
+
// 极简 React 桩:只覆盖 client 用到的 hook;createElement 记录树,
|
|
57
|
+
// 遇到函数组件就立即调用(测试要能看到 MemoryItem 内部的节点)。
|
|
58
|
+
const makeElement = (type, props, ...children) => {
|
|
59
|
+
if (typeof type === "function") return type({ ...(props || {}), children });
|
|
60
|
+
return { type, props, children };
|
|
61
|
+
};
|
|
62
|
+
const React = {
|
|
63
|
+
createElement: makeElement,
|
|
64
|
+
useState: (initial) => [initial, () => {}],
|
|
65
|
+
useEffect: () => {},
|
|
66
|
+
useCallback: (fn) => fn,
|
|
67
|
+
useRef: (value) => ({ current: value }),
|
|
68
|
+
};
|
|
69
|
+
const requireStub = (id) => {
|
|
70
|
+
if (id === "react") return React;
|
|
71
|
+
// 硬约束:不许 require 宿主的 @deepseek-ai/*(版本会变,且 bundle 里解析不到)。
|
|
72
|
+
throw new Error(`unexpected require: ${id}`);
|
|
73
|
+
};
|
|
74
|
+
|
|
75
|
+
let instance = null;
|
|
76
|
+
try {
|
|
77
|
+
instance = captured.factory(requireStub);
|
|
78
|
+
} catch (e) {
|
|
79
|
+
fails.push(`factory threw: ${e && e.message}`);
|
|
80
|
+
}
|
|
81
|
+
if (instance) {
|
|
82
|
+
ok(typeof instance.apply === "function", "factory must return { apply }");
|
|
83
|
+
ok(Array.isArray(instance.inject) && instance.inject.includes("slots") && instance.inject.includes("locale"),
|
|
84
|
+
"client must inject slots + locale", instance.inject);
|
|
85
|
+
|
|
86
|
+
const registrations = [];
|
|
87
|
+
const localeCalls = [];
|
|
88
|
+
const ctx = {
|
|
89
|
+
effect: (fn) => { fn(); },
|
|
90
|
+
locale: {
|
|
91
|
+
register: (...args) => localeCalls.push(args),
|
|
92
|
+
bind: () => (key) => key,
|
|
93
|
+
},
|
|
94
|
+
slots: {
|
|
95
|
+
inject: (name, fn) => fn(),
|
|
96
|
+
register: (opts, component) => { registrations.push({ opts, component }); return () => {}; },
|
|
97
|
+
},
|
|
98
|
+
};
|
|
99
|
+
try {
|
|
100
|
+
instance.apply(ctx);
|
|
101
|
+
} catch (e) {
|
|
102
|
+
fails.push(`apply threw: ${e && e.message}`);
|
|
103
|
+
}
|
|
104
|
+
ok(localeCalls.length === 1 && localeCalls[0][0] === "dsh-zcode-memory", "locale namespace", localeCalls[0]?.[0]);
|
|
105
|
+
ok(localeCalls[0]?.[1]?.zh && localeCalls[0]?.[1]?.en, "both zh/en dictionaries registered");
|
|
106
|
+
// 静态 t('...') 键必须两份字典都有——之前只靠肉眼,变异的缺键测试抓不住。
|
|
107
|
+
{
|
|
108
|
+
const dicts = localeCalls[0]?.[1] || {};
|
|
109
|
+
const keys = new Set(
|
|
110
|
+
[...code.matchAll(/\bt\('([A-Za-z0-9_.]+)'/g)]
|
|
111
|
+
.map((m) => m[1])
|
|
112
|
+
// `t('err.' + code)` / `t('type.' + it.type)` 是动态前缀,不是完整键。
|
|
113
|
+
.filter((k) => !k.endsWith('.')),
|
|
114
|
+
);
|
|
115
|
+
for (const key of keys) {
|
|
116
|
+
ok(dicts.zh && dicts.zh[key] !== undefined, `zh missing locale key: ${key}`);
|
|
117
|
+
ok(dicts.en && dicts.en[key] !== undefined, `en missing locale key: ${key}`);
|
|
118
|
+
}
|
|
119
|
+
// 动态拼的 err.* / state.* 也要完整——静态正则抓不到它们。
|
|
120
|
+
for (const code of ["forbidden", "unsupported_media_type", "bad_request", "too_large", "method_not_allowed", "read_failed", "write_failed"]) {
|
|
121
|
+
ok(dicts.zh && dicts.zh["err." + code] !== undefined, `zh missing err.${code}`);
|
|
122
|
+
ok(dicts.en && dicts.en["err." + code] !== undefined, `en missing err.${code}`);
|
|
123
|
+
}
|
|
124
|
+
for (const code of ["symlink", "not-file", "too-large", "invalid", "read"]) {
|
|
125
|
+
ok(dicts.zh && dicts.zh["state." + code] !== undefined, `zh missing state.${code}`);
|
|
126
|
+
ok(dicts.en && dicts.en["state." + code] !== undefined, `en missing state.${code}`);
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
const reg = registrations.find((r) => r.opts && r.opts.name === "settings.section");
|
|
131
|
+
ok(!!reg, "settings.section was not registered");
|
|
132
|
+
if (reg) {
|
|
133
|
+
ok(reg.opts.id === "dsh-zcode-memory", "section id", reg.opts.id);
|
|
134
|
+
ok(typeof reg.opts.label === "function", "section label must be a function");
|
|
135
|
+
ok(typeof reg.component === "function", "section component must be a function");
|
|
136
|
+
// 走一次渲染:没有数据时应输出 loading,而不是抛错。
|
|
137
|
+
try {
|
|
138
|
+
const tree = reg.component({ t: (key) => key, sessionId: "s1" });
|
|
139
|
+
ok(!!tree && tree.type === "div", "loading render shape", tree && tree.type);
|
|
140
|
+
} catch (e) {
|
|
141
|
+
fails.push(`component render threw: ${e && e.message}`);
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
// 再走一次「已加载」渲染:覆盖开关、清单、展开正文三个分支。
|
|
145
|
+
// useState 按调用顺序回填:1=view,6=openKey,其余用初始值。
|
|
146
|
+
const item = {
|
|
147
|
+
scope: "project",
|
|
148
|
+
workspace: "zcode",
|
|
149
|
+
workspaceId: "zcode-0123456789abcdef",
|
|
150
|
+
slug: "topic",
|
|
151
|
+
rel: "a/topic.md",
|
|
152
|
+
title: "A 版",
|
|
153
|
+
name: "topic-a",
|
|
154
|
+
description: "示例摘要",
|
|
155
|
+
type: "project",
|
|
156
|
+
updated: "2026-12-05",
|
|
157
|
+
chars: 12,
|
|
158
|
+
truncated: false,
|
|
159
|
+
body: "项目正文。",
|
|
160
|
+
};
|
|
161
|
+
// 同一工作区、同 basename、不同子目录:rel 必须让 React key 不撞。
|
|
162
|
+
const item2 = { ...item, rel: "b/topic.md", title: "B 版", name: "topic-b", body: "另一份正文。" };
|
|
163
|
+
const view = {
|
|
164
|
+
ok: true,
|
|
165
|
+
enabled: true,
|
|
166
|
+
configEnabled: true,
|
|
167
|
+
stateEnabled: null,
|
|
168
|
+
stateError: "",
|
|
169
|
+
memoriesRoot: "C:/memories",
|
|
170
|
+
counts: { total: 2, project: 2, global: 0 },
|
|
171
|
+
page: { offset: 0, limit: 200, returned: 2, hasMore: false },
|
|
172
|
+
items: [item, item2],
|
|
173
|
+
};
|
|
174
|
+
const renderWith = (stateView) => {
|
|
175
|
+
let call = 0;
|
|
176
|
+
const ReactStateful = {
|
|
177
|
+
createElement: makeElement,
|
|
178
|
+
useState: (initial) => {
|
|
179
|
+
call += 1;
|
|
180
|
+
if (call === 1) return [stateView, () => {}];
|
|
181
|
+
if (call === 6) return [`project\u0000zcode-0123456789abcdef\u0000a/topic.md`, () => {}];
|
|
182
|
+
return [initial, () => {}];
|
|
183
|
+
},
|
|
184
|
+
useEffect: () => {},
|
|
185
|
+
useCallback: (fn) => fn,
|
|
186
|
+
useRef: (value) => ({ current: value }),
|
|
187
|
+
};
|
|
188
|
+
const loaded = captured.factory((id) => {
|
|
189
|
+
if (id === "react") return ReactStateful;
|
|
190
|
+
throw new Error(`unexpected require: ${id}`);
|
|
191
|
+
});
|
|
192
|
+
let component = null;
|
|
193
|
+
loaded.apply({
|
|
194
|
+
effect: (fn) => { fn(); },
|
|
195
|
+
locale: ctx.locale,
|
|
196
|
+
slots: {
|
|
197
|
+
inject: (name, fn) => fn(),
|
|
198
|
+
register: (opts, comp) => { component = comp; return () => {}; },
|
|
199
|
+
},
|
|
200
|
+
});
|
|
201
|
+
ok(typeof component === "function", "stateful render must register a component");
|
|
202
|
+
return component({ t: (key) => key });
|
|
203
|
+
};
|
|
204
|
+
const findClass = (node, cls) => {
|
|
205
|
+
if (!node || typeof node !== "object") return null;
|
|
206
|
+
if (Array.isArray(node)) {
|
|
207
|
+
for (const child of node) {
|
|
208
|
+
const hit = findClass(child, cls);
|
|
209
|
+
if (hit) return hit;
|
|
210
|
+
}
|
|
211
|
+
return null;
|
|
212
|
+
}
|
|
213
|
+
if (node.props && node.props.className === cls) return node;
|
|
214
|
+
for (const child of node.children || []) {
|
|
215
|
+
const hit = findClass(child, cls);
|
|
216
|
+
if (hit) return hit;
|
|
217
|
+
}
|
|
218
|
+
return null;
|
|
219
|
+
};
|
|
220
|
+
const findAllClass = (node, cls, out = []) => {
|
|
221
|
+
if (!node || typeof node !== "object") return out;
|
|
222
|
+
if (Array.isArray(node)) {
|
|
223
|
+
for (const child of node) findAllClass(child, cls, out);
|
|
224
|
+
return out;
|
|
225
|
+
}
|
|
226
|
+
if (node.props && node.props.className === cls) out.push(node);
|
|
227
|
+
for (const child of node.children || []) findAllClass(child, cls, out);
|
|
228
|
+
return out;
|
|
229
|
+
};
|
|
230
|
+
try {
|
|
231
|
+
const loadedTree = renderWith(view);
|
|
232
|
+
ok(!!findClass(loadedTree, "dsh-zmem-switch"), "loaded view must render the switch");
|
|
233
|
+
const heads = findAllClass(loadedTree, "dsh-zmem-itemHead");
|
|
234
|
+
eq(heads.length, 2, "loaded view must render both memory rows");
|
|
235
|
+
const controls = heads.map((x) => x.props["aria-controls"]).filter(Boolean);
|
|
236
|
+
eq(new Set(controls).size, controls.length, "body ids must be unique across same-basename rows");
|
|
237
|
+
eq(controls.length, 1, "only the expanded row may point at a body");
|
|
238
|
+
ok(!heads[1].props["aria-controls"], "collapsed rows must not have a dangling aria-controls");
|
|
239
|
+
ok(!heads.some((x) => findClass(x, "dsh-zmem-body")), "body must be a sibling, not inside role=button");
|
|
240
|
+
const wrap = findClass(loadedTree, "dsh-zmem-bodyWrap");
|
|
241
|
+
ok(wrap && wrap.props.id === controls[0], "aria-controls must point at the rendered body", wrap && wrap.props.id);
|
|
242
|
+
ok(!!findClass(loadedTree, "dsh-zmem-body"), "expanded row must render the body");
|
|
243
|
+
const moreTree = renderWith({ ...view, page: { ...view.page, hasMore: true } });
|
|
244
|
+
ok(!!findClass(moreTree, "dsh-zmem-moreBtn"), "hasMore must render the load-more button");
|
|
245
|
+
const disabledTree = renderWith({ ...view, enabled: false, configEnabled: false });
|
|
246
|
+
const sw = findClass(disabledTree, "dsh-zmem-switch");
|
|
247
|
+
ok(sw && sw.props.disabled === true, "config hard-off must disable the switch", sw && sw.props.disabled);
|
|
248
|
+
} catch (e) {
|
|
249
|
+
fails.push(`loaded component render threw: ${e && e.message}`);
|
|
250
|
+
}
|
|
251
|
+
}
|
|
252
|
+
}
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
console.log(fails.length ? `FAIL ${fails.length}:\n - ` + fails.join("\n - ") : "ALL PASS");
|
|
256
|
+
process.exit(fails.length ? 1 : 0);
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
// N2 memo 作用域:同 cwd 不同 agentPreset 不能串注入;不同 cwd 不串;子代理不注入。
|
|
2
|
+
// 用法: node context-memo.mjs [index.js 路径]
|
|
3
|
+
import { pathToFileURL } from "node:url";
|
|
4
|
+
import { mkdtempSync, rmSync } from "node:fs";
|
|
5
|
+
import { tmpdir } from "node:os";
|
|
6
|
+
import { join } from "node:path";
|
|
7
|
+
|
|
8
|
+
const modUrl = process.argv[2] ? pathToFileURL(process.argv[2]).href : new URL("../index.js", import.meta.url).href;
|
|
9
|
+
const mod = await import(modUrl);
|
|
10
|
+
|
|
11
|
+
const root = mkdtempSync(join(tmpdir(), "zcm-memo-"));
|
|
12
|
+
const cwdA = mkdtempSync(join(tmpdir(), "zcm-memoA-"));
|
|
13
|
+
const cwdB = mkdtempSync(join(tmpdir(), "zcm-memoB-"));
|
|
14
|
+
const reg = { sections: [], contexts: [], tools: [], commands: [], handlers: new Map() };
|
|
15
|
+
const ctx = {
|
|
16
|
+
systemPrompt: { section: (o) => reg.sections.push(o), context: (o) => reg.contexts.push(o) },
|
|
17
|
+
tools: { register: (d) => reg.tools.push(d) },
|
|
18
|
+
commands: { register: (c) => reg.commands.push(c) },
|
|
19
|
+
on: (ev, fn) => { if (!reg.handlers.has(ev)) reg.handlers.set(ev, []); reg.handlers.get(ev).push(fn); },
|
|
20
|
+
llm: { stream: async function* () {} },
|
|
21
|
+
};
|
|
22
|
+
mod.apply(ctx, {
|
|
23
|
+
memoriesRoot: root,
|
|
24
|
+
enabled: true,
|
|
25
|
+
promptStyle: "native",
|
|
26
|
+
writeEnabled: true,
|
|
27
|
+
agentMemoryEnabled: true,
|
|
28
|
+
agentMemoryScope: "project",
|
|
29
|
+
agentMemoryName: "reviewer",
|
|
30
|
+
});
|
|
31
|
+
|
|
32
|
+
const save = reg.tools.find((t) => t.name === "memory_save");
|
|
33
|
+
const exec = { agent: { session: { id: "sess-memo", header: { cwd: cwdA, createdAt: "2026-12-05T10:00:00.000Z" } } } };
|
|
34
|
+
const saved = await save.execute({ title: "MemoAlpha", description: "alpha", body: "alpha body", scope: "project" }, exec);
|
|
35
|
+
if (!saved.ok) {
|
|
36
|
+
console.log("FAIL seed save:", saved.message);
|
|
37
|
+
process.exit(1);
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
const mem = reg.contexts.find((c) => c.name === "zcode-memory");
|
|
41
|
+
const rulesSec = reg.sections.find((c) => c.name === "zcode-memory-rules");
|
|
42
|
+
if (!mem || !rulesSec) {
|
|
43
|
+
console.log("FAIL: zcode-memory context/rules registration missing");
|
|
44
|
+
process.exit(1);
|
|
45
|
+
}
|
|
46
|
+
// G9:规则在 section、索引在 context;断言看两段拼起来的完整注入文本。
|
|
47
|
+
const text = (cwd, preset, extra = {}) => {
|
|
48
|
+
const arg = { agent: { session: { header: { cwd, agentPreset: preset, ...extra } } } };
|
|
49
|
+
return `${String(rulesSec.text(arg))}\n\n${String(mem.text(arg))}`;
|
|
50
|
+
};
|
|
51
|
+
const fails = [];
|
|
52
|
+
const check = (cond, msg, extra) => {
|
|
53
|
+
if (!cond) fails.push(msg + (extra !== undefined ? ` :: ${JSON.stringify(extra).slice(0, 300)}` : ""));
|
|
54
|
+
};
|
|
55
|
+
|
|
56
|
+
// 1. 自定义 agent → 有 Persistent Agent Memory;紧随其后的 standard 会话必须是纯项目索引。
|
|
57
|
+
const reviewer = text(cwdA, "reviewer");
|
|
58
|
+
const standard = text(cwdA, "standard");
|
|
59
|
+
check(reviewer.includes("Persistent Agent Memory"), "custom preset gets agent memory section", reviewer.length);
|
|
60
|
+
check(!standard.includes("Persistent Agent Memory"), "standard preset must not inherit agent section", standard.length);
|
|
61
|
+
check(reviewer.includes("MemoAlpha") && standard.includes("MemoAlpha"), "both sessions see the project index");
|
|
62
|
+
|
|
63
|
+
// 2. 反方向:先 standard 再 reviewer(间隔为 0,必须分别求值)。
|
|
64
|
+
const standard2 = text(cwdA, "standard");
|
|
65
|
+
const reviewer2 = text(cwdA, "reviewer");
|
|
66
|
+
check(!standard2.includes("Persistent Agent Memory"), "standard first must stay clean", standard2.length);
|
|
67
|
+
check(reviewer2.includes("Persistent Agent Memory"), "custom preset still gets its section after standard", reviewer2.length);
|
|
68
|
+
|
|
69
|
+
// 3. 不同 cwd:不能看到 A 的项目索引。
|
|
70
|
+
const other = text(cwdB, "standard");
|
|
71
|
+
check(!other.includes("MemoAlpha"), "different cwd must not share memo text", other.length);
|
|
72
|
+
|
|
73
|
+
// 4. 子代理不注入。
|
|
74
|
+
const sub = String(mem.text({ agent: { session: { header: { cwd: cwdA, agentPreset: "reviewer", origin: "subagent" } } } }));
|
|
75
|
+
check(sub === "", "subagent gets no memory context", sub);
|
|
76
|
+
|
|
77
|
+
console.log(fails.length ? `FAIL ${fails.length}:\n - ` + fails.join("\n - ") : "ALL PASS");
|
|
78
|
+
if (!fails.length) {
|
|
79
|
+
try {
|
|
80
|
+
rmSync(root, { recursive: true, force: true });
|
|
81
|
+
rmSync(cwdA, { recursive: true, force: true });
|
|
82
|
+
rmSync(cwdB, { recursive: true, force: true });
|
|
83
|
+
} catch {}
|
|
84
|
+
}
|
|
85
|
+
process.exit(fails.length ? 1 : 0);
|
|
@@ -0,0 +1,312 @@
|
|
|
1
|
+
// P4(2026-12-05)抽取成本默认值:
|
|
2
|
+
// 1. autoExtractMinIntervalMs 默认 300000(5 分钟合并一次,不再每个回合都抽)。
|
|
3
|
+
// 2. 默认配置下两个紧邻回合:第二个必须跳过,且 status 记 lastSkipReason="interval"。
|
|
4
|
+
// 3. 间隔过后再把两个回合的对话一起抽(跳过不动游标,消息不能丢)。
|
|
5
|
+
// 4. memory_save / memory_update 的 body 超过 6000 字符要被截断并明确提示。
|
|
6
|
+
// 5. memory_recall 默认单条正文 2500 字符(recallBodyChars)。
|
|
7
|
+
// 用法: node extract-cost.mjs [index.js 路径]
|
|
8
|
+
import { pathToFileURL } from "node:url";
|
|
9
|
+
import { mkdtempSync, mkdirSync, existsSync, readFileSync, writeFileSync, rmSync } from "node:fs";
|
|
10
|
+
import { tmpdir } from "node:os";
|
|
11
|
+
import { join } from "node:path";
|
|
12
|
+
|
|
13
|
+
const modUrl = process.argv[2] ? pathToFileURL(process.argv[2]).href : new URL("../index.js", import.meta.url).href;
|
|
14
|
+
const mod = await import(modUrl);
|
|
15
|
+
|
|
16
|
+
const fails = [];
|
|
17
|
+
const check = (cond, msg, extra) => {
|
|
18
|
+
if (!cond) fails.push(msg + (extra !== undefined ? ` :: ${JSON.stringify(extra).slice(0, 400)}` : ""));
|
|
19
|
+
};
|
|
20
|
+
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
|
|
21
|
+
|
|
22
|
+
function makeHarness(overrides = {}) {
|
|
23
|
+
const root = mkdtempSync(join(tmpdir(), "zcm-cost-"));
|
|
24
|
+
const cwd = mkdtempSync(join(tmpdir(), "zcm-cost-cwd-"));
|
|
25
|
+
const seen = [];
|
|
26
|
+
const reg = { handlers: new Map(), tools: [] };
|
|
27
|
+
const ctx = {
|
|
28
|
+
systemPrompt: { section: () => {}, context: () => {} },
|
|
29
|
+
tools: { register: (d) => reg.tools.push(d), schemas: () => [{ name: "write" }] },
|
|
30
|
+
commands: { register: () => {} },
|
|
31
|
+
on: (ev, fn) => {
|
|
32
|
+
if (!reg.handlers.has(ev)) reg.handlers.set(ev, []);
|
|
33
|
+
reg.handlers.get(ev).push(fn);
|
|
34
|
+
},
|
|
35
|
+
llm: {
|
|
36
|
+
stream: async function* (opts) {
|
|
37
|
+
const text = (opts.messages || [])
|
|
38
|
+
.map((m) => (Array.isArray(m.content) ? m.content : []).map((b) => b.text || "").join(""))
|
|
39
|
+
.join("\n");
|
|
40
|
+
seen.push(text);
|
|
41
|
+
yield { type: "text-delta", text: JSON.stringify({ writes: [] }) };
|
|
42
|
+
yield { type: "finish", reason: { kind: "stop" } };
|
|
43
|
+
},
|
|
44
|
+
},
|
|
45
|
+
};
|
|
46
|
+
mod.apply(ctx, { memoriesRoot: root, enabled: true, promptStyle: "native", ...overrides });
|
|
47
|
+
const emit = async (ev, ...args) => {
|
|
48
|
+
for (const fn of reg.handlers.get(ev) || []) await fn(...args);
|
|
49
|
+
};
|
|
50
|
+
const session = { header: { id: "sess-cost", cwd, createdAt: "2026-12-05T11:00:00.000Z" } };
|
|
51
|
+
const agent = {
|
|
52
|
+
session,
|
|
53
|
+
status: "idle",
|
|
54
|
+
inbox: { nextTurn: [], nextStep: [] },
|
|
55
|
+
model: { current: () => ({ provider: "mock", model: "mock-1" }) },
|
|
56
|
+
whenIdle: () => Promise.resolve(),
|
|
57
|
+
runMaintenance: async (fn) => fn(new AbortController().signal),
|
|
58
|
+
};
|
|
59
|
+
const statePath = join(root, "_extract-state.json");
|
|
60
|
+
const state = () => {
|
|
61
|
+
try {
|
|
62
|
+
return JSON.parse(readFileSync(statePath, "utf8"));
|
|
63
|
+
} catch {
|
|
64
|
+
return null;
|
|
65
|
+
}
|
|
66
|
+
};
|
|
67
|
+
let seq = 0;
|
|
68
|
+
// 跑一个回合:turn/start → user 消息 →(工具结果)→ turn-stopping。
|
|
69
|
+
const runTurn = async (turn, userText, toolTexts = []) => {
|
|
70
|
+
await emit("session/event", session, { type: "turn/start", seq: ++seq, data: { turn } });
|
|
71
|
+
await emit("session/event", session, {
|
|
72
|
+
type: "user/message",
|
|
73
|
+
seq: ++seq,
|
|
74
|
+
data: { source: { kind: "user" }, content: [{ type: "text", text: userText }] },
|
|
75
|
+
});
|
|
76
|
+
let i = 0;
|
|
77
|
+
for (const t of toolTexts) {
|
|
78
|
+
i++;
|
|
79
|
+
await emit("session/event", session, {
|
|
80
|
+
type: "tool/result",
|
|
81
|
+
seq: ++seq,
|
|
82
|
+
data: { turn, message: { toolCallId: `c${turn}-${i}`, content: [{ type: "text", text: t }] } },
|
|
83
|
+
});
|
|
84
|
+
}
|
|
85
|
+
const lastSeq = seq;
|
|
86
|
+
await emit("agent/turn-stopping", { agent, turn });
|
|
87
|
+
return lastSeq;
|
|
88
|
+
};
|
|
89
|
+
const waitFor = async (fn, ms = 4000) => {
|
|
90
|
+
const t0 = Date.now();
|
|
91
|
+
while (Date.now() - t0 < ms) {
|
|
92
|
+
if (fn()) return true;
|
|
93
|
+
await sleep(10);
|
|
94
|
+
}
|
|
95
|
+
return false;
|
|
96
|
+
};
|
|
97
|
+
const cleanup = () => {
|
|
98
|
+
try {
|
|
99
|
+
rmSync(root, { recursive: true, force: true });
|
|
100
|
+
rmSync(cwd, { recursive: true, force: true });
|
|
101
|
+
} catch {
|
|
102
|
+
/* noop */
|
|
103
|
+
}
|
|
104
|
+
};
|
|
105
|
+
const tool = (name) => reg.tools.find((t) => t.name === name);
|
|
106
|
+
const exec = { agent: { session } };
|
|
107
|
+
return { root, cwd, session, agent, seen, state, runTurn, waitFor, cleanup, tool, exec, emit };
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
// --- 1. 默认配置:紧邻两个回合,第二个必须跳过抽取,且状态可解释 ---
|
|
111
|
+
{
|
|
112
|
+
const h = makeHarness();
|
|
113
|
+
const s1 = await h.runTurn(1, "记住:这个项目的发布命令是 pnpm release,产物在 dist 目录。");
|
|
114
|
+
const ok1 = await h.waitFor(() => (h.state()?.cursorBySession?.["sess-cost"]?.seq || 0) >= s1);
|
|
115
|
+
check(ok1, "1: 第一回合应当抽取并把游标推进到本回合末条", h.state());
|
|
116
|
+
check(h.seen.length === 1, `1: 第一回合应有 1 次抽取调用(实际 ${h.seen.length})`);
|
|
117
|
+
const s2 = await h.runTurn(2, "顺便说一下:测试用 pnpm test,别用 npm test 跑全量。");
|
|
118
|
+
await h.waitFor(() => h.state()?.lastSkipReason === "interval");
|
|
119
|
+
const st = h.state();
|
|
120
|
+
check(st?.lastSkipReason === "interval", "1: 第二个回合应因默认间隔跳过(lastSkipReason=interval)", st);
|
|
121
|
+
check(h.seen.length === 1, `1: 跳过时不得调用抽取模型(实际调用 ${h.seen.length} 次)`);
|
|
122
|
+
check((st?.cursorBySession?.["sess-cost"]?.seq || 0) === s1, "1: 跳过时不得推进游标(消息要留到下次)", st?.cursorBySession);
|
|
123
|
+
h.cleanup();
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
// --- 2. 间隔过后:两个回合的对话一起抽,不丢第一个回合的消息 ---
|
|
127
|
+
{
|
|
128
|
+
const h = makeHarness({ autoExtractMinIntervalMs: 300 });
|
|
129
|
+
const s1 = await h.runTurn(1, "U1-MARK 记住发布命令是 pnpm release。");
|
|
130
|
+
await h.waitFor(() => (h.state()?.cursorBySession?.["sess-cost"]?.seq || 0) >= s1);
|
|
131
|
+
check(h.seen.length === 1, "2: 第一回合应抽取一次");
|
|
132
|
+
await h.runTurn(2, "U2-MARK 测试命令是 pnpm test。");
|
|
133
|
+
await h.waitFor(() => h.state()?.lastSkipReason === "interval");
|
|
134
|
+
check(h.seen.length === 1, "2: 间隔内第二回合应跳过抽取");
|
|
135
|
+
await sleep(360);
|
|
136
|
+
const s3 = await h.runTurn(3, "U3-MARK 产物目录是 dist。");
|
|
137
|
+
await h.waitFor(() => (h.state()?.cursorBySession?.["sess-cost"]?.seq || 0) >= s3);
|
|
138
|
+
check(h.seen.length === 2, `2: 间隔过后应再抽一次(实际 ${h.seen.length} 次调用)`);
|
|
139
|
+
const last = h.seen.at(-1) || "";
|
|
140
|
+
check(last.includes("U2-MARK"), "2: 跳过的那一回合消息必须一起进下一窗(不能丢)", last.slice(0, 400));
|
|
141
|
+
check(last.includes("U3-MARK"), "2: 本次回合消息也应在同一窗", last.slice(0, 400));
|
|
142
|
+
check((h.state()?.cursorBySession?.["sess-cost"]?.seq || 0) === s3, "2: 游标应覆盖到第三回合末条(跨过被跳过的区间)", h.state()?.cursorBySession);
|
|
143
|
+
h.cleanup();
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
// --- 3. memory_save 超长 body:截断 + 明确提示(不静默丢尾部) ---
|
|
147
|
+
{
|
|
148
|
+
const h = makeHarness();
|
|
149
|
+
const body = "A".repeat(4000) + "B".repeat(4000);
|
|
150
|
+
const saved = await h.tool("memory_save").execute({ title: "长正文探针", description: "cap", body, scope: "project" }, h.exec);
|
|
151
|
+
check(saved?.ok, "3: 超长 body 仍应保存成功", saved);
|
|
152
|
+
check(/截断/.test(String(saved?.message || "")), "3: message 必须提示已截断", saved?.message);
|
|
153
|
+
const rd = await h.tool("memory_read").execute({ name: "长正文探针" }, h.exec);
|
|
154
|
+
const kept = rd?.matches?.[0]?.body || "";
|
|
155
|
+
check(kept.length === 6000, `3: 正文应保留前 6000 字符(实际 ${kept.length})`);
|
|
156
|
+
// 必须逐字等于前缀:endsWith/includes 这类断言在「错误地保留尾部」时也会通过。
|
|
157
|
+
check(kept === body.slice(0, 6000), "3: 截断必须保留前缀 6000 字符(不能保留尾部或拼接)");
|
|
158
|
+
// 截断点落在代理对中间时不能写出孤立代理(读回会出现 U+FFFD)。
|
|
159
|
+
const emojiBody = "a" + "😀".repeat(4000);
|
|
160
|
+
const saved2 = await h.tool("memory_save").execute({ title: "emoji 探针", description: "cap", body: emojiBody, scope: "project" }, h.exec);
|
|
161
|
+
check(saved2?.ok, "3b: emoji 正文应保存成功", saved2);
|
|
162
|
+
const rd2 = await h.tool("memory_read").execute({ name: "emoji 探针" }, h.exec);
|
|
163
|
+
const kept2 = rd2?.matches?.[0]?.body || "";
|
|
164
|
+
check(kept2.length === 5999, `3b: 代理对必须整对保留(实际 ${kept2.length} 个 UTF-16 单元)`);
|
|
165
|
+
check(!kept2.includes("\uFFFD"), "3b: 截断处不得产生替换字符 U+FFFD");
|
|
166
|
+
h.cleanup();
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
// --- 4. memory_update:显式传超长 body 也截断;只改描述时不得动既有正文 ---
|
|
170
|
+
{
|
|
171
|
+
const h = makeHarness();
|
|
172
|
+
await h.tool("memory_save").execute(
|
|
173
|
+
{ title: "更新探针", description: "d0", body: "C".repeat(6000), scope: "project" },
|
|
174
|
+
h.exec,
|
|
175
|
+
);
|
|
176
|
+
const up = await h.tool("memory_update").execute({ name: "更新探针", body: "D".repeat(7000) }, h.exec);
|
|
177
|
+
check(up?.ok, "4: 超长 body 更新仍应成功", up);
|
|
178
|
+
check(/截断/.test(String(up?.message || "")), "4: update 也必须提示截断", up?.message);
|
|
179
|
+
const r1 = await h.tool("memory_read").execute({ name: "更新探针" }, h.exec);
|
|
180
|
+
check((r1?.matches?.[0]?.body || "").length === 6000, "4: 更新后正文应是 6000 字符", (r1?.matches?.[0]?.body || "").length);
|
|
181
|
+
// 直接往盘上补 2000 字符模拟历史遗留的超长正文,再只改 description。
|
|
182
|
+
const memDir = join(h.root, "projects");
|
|
183
|
+
const { readdirSync } = await import("node:fs");
|
|
184
|
+
const projDir = join(memDir, readdirSync(memDir)[0], "memory");
|
|
185
|
+
const file = join(projDir, "更新探针.md");
|
|
186
|
+
writeFileSync(file, readFileSync(file, "utf8") + "E".repeat(2000), "utf8");
|
|
187
|
+
const up2 = await h.tool("memory_update").execute({ name: "更新探针", description: "d1" }, h.exec);
|
|
188
|
+
check(up2?.ok, "4: 只改描述应成功", up2);
|
|
189
|
+
const after = readFileSync(file, "utf8");
|
|
190
|
+
check(after.includes("E".repeat(2000)), "4: 只改描述时不得截断既有正文(不能借更新偷偷削正文)");
|
|
191
|
+
h.cleanup();
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
// --- 5. memory_recall 默认单条正文 2500 字符 ---
|
|
195
|
+
{
|
|
196
|
+
const h = makeHarness();
|
|
197
|
+
const body = "x".repeat(5000);
|
|
198
|
+
const saved = await h.tool("memory_save").execute({ title: "召回预算探针", description: "recall", body, scope: "project" }, h.exec);
|
|
199
|
+
check(saved?.ok, "5: 前置保存应成功", saved);
|
|
200
|
+
const r = await h.tool("memory_recall").execute({ query: "召回预算探针" }, h.exec);
|
|
201
|
+
const m = r?.matches?.[0];
|
|
202
|
+
check(!!m, "5: 应召回该条记忆", r);
|
|
203
|
+
check((m?.body || "").length <= 2500, `5: 默认单条正文应 ≤2500(实际 ${(m?.body || "").length})`);
|
|
204
|
+
check(m?.truncated === true, "5: 应标记 truncated");
|
|
205
|
+
h.cleanup();
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
// --- 6. 抽取失败后紧接重试:不受 5 分钟间隔限制(否则毒丸要跨 15 分钟才判) ---
|
|
209
|
+
{
|
|
210
|
+
const root = mkdtempSync(join(tmpdir(), "zcm-cost-fail-"));
|
|
211
|
+
const cwd = mkdtempSync(join(tmpdir(), "zcm-cost-fail-cwd-"));
|
|
212
|
+
const seen = [];
|
|
213
|
+
const reg = { handlers: new Map(), tools: [] };
|
|
214
|
+
const ctx = {
|
|
215
|
+
systemPrompt: { section: () => {}, context: () => {} },
|
|
216
|
+
tools: { register: (d) => reg.tools.push(d), schemas: () => [{ name: "write" }] },
|
|
217
|
+
commands: { register: () => {} },
|
|
218
|
+
on: (ev, fn) => {
|
|
219
|
+
if (!reg.handlers.has(ev)) reg.handlers.set(ev, []);
|
|
220
|
+
reg.handlers.get(ev).push(fn);
|
|
221
|
+
},
|
|
222
|
+
llm: {
|
|
223
|
+
stream: async function* () {
|
|
224
|
+
seen.push(1);
|
|
225
|
+
throw new Error("mock llm failure");
|
|
226
|
+
},
|
|
227
|
+
},
|
|
228
|
+
};
|
|
229
|
+
mod.apply(ctx, { memoriesRoot: root, enabled: true, promptStyle: "native" });
|
|
230
|
+
const emit = async (ev, ...args) => {
|
|
231
|
+
for (const fn of reg.handlers.get(ev) || []) await fn(...args);
|
|
232
|
+
};
|
|
233
|
+
const session = { header: { id: "sess-fail", cwd, createdAt: "2026-12-05T11:00:00.000Z" } };
|
|
234
|
+
const agent = {
|
|
235
|
+
session,
|
|
236
|
+
status: "idle",
|
|
237
|
+
inbox: { nextTurn: [], nextStep: [] },
|
|
238
|
+
model: { current: () => ({ provider: "mock", model: "mock-1" }) },
|
|
239
|
+
whenIdle: () => Promise.resolve(),
|
|
240
|
+
runMaintenance: async (fn) => fn(new AbortController().signal),
|
|
241
|
+
};
|
|
242
|
+
const state = () => {
|
|
243
|
+
try {
|
|
244
|
+
return JSON.parse(readFileSync(join(root, "_extract-state.json"), "utf8"));
|
|
245
|
+
} catch {
|
|
246
|
+
return null;
|
|
247
|
+
}
|
|
248
|
+
};
|
|
249
|
+
let seq = 0;
|
|
250
|
+
const turn = async (n, text) => {
|
|
251
|
+
await emit("session/event", session, { type: "turn/start", seq: ++seq, data: { turn: n } });
|
|
252
|
+
await emit("session/event", session, {
|
|
253
|
+
type: "user/message",
|
|
254
|
+
seq: ++seq,
|
|
255
|
+
data: { source: { kind: "user" }, content: [{ type: "text", text }] },
|
|
256
|
+
});
|
|
257
|
+
await emit("agent/turn-stopping", { agent, turn: n });
|
|
258
|
+
};
|
|
259
|
+
const waitFor = async (fn, ms = 4000) => {
|
|
260
|
+
const t0 = Date.now();
|
|
261
|
+
while (Date.now() - t0 < ms) {
|
|
262
|
+
if (fn()) return true;
|
|
263
|
+
await sleep(10);
|
|
264
|
+
}
|
|
265
|
+
return false;
|
|
266
|
+
};
|
|
267
|
+
await turn(1, "第一次抽取会失败:记住发布命令是 pnpm release。");
|
|
268
|
+
await waitFor(() => Number(state()?.consecutiveFailures) >= 1);
|
|
269
|
+
check(Number(state()?.consecutiveFailures) >= 1, "6: 第一次应写失败状态", state());
|
|
270
|
+
await turn(2, "第二次:测试命令是 pnpm test,不要再失败。");
|
|
271
|
+
await waitFor(() => seen.length >= 2);
|
|
272
|
+
check(seen.length >= 2, `6: 失败后的重试必须立即发生(不受 5 分钟间隔限制,实际调用 ${seen.length} 次)`);
|
|
273
|
+
check(state()?.lastSkipReason !== "interval", "6: 失败重试不应被间隔跳过", state()?.lastSkipReason);
|
|
274
|
+
// 失败的异步处理器可能还要落一次状态:先等一拍再删,否则 writeExtractState 会把目录重建出来。
|
|
275
|
+
await sleep(120);
|
|
276
|
+
try {
|
|
277
|
+
rmSync(root, { recursive: true, force: true });
|
|
278
|
+
rmSync(cwd, { recursive: true, force: true });
|
|
279
|
+
} catch {
|
|
280
|
+
/* noop */
|
|
281
|
+
}
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
// --- 7. 间隔合并期间积压不能丢:多个大回合合起来超过 24k 时,间隔要让位于数据完整性 ---
|
|
285
|
+
// 旧实现里会话缓冲按 24k 裁剪,被跳过的回合会被删掉、游标随后越过它们 → 永久漏抽。
|
|
286
|
+
{
|
|
287
|
+
// 显式给 5 分钟间隔(与新的默认值一致):基线也认这个键,所以这条能被基线区分出来。
|
|
288
|
+
const h = makeHarness({ autoExtractMinIntervalMs: 300000 });
|
|
289
|
+
const big = (mark) => Array.from({ length: 8 }, (_, i) => `${mark} ${i} ` + "x".repeat(1980));
|
|
290
|
+
const s1 = await h.runTurn(1, "记住第一回合的事。", big("T1-MARK"));
|
|
291
|
+
await h.waitFor(() => (h.state()?.cursorBySession?.["sess-cost"]?.seq || 0) >= s1);
|
|
292
|
+
check(h.seen.length >= 1, "7: 第一回合应抽取");
|
|
293
|
+
await h.runTurn(2, "记住第二回合的事。", big("T2-MARK"));
|
|
294
|
+
const s3 = await h.runTurn(3, "记住第三回合的事。", big("T3-MARK"));
|
|
295
|
+
await h.waitFor(() => (h.state()?.cursorBySession?.["sess-cost"]?.seq || 0) >= s3, 8000);
|
|
296
|
+
const all = h.seen.join("\n---\n");
|
|
297
|
+
for (const m of ["T2-MARK", "T3-MARK"]) {
|
|
298
|
+
check(all.includes(m), `7: 被间隔跳过的回合(${m})必须最终被抽取,不能因缓冲裁剪丢失`);
|
|
299
|
+
}
|
|
300
|
+
check(Number(h.state()?.droppedUnextracted || 0) === 0, "7: 不应丢弃任何未抽取消息(droppedUnextracted=0)", {
|
|
301
|
+
dropped: h.state()?.droppedUnextracted,
|
|
302
|
+
});
|
|
303
|
+
check((h.state()?.cursorBySession?.["sess-cost"]?.seq || 0) >= s3, "7: 游标必须覆盖到第三回合末条", h.state()?.cursorBySession);
|
|
304
|
+
h.cleanup();
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
if (fails.length) {
|
|
308
|
+
console.error("FAIL extract-cost");
|
|
309
|
+
for (const f of fails) console.error(" -", f);
|
|
310
|
+
process.exit(1);
|
|
311
|
+
}
|
|
312
|
+
console.log("PASS extract-cost");
|