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
package/package.json
CHANGED
|
@@ -1,6 +1,51 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "dsh-zcode-memory",
|
|
3
|
-
"version": "
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "1.1.2",
|
|
4
|
+
"description": "在 DeepSeek Harness 中读写 ZCode/WorkBuddy 的文件式长期记忆:MEMORY.md 索引常驻 + memory_recall 按需召回 + 回合结束后台自动抽取 + save/update/delete 原地写回 + 设置页展示与总开关。",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"main": "index.js",
|
|
7
|
+
"exports": {
|
|
8
|
+
".": "./index.js",
|
|
9
|
+
"./client": "./client.js",
|
|
10
|
+
"./cordis.patch.yml": "./cordis.patch.yml",
|
|
11
|
+
"./package.json": "./package.json"
|
|
12
|
+
},
|
|
13
|
+
"files": [
|
|
14
|
+
"index.js",
|
|
15
|
+
"client.js",
|
|
16
|
+
"cordis.patch.yml",
|
|
17
|
+
"README.md",
|
|
18
|
+
"tests"
|
|
19
|
+
],
|
|
20
|
+
"license": "MIT",
|
|
21
|
+
"repository": {
|
|
22
|
+
"type": "git",
|
|
23
|
+
"url": "git+https://github.com/sssdex/dsh-zcode-memory.git"
|
|
24
|
+
},
|
|
25
|
+
"keywords": [
|
|
26
|
+
"dsh-plugin",
|
|
27
|
+
"deepseek-harness",
|
|
28
|
+
"dsh",
|
|
29
|
+
"memory",
|
|
30
|
+
"zcode",
|
|
31
|
+
"workbuddy"
|
|
32
|
+
],
|
|
33
|
+
"dsh": {
|
|
34
|
+
"bundle": {
|
|
35
|
+
"patch": "./cordis.patch.yml"
|
|
36
|
+
},
|
|
37
|
+
"client": {
|
|
38
|
+
"platform": "web",
|
|
39
|
+
"inject": [
|
|
40
|
+
"@deepseek-ai/dsh-client-locale",
|
|
41
|
+
"@deepseek-ai/dsh-client-ui-slots"
|
|
42
|
+
]
|
|
43
|
+
}
|
|
44
|
+
},
|
|
45
|
+
"engines": {
|
|
46
|
+
"dsh": ">=0.2.2-rc.3"
|
|
47
|
+
},
|
|
48
|
+
"scripts": {
|
|
49
|
+
"test": "node tests/smoke.mjs && node tests/func.mjs && node tests/extract.mjs && node tests/extract-retry.mjs && node tests/abort-loop.mjs && node tests/append-race.mjs && node tests/native-tools.mjs && node tests/native-tools-edge.mjs && node tests/save-append-edges.mjs && node tests/context-memo.mjs && node tests/sandbox-grants.mjs && node tests/memory-notes.mjs && node tests/prompt-split.mjs && node tests/resume-recovery.mjs && node tests/index-comments.mjs && node tests/ancestor-lookup.mjs && node tests/extract-system.mjs && node tests/sensitive-path.mjs && node tests/extract-window.mjs && node tests/backlog-state.mjs && node tests/index-truncate.mjs && node tests/index-budget.mjs && node tests/extract-cost.mjs && node tests/recall-score.mjs && node tests/settings-api.mjs && node tests/settings-disable.mjs && node tests/client-bundle.mjs"
|
|
50
|
+
}
|
|
51
|
+
}
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
// abort 不死循环:父 signal 永久 aborted 时,最多重试 2 次后停;事件循环必须还活着。
|
|
2
|
+
// 用法: node abort-loop.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-abt-"));
|
|
12
|
+
const cwd = mkdtempSync(join(tmpdir(), "zcm-abtc-"));
|
|
13
|
+
const state = { llmCalls: 0, maintenance: 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.llmCalls++;
|
|
24
|
+
yield { type: "text-delta", text: '{"writes":[]}' };
|
|
25
|
+
yield { type: "finish", reason: { kind: "stop" } };
|
|
26
|
+
},
|
|
27
|
+
},
|
|
28
|
+
};
|
|
29
|
+
mod.apply(ctx, { memoriesRoot: root, enabled: true, promptStyle: "native" });
|
|
30
|
+
|
|
31
|
+
const emit = (ev, ...args) => { for (const fn of reg.handlers.get(ev) || []) fn(...args); };
|
|
32
|
+
const fails = [];
|
|
33
|
+
const check = (c, m, e) => { if (!c) fails.push(m + (e !== undefined ? ` :: ${String(e).slice(0, 200)}` : "")); };
|
|
34
|
+
|
|
35
|
+
const session = { header: { id: "sess-abt", cwd, createdAt: "2026-12-05T12:00:00.000Z" } };
|
|
36
|
+
const agent = {
|
|
37
|
+
session, status: "idle", inbox: { nextTurn: [], nextStep: [] },
|
|
38
|
+
model: { current: () => ({ provider: "mock", model: "mock-1" }) },
|
|
39
|
+
whenIdle: () => Promise.resolve(),
|
|
40
|
+
// 关键:maintenance 的 signal 一进来就是 aborted(模拟父 signal 永久 aborted)
|
|
41
|
+
runMaintenance: async (fn) => {
|
|
42
|
+
state.maintenance++;
|
|
43
|
+
const ac = new AbortController();
|
|
44
|
+
ac.abort();
|
|
45
|
+
return fn(ac.signal);
|
|
46
|
+
},
|
|
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("agent/turn-stopping", { agent, turn: 1 });
|
|
55
|
+
|
|
56
|
+
// 存活断言:300ms 后事件循环仍能执行(若紧循环,这里永远不 resolve)
|
|
57
|
+
let alive = false;
|
|
58
|
+
await Promise.race([
|
|
59
|
+
new Promise((r) => setTimeout(() => { alive = true; r(); }, 300)),
|
|
60
|
+
new Promise((r) => setTimeout(r, 5000)),
|
|
61
|
+
]);
|
|
62
|
+
|
|
63
|
+
check(alive, "event loop starved (abort retry tight loop)");
|
|
64
|
+
check(state.maintenance <= 3, "abort retried too many times", state.maintenance);
|
|
65
|
+
check(state.llmCalls <= 3, "llm called too many times under permanent abort", state.llmCalls);
|
|
66
|
+
|
|
67
|
+
console.log(fails.length ? `FAIL ${fails.length}:\n - ` + fails.join("\n - ") : "ALL PASS", `(maintenance=${state.maintenance}, llm=${state.llmCalls})`);
|
|
68
|
+
if (fails.length) console.error("root=" + root);
|
|
69
|
+
else { try { rmSync(root, { recursive: true, force: true }); rmSync(cwd, { recursive: true, force: true }); } catch {} }
|
|
70
|
+
process.exit(fails.length ? 1 : 0);
|
|
@@ -0,0 +1,169 @@
|
|
|
1
|
+
// G7(v0.12):项目记忆默认按 workspaceRoot 精确哈希(对齐原生 Oqe)。
|
|
2
|
+
// - 子目录会话默认不读、也不写祖先目录的记忆
|
|
3
|
+
// - ancestorLookup:true 时才向上回溯,且注入文本标注「来自祖先工作区」
|
|
4
|
+
// - fallbackCwd 始终精确哈希,并标注「fallback 工作区」
|
|
5
|
+
// 用法: node ancestor-lookup.mjs [index.js 路径]
|
|
6
|
+
import { pathToFileURL } from "node:url";
|
|
7
|
+
import { mkdtempSync, mkdirSync, readFileSync, existsSync, rmSync } from "node:fs";
|
|
8
|
+
import { tmpdir } from "node:os";
|
|
9
|
+
import { join, dirname } from "node:path";
|
|
10
|
+
|
|
11
|
+
const modUrl = process.argv[2] ? pathToFileURL(process.argv[2]).href : new URL("../index.js", import.meta.url).href;
|
|
12
|
+
const mod = await import(modUrl);
|
|
13
|
+
|
|
14
|
+
const fails = [];
|
|
15
|
+
const check = (cond, msg, extra) => {
|
|
16
|
+
if (!cond) fails.push(msg + (extra !== undefined ? ` :: ${JSON.stringify(extra).slice(0, 400)}` : ""));
|
|
17
|
+
};
|
|
18
|
+
const cleanups = [];
|
|
19
|
+
const mkTmp = (p) => {
|
|
20
|
+
const d = mkdtempSync(join(tmpdir(), p));
|
|
21
|
+
cleanups.push(d);
|
|
22
|
+
return d;
|
|
23
|
+
};
|
|
24
|
+
|
|
25
|
+
// 每个场景独立 root/parent/sub:上一个场景在子目录写下的记忆不能影响下一个。
|
|
26
|
+
function newWorkspace() {
|
|
27
|
+
const root = mkTmp("zcm-anc-");
|
|
28
|
+
const parent = mkTmp("zcm-ancparent-");
|
|
29
|
+
const sub = join(parent, "pkg", "sub");
|
|
30
|
+
mkdirSync(sub, { recursive: true });
|
|
31
|
+
return { root, parent, sub };
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
function makeCtx() {
|
|
35
|
+
const reg = { sections: [], contexts: [], tools: [], commands: [], handlers: new Map() };
|
|
36
|
+
const ctx = {
|
|
37
|
+
systemPrompt: { section: (o) => reg.sections.push(o), context: (o) => reg.contexts.push(o) },
|
|
38
|
+
tools: { register: (d) => reg.tools.push(d), schemas: () => [{ name: "write" }] },
|
|
39
|
+
commands: { register: () => {} },
|
|
40
|
+
on: (ev, fn) => {
|
|
41
|
+
if (!reg.handlers.has(ev)) reg.handlers.set(ev, []);
|
|
42
|
+
reg.handlers.get(ev).push(fn);
|
|
43
|
+
},
|
|
44
|
+
llm: { stream: async function* () {} },
|
|
45
|
+
};
|
|
46
|
+
return { reg, ctx };
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
function sessionFor(id, cwd) {
|
|
50
|
+
return { header: { id, cwd, createdAt: "2026-12-05T10:00:00.000Z" } };
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
function indexText(reg, session) {
|
|
54
|
+
const idx = reg.contexts.find((c) => c.name === "zcode-memory");
|
|
55
|
+
return String(idx?.text({ agent: { session } }) || "");
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
async function seedParent(reg, ws, id = "sess-parent", title = "AncestorFact") {
|
|
59
|
+
const save = reg.tools.find((t) => t.name === "memory_save");
|
|
60
|
+
const session = sessionFor(id, ws.parent);
|
|
61
|
+
const r = await save.execute(
|
|
62
|
+
{ title, description: "ancestor hook", body: "ancestor body", scope: "project" },
|
|
63
|
+
{ agent: { session } },
|
|
64
|
+
);
|
|
65
|
+
if (!r?.ok) {
|
|
66
|
+
console.error("FAIL ancestor-lookup: seed save failed", r);
|
|
67
|
+
process.exit(1);
|
|
68
|
+
}
|
|
69
|
+
return { parentDir: dirname(r.file), session };
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
// 1. 默认精确哈希:子目录不读祖先目录;写入也不能落进祖先目录。
|
|
73
|
+
{
|
|
74
|
+
const ws = newWorkspace();
|
|
75
|
+
const { reg, ctx } = makeCtx();
|
|
76
|
+
mod.apply(ctx, { memoriesRoot: ws.root, enabled: true, promptStyle: "native" });
|
|
77
|
+
const { parentDir } = await seedParent(reg, ws);
|
|
78
|
+
const text = indexText(reg, sessionFor("sess-sub", ws.sub));
|
|
79
|
+
check(text === "", "subdirectory session must not inherit ancestor memory by default", text.slice(0, 300));
|
|
80
|
+
|
|
81
|
+
const save = reg.tools.find((t) => t.name === "memory_save");
|
|
82
|
+
const before = readFileSync(join(parentDir, "MEMORY.md"), "utf8");
|
|
83
|
+
const r = await save.execute(
|
|
84
|
+
{ title: "SubFact", description: "sub hook", body: "sub body", scope: "project" },
|
|
85
|
+
{ agent: { session: sessionFor("sess-sub", ws.sub) } },
|
|
86
|
+
);
|
|
87
|
+
check(r?.ok, "sub save ok", r);
|
|
88
|
+
check(dirname(r.file) !== parentDir, "subdirectory save must create its own project dir", dirname(r.file));
|
|
89
|
+
check(readFileSync(join(parentDir, "MEMORY.md"), "utf8") === before, "ancestor index must stay untouched");
|
|
90
|
+
check(existsSync(join(dirname(r.file), "MEMORY.md")), "sub project index created");
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
// 2. ancestorLookup:true:回溯并把来源标出来。
|
|
94
|
+
{
|
|
95
|
+
const ws = newWorkspace();
|
|
96
|
+
const { reg, ctx } = makeCtx();
|
|
97
|
+
mod.apply(ctx, { memoriesRoot: ws.root, enabled: true, promptStyle: "native", ancestorLookup: true });
|
|
98
|
+
await seedParent(reg, ws, "sess-parent-lookup");
|
|
99
|
+
const text = indexText(reg, sessionFor("sess-sub-lookup", ws.sub));
|
|
100
|
+
check(text.includes("AncestorFact"), "ancestorLookup:true must reuse the ancestor index", text.slice(0, 300));
|
|
101
|
+
check(/ancestor workspace/i.test(text), "ancestor index must be labeled", text.slice(0, 300));
|
|
102
|
+
|
|
103
|
+
// plugin 风格:目录行已移入索引段(system 规则段必须与目录存在性无关)。
|
|
104
|
+
const { reg: regP, ctx: ctxP } = makeCtx();
|
|
105
|
+
mod.apply(ctxP, { memoriesRoot: ws.root, enabled: true, promptStyle: "plugin", ancestorLookup: true });
|
|
106
|
+
const sessionP = sessionFor("sess-sub-plugin", ws.sub);
|
|
107
|
+
const rulesP = String(regP.sections.find((s) => s.name === "zcode-memory-rules")?.text({ agent: { session: sessionP } }));
|
|
108
|
+
const indexP = indexText(regP, sessionP);
|
|
109
|
+
check(!/来自祖先工作区/.test(rulesP), "plugin rules must not depend on which project dir was found", rulesP.slice(0, 400));
|
|
110
|
+
check(/来自祖先工作区/.test(indexP), "plugin index must label the ancestor workspace", indexP.slice(0, 400));
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
// 3. fallbackCwd:精确哈希 + 标注 fallback 工作区;fallback 指向子目录时不回溯。
|
|
114
|
+
{
|
|
115
|
+
const ws = newWorkspace();
|
|
116
|
+
const { reg, ctx } = makeCtx();
|
|
117
|
+
mod.apply(ctx, { memoriesRoot: ws.root, enabled: true, promptStyle: "native", fallbackCwd: ws.parent });
|
|
118
|
+
await seedParent(reg, ws, "sess-parent-fb");
|
|
119
|
+
const text = indexText(reg, sessionFor("sess-fb", ws.sub));
|
|
120
|
+
check(text.includes("AncestorFact"), "fallbackCwd must still be readable", text.slice(0, 300));
|
|
121
|
+
check(/fallback workspace/i.test(text), "fallback index must be labeled", text.slice(0, 300));
|
|
122
|
+
|
|
123
|
+
const ws2 = newWorkspace();
|
|
124
|
+
const { reg: reg2, ctx: ctx2 } = makeCtx();
|
|
125
|
+
mod.apply(ctx2, { memoriesRoot: ws2.root, enabled: true, promptStyle: "native", fallbackCwd: ws2.sub });
|
|
126
|
+
await seedParent(reg2, ws2, "sess-parent-fb2");
|
|
127
|
+
const t2 = indexText(reg2, sessionFor("sess-fb2", ws2.sub));
|
|
128
|
+
check(t2 === "", "fallbackCwd must be exact: no ancestor walk-up", t2.slice(0, 300));
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
// 4. P2-2:fallback 是只读次级 project scope。子会话保存了自己的项目记忆后,
|
|
132
|
+
// fallback 工作区的记忆不能被「精确目录」整段遮住(数据没丢,但注入/read/recall 都看不见)。
|
|
133
|
+
{
|
|
134
|
+
const ws = newWorkspace();
|
|
135
|
+
const { reg, ctx } = makeCtx();
|
|
136
|
+
mod.apply(ctx, { memoriesRoot: ws.root, enabled: true, promptStyle: "native", fallbackCwd: ws.parent });
|
|
137
|
+
const { parentDir } = await seedParent(reg, ws, "sess-parent-fb3");
|
|
138
|
+
const subSession = sessionFor("sess-fb3", ws.sub);
|
|
139
|
+
const save = reg.tools.find((t) => t.name === "memory_save");
|
|
140
|
+
const r = await save.execute(
|
|
141
|
+
{ title: "SubFact", description: "sub hook", body: "sub body", scope: "project" },
|
|
142
|
+
{ agent: { session: subSession } },
|
|
143
|
+
);
|
|
144
|
+
check(r?.ok, "fallback case: sub save ok", r);
|
|
145
|
+
check(dirname(r.file) !== parentDir, "fallback case: sub save must not write into the fallback dir", dirname(r.file));
|
|
146
|
+
const text = indexText(reg, subSession);
|
|
147
|
+
check(text.includes("SubFact"), "fallback case: sub index must be injected", text.slice(0, 500));
|
|
148
|
+
check(
|
|
149
|
+
text.includes("AncestorFact"),
|
|
150
|
+
"fallback memory must stay visible after the sub session creates its own project dir",
|
|
151
|
+
text.slice(0, 500),
|
|
152
|
+
);
|
|
153
|
+
check(/fallback workspace/i.test(text), "fallback block must stay labeled", text.slice(0, 500));
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
for (const d of cleanups) {
|
|
157
|
+
try {
|
|
158
|
+
rmSync(d, { recursive: true, force: true });
|
|
159
|
+
} catch {
|
|
160
|
+
/* noop */
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
if (fails.length) {
|
|
165
|
+
console.error("FAIL ancestor-lookup");
|
|
166
|
+
for (const f of fails) console.error(" -", f);
|
|
167
|
+
process.exit(1);
|
|
168
|
+
}
|
|
169
|
+
console.log("PASS ancestor-lookup");
|
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
// N1 验收:memory_save 的新索引行走 O_APPEND 纯追加,外部进程同时追加的行不会被覆盖。
|
|
2
|
+
// 两个进程:子进程每 2ms 往 MEMORY.md 追加一行编号;父进程循环 memory_save 200 次。
|
|
3
|
+
// 判定:外部行编号必须连续(1..N 无缺口)、每条记忆索引行恰好一次。
|
|
4
|
+
// 用法: node append-race.mjs [index.js 路径]
|
|
5
|
+
import { pathToFileURL } from "node:url";
|
|
6
|
+
import { mkdtempSync, readFileSync, rmSync } from "node:fs";
|
|
7
|
+
import { tmpdir } from "node:os";
|
|
8
|
+
import { join, dirname } from "node:path";
|
|
9
|
+
import { spawn } from "node:child_process";
|
|
10
|
+
|
|
11
|
+
const modUrl = process.argv[2] ? pathToFileURL(process.argv[2]).href : new URL("../index.js", import.meta.url).href;
|
|
12
|
+
const mod = await import(modUrl);
|
|
13
|
+
|
|
14
|
+
const 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
|
+
|
|
23
|
+
const root = mkdtempSync(join(tmpdir(), "zcm-race-"));
|
|
24
|
+
const cfg = { memoriesRoot: root, enabled: true };
|
|
25
|
+
mod.apply(ctx, cfg);
|
|
26
|
+
const save = reg.tools.find((t) => t.name === "memory_save");
|
|
27
|
+
const exec = { agent: { session: { id: "sess-race", header: { cwd: process.cwd(), createdAt: new Date().toISOString() } } } };
|
|
28
|
+
|
|
29
|
+
const first = await save.execute({ title: "race seed", description: "seed", body: "seed body", scope: "project" }, exec);
|
|
30
|
+
if (!first.ok) {
|
|
31
|
+
console.log("FAIL seed save:", JSON.stringify(first));
|
|
32
|
+
process.exit(1);
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
const dir = join(root, "projects");
|
|
36
|
+
const projectDir = dirname(first.file);
|
|
37
|
+
const mem = join(projectDir, "MEMORY.md");
|
|
38
|
+
|
|
39
|
+
// 子进程:持续追加外部行(模拟 ZCode 直写 MEMORY.md)。
|
|
40
|
+
const childCode = `
|
|
41
|
+
const fs = require("node:fs");
|
|
42
|
+
const p = process.argv[1];
|
|
43
|
+
let i = 0;
|
|
44
|
+
const t = setInterval(() => { i += 1; try { fs.appendFileSync(p, "- EXTERNAL " + i + "\\n"); } catch {} }, 2);
|
|
45
|
+
setTimeout(() => { clearInterval(t); process.stdout.write(String(i)); process.exit(0); }, 4000);
|
|
46
|
+
`;
|
|
47
|
+
const child = spawn(process.execPath, ["-e", childCode, mem], { stdio: ["ignore", "pipe", "inherit"] });
|
|
48
|
+
let externalCount = 0;
|
|
49
|
+
const done = new Promise((resolve) => {
|
|
50
|
+
child.stdout.on("data", (b) => (externalCount = Number(String(b).trim()) || externalCount));
|
|
51
|
+
child.on("exit", resolve);
|
|
52
|
+
});
|
|
53
|
+
|
|
54
|
+
const N = 200;
|
|
55
|
+
let failed = 0;
|
|
56
|
+
for (let i = 1; i <= N; i++) {
|
|
57
|
+
const r = await save.execute(
|
|
58
|
+
{ title: `race ${i}`, description: `race item ${i}`, body: `body ${i}`, scope: "project" },
|
|
59
|
+
exec,
|
|
60
|
+
);
|
|
61
|
+
if (!r.ok) {
|
|
62
|
+
failed += 1;
|
|
63
|
+
if (failed <= 3) console.log("save failed:", r.message);
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
await done;
|
|
67
|
+
|
|
68
|
+
const text = readFileSync(mem, "utf8");
|
|
69
|
+
const external = [...text.matchAll(/^- EXTERNAL (\d+)$/gm)].map((m) => Number(m[1]));
|
|
70
|
+
const gaps = [];
|
|
71
|
+
for (let i = 1; i <= externalCount; i++) if (!external.includes(i)) gaps.push(i);
|
|
72
|
+
const memLines = new Map();
|
|
73
|
+
for (const m of text.matchAll(/^- \[race (\d+)\]/gm)) memLines.set(Number(m[1]), (memLines.get(Number(m[1])) || 0) + 1);
|
|
74
|
+
const dupes = [...memLines].filter(([, n]) => n > 1).map(([k]) => k);
|
|
75
|
+
const missing = [];
|
|
76
|
+
for (let i = 1; i <= N; i++) if (!memLines.has(i)) missing.push(i);
|
|
77
|
+
|
|
78
|
+
const fails = [];
|
|
79
|
+
if (externalCount < 10) fails.push(`external writer only wrote ${externalCount} lines (test ineffective)`);
|
|
80
|
+
if (gaps.length) fails.push(`external lines lost: ${gaps.slice(0, 10).join(",")}${gaps.length > 10 ? "…" : ""}`);
|
|
81
|
+
if (failed) fails.push(`memory_save failures: ${failed}/${N}`);
|
|
82
|
+
if (missing.length) fails.push(`missing index lines: ${missing.slice(0, 10).join(",")}${missing.length > 10 ? "…" : ""}`);
|
|
83
|
+
if (dupes.length) fails.push(`duplicate index lines: ${dupes.slice(0, 10).join(",")}`);
|
|
84
|
+
|
|
85
|
+
console.log(`external=${externalCount} kept=${external.length} saves=${N - failed}/${N}`);
|
|
86
|
+
console.log(fails.length ? `FAIL ${fails.length}:\n - ` + fails.join("\n - ") : "ALL PASS");
|
|
87
|
+
try {
|
|
88
|
+
rmSync(root, { recursive: true, force: true });
|
|
89
|
+
} catch {}
|
|
90
|
+
process.exit(fails.length ? 1 : 0);
|
|
@@ -0,0 +1,274 @@
|
|
|
1
|
+
// v0.12 backlog 状态统一(对抗复查 P2 后续):
|
|
2
|
+
// - 失败分支保留已成功窗口的 writes/written/lastWrites(不能一律清零)
|
|
3
|
+
// - 失败/abort/跳过都按当前游标重算 backlogCount/backlogThroughSeq(不留脏计数)
|
|
4
|
+
// - 最终 backlog 写 lastLimit(不再借用 lastSkipReason)
|
|
5
|
+
// - 多窗后失败时 lastPoison.throughSeq 指向失败窗末条(不是第一窗)
|
|
6
|
+
// - /memory status 与 memory_status 都能看见 backlog/lastLimit
|
|
7
|
+
// 用法: node backlog-state.mjs [index.js 路径]
|
|
8
|
+
import { pathToFileURL } from "node:url";
|
|
9
|
+
import { mkdtempSync, existsSync, readFileSync, 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
|
+
|
|
21
|
+
const cleanups = [];
|
|
22
|
+
const mkTmp = (p) => {
|
|
23
|
+
const d = mkdtempSync(join(tmpdir(), p));
|
|
24
|
+
cleanups.push(d);
|
|
25
|
+
return d;
|
|
26
|
+
};
|
|
27
|
+
|
|
28
|
+
function makeCtx(stream) {
|
|
29
|
+
const reg = { tools: [], commands: [], handlers: new Map() };
|
|
30
|
+
const ctx = {
|
|
31
|
+
systemPrompt: { section: () => {}, context: () => {} },
|
|
32
|
+
tools: { register: (d) => reg.tools.push(d), schemas: () => [{ name: "write" }] },
|
|
33
|
+
commands: { register: (c) => reg.commands.push(c) },
|
|
34
|
+
on: (ev, fn) => {
|
|
35
|
+
if (!reg.handlers.has(ev)) reg.handlers.set(ev, []);
|
|
36
|
+
reg.handlers.get(ev).push(fn);
|
|
37
|
+
},
|
|
38
|
+
llm: { stream },
|
|
39
|
+
};
|
|
40
|
+
return { reg, ctx };
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
function sessionFor(cwd) {
|
|
44
|
+
return { header: { id: "sess-bl", cwd, createdAt: "2026-12-05T11:00:00.000Z" } };
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
function agentFor(session, runMaintenance) {
|
|
48
|
+
return {
|
|
49
|
+
session,
|
|
50
|
+
status: "idle",
|
|
51
|
+
inbox: { nextTurn: [], nextStep: [] },
|
|
52
|
+
model: { current: () => ({ provider: "mock", model: "mock-1" }) },
|
|
53
|
+
whenIdle: () => Promise.resolve(),
|
|
54
|
+
runMaintenance: runMaintenance || (async (fn) => fn(new AbortController().signal)),
|
|
55
|
+
};
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
const emit = async (reg, ev, ...args) => {
|
|
59
|
+
for (const fn of reg.handlers.get(ev) || []) await fn(...args);
|
|
60
|
+
};
|
|
61
|
+
|
|
62
|
+
async function seedTurn(reg, session, tools = 29) {
|
|
63
|
+
await emit(reg, "session/event", session, { type: "turn/start", seq: 1, data: { turn: 1 } });
|
|
64
|
+
await emit(reg, "session/event", session, {
|
|
65
|
+
type: "user/message",
|
|
66
|
+
seq: 2,
|
|
67
|
+
data: {
|
|
68
|
+
source: { kind: "user" },
|
|
69
|
+
content: [{ type: "text", text: "请把这个回合里验证过的发布命令和产物目录都记到长期记忆,后面还要用。" }],
|
|
70
|
+
},
|
|
71
|
+
});
|
|
72
|
+
let seq = 3;
|
|
73
|
+
for (let i = 1; i <= tools; i++) {
|
|
74
|
+
await emit(reg, "session/event", session, {
|
|
75
|
+
type: "tool/result",
|
|
76
|
+
seq: seq++,
|
|
77
|
+
data: { turn: 1, message: { toolCallId: `c${i}`, content: [{ type: "text", text: `TOOL-${i}` }] } },
|
|
78
|
+
});
|
|
79
|
+
}
|
|
80
|
+
return seq - 1; // 本回合末条 seq
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
function readState(root) {
|
|
84
|
+
const f = join(root, "_extract-state.json");
|
|
85
|
+
if (!existsSync(f)) return null;
|
|
86
|
+
try {
|
|
87
|
+
return JSON.parse(readFileSync(f, "utf8"));
|
|
88
|
+
} catch {
|
|
89
|
+
return null;
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
async function waitState(root, pred, ms = 4000) {
|
|
94
|
+
const t0 = Date.now();
|
|
95
|
+
for (;;) {
|
|
96
|
+
const st = readState(root);
|
|
97
|
+
if (st && pred(st)) return st;
|
|
98
|
+
if (Date.now() - t0 > ms) return st;
|
|
99
|
+
await new Promise((r) => setTimeout(r, 10));
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
const baseCfg = (root) => ({
|
|
104
|
+
memoriesRoot: root,
|
|
105
|
+
enabled: true,
|
|
106
|
+
writeEnabled: true,
|
|
107
|
+
promptStyle: "native",
|
|
108
|
+
autoExtractMaxMessages: 10,
|
|
109
|
+
autoExtractToolAgent: false,
|
|
110
|
+
autoExtractMinUserWords: 0,
|
|
111
|
+
autoExtractMaxChars: 24000,
|
|
112
|
+
});
|
|
113
|
+
|
|
114
|
+
// 1. 失败分支(非 abort):每个 job 第一窗成功、第二窗抛错。
|
|
115
|
+
// writes/written 不能清零;backlog 按游标重算;连续 3 次失败后毒丸区间指向失败窗末条
|
|
116
|
+
// (多窗 job 里不能退回第一窗的末条——那一段已经抽过了)。
|
|
117
|
+
{
|
|
118
|
+
const root = mkTmp("zcm-bl-fail-");
|
|
119
|
+
const cwd = mkTmp("zcm-bl-failcwd-");
|
|
120
|
+
let calls = 0;
|
|
121
|
+
const { reg, ctx } = makeCtx(async function* () {
|
|
122
|
+
calls += 1;
|
|
123
|
+
if (calls % 2 === 1) {
|
|
124
|
+
yield {
|
|
125
|
+
type: "text-delta",
|
|
126
|
+
text: JSON.stringify({
|
|
127
|
+
writes: [{ op: "create", title: `Window${calls}`, description: "d", body: "b", type: "project" }],
|
|
128
|
+
}),
|
|
129
|
+
};
|
|
130
|
+
yield { type: "finish", reason: { kind: "stop" } };
|
|
131
|
+
return;
|
|
132
|
+
}
|
|
133
|
+
throw new Error("mock window failure");
|
|
134
|
+
});
|
|
135
|
+
mod.apply(ctx, baseCfg(root));
|
|
136
|
+
const session = sessionFor(cwd);
|
|
137
|
+
const agent = agentFor(session);
|
|
138
|
+
const lastSeq = await seedTurn(reg, session, 39);
|
|
139
|
+
await emit(reg, "agent/turn-stopping", { agent, turn: 1 });
|
|
140
|
+
const st1 = await waitState(root, (s) => s.lastOutcome === "failed");
|
|
141
|
+
check(st1?.lastOutcome === "failed", "failure outcome recorded", st1?.lastOutcome);
|
|
142
|
+
check(st1?.writes === 1 && st1?.written === 1, "failure must keep writes from the successful window", {
|
|
143
|
+
writes: st1?.writes,
|
|
144
|
+
written: st1?.written,
|
|
145
|
+
});
|
|
146
|
+
check(st1?.backlogCount === 30, `failure must report the remaining backlog (got ${st1?.backlogCount})`, st1);
|
|
147
|
+
check(st1?.backlogThroughSeq === lastSeq, "failure backlog must run through the turn tail", st1?.backlogThroughSeq);
|
|
148
|
+
check(st1?.lastLimit === "", "failure must not leave a stale lastLimit", st1?.lastLimit);
|
|
149
|
+
check(Array.isArray(st1?.lastWrites) && st1.lastWrites.length === 1, "failure must keep lastWrites", st1?.lastWrites);
|
|
150
|
+
|
|
151
|
+
// 再失败两次(同一回合)→ 毒丸。等待 extracting 结束再触发,避免被 startPending 的早退吞掉。
|
|
152
|
+
for (let i = 0; i < 2; i++) {
|
|
153
|
+
await new Promise((r) => setTimeout(r, 120));
|
|
154
|
+
await emit(reg, "agent/turn-stopping", { agent, turn: 1 });
|
|
155
|
+
}
|
|
156
|
+
const st2 = await waitState(root, (s) => Number(s.lastPoison?.throughSeq) > 0);
|
|
157
|
+
check(
|
|
158
|
+
Number(st2?.lastPoison?.throughSeq) === 41,
|
|
159
|
+
`poison must point at the failed window tail (41), not the already-extracted first window (got ${st2?.lastPoison?.throughSeq})`,
|
|
160
|
+
st2?.lastPoison,
|
|
161
|
+
);
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
// 2. abort 分支:第一窗成功后维护信号被中止。
|
|
165
|
+
// abort 前已写入的计数与剩余 backlog 都必须落盘。
|
|
166
|
+
{
|
|
167
|
+
const root = mkTmp("zcm-bl-abort-");
|
|
168
|
+
const cwd = mkTmp("zcm-bl-abortcwd-");
|
|
169
|
+
let calls = 0;
|
|
170
|
+
let acRef = null;
|
|
171
|
+
const { reg, ctx } = makeCtx(async function* () {
|
|
172
|
+
calls += 1;
|
|
173
|
+
if (calls === 1) {
|
|
174
|
+
yield {
|
|
175
|
+
type: "text-delta",
|
|
176
|
+
text: JSON.stringify({
|
|
177
|
+
writes: [{ op: "create", title: "AbortWindow", description: "d", body: "b", type: "project" }],
|
|
178
|
+
}),
|
|
179
|
+
};
|
|
180
|
+
yield { type: "finish", reason: { kind: "stop" } };
|
|
181
|
+
acRef?.abort();
|
|
182
|
+
return;
|
|
183
|
+
}
|
|
184
|
+
// 后续重试挂起:不让它覆盖 abort 状态(测试只关心 abort 落盘)。
|
|
185
|
+
await new Promise(() => {});
|
|
186
|
+
});
|
|
187
|
+
mod.apply(ctx, baseCfg(root));
|
|
188
|
+
const session = sessionFor(cwd);
|
|
189
|
+
const agent = agentFor(session, async (fn) => {
|
|
190
|
+
const ctrl = new AbortController();
|
|
191
|
+
acRef = ctrl;
|
|
192
|
+
return fn(ctrl.signal);
|
|
193
|
+
});
|
|
194
|
+
const lastSeq = await seedTurn(reg, session);
|
|
195
|
+
await emit(reg, "agent/turn-stopping", { agent, turn: 1 });
|
|
196
|
+
const st = await waitState(root, (s) => s.lastOutcome === "aborted");
|
|
197
|
+
check(st?.lastOutcome === "aborted", "abort outcome recorded", st?.lastOutcome);
|
|
198
|
+
check(st?.writes === 1 && st?.written === 1, "abort must keep writes from completed windows", {
|
|
199
|
+
writes: st?.writes,
|
|
200
|
+
written: st?.written,
|
|
201
|
+
});
|
|
202
|
+
check(st?.backlogCount === 20, `abort must report the remaining backlog (got ${st?.backlogCount})`, st);
|
|
203
|
+
check(st?.backlogThroughSeq === lastSeq, "abort backlog must run through the turn tail", st?.backlogThroughSeq);
|
|
204
|
+
check(st?.lastLimit === "", "abort must not leave a stale lastLimit", st?.lastLimit);
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
// 3. 触顶 backlog 的可观测性 + 跳过清脏状态:
|
|
208
|
+
// deadline 触顶写 lastLimit(不借 lastSkipReason);随后同回合直写跳过把游标推过积压,
|
|
209
|
+
// backlog 计数必须归零而不是继续显示旧值。
|
|
210
|
+
{
|
|
211
|
+
const root = mkTmp("zcm-bl-limit-");
|
|
212
|
+
const cwd = mkTmp("zcm-bl-limitcwd-");
|
|
213
|
+
const realNow = Date.now;
|
|
214
|
+
let calls = 0;
|
|
215
|
+
const { reg, ctx } = makeCtx(async function* () {
|
|
216
|
+
calls += 1;
|
|
217
|
+
if (calls === 1) Date.now = () => realNow() + 400000;
|
|
218
|
+
yield { type: "text-delta", text: JSON.stringify({ writes: [] }) };
|
|
219
|
+
yield { type: "finish", reason: { kind: "stop" } };
|
|
220
|
+
});
|
|
221
|
+
mod.apply(ctx, baseCfg(root));
|
|
222
|
+
const session = sessionFor(cwd);
|
|
223
|
+
const agent = agentFor(session);
|
|
224
|
+
const lastSeq = await seedTurn(reg, session);
|
|
225
|
+
await emit(reg, "agent/turn-stopping", { agent, turn: 1 });
|
|
226
|
+
const st1 = await waitState(root, (s) => s.lastOutcome === "backlog");
|
|
227
|
+
Date.now = realNow;
|
|
228
|
+
check(st1?.lastOutcome === "backlog", "deadline must be recorded as backlog", st1?.lastOutcome);
|
|
229
|
+
check(st1?.lastLimit === "deadline", `deadline must be recorded in lastLimit (got ${st1?.lastLimit})`, st1);
|
|
230
|
+
check(!st1?.lastSkipReason, "backlog must not borrow lastSkipReason", st1?.lastSkipReason);
|
|
231
|
+
check(st1?.backlogCount === 20, `deadline backlog count should be 20 (got ${st1?.backlogCount})`, st1);
|
|
232
|
+
|
|
233
|
+
// memory_status 工具:能看到积压与触顶原因。
|
|
234
|
+
const statusTool = reg.tools.find((t) => t.name === "memory_status");
|
|
235
|
+
const sr = await statusTool.execute({}, { agent: { session } });
|
|
236
|
+
check(/积压/.test(String(sr?.message)), "memory_status must show backlog", sr?.message);
|
|
237
|
+
check(/续抽触顶(deadline)/.test(String(sr?.message)), "memory_status must show lastLimit", sr?.message);
|
|
238
|
+
|
|
239
|
+
// /memory status 命令:同样要显示。
|
|
240
|
+
const cmd = reg.commands.find((c) => c.name === "memory");
|
|
241
|
+
const cr = await cmd.handler({ rawInput: "status", agent: { session } });
|
|
242
|
+
check(/积压/.test(String(cr?.text)), "/memory status must show backlog", cr?.text);
|
|
243
|
+
check(/续抽触顶(deadline)/.test(String(cr?.text)), "/memory status must show lastLimit", cr?.text);
|
|
244
|
+
|
|
245
|
+
// 同回合直写跳过:游标推到本回合末条,backlog 计数必须清掉。
|
|
246
|
+
await emit(reg, "session/event", session, {
|
|
247
|
+
type: "tool/call",
|
|
248
|
+
seq: lastSeq + 1,
|
|
249
|
+
data: { turn: 1, callId: "w1", name: "memory_save", arguments: "{}" },
|
|
250
|
+
});
|
|
251
|
+
await emit(reg, "agent/turn-stopping", { agent, turn: 1 });
|
|
252
|
+
const st2 = await waitState(root, (s) => s.lastSkipReason === "direct-write");
|
|
253
|
+
check(st2?.lastSkipReason === "direct-write", "same-turn direct write should skip extraction", st2?.lastSkipReason);
|
|
254
|
+
check(st2?.backlogCount === 0 && st2?.backlogThroughSeq === 0, "skip past the backlog must clear stale backlog state", {
|
|
255
|
+
backlogCount: st2?.backlogCount,
|
|
256
|
+
backlogThroughSeq: st2?.backlogThroughSeq,
|
|
257
|
+
});
|
|
258
|
+
check(st2?.lastLimit === "", "skip past the backlog must clear lastLimit", st2?.lastLimit);
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
for (const d of cleanups) {
|
|
262
|
+
try {
|
|
263
|
+
rmSync(d, { recursive: true, force: true });
|
|
264
|
+
} catch {
|
|
265
|
+
/* noop */
|
|
266
|
+
}
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
if (fails.length) {
|
|
270
|
+
console.error("FAIL backlog-state");
|
|
271
|
+
for (const f of fails) console.error(" -", f);
|
|
272
|
+
process.exit(1);
|
|
273
|
+
}
|
|
274
|
+
console.log("PASS backlog-state");
|