@240xu/dsh-message-ops 0.8.0 → 0.9.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/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
  }
@@ -162,7 +308,7 @@ export function planRestore(events, restoreSeq, upToSeq, excludeSeqs) {
162
308
  // dock 会为这类标记常驻显示恢复按钮,409 死按钮 = 永远清不掉(实测 8 连 409)。
163
309
  // 改为返回空计划:applyRestore 仍追加说明 notice(含 restoresSeq)→ 标记停用、
164
310
  // dock 计数递减;语义如实:0 条重放 + 文案说明区间无 user/assistant 内容。
165
- return { restoreSeq, startSeq, endSeq, upToSeq: Number.isSafeInteger(upToSeq) ? cap : endSeq, replayable, skipped, turnStep: deriveTurnStep(events) };
311
+ return { restoreSeq, startSeq, endSeq, upToSeq: Number.isSafeInteger(upToSeq) ? cap : endSeq, replayable, skipped };
166
312
  }
167
313
 
168
314
  /**
@@ -183,21 +329,23 @@ export function restoreNoticeText(plan) {
183
329
 
184
330
  export function applyRestore(session, plan, { flush } = {}) {
185
331
  const eventSeqs = [];
186
- const notice = restoreNoticeText(plan);
332
+ const notice = plan.discard
333
+ ? `[消息操作] 回撤标记 seq ${plan.restoreSeq} 已停用(丢弃):区间内容保持遮蔽、未重放;日志原文仍在,可搜索`
334
+ : restoreNoticeText(plan);
187
335
  // 0.4.2:notice 事件携带 restoresSeq —— dock 据此把被恢复的标记从「活跃回撤」
188
336
  // 中移除(对齐 opencode clear 语义:恢复后不再显示为待恢复项)。
189
337
  const ts = plan.turnStep && Number.isSafeInteger(plan.turnStep.turn) && plan.turnStep.turn > 0
190
338
  ? plan.turnStep : { turn: 1, step: 1 };
191
339
  const noticeEvent = session.append(
192
340
  "system/message",
193
- { turn: ts.turn, step: ts.step, message: { id: randomUUID(), role: "system", content: [{ type: "text", text: notice }] }, restoresSeq: plan.restoreSeq, restoredSourceSeqs: plan.replayable.map((i) => i.seq) },
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 } : {}) },
194
342
  { surfaceOp: "append" },
195
343
  );
196
344
  if (noticeEvent && noticeEvent.seq != null) eventSeqs.push(noticeEvent.seq);
197
- for (const item of plan.replayable) {
345
+ for (const item of plan.discard ? [] : plan.replayable) {
198
346
  const event = session.append(
199
347
  item.type,
200
- { message: { role: item.role, content: [{ type: "text", text: item.text }] } },
348
+ replayEventData(item, ts),
201
349
  { surfaceOp: "append" },
202
350
  );
203
351
  if (event && event.seq != null) eventSeqs.push(event.seq);
@@ -205,7 +353,7 @@ export function applyRestore(session, plan, { flush } = {}) {
205
353
  if (flush) {
206
354
  try { flush(); } catch { /* flush 失败不回滚已接受的事件 */ }
207
355
  }
208
- return { restoredCount: plan.replayable.length, skipped: plan.skipped, eventSeqs };
356
+ return { restoredCount: plan.discard ? 0 : plan.replayable.length, skipped: plan.skipped, eventSeqs };
209
357
  }
210
358
 
211
359
  /**
@@ -238,7 +386,11 @@ export function restoreProgress(events, markerSeq) {
238
386
  const notices = list.filter((e) => e && e.data && e.data.restoresSeq === markerSeq);
239
387
  const restored = new Set();
240
388
  let legacy = false;
389
+ let discarded = false;
241
390
  for (const n of notices) {
391
+ // 0.8.1:显式丢弃(不重放内容、仅停用标记)也算完成——
392
+ // 用户场景"我都没回滚过,清掉测试遗留条",2709 条重放是另一种污染。
393
+ if (n.data.discarded === true) { discarded = true; continue; }
242
394
  const seqs = n.data && Array.isArray(n.data.restoredSourceSeqs) ? n.data.restoredSourceSeqs : null;
243
395
  if (!seqs) { legacy = true; continue; }
244
396
  for (const q of seqs) if (Number.isSafeInteger(q)) restored.add(q);
@@ -249,8 +401,9 @@ export function restoreProgress(events, markerSeq) {
249
401
  endSeq,
250
402
  restoredSeqs: Array.from(restored).sort((a, b) => a - b),
251
403
  pendingSeqs: pending,
252
- complete: legacy ? true : pending.length === 0,
404
+ complete: legacy || discarded ? true : pending.length === 0,
253
405
  legacy,
406
+ discarded,
254
407
  };
255
408
  }
256
409
 
@@ -278,51 +431,6 @@ export function pendingRestoreTurns(events, markerSeq) {
278
431
  return turns;
279
432
  }
280
433
 
281
- /**
282
- * exportMarkdown:把到 upToSeq(含)为止的事件流渲染为 Markdown。
283
- * user/assistant/system 消息按角色小节展开,工具调用折叠为单行引用。
284
- * @param {object} header 会话 header(readSessionFile)
285
- * @param {Array} events 全量事件
286
- * @param {number=} upToSeq 可选上界(含);缺省导出全部
287
- */
288
- export function exportMarkdown(header, events, upToSeq) {
289
- if (upToSeq !== undefined && (!Number.isSafeInteger(upToSeq) || upToSeq < 0)) {
290
- throw new OpsError("invalid seq", 400);
291
- }
292
- const sessionId = header && header.id ? header.id : "unknown";
293
- const scoped = upToSeq === undefined ? events : events.filter((e) => e && typeof e.seq === "number" && e.seq <= upToSeq);
294
- const lines = [];
295
- lines.push(`# DSH 会话导出:${sessionId}`);
296
- lines.push("");
297
- lines.push(`- 会话 id:${sessionId}`);
298
- if (header && header.parentSession) lines.push(`- 来源分支:${header.parentSession}`);
299
- lines.push(`- 导出范围:${upToSeq === undefined ? "全部" : `seq ≤ ${upToSeq}`}`);
300
- lines.push(`- 生成时间:${new Date().toISOString()}`);
301
- lines.push("");
302
- lines.push("---");
303
- lines.push("");
304
- for (const e of scoped) {
305
- if (!e || typeof e.seq !== "number") continue;
306
- if (e.type === "user/message" || e.type === "assistant/message" || e.type === "system/message") {
307
- const role = (e.data && e.data.message && e.data.message.role) ||
308
- (e.type === "user/message" ? "user" : e.type === "assistant/message" ? "assistant" : "system");
309
- const text = messageText(e);
310
- lines.push(`## [seq ${e.seq}] ${role}`);
311
- lines.push("");
312
- lines.push(text || "(无文本内容)");
313
- lines.push("");
314
- } else if (e.type === "tool/call") {
315
- const d = e.data || {};
316
- const name = d.name || (d.call && d.call.name) || "tool";
317
- const argsHint = d.call && d.call.arguments !== undefined
318
- ? JSON.stringify(d.call.arguments).slice(0, 80)
319
- : "";
320
- lines.push(`> [seq ${e.seq}] 🔧 工具调用:${name}${argsHint ? ` — ${argsHint}` : ""}`);
321
- lines.push("");
322
- }
323
- }
324
- return lines.join("\n");
325
- }
326
434
 
327
435
  // ---------------------------------------------------------------------------
328
436
  // HTTP 信任围栏(评审 P0):插件经 webServer.register 挂载的路由不经过宿主
@@ -426,32 +534,58 @@ export function isSurfaceMessageType(type) {
426
534
  }
427
535
 
428
536
  /** 磁盘可见节点:按事件流推导的 message 类 seq(剔除既有遮蔽)。 */
429
- 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) {
430
549
  const shadowed = computeShadowed(events);
431
550
  const nodes = [];
432
551
  for (const e of events) {
433
552
  if (!e || !Number.isSafeInteger(e.seq)) continue;
434
553
  if (shadowed.has(e.seq)) continue;
435
- if (isSurfaceMessageType(e.type)) nodes.push(e.seq);
554
+ if (isSurfaceType(e.type)) nodes.push(e.seq);
436
555
  }
437
556
  return nodes;
438
557
  }
439
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
+
440
570
  /** 磁盘版 planRevert:target 必须可见,遮蔽 target 之后(含)全部可见节点。 */
441
571
  export function planRevertFromEvents(events, targetSeq) {
572
+ // 目标用「消息」集合(回滚对象是消息),溯源用「全部 surface」集合(0.8.2 修正)
442
573
  const nodes = diskVisibleNodes(events);
443
574
  const startIdx = nodes.indexOf(targetSeq);
444
575
  if (startIdx === -1) throw new OpsError(`surface replace: start seq ${targetSeq} not found in surface`, 409);
445
- const shadowedSeqs = nodes.slice(startIdx);
576
+ const surface = diskSurfaceNodes(events);
577
+ const shadowedSeqs = surface.slice(surface.indexOf(targetSeq));
446
578
  if (shadowedSeqs.length === 0) throw new OpsError("nothing to revert", 409);
447
579
  return { startSeq: targetSeq, endSeq: shadowedSeqs[shadowedSeqs.length - 1], shadowedSeqs };
448
580
  }
449
581
 
450
582
  /** 磁盘版 planDelete:单条可见遮蔽。 */
451
583
  export function planDeleteFromEvents(events, seq) {
452
- if (!diskVisibleNodes(events).includes(seq)) {
584
+ const surface = diskSurfaceNodes(events);
585
+ if (!diskVisibleNodes(events).includes(seq) || !surface.includes(seq)) {
453
586
  throw new OpsError(`seq ${seq} not visible on current surface`, 409);
454
587
  }
588
+ // 单节点遮蔽:溯源就是它自己(0.8.2:也走完整 surface 判定,避免非 surface 节点)
455
589
  return { startSeq: seq, endSeq: seq, shadowedSeqs: [seq] };
456
590
  }
457
591
 
@@ -463,7 +597,7 @@ export function nextSeqFrom(events) {
463
597
  }
464
598
 
465
599
  /** 磁盘回撤/删除标记事件(字段镜像引擎金标准:type/seq/time/data/sourceEventSeqs/surfaceOp)。 */
466
- export function buildMarkerEvent({ seq, time, turnStep, text, startSeq, endSeq, shadowedSeqs }) {
600
+ export function buildMarkerEvent({ seq, time, turnStep, text, startSeq, endSeq, shadowedSeqs, version = 4 }) {
467
601
  return {
468
602
  type: "system/message",
469
603
  seq,
@@ -471,7 +605,7 @@ export function buildMarkerEvent({ seq, time, turnStep, text, startSeq, endSeq,
471
605
  data: {
472
606
  turn: turnStep.turn,
473
607
  step: turnStep.step,
474
- message: { id: randomUUID(), role: "system", content: [{ type: "text", text }] },
608
+ message: { id: randomUUID(), role: "system", source: messageSource("system", version), content: [{ type: "text", text }] },
475
609
  },
476
610
  sourceEventSeqs: [...shadowedSeqs],
477
611
  surfaceOp: { op: "replace", startSeq, endSeq },
@@ -479,7 +613,7 @@ export function buildMarkerEvent({ seq, time, turnStep, text, startSeq, endSeq,
479
613
  }
480
614
 
481
615
  /** 磁盘恢复说明事件(restoresSeq → dock 移除该行;surfaceOp 恒 "append")。 */
482
- export function buildRestoreNoticeEvent({ seq, time, turnStep, text, restoreSeq }) {
616
+ export function buildRestoreNoticeEvent({ seq, time, turnStep, text, restoreSeq, discard, version = 4 }) {
483
617
  return {
484
618
  type: "system/message",
485
619
  seq,
@@ -487,20 +621,34 @@ export function buildRestoreNoticeEvent({ seq, time, turnStep, text, restoreSeq
487
621
  data: {
488
622
  turn: turnStep.turn,
489
623
  step: turnStep.step,
490
- message: { id: randomUUID(), role: "system", content: [{ type: "text", text }] },
624
+ message: { id: randomUUID(), role: "system", source: messageSource("system", version), content: [{ type: "text", text }] },
491
625
  restoresSeq: restoreSeq,
626
+ ...(discard ? { discarded: true } : {}),
492
627
  },
493
628
  surfaceOp: "append",
494
629
  };
495
630
  }
496
631
 
497
- /** 磁盘重放事件(镜像引擎:无 id、干净文本无前缀(0.6.0 对齐 opencode)、surfaceOp "append")。 */
498
- 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); })();
499
647
  return {
500
648
  type: item.type,
501
649
  seq,
502
650
  time,
503
- data: { message: { role: item.role, content: [{ type: "text", text: item.text }] } },
651
+ data: replayEventData(item, ts, version),
504
652
  surfaceOp: "append",
505
653
  };
506
654
  }
@@ -164,6 +164,29 @@ export function newSessionId() {
164
164
  }
165
165
 
166
166
  /** 从事件流提取消息级列表(user/assistant/system message + tool/call 摘要)。 */
167
+ /**
168
+ * turn 号 → 该 turn 首/末事件 seq 的映射。
169
+ *
170
+ * 0.9.1:宿主把「回合页脚/过程条/错误」渲染成 node-key 为 `9:turn-tail<turn>` /
171
+ * `12:turn-process<turn>` / `10:turn-error<turn>` 的行 —— 它们的 id 就是 turn 号,
172
+ * 不带 seq。回滚边界落在某个 turn 之后时,这些行也必须一起藏,否则会留下
173
+ * 「孤立的分支/复制按钮」,视觉上像"只回滚了一半"。
174
+ *
175
+ * @returns {{starts: Map<number, number>, ends: Map<number, number>}}
176
+ */
177
+ export function turnBounds(events) {
178
+ const starts = new Map();
179
+ const ends = new Map();
180
+ for (const e of events) {
181
+ if (!e || typeof e.seq !== "number") continue;
182
+ const t = e.data && e.data.turn;
183
+ if (!Number.isSafeInteger(t)) continue;
184
+ if (e.type === "turn/start") starts.set(t, e.seq);
185
+ else if (e.type === "turn/end") ends.set(t, e.seq);
186
+ }
187
+ return { starts, ends };
188
+ }
189
+
167
190
  export function listMessages(events) {
168
191
  const messages = [];
169
192
  for (const e of events) {
@@ -193,13 +216,18 @@ export function listMessages(events) {
193
216
  ? e.data.restoresSeq : null,
194
217
  time: e.time ?? null,
195
218
  turn: (e.data && e.data.turn) ?? null,
219
+ // 0.9.1:assistant 节点的宿主 node-key 是 `14:assistant-step<turn>:<step>`,
220
+ // 没有 step 就无法把渲染行映射回日志 seq → 回滚时助手回答藏不掉。
221
+ step: (e.data && e.data.step) ?? null,
196
222
  });
197
223
  } else if (e.type === "tool/call") {
198
224
  const d = e.data || {};
199
225
  const name = d.name || (d.call && d.call.name) || "tool";
200
226
  messages.push({
201
227
  seq: e.seq, type: "tool/call", role: "tool", snippet: `[tool] ${name}`,
202
- time: e.time ?? null, turn: d.turn ?? null,
228
+ time: e.time ?? null, turn: d.turn ?? null, step: d.step ?? null,
229
+ // 0.9.1:工具节点的宿主 node-key 是 `9:tool-call<callId>`
230
+ id: d.callId ?? null,
203
231
  });
204
232
  }
205
233
  }
@@ -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
 
@@ -0,0 +1,62 @@
1
+ /**
2
+ * injected() 正则回归(0.9.0 修复)。
3
+ *
4
+ * 实机 bug:client.js 的 `norm()` 是 `replace(/\s+/g,'')` —— 删掉**全部**空白,
5
+ * 而 `injected()` 里的 `current\s+runtime\s+context` 跑在 norm 之后的字符串上,
6
+ * `\s+` 永远匹配不上 → 「Current runtime context…」伪 user 行漏进 DOM 配对,
7
+ * 导致按序配对错位(实测 [8,9,54],应为 [8,54])。
8
+ *
9
+ * 修法:injected() 必须对**未去空白的原始 snippet** 判定。
10
+ */
11
+ import test from 'node:test'
12
+ import assert from 'node:assert/strict'
13
+
14
+ // 与 client.js:957 保持一致的归一化
15
+ const norm = (x) => String(x || '').replace(/\s+/g, '')
16
+
17
+ /** 修复后的判定:吃 raw(原始 snippet),不依赖 norm */
18
+ export function injectedFixed(raw) {
19
+ return /^<system-reminder|current\s+runtime\s+context|^<system-Reminder/i.test(String(raw || ''))
20
+ }
21
+
22
+ /** 修复前的判定(回归对照:对 norm 后的串跑) */
23
+ function injectedBuggy(normalised) {
24
+ return /^<system-reminder|current\s+runtime\s+context|^<system-Reminder/i.test(String(normalised || ''))
25
+ }
26
+
27
+ test('injectedFixed:Current runtime context(大小写混合+空格)被识别', () => {
28
+ assert.equal(injectedFixed('Current runtime context. This snapshot supersedes earlier'), true)
29
+ assert.equal(injectedFixed('current runtime context'), true)
30
+ assert.equal(injectedFixed('Current runtime context'), true)
31
+ })
32
+
33
+ test('回归证明:对 norm 后的串判定必然失败(这正是原 bug)', () => {
34
+ const raw = 'Current runtime context. This snapshot supersedes earlier runtime-context snapshots.'
35
+ assert.equal(injectedBuggy(norm(raw)), false, 'norm 删掉空白后 \\s+ 永不匹配')
36
+ assert.equal(injectedFixed(raw), true)
37
+ })
38
+
39
+ test('injectedFixed:<system-reminder> 前缀仍被识别', () => {
40
+ assert.equal(injectedFixed('<system-reminder> A skill is a reusable set of instructions.'), true)
41
+ assert.equal(injectedFixed('<system-Reminder> The following workspace instructions'), true)
42
+ })
43
+
44
+ test('injectedFixed:真实用户消息不被误判', () => {
45
+ assert.equal(injectedFixed('继续,你把 mimo 的搞好'), false)
46
+ assert.equal(injectedFixed('基础价格按官方 api 价格来,缓存命中价格加上。'), false)
47
+ assert.equal(injectedFixed(''), false)
48
+ assert.equal(injectedFixed(null), false)
49
+ })
50
+
51
+ test('fetchRows 行构造:保留 raw 供 injected 判定', () => {
52
+ // 模拟 client.js:969 的 map:既要 norm 后的 sn(配对用),也要 raw(判定用)
53
+ const msgs = [
54
+ { seq: 8, role: 'user', snippet: '分配几个子代理把模型广场的模型价格' },
55
+ { seq: 9, role: 'user', snippet: 'Current runtime context. This snapshot supersedes earlier runtime-context snapshots.' },
56
+ { seq: 10, role: 'user', snippet: '<system-reminder> A skill is a reusable set of task-specific instructions.' },
57
+ { seq: 54, role: 'user', snippet: '基础价格按官方api价格来,缓存命中价格加上。' },
58
+ ]
59
+ const rows = msgs.map((m) => ({ seq: m.seq, sn: norm(m.snippet), raw: String(m.snippet ?? '') }))
60
+ .filter((r) => r.sn && !injectedFixed(r.raw))
61
+ assert.deepEqual(rows.map((r) => r.seq), [8, 54], '伪 user 行必须被滤掉')
62
+ })