@240xu/dsh-message-ops 0.7.0 → 0.9.0

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/src/ops-core.js CHANGED
@@ -20,7 +20,7 @@ import { randomUUID } from "node:crypto";
20
20
  import { readReplaceOp, messageText, computeShadowed } from "./session-file.js";
21
21
 
22
22
  // messageText 的单点实现在 session-file.js(listMessages 同用);此处转出保持
23
- // 既有导入面兼容(ops-core 的 messageText/exportMarkdown 调用方不受影响)。
23
+ // 既有导入面兼容(ops-core 的 messageText 调用方不受影响)。
24
24
  export { messageText };
25
25
 
26
26
  /** 带语义状态码的操作错误(HTTP 直接映射,工具端转为失败文本)。 */
@@ -71,6 +71,91 @@ function replaceOpFor(shape, startSeq, endSeq) {
71
71
  /** 测试专用:重置写端拼写探测缓存。 */
72
72
  export function _resetReplaceShape() { replaceShape = null; }
73
73
 
74
+ /**
75
+ * v4 消息归属(producer-owned source)构造。
76
+ *
77
+ * 0.8.1 P0 实机事故:dsh 0.2.0 收紧 v4 准入后,本插件写的每条消息都缺
78
+ * `message.source` → `format v4 message requires a producer-owned source kind`
79
+ * → **整份日志被拒绝,20 个会话在 UI 打不开**(v4 要求 kind 非空且非
80
+ * "plugin";v3 反过来要求 system/message 的 kind==="plugin",两边都不
81
+ * 接受缺失)。
82
+ *
83
+ * 形状必须**同时满足 v3 与迁移后的 v4**(实测踩出来的):
84
+ * - v3(v2-to-v3 `assertV3RowAdmission`)要求 `system/message` 的
85
+ * `message.source.kind === "plugin"`,否则报 `system message requires
86
+ * plugin source`。而插件的 `findSessionDirs` 会 v4 → v3 → 旧单帧逐级回退,
87
+ * 24 个 v3 日志是活靶子。
88
+ * - v4 的 `source()` 只拒绝**字面量** `"plugin"`(v3-to-v4:126),而
89
+ * `producerKind()` 对未知插件返回 `plugin:<name>` —— 该值 v4 接受。
90
+ * → `{kind:"plugin", plugin:"<name>"}` 是唯一两边都合法的形状:迁移时
91
+ * `rewritePluginSource` → `producerKind` → `plugin:@240xu/dsh-message-ops`。
92
+ *
93
+ * ⚠️ 不要改成 `{kind:"message-ops"}`:它在 v3 直接非法(实测 FAIL)。
94
+ */
95
+ const PLUGIN_NAME = "@240xu/dsh-message-ops";
96
+ const PRODUCER_KIND = `plugin:${PLUGIN_NAME}`; // 迁移后的 v4 形态
97
+
98
+ /**
99
+ * 按**目标代**构造消息 source —— v3 与 v4 的合法形状互斥(实测):
100
+ *
101
+ * source v3 日志 v4 日志
102
+ * {kind:"plugin", plugin:<name>} PASS ✅ FAIL ✗(拒字面量 "plugin")
103
+ * {kind:"plugin:<name>"}(producerKind) FAIL ✗ PASS ✅
104
+ * {kind:"message-ops"} FAIL ✗ PASS ✅
105
+ *
106
+ * 根因:v3 的 `assertV3RowAdmission` 要求 system 类消息 `source.kind==="plugin"`;
107
+ * v4 的 `source()` 只拒绝**字面量** "plugin",而 `producerKind()` 对未知插件产出
108
+ * `plugin:<name>`,该值 v4 接���。
109
+ * 插件的 `findSessionDirs` 会 v4 → v3 → 旧单帧逐级回退(语料里 24 个 v3 日志),
110
+ * 所以**必须按写到哪里决定形状**,不能一刀切。
111
+ *
112
+ * @param {number|undefined} version 目标日志的 header.version(4 = v4;其余按 v3 形状)
113
+ */
114
+ function messageSource(role, version) {
115
+ const r = role ?? "system";
116
+ // ⚠️ role=system 只能写 "system-prompt":Session 运行时层(dsh-session/lib/index.js:1206)
117
+ // 对 `system/message` 要求 kind **严格等于** "system-prompt",比 v4 格式闸更严,
118
+ // 任何 producer-owned kind(含 plugin:<name>)都会被加载端拒���:
119
+ // `session event at seq N message must have system-prompt source`
120
+ if (r === "system") return { kind: "system-prompt" };
121
+ if (version === 4) return { kind: PRODUCER_KIND, role: r };
122
+ return { kind: "plugin", plugin: PLUGIN_NAME, role: r };
123
+ }
124
+
125
+ /**
126
+ * 重放事件的 data 形状 —— **按事件类型分派**。
127
+ *
128
+ * 0.8.1 P0 实机事故(第二处):`user/message` 的 v4 契约里**消息本体字段
129
+ * 直接摊在 data 上**(`data.id` / `data.role` / `data.source` /
130
+ * `data.content`),而 `assistant/message` 才包一层 `data.message`
131
+ * (并带 turn/step)。旧代码对两者一律写 `{ message: {...} }` →
132
+ * user/message 被双重包裹成 `data.message.role`,且丢 id、丢 source。
133
+ * 正确形状见 `dsh-session-format-v2-to-v3/lib/index.js:264-271`。
134
+ */
135
+ export function replayEventData(item, ts, version = 4) {
136
+ if (item.type === "user/message") {
137
+ return {
138
+ id: item.id ?? randomUUID(),
139
+ role: "user",
140
+ source: messageSource("user", version),
141
+ content: [{ type: "text", text: item.text }],
142
+ };
143
+ }
144
+ if (!ts || !Number.isSafeInteger(ts.turn) || ts.turn <= 0 || !Number.isSafeInteger(ts.step) || ts.step <= 0) {
145
+ throw new OpsError("replayEventData: assistant/message 需要打开的 turn/step,拒绝写出注定无法加载的事件", 500);
146
+ }
147
+ return {
148
+ turn: ts.turn,
149
+ step: ts.step,
150
+ message: {
151
+ id: item.id ?? randomUUID(),
152
+ role: "assistant",
153
+ source: messageSource("assistant", version),
154
+ content: [{ type: "text", text: item.text }],
155
+ },
156
+ };
157
+ }
158
+
74
159
  /**
75
160
  * surface replace 落定:append 一条承载 replace 的 system/message。
76
161
  * sourceEventSeqs 必须覆盖被遮蔽的全部 surface 节点(引擎
@@ -98,10 +183,71 @@ export function deriveTurnStep(events) {
98
183
  return { turn: 1, step: 1 };
99
184
  }
100
185
 
186
+ /**
187
+ * 规划承载 notice 的 turn/step 窗口。
188
+ *
189
+ * v4 关系状态机要求 `system/message` 的 `data.turn/step` 匹配**当前打开**的
190
+ * turn+step(`assertReleasedV4Relationships` → `requireStep`)。但用户恰恰在会话
191
+ * **空闲**时想回滚消息,而正常会话都以 `turn/end` 收尾 —— 实测 364 个日志里
192
+ * **340 个(93%)空闲时 turn+step 是关闭的**。若此时拒绝,功能等于不存在。
193
+ *
194
+ * 出路:引擎 append-only(Session 公开方法里确无 insert/splice),所以把 notice
195
+ * 包进一个**自足的合成 turn**:turn/start → step/start → notice → step/end → turn/end。
196
+ * 这正是 dsh 自己的崩溃恢复(`openTurnClosers`���用同一手法合��闭合事件。
197
+ * 已对官方校验闸实测四种情形全部通过:append 型 / 单节点 replace / 多节点 replace /
198
+ * 遮蔽受保护头(正确拒绝)。
199
+ *
200
+ * 合成 turn 带 `reason:"message-ops"`,UI 与审计可据此识别,不与真实模型轮次混淆。
201
+ *
202
+ * @returns {{synthetic: boolean, turn: number, step: number,
203
+ * preamble?: Array, postamble?: Array}}
204
+ */
205
+ export function planNoticeWindow(events) {
206
+ let turn = null, step = null, maxTurn = 0;
207
+ for (const e of events ?? []) {
208
+ const d = e?.data;
209
+ if (Number.isSafeInteger(d?.turn) && d.turn > maxTurn) maxTurn = d.turn;
210
+ switch (e?.type) {
211
+ case "turn/start": turn = d?.turn ?? null; step = null; break;
212
+ case "step/start": step = d?.step ?? null; break;
213
+ case "step/end": step = null; break;
214
+ case "turn/end": turn = null; step = null; break;
215
+ default: break;
216
+ }
217
+ }
218
+ // 会话正开着 turn+step(例如上一轮被中断)→ 直接用现成窗口,不造合成 turn
219
+ if (turn !== null && step !== null) return { synthetic: false, turn, step };
220
+ const nextTurn = maxTurn + 1;
221
+ return { synthetic: true, turn: nextTurn, step: 1 };
222
+ }
223
+
224
+ /** 合成窗口的前缀事件(seq/time 由调用方分配)。 */
225
+ export function noticeWindowPreamble(win) {
226
+ if (!win.synthetic) return [];
227
+ return [
228
+ { kind: "turn/start", data: { turn: win.turn, reason: "message-ops" } },
229
+ { kind: "step/start", data: { turn: win.turn, step: win.step } },
230
+ ];
231
+ }
232
+
233
+ /** 合成窗口的后缀事件。 */
234
+ export function noticeWindowPostamble(win) {
235
+ if (!win.synthetic) return [];
236
+ return [
237
+ { kind: "step/end", data: { turn: win.turn, step: win.step } },
238
+ // ⚠️ turn/end.data.reason 是**必填契约**(types.d.ts:271-276),引擎自己也这么写
239
+ // (dsh-session/lib/index.js:783-786)。UI 的 trajectory 装配器无防护地读
240
+ // `match.event.data.reason.kind`(dsh-client-ui-trajectory/lib/client.js:997-998)
241
+ // → 缺字段会让整个会话页白屏(ConversationNodeAssembler.replayContext 抛 TypeError)。
242
+ // kind 选 "interrupted":语义上就是"非模型驱动的 turn"(引擎用它标记被打断的轮次)。
243
+ { kind: "turn/end", data: { turn: win.turn, reason: { kind: "interrupted" } } },
244
+ ];
245
+ }
246
+
101
247
  export function applySurfaceReplace(session, startSeq, endSeq, sourceEventSeqs, noticeText, turnStep) {
102
248
  const ts = turnStep && Number.isSafeInteger(turnStep.turn) && turnStep.turn > 0
103
249
  ? turnStep : { turn: 1, step: 1 };
104
- const data = { turn: ts.turn, step: ts.step, message: { id: randomUUID(), role: "system", content: [{ type: "text", text: noticeText }] } };
250
+ const data = { turn: ts.turn, step: ts.step, message: { id: randomUUID(), role: "system", source: messageSource("system", 4), content: [{ type: "text", text: noticeText }] } };
105
251
  if (replaceShape) {
106
252
  return session.append("system/message", data, { surfaceOp: replaceOpFor(replaceShape, startSeq, endSeq), sourceEventSeqs });
107
253
  }
@@ -124,7 +270,7 @@ export function applySurfaceReplace(session, startSeq, endSeq, sourceEventSeqs,
124
270
  * @param {number} restoreSeq 一次 revert/delete 落定的 system/message 事件的
125
271
  * seq(其 surfaceOp 为 replace、sourceEventSeqs 记录了被遮蔽节点)
126
272
  */
127
- export function planRestore(events, restoreSeq) {
273
+ export function planRestore(events, restoreSeq, upToSeq, excludeSeqs) {
128
274
  if (!Array.isArray(events)) throw new OpsError("restore: events must be an array", 500);
129
275
  if (!Number.isSafeInteger(restoreSeq) || restoreSeq < 0) throw new OpsError("invalid seq", 400);
130
276
  const ev = events.find((e) => e && e.seq === restoreSeq);
@@ -135,11 +281,17 @@ export function planRestore(events, restoreSeq) {
135
281
  throw new OpsError(`restore: seq ${restoreSeq} is not a revert/delete marker event (no well-formed replace surfaceOp)`, 409);
136
282
  }
137
283
  const { startSeq, endSeq } = range;
284
+ // 0.8.0 按轮步进:upToSeq 给定则只重放到该 seq(含),后续仍保持遮蔽;
285
+ // excludeSeqs = 已重放过(先前轮次 notice 的 restoredSourceSeqs 并集),
286
+ // **必须排除,否则每轮都从区间头重放 → 消息副本刷屏**(0.8.0 实测 B1)。
287
+ const cap = Number.isSafeInteger(upToSeq) ? Math.min(upToSeq, endSeq) : endSeq;
288
+ const excluded = Array.isArray(excludeSeqs) ? new Set(excludeSeqs.filter((q) => Number.isSafeInteger(q))) : null;
138
289
  const replayable = [];
139
290
  let skipped = 0;
140
291
  for (const e of events) {
141
- if (!e || typeof e.seq !== "number" || e.seq < startSeq || e.seq > endSeq) continue;
292
+ if (!e || typeof e.seq !== "number" || e.seq < startSeq || e.seq > cap) continue;
142
293
  if (e.type === "user/message" || e.type === "assistant/message") {
294
+ if (excluded && excluded.has(e.seq)) continue;
143
295
  const text = messageText(e);
144
296
  if (!text.trim()) { skipped++; continue; }
145
297
  replayable.push({
@@ -156,7 +308,7 @@ export function planRestore(events, restoreSeq) {
156
308
  // dock 会为这类标记常驻显示恢复按钮,409 死按钮 = 永远清不掉(实测 8 连 409)。
157
309
  // 改为返回空计划:applyRestore 仍追加说明 notice(含 restoresSeq)→ 标记停用、
158
310
  // dock 计数递减;语义如实:0 条重放 + 文案说明区间无 user/assistant 内容。
159
- return { restoreSeq, startSeq, endSeq, replayable, skipped, turnStep: deriveTurnStep(events) };
311
+ return { restoreSeq, startSeq, endSeq, upToSeq: Number.isSafeInteger(upToSeq) ? cap : endSeq, replayable, skipped };
160
312
  }
161
313
 
162
314
  /**
@@ -169,28 +321,31 @@ export function restoreNoticeText(plan) {
169
321
  return plan.replayable.length === 0
170
322
  ? `[消息恢复] seq ${plan.startSeq}..${plan.endSeq} 区间无可重放的 user/assistant 消息(` +
171
323
  `内容为 tool/system 事件或空文本)——该回撤标记就此停用,区间保持遮蔽`
172
- : `[消息恢复] 重放 seq ${plan.startSeq}..${plan.endSeq} 的 ${plan.replayable.length} 条消息` +
324
+ : `[消息恢复] 重放 seq ${plan.startSeq}..${(plan.upToSeq != null ? plan.upToSeq : plan.endSeq)} 的 ${plan.replayable.length} 条消息` +
325
+ (plan.upToSeq != null && plan.upToSeq < plan.endSeq ? `(按轮步进:seq ${plan.upToSeq + 1}..${plan.endSeq} 仍遮蔽)` : "") +
173
326
  (plan.skipped > 0 ? `(另有 ${plan.skipped} 条不可重放事件已跳过)` : "") +
174
327
  `;原区间仍处于遮蔽状态,恢复为重放而非解除遮蔽`;
175
328
  }
176
329
 
177
330
  export function applyRestore(session, plan, { flush } = {}) {
178
331
  const eventSeqs = [];
179
- const notice = restoreNoticeText(plan);
332
+ const notice = plan.discard
333
+ ? `[消息操作] 回撤标记 seq ${plan.restoreSeq} 已停用(丢弃):区间内容保持遮蔽、未重放;日志原文仍在,可搜索`
334
+ : restoreNoticeText(plan);
180
335
  // 0.4.2:notice 事件携带 restoresSeq —— dock 据此把被恢复的标记从「活跃回撤」
181
336
  // 中移除(对齐 opencode clear 语义:恢复后不再显示为待恢复项)。
182
337
  const ts = plan.turnStep && Number.isSafeInteger(plan.turnStep.turn) && plan.turnStep.turn > 0
183
338
  ? plan.turnStep : { turn: 1, step: 1 };
184
339
  const noticeEvent = session.append(
185
340
  "system/message",
186
- { turn: ts.turn, step: ts.step, message: { id: randomUUID(), role: "system", content: [{ type: "text", text: notice }] }, restoresSeq: plan.restoreSeq },
341
+ { turn: ts.turn, step: ts.step, message: { id: randomUUID(), role: "system", source: messageSource("system", 4), content: [{ type: "text", text: notice }] }, restoresSeq: plan.restoreSeq, restoredSourceSeqs: plan.discard ? [] : plan.replayable.map((i) => i.seq), ...(plan.discard ? { discarded: true } : {}) },
187
342
  { surfaceOp: "append" },
188
343
  );
189
344
  if (noticeEvent && noticeEvent.seq != null) eventSeqs.push(noticeEvent.seq);
190
- for (const item of plan.replayable) {
345
+ for (const item of plan.discard ? [] : plan.replayable) {
191
346
  const event = session.append(
192
347
  item.type,
193
- { message: { role: item.role, content: [{ type: "text", text: item.text }] } },
348
+ replayEventData(item, ts),
194
349
  { surfaceOp: "append" },
195
350
  );
196
351
  if (event && event.seq != null) eventSeqs.push(event.seq);
@@ -198,55 +353,85 @@ export function applyRestore(session, plan, { flush } = {}) {
198
353
  if (flush) {
199
354
  try { flush(); } catch { /* flush 失败不回滚已接受的事件 */ }
200
355
  }
201
- return { restoredCount: plan.replayable.length, skipped: plan.skipped, eventSeqs };
356
+ return { restoredCount: plan.discard ? 0 : plan.replayable.length, skipped: plan.skipped, eventSeqs };
202
357
  }
203
358
 
204
359
  /**
205
- * exportMarkdown:把到 upToSeq(含)为止的事件流渲染为 Markdown。
206
- * user/assistant/system 消息按角色小节展开,工具调用折叠为单行引用。
207
- * @param {object} header 会话 header(readSessionFile)
208
- * @param {Array} events 全量事件
209
- * @param {number=} upToSeq 可选上界(含);缺省导出全部
360
+ * 0.8.0:计算一次 revert/delete 标记的「恢复进度」。
361
+ *
362
+ * @param {Array} events 全量事件(含标记与其后的恢复 notice)
363
+ * @param {number} markerSeq 标记事件 seq
364
+ * @returns {{ startSeq:number, endSeq:number, restoredSeqs:number[], pendingSeqs:number[], complete:boolean, legacy:boolean }}
365
+ * - restoredSeqs:已被重放过的源 seq(来自各 notice 的 restoredSourceSeqs)
366
+ * - pendingSeqs:仍未重放的、可重放的源 seq(贴条按行展示用)
367
+ * - complete:是否已全部恢复(标记不再活跃)
368
+ * - legacy:旧通知(无 restoredSourceSeqs 字段)→ 视为整段已恢复
210
369
  */
211
- export function exportMarkdown(header, events, upToSeq) {
212
- if (upToSeq !== undefined && (!Number.isSafeInteger(upToSeq) || upToSeq < 0)) {
213
- throw new OpsError("invalid seq", 400);
370
+ export function restoreProgress(events, markerSeq) {
371
+ const list = Array.isArray(events) ? events : [];
372
+ const marker = list.find((e) => e && e.seq === markerSeq);
373
+ if (!marker) return null;
374
+ const range = readReplaceOp(marker);
375
+ if (!range) return null;
376
+ const { startSeq, endSeq } = range;
377
+ // 该区间内可重放的消息型事件
378
+ const candidates = [];
379
+ for (const e of list) {
380
+ if (!e || typeof e.seq !== "number" || e.seq < startSeq || e.seq > endSeq) continue;
381
+ if (e.type !== "user/message" && e.type !== "assistant/message") continue;
382
+ if (!(messageText(e) || "").trim()) continue;
383
+ candidates.push(e.seq);
214
384
  }
215
- const sessionId = header && header.id ? header.id : "unknown";
216
- const scoped = upToSeq === undefined ? events : events.filter((e) => e && typeof e.seq === "number" && e.seq <= upToSeq);
217
- const lines = [];
218
- lines.push(`# DSH 会话导出:${sessionId}`);
219
- lines.push("");
220
- lines.push(`- 会话 id:${sessionId}`);
221
- if (header && header.parentSession) lines.push(`- 来源分支:${header.parentSession}`);
222
- lines.push(`- 导出范围:${upToSeq === undefined ? "全部" : `seq ≤ ${upToSeq}`}`);
223
- lines.push(`- 生成时间:${new Date().toISOString()}`);
224
- lines.push("");
225
- lines.push("---");
226
- lines.push("");
227
- for (const e of scoped) {
228
- if (!e || typeof e.seq !== "number") continue;
229
- if (e.type === "user/message" || e.type === "assistant/message" || e.type === "system/message") {
230
- const role = (e.data && e.data.message && e.data.message.role) ||
231
- (e.type === "user/message" ? "user" : e.type === "assistant/message" ? "assistant" : "system");
232
- const text = messageText(e);
233
- lines.push(`## [seq ${e.seq}] ${role}`);
234
- lines.push("");
235
- lines.push(text || "(无文本内容)");
236
- lines.push("");
237
- } else if (e.type === "tool/call") {
238
- const d = e.data || {};
239
- const name = d.name || (d.call && d.call.name) || "tool";
240
- const argsHint = d.call && d.call.arguments !== undefined
241
- ? JSON.stringify(d.call.arguments).slice(0, 80)
242
- : "";
243
- lines.push(`> [seq ${e.seq}] 🔧 工具调用:${name}${argsHint ? ` — ${argsHint}` : ""}`);
244
- lines.push("");
245
- }
385
+ // 收集针对该标记的所有恢复 notice
386
+ const notices = list.filter((e) => e && e.data && e.data.restoresSeq === markerSeq);
387
+ const restored = new Set();
388
+ let legacy = false;
389
+ let discarded = false;
390
+ for (const n of notices) {
391
+ // 0.8.1:显式丢弃(不重放内容、仅停用标记)也算完成——
392
+ // 用户场景"我都没回滚过,清掉测试遗留条",2709 条重放是另一种污染。
393
+ if (n.data.discarded === true) { discarded = true; continue; }
394
+ const seqs = n.data && Array.isArray(n.data.restoredSourceSeqs) ? n.data.restoredSourceSeqs : null;
395
+ if (!seqs) { legacy = true; continue; }
396
+ for (const q of seqs) if (Number.isSafeInteger(q)) restored.add(q);
246
397
  }
247
- return lines.join("\n");
398
+ const pending = candidates.filter((q) => !restored.has(q));
399
+ return {
400
+ startSeq,
401
+ endSeq,
402
+ restoredSeqs: Array.from(restored).sort((a, b) => a - b),
403
+ pendingSeqs: pending,
404
+ complete: legacy || discarded ? true : pending.length === 0,
405
+ legacy,
406
+ discarded,
407
+ };
248
408
  }
249
409
 
410
+ /**
411
+ * 0.8.0:贴条按行展示用 —— 列出该标记仍未重放的「轮」(一个 user 消息及其后
412
+ * 到下一个 user 之前的 assistant 回复算一轮,对齐 opencode 按轮步进恢复)。
413
+ *
414
+ * @returns {Array<{ turnSeq:number, seqs:number[] }>} 按 seq 升序
415
+ */
416
+ export function pendingRestoreTurns(events, markerSeq) {
417
+ const prog = restoreProgress(events, markerSeq);
418
+ if (!prog || prog.pendingSeqs.length === 0) return [];
419
+ const list = Array.isArray(events) ? events : [];
420
+ const bySeq = new Map();
421
+ for (const e of list) if (e && typeof e.seq === "number") bySeq.set(e.seq, e);
422
+ const turns = [];
423
+ let current = null;
424
+ for (const q of prog.pendingSeqs) {
425
+ const e = bySeq.get(q);
426
+ if (!e) continue;
427
+ if (e.type === "user/message") { current = { turnSeq: q, seqs: [q] }; turns.push(current) }
428
+ else if (current) current.seqs.push(q);
429
+ else turns.push({ turnSeq: q, seqs: [q] }); // 孤立 assistant(无前导 user)
430
+ }
431
+ return turns;
432
+ }
433
+
434
+
250
435
  // ---------------------------------------------------------------------------
251
436
  // HTTP 信任围栏(评审 P0):插件经 webServer.register 挂载的路由不经过宿主
252
437
  // connection RPC 面的 isTrustedApiRequest 围栏(dsh-src
@@ -349,32 +534,58 @@ export function isSurfaceMessageType(type) {
349
534
  }
350
535
 
351
536
  /** 磁盘可见节点:按事件流推导的 message 类 seq(剔除既有遮蔽)。 */
352
- export function diskVisibleNodes(events) {
537
+ /**
538
+ * 当前 surface 上的**全部**节点(v4 的 5 种 surface 类型),已剔除被遮蔽的。
539
+ *
540
+ * ⚠️ 与 `diskVisibleNodes` 的区别是关键的(0.8.2 实机事故):
541
+ * `diskVisibleNodes` 只收 4 种**消息**类型(UI 列表用),而 v4 的 surface 还包含
542
+ * `tool/result`。surface replace 的 `sourceEventSeqs` 必须覆盖**被遮蔽的每一个
543
+ * surface 节点**(`foldSurface`:`if (removed.some(s => !sources.includes(s))) throw
544
+ * "replacement sourceEventSeqs omit a shadowed surface node"`)—— 用消息集合当溯源
545
+ * 会漏掉区间内的 tool/result,**整份日志被加载端拒绝**。这正是历史上 14 个打不开的
546
+ * 会话的真正成因(不是区间压缩编码问题)。
547
+ */
548
+ export function diskSurfaceNodes(events) {
353
549
  const shadowed = computeShadowed(events);
354
550
  const nodes = [];
355
551
  for (const e of events) {
356
552
  if (!e || !Number.isSafeInteger(e.seq)) continue;
357
553
  if (shadowed.has(e.seq)) continue;
358
- if (isSurfaceMessageType(e.type)) nodes.push(e.seq);
554
+ if (isSurfaceType(e.type)) nodes.push(e.seq);
359
555
  }
360
556
  return nodes;
361
557
  }
362
558
 
559
+ function isSurfaceType(type) {
560
+ return isSurfaceMessageType(type) || type === "tool/result";
561
+ }
562
+
563
+ export function diskVisibleNodes(events) {
564
+ return diskSurfaceNodes(events).filter((seq) => {
565
+ const e = events.find((x) => x && x.seq === seq);
566
+ return e && isSurfaceMessageType(e.type);
567
+ });
568
+ }
569
+
363
570
  /** 磁盘版 planRevert:target 必须可见,遮蔽 target 之后(含)全部可见节点。 */
364
571
  export function planRevertFromEvents(events, targetSeq) {
572
+ // 目标用「消息」集合(回滚对象是消息),溯源用「全部 surface」集合(0.8.2 修正)
365
573
  const nodes = diskVisibleNodes(events);
366
574
  const startIdx = nodes.indexOf(targetSeq);
367
575
  if (startIdx === -1) throw new OpsError(`surface replace: start seq ${targetSeq} not found in surface`, 409);
368
- const shadowedSeqs = nodes.slice(startIdx);
576
+ const surface = diskSurfaceNodes(events);
577
+ const shadowedSeqs = surface.slice(surface.indexOf(targetSeq));
369
578
  if (shadowedSeqs.length === 0) throw new OpsError("nothing to revert", 409);
370
579
  return { startSeq: targetSeq, endSeq: shadowedSeqs[shadowedSeqs.length - 1], shadowedSeqs };
371
580
  }
372
581
 
373
582
  /** 磁盘版 planDelete:单条可见遮蔽。 */
374
583
  export function planDeleteFromEvents(events, seq) {
375
- if (!diskVisibleNodes(events).includes(seq)) {
584
+ const surface = diskSurfaceNodes(events);
585
+ if (!diskVisibleNodes(events).includes(seq) || !surface.includes(seq)) {
376
586
  throw new OpsError(`seq ${seq} not visible on current surface`, 409);
377
587
  }
588
+ // 单节点遮蔽:溯源就是它自己(0.8.2:也走完整 surface 判定,避免非 surface 节点)
378
589
  return { startSeq: seq, endSeq: seq, shadowedSeqs: [seq] };
379
590
  }
380
591
 
@@ -386,7 +597,7 @@ export function nextSeqFrom(events) {
386
597
  }
387
598
 
388
599
  /** 磁盘回撤/删除标记事件(字段镜像引擎金标准:type/seq/time/data/sourceEventSeqs/surfaceOp)。 */
389
- export function buildMarkerEvent({ seq, time, turnStep, text, startSeq, endSeq, shadowedSeqs }) {
600
+ export function buildMarkerEvent({ seq, time, turnStep, text, startSeq, endSeq, shadowedSeqs, version = 4 }) {
390
601
  return {
391
602
  type: "system/message",
392
603
  seq,
@@ -394,7 +605,7 @@ export function buildMarkerEvent({ seq, time, turnStep, text, startSeq, endSeq,
394
605
  data: {
395
606
  turn: turnStep.turn,
396
607
  step: turnStep.step,
397
- message: { id: randomUUID(), role: "system", content: [{ type: "text", text }] },
608
+ message: { id: randomUUID(), role: "system", source: messageSource("system", version), content: [{ type: "text", text }] },
398
609
  },
399
610
  sourceEventSeqs: [...shadowedSeqs],
400
611
  surfaceOp: { op: "replace", startSeq, endSeq },
@@ -402,7 +613,7 @@ export function buildMarkerEvent({ seq, time, turnStep, text, startSeq, endSeq,
402
613
  }
403
614
 
404
615
  /** 磁盘恢复说明事件(restoresSeq → dock 移除该行;surfaceOp 恒 "append")。 */
405
- export function buildRestoreNoticeEvent({ seq, time, turnStep, text, restoreSeq }) {
616
+ export function buildRestoreNoticeEvent({ seq, time, turnStep, text, restoreSeq, discard, version = 4 }) {
406
617
  return {
407
618
  type: "system/message",
408
619
  seq,
@@ -410,20 +621,34 @@ export function buildRestoreNoticeEvent({ seq, time, turnStep, text, restoreSeq
410
621
  data: {
411
622
  turn: turnStep.turn,
412
623
  step: turnStep.step,
413
- message: { id: randomUUID(), role: "system", content: [{ type: "text", text }] },
624
+ message: { id: randomUUID(), role: "system", source: messageSource("system", version), content: [{ type: "text", text }] },
414
625
  restoresSeq: restoreSeq,
626
+ ...(discard ? { discarded: true } : {}),
415
627
  },
416
628
  surfaceOp: "append",
417
629
  };
418
630
  }
419
631
 
420
- /** 磁盘重放事件(镜像引擎:无 id、干净文本无前缀(0.6.0 对齐 opencode)、surfaceOp "append")。 */
421
- export function buildReplayEvent({ seq, time, item }) {
632
+ /**
633
+ * 磁盘重放事件(镜像引擎:干净文本无前缀(0.6.0 对齐 opencode)、surfaceOp "append")。
634
+ *
635
+ * turnStep 由调用方传**打开的** turn/step(index.js 的 `plan.turnStep`,由
636
+ * `requireOpenTurnStep` 校验)。曾经硬编码 {turn:1,step:1} —— 那是同一类事故的
637
+ * "修了一半"版本:notice 用了正确坐标、replay 仍写死 1/1,一旦会话当前打开的
638
+ * turn ≠ 1,`assertReleasedV4Relationships` 报
639
+ * `assistant/message does not match an open turn and step` → **整份日志被拒**,
640
+ * 而 `diskAppend` 是裸 zstd 写、零校验,拦不住。
641
+ */
642
+ export function buildReplayEvent({ seq, time, item, turnStep, version = 4 }) {
643
+ const ts = turnStep && Number.isSafeInteger(turnStep.turn) && turnStep.turn > 0
644
+ && Number.isSafeInteger(turnStep.step) && turnStep.step > 0
645
+ ? turnStep
646
+ : (() => { throw new OpsError("buildReplayEvent: 缺少合法的打开 turn/step,拒绝写出注定无法加载的事件", 500); })();
422
647
  return {
423
648
  type: item.type,
424
649
  seq,
425
650
  time,
426
- data: { message: { role: item.role, content: [{ type: "text", text: item.text }] } },
651
+ data: replayEventData(item, ts, version),
427
652
  surfaceOp: "append",
428
653
  };
429
654
  }
@@ -0,0 +1,73 @@
1
+ /**
2
+ * 0.9.0 结构性回归:与 dsh 官方重复的能力必须**不存在**于本插件。
3
+ *
4
+ * 背景(专家核查结论):
5
+ * - 分支:官方有完整 `session/fork`(RPC typert.host.js:1512,atSeq 任意)
6
+ * + SessionStore.fork() + UI 消息级按钮 + 埋点 branch_session_click。
7
+ * 本插件的磁盘分支实现语义是**错的**:branch.js 删掉了 isSeeded(官方设 true)、
8
+ * 不写 inheritedEventCount、不调 buildForkSeed 补 closers → 子会话 turn 边界可能悬空。
9
+ * 官方 fork 失败通常意味着源会话在运行,正确做法是拒绝而非绕过引擎。
10
+ * - 导出:官方 /api/session.export 已有;但用户决定**直接删掉我们的 Markdown 导出**,
11
+ * 导出一律用官方(尽管两者格式不重叠:官方 ZIP 归档 vs 我们 Markdown)。
12
+ *
13
+ * 本测试锁死这两个能力不复活,并验证 branch 只走官方。
14
+ */
15
+ import test from 'node:test'
16
+ import assert from 'node:assert/strict'
17
+ import fs from 'node:fs'
18
+ import path from 'node:path'
19
+ import url from 'node:url'
20
+
21
+ const ROOT = path.resolve(path.dirname(url.fileURLToPath(import.meta.url)), '..')
22
+ const read = (p) => fs.readFileSync(path.join(ROOT, p), 'utf8')
23
+
24
+ test('src/branch.js 已删除(磁盘分支不再存在)', () => {
25
+ assert.equal(fs.existsSync(path.join(ROOT, 'src/branch.js')), false, 'src/branch.js 仍在 —— 磁盘分支实现未清除')
26
+ })
27
+
28
+ test('src/index.js 不再 import applyBranch', () => {
29
+ const s = read('src/index.js')
30
+ assert.ok(!/import\s*\{[^}]*applyBranch/.test(s), 'index.js 仍 import applyBranch')
31
+ assert.ok(!s.includes('applyBranch('), 'index.js 仍有 applyBranch( 调用')
32
+ })
33
+
34
+ test('后端不再有 /api/message-ops/branch 路由', () => {
35
+ const s = read('src/index.js')
36
+ assert.ok(!s.includes('/api/message-ops/branch'), 'branch 路由仍在')
37
+ })
38
+
39
+ test('后端不再有 /api/message-ops/export 路由', () => {
40
+ const s = read('src/index.js')
41
+ assert.ok(!s.includes('/api/message-ops/export'), 'export 路由仍在')
42
+ })
43
+
44
+ test('客户端不再有磁盘分支回落(只走官方 sessions.fork)', () => {
45
+ const s = read('src/client.js')
46
+ assert.ok(!s.includes('diskBranch'), 'client.js 仍有 diskBranch 回落')
47
+ assert.ok(!s.includes('/api/message-ops/branch'), 'client.js 仍调磁盘分支端点')
48
+ assert.ok(s.includes('fork'), 'client.js 应保留官方 fork 调用')
49
+ })
50
+
51
+ test('客户端不再有 fork.disk 文案', () => {
52
+ const s = read('src/client.js')
53
+ assert.ok(!s.includes('fork.disk'), 'fork.disk locale 仍在')
54
+ })
55
+
56
+ test('ops-core 不再导出 exportMarkdown', async () => {
57
+ const mod = await import('../src/ops-core.js')
58
+ assert.equal(mod.exportMarkdown, undefined, 'exportMarkdown 仍被导出')
59
+ })
60
+
61
+ test('message_ops tool 的 enum 不含 export', () => {
62
+ const s = read('src/index.js')
63
+ const m = s.match(/enum:\s*\[([^\]]+)\]/g) ?? [];
64
+ const enums = m.map((x) => x).join(' ');
65
+ assert.ok(!/["']export["']/.test(enums), `tool enum 仍含 export: ${enums}`)
66
+ })
67
+
68
+ test('message_ops tool 仍保留核心三操作(revert/delete/restore)', () => {
69
+ const s = read('src/index.js')
70
+ for (const op of ['revert', 'delete', 'restore']) {
71
+ assert.ok(s.includes(`"${op}"`), `tool enum 缺少 ${op}`)
72
+ }
73
+ })
@@ -110,33 +110,6 @@ test('路由级:写操作 text/plain 绕预检 → 415;超大 body → 413',
110
110
  assert.equal(res2.status, 413)
111
111
  })
112
112
 
113
- test('路由级:回环同源 GET export → 200 附件;非法 body JSON → 400', async () => {
114
- const id = 'session-99999999-8888-7777-6666-555555555555'
115
- const dir = path.join(process.env.DSH_HOME, 'sessions', 'proj-fence', id)
116
- fs.mkdirSync(dir, { recursive: true })
117
- const events = [
118
- { type: 'user/message', seq: 0, surfaceOp: 'append', data: { message: { role: 'user', content: [{ type: 'text', text: '围栏测试' }] } } },
119
- ]
120
- fs.writeFileSync(path.join(dir, 'session.v3.jsonl.zstd'), encodeSessionFile({ type: 'session', version: 3, id, createdAt: 1 }, events))
121
-
122
- const routes = makeCtx()
123
- const res1 = mockRes()
124
- await routes.get('/api/message-ops/export')(mockReq({
125
- url: `/api/message-ops/export?sessionId=${id}`,
126
- headers: { host: 'localhost:3080', origin: 'http://localhost:3080' },
127
- }), res1)
128
- assert.equal(res1.status, 200)
129
- assert.match(res1.headers['content-type'], /text\/markdown/)
130
- assert.match(res1.headers['content-disposition'], /attachment/)
131
- assert.match(res1.body, /围栏测试/)
132
-
133
- const res2 = mockRes()
134
- await routes.get('/api/message-ops/revert')(mockReq({
135
- method: 'POST', url: '/api/message-ops/revert',
136
- headers: { host: '127.0.0.1', 'content-type': 'application/json' }, body: '{broken',
137
- }), res2)
138
- assert.equal(res2.status, 400)
139
- })
140
113
 
141
114
  // --- 写端 replace 拼写运行时探测(P1 前向雷) -----------------------------------
142
115