@240xu/dsh-message-ops 0.11.1 → 0.11.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.
@@ -1,202 +0,0 @@
1
- /**
2
- * 0.9.7 · 文件派生缓存(P0-1)的行为契约。
3
- *
4
- * 锁四件事:
5
- * 1. **visible 绝不进缓存** —— 它依赖 live.surface.nodes;陈旧的 visible 会让
6
- * /undo 的 lastRevertable() 挑到不在 surface 上的 seq(服务端 409 / 回填错目标)。
7
- * 这是 0.9.6 修复的红线,本文件用「同文件两次 list、中间换 surface」直接钉死。
8
- * 2. running / runningSource 不进缓存(agents 注册表随时变)。
9
- * 3. 缓存条目**不含 raw events**(114MB/次的短命堆分配),只含派生结果;
10
- * 且缓存对象不被每请求字段改写(每次返回的是新拷贝)。
11
- * 4. 在途去重:3 个并发 list 只读 1 次盘;mtime+size 变化(追加一帧)必须失效。
12
- *
13
- * 藏行判据仍是 shadowed(不是 visible)——见 surface-visibility / transcript
14
- * 那两组测试;这里额外断言 shadowed 在缓存前后逐位一致。
15
- */
16
- import test from "node:test"
17
- import assert from "node:assert/strict"
18
- import fs from "node:fs"
19
- import os from "node:os"
20
- import path from "node:path"
21
- import url from "node:url"
22
- import { zstdCompressSync, constants } from "node:zlib"
23
-
24
- const ROOT = path.resolve(path.dirname(url.fileURLToPath(import.meta.url)), "..")
25
- process.env.DSH_HOME = fs.mkdtempSync(path.join(os.tmpdir(), "dsh-msgops-cache-"))
26
-
27
- const { encodeSessionFile, listMessages } = await import("../src/session-file.js")
28
- const { _internals } = await import("../src/index.js")
29
- const { opsList, loadDerived, derivedCache } = _internals
30
-
31
- const SID = "session-00000000-4444-5555-6666-777777777777"
32
- const BARE = SID.slice("session-".length)
33
-
34
- function header() {
35
- return { type: "session", version: 3, id: SID, createdAt: 1, cwd: "/tmp/x", delegationDepth: 0 }
36
- }
37
- function msg(type, seq, text) {
38
- return {
39
- type, seq, time: 1000 + seq, surfaceOp: "append",
40
- data: { turn: 1, step: 1, message: { role: type === "user/message" ? "user" : "assistant", content: [{ type: "text", text }] } },
41
- }
42
- }
43
- const EVENTS = [
44
- msg("user/message", 0, "问题一"),
45
- msg("assistant/message", 1, "回答一"),
46
- msg("user/message", 2, "问题二"),
47
- msg("assistant/message", 3, "回答二"),
48
- {
49
- type: "system/message", seq: 4, time: 1100,
50
- surfaceOp: { op: "replace", startSeq: 1, endSeq: 2 },
51
- sourceEventSeqs: [1, 2],
52
- data: { turn: 1, step: 1, message: { role: "system", content: [{ type: "text", text: "[消息回滚] 到 seq 1" }] } },
53
- },
54
- msg("user/message", 5, "问题三"),
55
- msg("assistant/message", 6, "回答三"),
56
- ]
57
-
58
- const logPath = path.join(process.env.DSH_HOME, "sessions", "proj-cache", SID, "session.v3.jsonl.zstd")
59
- fs.mkdirSync(path.dirname(logPath), { recursive: true })
60
- fs.writeFileSync(logPath, encodeSessionFile(header(), EVENTS))
61
-
62
- /** 测试用 ctx:sessions/agents 两个注册表都可换,模拟 live surface / 运行状态变化。 */
63
- function ctxFor({ nodes = null, status = "idle" } = {}) {
64
- const session = nodes === null ? undefined : { id: SID, surface: { nodes } }
65
- const agent = { status }
66
- const sessions = { get: () => session, list: () => (session ? [session] : []) }
67
- const agents = { get: () => agent }
68
- return {
69
- sessions, agents,
70
- get(name) { return name === "sessions" ? sessions : name === "agents" ? agents : undefined },
71
- }
72
- }
73
- const visibleMap = (r) => r.messages.filter((m) => m.visible).map((m) => m.seq)
74
-
75
- test("缓存命中后 visible 仍随 live surface 重算(0.9.6 红线)", async () => {
76
- // 第一次:会话不在对象层 → 走 !shadowed 兜底
77
- const r1 = await opsList(ctxFor({ nodes: null }), SID)
78
- assert.equal(r1.ok, true)
79
- assert.deepEqual(visibleMap(r1), [0, 3, 4, 5, 6], "兜底判据 = !shadowed(seq 1,2 被 replace 遮蔽;marker seq 4 自己可见)")
80
- assert.equal(r1.visibleCount, 5)
81
-
82
- // 第二次:live surface 只挂 0 与 1 —— 文件没变,纯缓存命中
83
- const r2 = await opsList(ctxFor({ nodes: [0, 1] }), SID)
84
- assert.deepEqual(visibleMap(r2), [0, 1], "缓存命中也必须用新 surface,绝不能回放上一次的 visible")
85
- assert.equal(r2.visibleCount, 2)
86
-
87
- // 第三次:再换一个 surface
88
- const r3 = await opsList(ctxFor({ nodes: [5] }), SID)
89
- assert.deepEqual(visibleMap(r3), [5])
90
- assert.equal(r3.visibleCount, 1)
91
-
92
- // 三次返回的 messages 必须是**不同对象**(缓存对象不被改写)
93
- assert.notStrictEqual(r1.messages, r2.messages)
94
- assert.notStrictEqual(r1.messages[0], r2.messages[0])
95
- // 但文件派生字段逐位一致
96
- assert.deepEqual(r1.messages.map((m) => [m.seq, m.snippet, m.shadowed]), r3.messages.map((m) => [m.seq, m.snippet, m.shadowed]))
97
- })
98
-
99
- test("藏行判据是 shadowed 且跨请求稳定(0.9.6)", async () => {
100
- const a = await opsList(ctxFor({ nodes: [1, 2] }), SID) // 即使 surface 上有 1,2
101
- const b = await opsList(ctxFor({ nodes: [1, 2] }), SID)
102
- for (const r of [a, b]) {
103
- assert.equal(r.messages.find((m) => m.seq === 1).shadowed, true)
104
- assert.equal(r.messages.find((m) => m.seq === 2).shadowed, true)
105
- assert.equal(r.messages.find((m) => m.seq === 0).shadowed, false)
106
- // shadowed 恒由 computeShadowed 得出,与 visible 是否为 true 无关
107
- assert.equal(r.messages.find((m) => m.seq === 1).visible, true)
108
- }
109
- assert.deepEqual(a.messages.map((m) => m.shadowed), b.messages.map((m) => m.shadowed))
110
- })
111
-
112
- test("running / runningSource 每请求重算,不进缓存", async () => {
113
- const idle = await opsList(ctxFor({ status: "idle" }), SID)
114
- assert.equal(idle.running, false)
115
- const run = await opsList(ctxFor({ status: "running" }), SID)
116
- assert.equal(run.running, true)
117
- assert.equal(run.runningSource, "agent-status-running")
118
- assert.equal((await opsList(ctxFor({ status: "idle" }), SID)).running, false)
119
- })
120
-
121
- test("缓存条目不含 raw events,且 LRU 上限 16", async () => {
122
- derivedCache.clear()
123
- await opsList(ctxFor(), SID)
124
- assert.equal(derivedCache.size, 1)
125
- const entry = derivedCache.get(logPath)
126
- assert.ok(entry, "应按 logPath 建条目")
127
- assert.deepEqual(Object.keys(entry).sort(), ["mtimeMs", "promise", "size"])
128
- const derived = await entry.promise
129
- assert.ok(!("events" in derived), "derived 不得持有 raw events(114MB/次)")
130
- assert.deepEqual(Object.keys(derived).sort(), ["header", "messages", "shadowed", "turnEndSeq"])
131
- assert.equal(derived.messages.length, listMessages(EVENTS).length)
132
-
133
- // 再灌 20 个真实会话日志 → 上限必须是 16,且最早插入的被淘汰
134
- const extra = [];
135
- for (let i = 0; i < 20; i++) {
136
- const id = `session-00000000-0000-4000-8000-${String(i).padStart(12, "0")}`;
137
- const dir = path.join(process.env.DSH_HOME, "sessions", "proj-lru", id);
138
- fs.mkdirSync(dir, { recursive: true });
139
- fs.writeFileSync(path.join(dir, "session.v3.jsonl.zstd"), encodeSessionFile({ ...header(), id }, [msg("user/message", 0, "x" + i)]));
140
- extra.push(path.join(dir, "session.v3.jsonl.zstd"));
141
- }
142
- for (const p of extra) await loadDerived(p);
143
- assert.equal(derivedCache.size, 16, `LRU 未生效:size=${derivedCache.size}`)
144
- assert.equal(derivedCache.has(logPath), false, "最早插入的条目应被淘汰")
145
- })
146
-
147
- test("在途去重:3 个并发 list 只读 1 次盘", async () => {
148
- derivedCache.clear()
149
- const realReadFile = fs.promises.readFile
150
- let reads = 0
151
- fs.promises.readFile = async (...args) => { reads++; return realReadFile(...args) }
152
- try {
153
- const [a, b, c] = await Promise.all([opsList(ctxFor(), SID), opsList(ctxFor(), SID), opsList(ctxFor(), SID)])
154
- assert.equal(reads, 1, `并发应共享一次读取,实际 ${reads} 次`)
155
- assert.equal(a.total, b.total)
156
- assert.deepEqual(visibleMap(a), visibleMap(c))
157
- } finally {
158
- fs.promises.readFile = realReadFile
159
- }
160
- assert.equal(derivedCache.size, 1)
161
- // 串行再问一次:仍是缓存命中(不再读盘)
162
- const before = fs.promises.readFile
163
- let reads2 = 0
164
- fs.promises.readFile = async (...args) => { reads2++; return before(...args) }
165
- try { await opsList(ctxFor(), SID) } finally { fs.promises.readFile = before }
166
- assert.equal(reads2, 0, "命中不应再读盘")
167
- })
168
-
169
- test("mtime+size 失效:追加一帧后立即看到新事件", async () => {
170
- derivedCache.clear()
171
- const first = await opsList(ctxFor(), SID)
172
- assert.equal(first.total, EVENTS.length)
173
-
174
- // append-only 追加一个 user 消息帧(裸 zstd,与 diskAppend 同构)
175
- const extra = msg("user/message", 7, "问题四")
176
- const frame = zstdCompressSync(Buffer.from(JSON.stringify(extra) + "\n", "utf8"), {
177
- params: { [constants.ZSTD_c_checksumFlag]: 1 },
178
- })
179
- const stBefore = fs.statSync(logPath)
180
- fs.appendFileSync(logPath, frame)
181
- // 保证 mtime/size 至少有一个变化(size 必变)
182
- assert.ok(fs.statSync(logPath).size > stBefore.size)
183
-
184
- const second = await opsList(ctxFor(), SID)
185
- assert.equal(second.total, EVENTS.length + 1, "读前 stat 必须让追加生效")
186
- assert.equal(second.messages.at(-1).snippet, "问题四")
187
-
188
- // 同步 loadDerived 也走重算路径
189
- const st = fs.statSync(logPath)
190
- const entry = derivedCache.get(logPath)
191
- assert.equal(entry.size, st.size)
192
- assert.equal(entry.mtimeMs, st.mtimeMs)
193
- })
194
-
195
- test("findSessionDirs 两种 id 拼写都能命中缓存(key 是 logPath 不是 sessionId)", async () => {
196
- derivedCache.clear()
197
- const byFull = await opsList(ctxFor(), SID)
198
- const byBare = await opsList(ctxFor(), BARE)
199
- assert.equal(byFull.session.id, SID)
200
- assert.equal(byBare.session.id, SID)
201
- assert.equal(derivedCache.size, 1, "同一文件的两种 id 拼写必须命中同一条缓存")
202
- })