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,88 @@
|
|
|
1
|
+
// 失败/abort 后自动重跑:第一次 llm 抛错 → pending 保留 → finally 里 idle 直接重试成功
|
|
2
|
+
// 用法: node extract-retry.mjs [index.js 路径]
|
|
3
|
+
import { pathToFileURL } from "node:url";
|
|
4
|
+
import { mkdtempSync, readFileSync, readdirSync, existsSync, 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-rty-"));
|
|
12
|
+
const cwd = mkdtempSync(join(tmpdir(), "zcm-rtyc-"));
|
|
13
|
+
const state = { calls: 0 };
|
|
14
|
+
|
|
15
|
+
const reg = { sections: [], tools: [], commands: [], handlers: new Map() };
|
|
16
|
+
const ctx = {
|
|
17
|
+
systemPrompt: { section: (o) => reg.sections.push(o) },
|
|
18
|
+
tools: { register: (d) => reg.tools.push(d) },
|
|
19
|
+
commands: { register: (c) => reg.commands.push(c) },
|
|
20
|
+
on: (ev, fn) => { if (!reg.handlers.has(ev)) reg.handlers.set(ev, []); reg.handlers.get(ev).push(fn); },
|
|
21
|
+
llm: {
|
|
22
|
+
stream: async function* () {
|
|
23
|
+
state.calls++;
|
|
24
|
+
if (state.calls === 1) throw new Error("mock transient failure");
|
|
25
|
+
yield {
|
|
26
|
+
type: "text-delta",
|
|
27
|
+
text: JSON.stringify({
|
|
28
|
+
writes: [{ op: "create", title: "重试成功条目", description: "第二次调用写入", type: "project", body: "重试后的正文。" }],
|
|
29
|
+
}),
|
|
30
|
+
};
|
|
31
|
+
yield { type: "finish", reason: { kind: "stop" } };
|
|
32
|
+
},
|
|
33
|
+
},
|
|
34
|
+
};
|
|
35
|
+
mod.apply(ctx, { memoriesRoot: root, enabled: true, promptStyle: "native" });
|
|
36
|
+
|
|
37
|
+
const emit = (ev, ...args) => { for (const fn of reg.handlers.get(ev) || []) fn(...args); };
|
|
38
|
+
const fails = [];
|
|
39
|
+
const check = (c, m, e) => { if (!c) fails.push(m + (e ? ` :: ${String(e).slice(0, 300)}` : "")); };
|
|
40
|
+
|
|
41
|
+
const session = { header: { id: "sess-rty", cwd, createdAt: "2026-12-05T11:00:00.000Z" } };
|
|
42
|
+
const agent = {
|
|
43
|
+
session, status: "idle", inbox: { nextTurn: [], nextStep: [] },
|
|
44
|
+
model: { current: () => ({ provider: "mock", model: "mock-1" }) },
|
|
45
|
+
whenIdle: () => Promise.resolve(),
|
|
46
|
+
runMaintenance: async (fn) => fn(new AbortController().signal),
|
|
47
|
+
};
|
|
48
|
+
|
|
49
|
+
emit("session/event", session, { type: "turn/start", seq: 1, data: { turn: 1 } });
|
|
50
|
+
emit("session/event", session, {
|
|
51
|
+
type: "user/message", seq: 2,
|
|
52
|
+
data: { source: { kind: "user" }, content: [{ type: "text", text: "请记住这个项目的部署方式,以后每次都要用到它。" }] },
|
|
53
|
+
});
|
|
54
|
+
emit("session/event", session, { type: "assistant/message", seq: 3, data: { turn: 1, message: { content: [{ type: "text", text: "部署用 pnpm deploy。" }] } } });
|
|
55
|
+
emit("agent/turn-stopping", { agent, turn: 1 });
|
|
56
|
+
|
|
57
|
+
// 等两次调用与落盘
|
|
58
|
+
for (let i = 0; i < 120; i++) {
|
|
59
|
+
const p = join(root, "projects");
|
|
60
|
+
if (existsSync(p)) {
|
|
61
|
+
const s = readdirSync(p);
|
|
62
|
+
if (s.length) {
|
|
63
|
+
const md = join(p, s[0], "memory");
|
|
64
|
+
if (existsSync(md) && readdirSync(md).some((f) => f.endsWith(".md") && f !== "MEMORY.md")) break;
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
await new Promise((r) => setTimeout(r, 50));
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
check(state.calls >= 2, "retry attempted after transient failure", state.calls);
|
|
71
|
+
const slugs = existsSync(join(root, "projects")) ? readdirSync(join(root, "projects")) : [];
|
|
72
|
+
const memDir = join(root, "projects", slugs[0] || "x", "memory");
|
|
73
|
+
const files = existsSync(memDir) ? readdirSync(memDir).filter((f) => f.endsWith(".md") && f !== "MEMORY.md") : [];
|
|
74
|
+
check(files.length === 1, "retry wrote memory", files);
|
|
75
|
+
if (files.length) {
|
|
76
|
+
const t = readFileSync(join(memDir, files[0]), "utf8");
|
|
77
|
+
check(t.includes("重试后的正文"), "retry body", t);
|
|
78
|
+
}
|
|
79
|
+
const stFile = join(root, "_extract-state.json");
|
|
80
|
+
if (existsSync(stFile)) {
|
|
81
|
+
const st = JSON.parse(readFileSync(stFile, "utf8"));
|
|
82
|
+
check(st.lastOutcome === "ok", "final outcome ok after retry", st.lastOutcome);
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
console.log(fails.length ? `FAIL ${fails.length}:\n - ` + fails.join("\n - ") : "ALL PASS");
|
|
86
|
+
if (fails.length) console.error("root=" + root);
|
|
87
|
+
else { try { rmSync(root, { recursive: true, force: true }); rmSync(cwd, { recursive: true, force: true }); } catch {} }
|
|
88
|
+
process.exit(fails.length ? 1 : 0);
|
|
@@ -0,0 +1,138 @@
|
|
|
1
|
+
// B(v0.11)抽取 system 复用 Memory 规则 + Notes:
|
|
2
|
+
// - 含 when_to_save / applicable / durable(来自 Memory 段与 # Memory, notes and feedback)
|
|
3
|
+
// - 不含「用 Write 直接写 / mkdir」这类会让抽取器去找写工具的机制描述
|
|
4
|
+
// - JSON 输出约束在最后 300 字符内
|
|
5
|
+
// - 总长 ≤ 4500 字符(三条路径都验)
|
|
6
|
+
// 用法: node extract-system.mjs [index.js 路径]
|
|
7
|
+
import { pathToFileURL } from "node:url";
|
|
8
|
+
import { mkdtempSync, rmSync } from "node:fs";
|
|
9
|
+
import { tmpdir } from "node:os";
|
|
10
|
+
import { join } from "node:path";
|
|
11
|
+
|
|
12
|
+
const modUrl = process.argv[2] ? pathToFileURL(process.argv[2]).href : new URL("../index.js", import.meta.url).href;
|
|
13
|
+
const mod = await import(modUrl);
|
|
14
|
+
|
|
15
|
+
const fails = [];
|
|
16
|
+
const check = (cond, msg, extra) => {
|
|
17
|
+
if (!cond) fails.push(msg + (extra !== undefined ? ` :: ${JSON.stringify(extra).slice(0, 300)}` : ""));
|
|
18
|
+
};
|
|
19
|
+
|
|
20
|
+
async function captureSystem(overrides, schemas) {
|
|
21
|
+
const root = mkdtempSync(join(tmpdir(), "zcm-sysroot-"));
|
|
22
|
+
const cwd = mkdtempSync(join(tmpdir(), "zcm-syscwd-"));
|
|
23
|
+
const seen = [];
|
|
24
|
+
const reg = { tools: [], handlers: new Map() };
|
|
25
|
+
const ctx = {
|
|
26
|
+
systemPrompt: { section: () => {}, context: () => {} },
|
|
27
|
+
tools: {
|
|
28
|
+
register: (d) => reg.tools.push(d),
|
|
29
|
+
schemas: schemas || (() => [{ name: "memory_list", description: "list", parameters: { type: "object", properties: {} } }]),
|
|
30
|
+
execute: async () => ({ ok: true, value: { message: "ok" } }),
|
|
31
|
+
},
|
|
32
|
+
commands: { register: () => {} },
|
|
33
|
+
on: (ev, fn) => {
|
|
34
|
+
if (!reg.handlers.has(ev)) reg.handlers.set(ev, []);
|
|
35
|
+
reg.handlers.get(ev).push(fn);
|
|
36
|
+
},
|
|
37
|
+
llm: {
|
|
38
|
+
stream: async function* (opts) {
|
|
39
|
+
seen.push({ system: String(opts.system || ""), tools: opts.tools });
|
|
40
|
+
yield { type: "text-delta", text: JSON.stringify({ writes: [] }) };
|
|
41
|
+
yield { type: "finish", reason: { kind: "stop" } };
|
|
42
|
+
},
|
|
43
|
+
},
|
|
44
|
+
};
|
|
45
|
+
const cfg = {
|
|
46
|
+
memoriesRoot: root,
|
|
47
|
+
enabled: true,
|
|
48
|
+
promptStyle: "native",
|
|
49
|
+
autoExtractToolAgent: true,
|
|
50
|
+
autoExtractNativeTools: true,
|
|
51
|
+
...overrides,
|
|
52
|
+
};
|
|
53
|
+
mod.apply(ctx, cfg);
|
|
54
|
+
const emit = async (ev, ...args) => {
|
|
55
|
+
for (const fn of reg.handlers.get(ev) || []) await fn(...args);
|
|
56
|
+
};
|
|
57
|
+
const session = { header: { id: "sess-sys", cwd, createdAt: "2026-12-05T09:00:00.000Z" } };
|
|
58
|
+
const agent = {
|
|
59
|
+
session,
|
|
60
|
+
status: "idle",
|
|
61
|
+
inbox: { nextTurn: [], nextStep: [] },
|
|
62
|
+
model: { current: () => ({ provider: "mock", model: "mock-1" }) },
|
|
63
|
+
whenIdle: () => Promise.resolve(),
|
|
64
|
+
runMaintenance: async (fn) => fn(new AbortController().signal),
|
|
65
|
+
};
|
|
66
|
+
await emit("session/event", session, { type: "turn/start", seq: 1, data: { turn: 1 } });
|
|
67
|
+
await emit("session/event", session, {
|
|
68
|
+
type: "user/message",
|
|
69
|
+
seq: 2,
|
|
70
|
+
data: { source: { kind: "user" }, content: [{ type: "text", text: "请记住:这个项目的发布命令是 pnpm release,产物在 dist 目录里。" }] },
|
|
71
|
+
});
|
|
72
|
+
await emit("session/event", session, {
|
|
73
|
+
type: "assistant/message",
|
|
74
|
+
seq: 3,
|
|
75
|
+
data: { turn: 1, message: { content: [{ type: "text", text: "好的,发布命令是 pnpm release,产物在 dist。" }] } },
|
|
76
|
+
});
|
|
77
|
+
await emit("agent/turn-stopping", { agent, turn: 1 });
|
|
78
|
+
for (let i = 0; i < 200 && !seen.length; i++) await new Promise((r) => setTimeout(r, 10));
|
|
79
|
+
try {
|
|
80
|
+
rmSync(root, { recursive: true, force: true });
|
|
81
|
+
rmSync(cwd, { recursive: true, force: true });
|
|
82
|
+
} catch {
|
|
83
|
+
/* noop */
|
|
84
|
+
}
|
|
85
|
+
return seen[0] || { system: "", tools: undefined };
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
const cases = [
|
|
89
|
+
["native-tools", { autoExtractToolAgent: true, autoExtractNativeTools: true }],
|
|
90
|
+
["legacy-json", { autoExtractToolAgent: true, autoExtractNativeTools: false }],
|
|
91
|
+
["single-json", { autoExtractToolAgent: false }],
|
|
92
|
+
];
|
|
93
|
+
const lengths = {};
|
|
94
|
+
for (const [label, overrides] of cases) {
|
|
95
|
+
const { system, tools } = await captureSystem(overrides);
|
|
96
|
+
lengths[label] = system.length;
|
|
97
|
+
check(system.length > 0, `${label}: no system captured`);
|
|
98
|
+
check(system.includes("when_to_save"), `${label}: missing when_to_save`);
|
|
99
|
+
check(system.includes("applicable"), `${label}: missing applicable`);
|
|
100
|
+
check(system.includes("durable"), `${label}: missing durable`);
|
|
101
|
+
check(system.length <= 4500, `${label}: system too long (${system.length})`);
|
|
102
|
+
const tail = system.slice(-300);
|
|
103
|
+
check(tail.includes('"writes"'), `${label}: JSON contract not within last 300 chars`, tail);
|
|
104
|
+
check(tail.includes("Output strict JSON"), `${label}: JSON-only instruction not last`, tail);
|
|
105
|
+
// 抽取器没有写工具:system 不能教它用 Write/mkdir(出现「不要用」是否定句,允许)。
|
|
106
|
+
check(!/write to it directly with the Write tool/i.test(system), `${label}: leaked direct-write instructions`);
|
|
107
|
+
check(!/do not run mkdir/i.test(system), `${label}: leaked mkdir instruction`);
|
|
108
|
+
check(!/You have a persistent file-based memory/i.test(system), `${label}: leaked plugin memory header`);
|
|
109
|
+
// G3(v0.12):原生 `_di` 的角色句在最前,带窗口条数——缺它时模型更容易判空。
|
|
110
|
+
check(
|
|
111
|
+
system.startsWith("You are now acting as the memory extraction subagent."),
|
|
112
|
+
`${label}: role sentence must lead the system prompt`,
|
|
113
|
+
system.slice(0, 120),
|
|
114
|
+
);
|
|
115
|
+
check(system.includes("~2 messages above"), `${label}: role sentence should carry the window size`, system.slice(0, 260));
|
|
116
|
+
// 角色/探索边界:不能把原生「Read/Grep/Bash 工具」段带进来。
|
|
117
|
+
check(!/Available tools: Read, Grep, Glob/i.test(system), `${label}: leaked native tool inventory`);
|
|
118
|
+
if (label === "native-tools") check(Array.isArray(tools) && tools.length > 0, "native path should declare tools");
|
|
119
|
+
}
|
|
120
|
+
console.log("system lengths:", JSON.stringify(lengths));
|
|
121
|
+
|
|
122
|
+
// 回退路径:配置仍是 native tools,但本会话没有 memory_* schema →
|
|
123
|
+
// runMemoryToolAgent 返回 null,必须用 legacy 协议 system(含 {"tool":"list"}),
|
|
124
|
+
// 不能继续发 EXTRACT_TOOLS_NATIVE(否则模型不知道单 JSON 动作格式)。
|
|
125
|
+
{
|
|
126
|
+
const fb = await captureSystem({ autoExtractToolAgent: true, autoExtractNativeTools: true }, () => []);
|
|
127
|
+
check(fb.system.length > 0, "fallback: no system captured");
|
|
128
|
+
check(fb.system.includes('{"tool":"list"}'), "fallback must use legacy JSON-action protocol", fb.system.slice(-600));
|
|
129
|
+
check(!fb.system.includes("一轮可以并行多个调用"), "fallback must not keep native tool instructions");
|
|
130
|
+
check(fb.tools === undefined || !Array.isArray(fb.tools), "fallback should not declare tools");
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
if (fails.length) {
|
|
134
|
+
console.error("FAIL extract-system");
|
|
135
|
+
for (const f of fails) console.error(" -", f);
|
|
136
|
+
process.exit(1);
|
|
137
|
+
}
|
|
138
|
+
console.log("PASS extract-system");
|
|
@@ -0,0 +1,236 @@
|
|
|
1
|
+
// D(v0.11)长回合动态抽取窗口:
|
|
2
|
+
// - 默认窗口 48(v0.10 是 24):60 条消息时第一次抽取覆盖前 48 条,游标停在 48 条的高水位
|
|
3
|
+
// - 30 条工具结果的回合:末尾工具结论仍在 prompt 里(尾部优先裁剪)
|
|
4
|
+
// - 超预算时从尾部保留,单条工具输出 2k 截断,prompt 不爆
|
|
5
|
+
// G1(v0.12)积压续抽:
|
|
6
|
+
// - 单回合 100 条消息、之后没有新回合:同一次 idle 内续抽到末条(游标覆盖全部)
|
|
7
|
+
// - 续抽必须在同一个 runMaintenance 里完成(跨 job 接续会让 headless 在窗口之间退出)
|
|
8
|
+
// 用法: node extract-window.mjs [index.js 路径]
|
|
9
|
+
import { pathToFileURL } from "node:url";
|
|
10
|
+
import { mkdtempSync, existsSync, readFileSync, rmSync } from "node:fs";
|
|
11
|
+
import { tmpdir } from "node:os";
|
|
12
|
+
import { join } from "node:path";
|
|
13
|
+
|
|
14
|
+
const modUrl = process.argv[2] ? pathToFileURL(process.argv[2]).href : new URL("../index.js", import.meta.url).href;
|
|
15
|
+
const mod = await import(modUrl);
|
|
16
|
+
|
|
17
|
+
const fails = [];
|
|
18
|
+
const check = (cond, msg, extra) => {
|
|
19
|
+
if (!cond) fails.push(msg + (extra !== undefined ? ` :: ${JSON.stringify(extra).slice(0, 400)}` : ""));
|
|
20
|
+
};
|
|
21
|
+
|
|
22
|
+
async function runScenario({ overrides = {}, toolCount, toolText = (i) => `TOOL-${i}`, userText, userTexts, dateJumpMs }) {
|
|
23
|
+
const users = Array.isArray(userTexts) ? userTexts : userText ? [userText] : [];
|
|
24
|
+
const realNow = Date.now;
|
|
25
|
+
const root = mkdtempSync(join(tmpdir(), "zcm-winroot-"));
|
|
26
|
+
const cwd = mkdtempSync(join(tmpdir(), "zcm-wincwd-"));
|
|
27
|
+
const seen = [];
|
|
28
|
+
const reg = { handlers: new Map() };
|
|
29
|
+
const ctx = {
|
|
30
|
+
systemPrompt: { section: () => {}, context: () => {} },
|
|
31
|
+
tools: { register: () => {} },
|
|
32
|
+
commands: { register: () => {} },
|
|
33
|
+
on: (ev, fn) => {
|
|
34
|
+
if (!reg.handlers.has(ev)) reg.handlers.set(ev, []);
|
|
35
|
+
reg.handlers.get(ev).push(fn);
|
|
36
|
+
},
|
|
37
|
+
llm: {
|
|
38
|
+
stream: async function* (opts) {
|
|
39
|
+
const text = (opts.messages || []).map((m) => (m.content || []).map((b) => b.text || "").join("")).join("\n");
|
|
40
|
+
seen.push({ prompt: text, system: String(opts.system || "") });
|
|
41
|
+
// 模拟「每窗耗时超过 300s 总时限」:第一窗后把时钟拨快,触发 deadline 分支。
|
|
42
|
+
if (dateJumpMs && seen.length === 1) Date.now = () => realNow() + dateJumpMs;
|
|
43
|
+
yield { type: "text-delta", text: JSON.stringify({ writes: [] }) };
|
|
44
|
+
yield { type: "finish", reason: { kind: "stop" } };
|
|
45
|
+
},
|
|
46
|
+
},
|
|
47
|
+
};
|
|
48
|
+
const cfg = { memoriesRoot: root, enabled: true, promptStyle: "native", ...overrides };
|
|
49
|
+
mod.apply(ctx, cfg);
|
|
50
|
+
const emit = async (ev, ...args) => {
|
|
51
|
+
for (const fn of reg.handlers.get(ev) || []) await fn(...args);
|
|
52
|
+
};
|
|
53
|
+
const session = { header: { id: "sess-win", cwd, createdAt: "2026-12-05T11:00:00.000Z" } };
|
|
54
|
+
const agent = {
|
|
55
|
+
session,
|
|
56
|
+
status: "idle",
|
|
57
|
+
inbox: { nextTurn: [], nextStep: [] },
|
|
58
|
+
model: { current: () => ({ provider: "mock", model: "mock-1" }) },
|
|
59
|
+
whenIdle: () => Promise.resolve(),
|
|
60
|
+
runMaintenance: async (fn) => fn(new AbortController().signal),
|
|
61
|
+
};
|
|
62
|
+
await emit("session/event", session, { type: "turn/start", seq: 1, data: { turn: 1 } });
|
|
63
|
+
let seq = 2;
|
|
64
|
+
for (const u of users) {
|
|
65
|
+
await emit("session/event", session, {
|
|
66
|
+
type: "user/message",
|
|
67
|
+
seq: seq++,
|
|
68
|
+
data: { source: { kind: "user" }, content: [{ type: "text", text: u }] },
|
|
69
|
+
});
|
|
70
|
+
}
|
|
71
|
+
for (let i = 1; i <= toolCount; i++) {
|
|
72
|
+
await emit("session/event", session, {
|
|
73
|
+
type: "tool/result",
|
|
74
|
+
seq: seq++,
|
|
75
|
+
data: { turn: 1, message: { toolCallId: `c${i}`, content: [{ type: "text", text: toolText(i) }] } },
|
|
76
|
+
});
|
|
77
|
+
}
|
|
78
|
+
// 续抽(G1)后一次 idle 会有多次 llm 调用:等到游标覆盖到本回合末条再断言。
|
|
79
|
+
const lastSeq = seq - 1;
|
|
80
|
+
await emit("agent/turn-stopping", { agent, turn: 1 });
|
|
81
|
+
for (let i = 0; i < 600 && !seen.length; i++) await new Promise((r) => setTimeout(r, 10));
|
|
82
|
+
// 状态文件在 runMaintenance 的 promise 里写:等游标覆盖末条落盘,别只等 llm 调用。
|
|
83
|
+
for (let i = 0; i < 300; i++) {
|
|
84
|
+
const f = join(root, "_extract-state.json");
|
|
85
|
+
if (existsSync(f)) {
|
|
86
|
+
try {
|
|
87
|
+
const s = JSON.parse(readFileSync(f, "utf8"));
|
|
88
|
+
if (s?.cursorBySession?.["sess-win"]?.seq >= lastSeq) break;
|
|
89
|
+
} catch {
|
|
90
|
+
/* 写一半 */
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
await new Promise((r) => setTimeout(r, 10));
|
|
94
|
+
}
|
|
95
|
+
const stFile = join(root, "_extract-state.json");
|
|
96
|
+
const state = existsSync(stFile) ? JSON.parse(readFileSync(stFile, "utf8")) : null;
|
|
97
|
+
Date.now = realNow;
|
|
98
|
+
try {
|
|
99
|
+
rmSync(root, { recursive: true, force: true });
|
|
100
|
+
rmSync(cwd, { recursive: true, force: true });
|
|
101
|
+
} catch {
|
|
102
|
+
/* noop */
|
|
103
|
+
}
|
|
104
|
+
return {
|
|
105
|
+
prompt: seen[0]?.prompt || "",
|
|
106
|
+
system: seen[0]?.system || "",
|
|
107
|
+
prompts: seen.map((x) => x.prompt),
|
|
108
|
+
state,
|
|
109
|
+
calls: seen.length,
|
|
110
|
+
lastSeq,
|
|
111
|
+
};
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
try {
|
|
115
|
+
// 1. 60 条消息:默认窗口 48 → 第一窗覆盖 seq 2..49(RESULT-1..47),然后续抽剩余 12 条。
|
|
116
|
+
const big = await runScenario({
|
|
117
|
+
toolCount: 59,
|
|
118
|
+
toolText: (i) => `RESULT-${i}`,
|
|
119
|
+
userText: "请把这个长回合里出现的发布命令和产物目录都记到长期记忆里,后面还要用。",
|
|
120
|
+
});
|
|
121
|
+
check(big.calls >= 2, `60-message turn should continue past the first window (calls=${big.calls})`);
|
|
122
|
+
check(big.prompt.includes("RESULT-47"), "window should cover the 48th message (RESULT-47)", big.prompt.slice(0, 200));
|
|
123
|
+
check(!big.prompt.includes("RESULT-50"), "window of 48 must not cover seq 51+", big.prompt.slice(-300));
|
|
124
|
+
const cur = big.state?.cursorBySession?.["sess-win"]?.seq;
|
|
125
|
+
// G1:续抽后游标必须覆盖本回合末条,否则结尾结论永不落盘。
|
|
126
|
+
check(cur === big.lastSeq, `cursor should advance to the turn's last seq (${big.lastSeq})`, cur);
|
|
127
|
+
check(big.prompts.at(-1).includes("RESULT-59"), "continuation window must cover the tail", big.prompts.at(-1).slice(-300));
|
|
128
|
+
|
|
129
|
+
// 2. 30 条工具结果:末尾事实仍在 prompt(尾部优先)。
|
|
130
|
+
const tail = await runScenario({
|
|
131
|
+
toolCount: 30,
|
|
132
|
+
toolText: (i) => `RESULT-${i}`,
|
|
133
|
+
userText: "请记住:这个项目用 pnpm release 发布,产物在 dist。",
|
|
134
|
+
});
|
|
135
|
+
check(tail.prompt.includes("RESULT-30"), "tail tool result must survive", tail.prompt.slice(-300));
|
|
136
|
+
check(tail.prompt.includes("pnpm release"), "latest user message must survive");
|
|
137
|
+
|
|
138
|
+
// 3. 超预算:maxChars 小 + 30 条 600 字符工具输出。G1 复查后改为「前缀优先、绝不省略」:
|
|
139
|
+
// 第一窗只带得下前若干条,余下由续抽继续;所有窗口合计覆盖全部消息,游标到末条。
|
|
140
|
+
const budget = await runScenario({
|
|
141
|
+
overrides: { autoExtractMaxChars: 12000, autoExtractToolChars: 1000, autoExtractToolAgent: false },
|
|
142
|
+
toolCount: 30,
|
|
143
|
+
toolText: (i) => `${String(i).padStart(2, "0")}-` + "x".repeat(600),
|
|
144
|
+
userText: "请记住这个项目的发布命令是 pnpm release,产物在 dist 目录。",
|
|
145
|
+
});
|
|
146
|
+
check(budget.calls >= 2, `budget scenario should continue (calls=${budget.calls})`);
|
|
147
|
+
check(budget.prompt.length <= 12000 + 1000, `prompt length ${budget.prompt.length} exceeds autoExtractMaxChars + toolChars`);
|
|
148
|
+
check(budget.prompt.includes("pnpm release"), "user message survives budget trimming");
|
|
149
|
+
check(budget.prompt.includes("01-"), "prefix must start from the oldest unextracted message", budget.prompt.slice(0, 400));
|
|
150
|
+
check(/只带前|已截断/.test(budget.prompt), "truncation/deferral note present when trimmed", budget.prompt.slice(-200));
|
|
151
|
+
check(budget.prompts.at(-1).includes("30-"), "continuation must eventually cover the newest tail", budget.prompts.at(-1).slice(-400));
|
|
152
|
+
check(budget.state?.cursorBySession?.["sess-win"]?.seq === budget.lastSeq, "continuation must reach the tail", budget.state?.cursorBySession?.["sess-win"]);
|
|
153
|
+
|
|
154
|
+
// 4. 单条用户消息超过对话净预算:不得整条静默丢掉(v0.11 第一版会丢)。
|
|
155
|
+
const longUser = await runScenario({
|
|
156
|
+
overrides: { autoExtractMaxChars: 6000, autoExtractToolAgent: false },
|
|
157
|
+
toolCount: 0,
|
|
158
|
+
userText: "LONGUSER-MARK " + "甲".repeat(5000),
|
|
159
|
+
});
|
|
160
|
+
check(longUser.calls >= 1, "long-user scenario should call llm");
|
|
161
|
+
check(longUser.prompt.includes("LONGUSER-MARK"), "long user message must not be dropped", longUser.prompt.slice(-200));
|
|
162
|
+
check(/用户消息已截断/.test(longUser.prompt), "long user message should be marked truncated", longUser.prompt.slice(-200));
|
|
163
|
+
|
|
164
|
+
// 5. 多用户积压 + 预算紧张:G1 复查后按前缀续抽——每条用户消息最终都要被覆盖
|
|
165
|
+
// (不要求同一条 prompt 里;旧版「单窗口内全部用户消息」在 200 字符净预算下不可能)。
|
|
166
|
+
const users = Array.from({ length: 6 }, (_, i) => `U${i + 1}: ` + "乙".repeat(800));
|
|
167
|
+
const multi = await runScenario({
|
|
168
|
+
overrides: { autoExtractMaxChars: 3000, autoExtractToolAgent: false },
|
|
169
|
+
toolCount: 10,
|
|
170
|
+
toolText: (i) => `T${i}`,
|
|
171
|
+
userTexts: users,
|
|
172
|
+
});
|
|
173
|
+
check(multi.calls >= 2, `multi-user scenario should continue (calls=${multi.calls})`);
|
|
174
|
+
const multiJoined = multi.prompts.join("\n---\n");
|
|
175
|
+
for (let i = 1; i <= 6; i++) check(multiJoined.includes(`U${i}:`), `user message U${i} dropped`, multiJoined.slice(0, 400));
|
|
176
|
+
check(/用户消息已截断/.test(multiJoined), "long user messages should be marked truncated");
|
|
177
|
+
check(multi.state?.cursorBySession?.["sess-win"]?.seq === multi.lastSeq, "multi-user backlog must be fully covered");
|
|
178
|
+
|
|
179
|
+
// 6. G1:100 条消息单回合、无新回合 → 同一 idle 内续抽,游标覆盖末条,无中间缺口。
|
|
180
|
+
const huge = await runScenario({
|
|
181
|
+
toolCount: 99,
|
|
182
|
+
toolText: (i) => `RESULT-${i}`,
|
|
183
|
+
userText: "这个回合很长:请把发布命令、产物目录和验证过的环境坑都记到长期记忆。",
|
|
184
|
+
});
|
|
185
|
+
check(huge.calls >= 3, `100-message turn should need >=3 windows (calls=${huge.calls})`);
|
|
186
|
+
check(huge.calls <= 6, `continuation must be bounded (calls=${huge.calls})`);
|
|
187
|
+
check(huge.state?.cursorBySession?.["sess-win"]?.seq === huge.lastSeq, "cursor must reach turn tail", huge.state?.cursorBySession?.["sess-win"]);
|
|
188
|
+
const joined = huge.prompts.join("\n---\n");
|
|
189
|
+
const missing = [];
|
|
190
|
+
for (let i = 1; i <= 99; i++) if (!joined.includes(`RESULT-${i}`)) missing.push(i);
|
|
191
|
+
check(missing.length === 0, `continuation must not leave gaps (missing ${JSON.stringify(missing.slice(0, 10))})`);
|
|
192
|
+
check(huge.prompts.at(-1).includes("RESULT-99"), "last window must contain the newest message", huge.prompts.at(-1).slice(-300));
|
|
193
|
+
|
|
194
|
+
// 7. 触到 300s 总时限:剩余区间记为 backlog(游标停在已覆盖处,不伪造「已抽」)。
|
|
195
|
+
const stalled = await runScenario({
|
|
196
|
+
overrides: { autoExtractMaxMessages: 10, autoExtractToolAgent: false },
|
|
197
|
+
toolCount: 29,
|
|
198
|
+
toolText: (i) => `RESULT-${i}`,
|
|
199
|
+
userText: "这次要记住很多东西:把发布命令和产物目录都记下来。",
|
|
200
|
+
dateJumpMs: 400000,
|
|
201
|
+
});
|
|
202
|
+
check(stalled.calls === 1, `deadline should stop after the first window (calls=${stalled.calls})`);
|
|
203
|
+
check(stalled.state?.lastOutcome === "backlog", "deadline must be recorded as backlog", stalled.state?.lastOutcome);
|
|
204
|
+
check(stalled.state?.lastLimit === "deadline", "deadline must be recorded in lastLimit", stalled.state?.lastLimit);
|
|
205
|
+
check(!stalled.state?.lastSkipReason, "backlog must not borrow lastSkipReason", stalled.state?.lastSkipReason);
|
|
206
|
+
check(stalled.state?.backlogCount === 20, `backlog count should be 20 (got ${stalled.state?.backlogCount})`);
|
|
207
|
+
check(
|
|
208
|
+
stalled.state?.cursorBySession?.["sess-win"]?.seq === 11,
|
|
209
|
+
"cursor must stop at the last covered message (10 messages)",
|
|
210
|
+
stalled.state?.cursorBySession?.["sess-win"],
|
|
211
|
+
);
|
|
212
|
+
|
|
213
|
+
// 8. 500 条单回合:缓冲不再按 3× 窗口裁剪(坏消息是没有抽就丢 356 条),
|
|
214
|
+
// 续抽在 12 窗内覆盖全部消息且没有 dropped。
|
|
215
|
+
const monster = await runScenario({
|
|
216
|
+
toolCount: 499,
|
|
217
|
+
toolText: (i) => `RESULT-${i}`,
|
|
218
|
+
userText: "超长工具回合:把所有验证过的结论都记下来。",
|
|
219
|
+
});
|
|
220
|
+
check(monster.calls >= 10 && monster.calls <= 12, `long turn should use 10-12 windows (calls=${monster.calls})`);
|
|
221
|
+
check(monster.state?.cursorBySession?.["sess-win"]?.seq === monster.lastSeq, "500-message turn cursor must reach tail");
|
|
222
|
+
check(
|
|
223
|
+
(monster.state?.droppedUnextracted || 0) === 0,
|
|
224
|
+
"buffer cap must not drop unextracted current-turn messages",
|
|
225
|
+
monster.state?.droppedUnextracted,
|
|
226
|
+
);
|
|
227
|
+
} finally {
|
|
228
|
+
/* 清理在各 scenario 内完成 */
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
if (fails.length) {
|
|
232
|
+
console.error("FAIL extract-window");
|
|
233
|
+
for (const f of fails) console.error(" -", f);
|
|
234
|
+
process.exit(1);
|
|
235
|
+
}
|
|
236
|
+
console.log("PASS extract-window");
|
|
@@ -0,0 +1,126 @@
|
|
|
1
|
+
// 后台抽取回归:mock 事件流 + mock llm,验证 5 轮工具代理 → 落盘 → 游标持久化
|
|
2
|
+
// 用法: node extract.mjs [index.js 路径]
|
|
3
|
+
import { pathToFileURL } from "node:url";
|
|
4
|
+
import {
|
|
5
|
+
mkdtempSync, mkdirSync, readFileSync, readdirSync, existsSync, rmSync, statSync,
|
|
6
|
+
} from "node:fs";
|
|
7
|
+
import { tmpdir } from "node:os";
|
|
8
|
+
import { join } from "node:path";
|
|
9
|
+
|
|
10
|
+
const modUrl = process.argv[2] ? pathToFileURL(process.argv[2]).href : new URL("../index.js", import.meta.url).href;
|
|
11
|
+
const mod = await import(modUrl);
|
|
12
|
+
|
|
13
|
+
const root = mkdtempSync(join(tmpdir(), "zcm-ex-"));
|
|
14
|
+
const cwd = mkdtempSync(join(tmpdir(), "zcm-excwd-"));
|
|
15
|
+
const state = { llmCalls: 0, lastPrompt: "" };
|
|
16
|
+
|
|
17
|
+
const reg = { sections: [], tools: [], commands: [], handlers: new Map() };
|
|
18
|
+
const ctx = {
|
|
19
|
+
systemPrompt: { section: (o) => reg.sections.push(o) },
|
|
20
|
+
tools: { register: (d) => reg.tools.push(d) },
|
|
21
|
+
commands: { register: (c) => reg.commands.push(c) },
|
|
22
|
+
on: (ev, fn) => { if (!reg.handlers.has(ev)) reg.handlers.set(ev, []); reg.handlers.get(ev).push(fn); },
|
|
23
|
+
llm: {
|
|
24
|
+
stream: async function* (opts) {
|
|
25
|
+
state.llmCalls++;
|
|
26
|
+
state.lastPrompt = JSON.stringify(opts.messages || "").slice(0, 4000);
|
|
27
|
+
yield {
|
|
28
|
+
type: "text-delta",
|
|
29
|
+
text: JSON.stringify({
|
|
30
|
+
writes: [
|
|
31
|
+
{ op: "create", title: "抽取回归条目", description: "自动抽取写入的条目", type: "project", body: "这是后台抽取写入的正文。" },
|
|
32
|
+
],
|
|
33
|
+
}),
|
|
34
|
+
};
|
|
35
|
+
yield { type: "finish", reason: { kind: "stop" } };
|
|
36
|
+
},
|
|
37
|
+
},
|
|
38
|
+
};
|
|
39
|
+
const cfg = { memoriesRoot: root, enabled: true, promptStyle: "native" };
|
|
40
|
+
mod.apply(ctx, cfg);
|
|
41
|
+
|
|
42
|
+
const emit = (ev, ...args) => { for (const fn of reg.handlers.get(ev) || []) fn(...args); };
|
|
43
|
+
const fails = [];
|
|
44
|
+
const check = (cond, msg, extra) => { if (!cond) fails.push(msg + (extra ? ` :: ${String(extra).slice(0, 300)}` : "")); };
|
|
45
|
+
|
|
46
|
+
const session = { header: { id: "sess-ex", cwd, createdAt: "2026-12-05T10:00:00.000Z" } };
|
|
47
|
+
let maintenanceRan = false;
|
|
48
|
+
const agent = {
|
|
49
|
+
session, status: "idle", inbox: { nextTurn: [], nextStep: [] },
|
|
50
|
+
model: { current: () => ({ provider: "mock", model: "mock-1" }) },
|
|
51
|
+
whenIdle: () => Promise.resolve(),
|
|
52
|
+
runMaintenance: async (fn) => { maintenanceRan = true; return fn(new AbortController().signal); },
|
|
53
|
+
};
|
|
54
|
+
|
|
55
|
+
emit("session/event", session, { type: "turn/start", seq: 1, data: { turn: 1 } });
|
|
56
|
+
emit("session/event", session, {
|
|
57
|
+
type: "user/message", seq: 2,
|
|
58
|
+
data: { source: { kind: "user" }, content: [{ type: "text", text: "请帮我把这个项目的构建命令和路径整理成长期记忆,后面还要用。" }] },
|
|
59
|
+
});
|
|
60
|
+
emit("session/event", session, {
|
|
61
|
+
type: "assistant/message", seq: 3,
|
|
62
|
+
data: { turn: 1, message: { content: [{ type: "text", text: "构建命令是 pnpm build,产物在 dist。" }] } },
|
|
63
|
+
});
|
|
64
|
+
emit("agent/turn-stopping", { agent, turn: 1 });
|
|
65
|
+
|
|
66
|
+
// 等待异步抽取完成(最多 5s)
|
|
67
|
+
for (let i = 0; i < 100 && !maintenanceRan; i++) await new Promise((r) => setTimeout(r, 50));
|
|
68
|
+
for (let i = 0; i < 100; i++) {
|
|
69
|
+
const p = join(root, "projects");
|
|
70
|
+
if (existsSync(p)) {
|
|
71
|
+
const s = readdirSync(p);
|
|
72
|
+
if (s.length) {
|
|
73
|
+
const memDirs = readdirSync(join(p, s[0], "memory"), { withFileTypes: true }).filter((d) => d.isFile() && d.name.endsWith(".md") && d.name !== "MEMORY.md");
|
|
74
|
+
if (memDirs.length) break;
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
await new Promise((r) => setTimeout(r, 50));
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
check(maintenanceRan, "runMaintenance not called");
|
|
81
|
+
check(state.llmCalls >= 1, "llm not called");
|
|
82
|
+
|
|
83
|
+
const projRoot = join(root, "projects");
|
|
84
|
+
const slugs = existsSync(projRoot) ? readdirSync(projRoot) : [];
|
|
85
|
+
check(slugs.length === 1, "project dir", slugs);
|
|
86
|
+
const memDir = join(projRoot, slugs[0] || "x", "memory");
|
|
87
|
+
const files = existsSync(memDir)
|
|
88
|
+
? readdirSync(memDir, { withFileTypes: true }).filter((d) => d.isFile() && d.name.endsWith(".md") && d.name !== "MEMORY.md").map((d) => d.name)
|
|
89
|
+
: [];
|
|
90
|
+
check(files.length === 1, "extracted memory file", files);
|
|
91
|
+
if (files.length) {
|
|
92
|
+
const t = readFileSync(join(memDir, files[0]), "utf8");
|
|
93
|
+
check(t.includes("后台抽取写入的正文"), "extracted body", t);
|
|
94
|
+
check(/node_type:\s*memory/.test(t), "extracted frontmatter node_type", t);
|
|
95
|
+
check(/originSessionId:\s*"?sess-ex"?/.test(t), "extracted originSessionId", t);
|
|
96
|
+
const idx = readFileSync(join(memDir, "MEMORY.md"), "utf8");
|
|
97
|
+
check(idx.includes("抽取回归条目"), "index synced", idx);
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
// 游标持久化
|
|
101
|
+
const stFile = join(root, "_extract-state.json");
|
|
102
|
+
check(existsSync(stFile), "extract state file");
|
|
103
|
+
if (existsSync(stFile)) {
|
|
104
|
+
const st = JSON.parse(readFileSync(stFile, "utf8"));
|
|
105
|
+
check(st.lastOutcome && st.lastOutcome !== "", "lastOutcome", st);
|
|
106
|
+
const cur = st.cursorBySession?.["sess-ex"];
|
|
107
|
+
check(cur && cur.seq === 3, "cursor seq persisted = 3", JSON.stringify(st.cursorBySession));
|
|
108
|
+
check(cur && cur.createdAt === Date.parse("2026-12-05T10:00:00.000Z"), "cursor createdAt", JSON.stringify(cur));
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
// 第二轮:短文本应跳过且不调 llm
|
|
112
|
+
const before = state.llmCalls;
|
|
113
|
+
emit("session/event", session, { type: "turn/start", seq: 4, data: { turn: 2 } });
|
|
114
|
+
emit("session/event", session, { type: "user/message", seq: 5, data: { source: { kind: "user" }, content: [{ type: "text", text: "嗯" }] } });
|
|
115
|
+
emit("agent/turn-stopping", { agent, turn: 2 });
|
|
116
|
+
await new Promise((r) => setTimeout(r, 300));
|
|
117
|
+
check(state.llmCalls === before, "short prose should skip extraction", { before, after: state.llmCalls });
|
|
118
|
+
if (existsSync(stFile)) {
|
|
119
|
+
const st = JSON.parse(readFileSync(stFile, "utf8"));
|
|
120
|
+
check(st.lastSkipReason === "short-prose", "skip reason recorded", st.lastSkipReason);
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
console.log(fails.length ? `FAIL ${fails.length}:\n - ` + fails.join("\n - ") : "ALL PASS");
|
|
124
|
+
if (fails.length) console.error("root=" + root);
|
|
125
|
+
else { try { rmSync(root, { recursive: true, force: true }); rmSync(cwd, { recursive: true, force: true }); } catch {} }
|
|
126
|
+
process.exit(fails.length ? 1 : 0);
|