@240xu/dsh-message-ops 0.23.0 → 0.47.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.
@@ -0,0 +1,301 @@
1
+ /**
2
+ * 服务端写路径的单一编排层(M1/M2,0.34.0)。
3
+ *
4
+ * 背景:`opsCommit` / `opsRestore` 的 live 与 disk 两条路径各自拼事件序列,
5
+ * seq/time 分配、窗口开合、重放 step 分配三处逻辑重复(见 docs/revert-restore-audit.md
6
+ * 「服务端 single-service」债务)。这里把**与落地方式无关**的那部分收敛为
7
+ * 「语义脚本」:
8
+ *
9
+ * buildCommitScript / buildRestoreScript → steps(replace / notice / replay / advance)
10
+ * materializeDisk(script, env) → 磁盘 batch(唯一的 seq/time 分配实现)
11
+ *
12
+ * 物化仍只经 ops-core 的 `buildMarkerEvent` / `buildRestoreNoticeEvent` /
13
+ * `buildReplayEvent`,不在这里自拼 surfaceOp(写端拼写探测是 ops-core 的模块级状态)。
14
+ * live 路径暂保持原实现,下一轮把同一份脚本接到 live surface 上。
15
+ * @module dsh-message-ops/ops-write
16
+ */
17
+
18
+ import {
19
+ restoreNoticeText,
20
+ restoreDiscardText,
21
+ noticeWindowPreamble,
22
+ noticeWindowPostamble,
23
+ buildMarkerEvent,
24
+ buildRestoreNoticeEvent,
25
+ buildReplayEvent,
26
+ applySurfaceReplace,
27
+ } from './ops-core.js'
28
+
29
+ /**
30
+ * 回撤/删除的说明文案(commit 与 tool 渲染共用)。
31
+ * @param {'revert'|'delete'} mode 操作
32
+ * @param {number} seq 目标 seq
33
+ * @param {{shadowedSeqs:number[]}} plan 规划结果
34
+ * @returns {string} 说明正文
35
+ */
36
+ export function commitNoticeText(mode, seq, plan) {
37
+ const n = Array.isArray(plan && plan.shadowedSeqs) ? plan.shadowedSeqs.length : 0
38
+ return mode === 'delete' ? `[消息删除] 已遮蔽 seq ${seq}` : `[消息回滚] 已回滚到 seq ${seq}(含)之后的 ${n} 个节点`
39
+ }
40
+
41
+ /**
42
+ * 构造 commit 的语义脚本。
43
+ * @param {{mode:'revert'|'delete', seq:number, win:{synthetic:boolean,turn:number,step:number}, plan:{startSeq:number,endSeq:number,shadowedSeqs:number[]}}} input
44
+ * @returns {{kind:'commit', win:object, plan:object, text:string, steps:Array}} 脚本
45
+ */
46
+ export function buildCommitScript({ mode, seq, win, plan }) {
47
+ return {
48
+ kind: 'commit',
49
+ win,
50
+ plan,
51
+ text: commitNoticeText(mode, seq, plan),
52
+ steps: [
53
+ {
54
+ form: 'replace',
55
+ startSeq: plan.startSeq,
56
+ endSeq: plan.endSeq,
57
+ shadowedSeqs: plan.shadowedSeqs,
58
+ turnStep: { turn: win.turn, step: win.step },
59
+ },
60
+ ],
61
+ }
62
+ }
63
+
64
+ /**
65
+ * 构造 restore 的语义脚本,并把「多助手独占 step」预先算进脚本。
66
+ *
67
+ * 宿主 UI 以 `(turn, step)` 作 assistant 消息 id,同一步只保留最后一条;所以每条
68
+ * 助手重放前若当前 step 已有助手,必须先 `advance` 到新 step。
69
+ * @param {{win:{synthetic:boolean,turn:number,step:number}, plan:object}} input 窗口与恢复计划
70
+ * @returns {{kind:'restore', win:object, plan:object, text:string, steps:Array, finalStep:number}} 脚本
71
+ */
72
+ export function buildRestoreScript({ win, plan }) {
73
+ const text = plan.discard ? restoreDiscardText(plan) : restoreNoticeText(plan)
74
+ // 0.40.0(srv-audit D3):记账 notice 必须**最后**写 —— 旧实现把它放在最前面并
75
+ // 按计划记账(`restoredSourceSeqs = 全部计划`),若中途重放失败,日志会谎称
76
+ // 全部恢复完(restoreProgress.complete=true),剩余消息永久 409 且区间仍遮蔽。
77
+ // 现在:先重放,全部成功后才写「完成」notice;失败路径由 applyScriptLive 按
78
+ // **实际成功的副本**补一条记账 notice(见其 catch)。
79
+ const steps = []
80
+ let step = plan.turnStep.step
81
+ let assistantInStep = false
82
+ const replays = plan.discard ? [] : plan.replayable
83
+ for (const item of replays) {
84
+ if (item.role === 'assistant' && assistantInStep) {
85
+ steps.push({ form: 'advance', turn: plan.turnStep.turn, fromStep: step, toStep: step + 1 })
86
+ step += 1
87
+ assistantInStep = false
88
+ }
89
+ steps.push({ form: 'replay', item, turnStep: { turn: plan.turnStep.turn, step } })
90
+ if (item.role === 'assistant') assistantInStep = true
91
+ }
92
+ steps.push({
93
+ form: 'notice',
94
+ text,
95
+ restoreSeq: plan.restoreSeq,
96
+ discard: plan.discard === true,
97
+ restoredSourceSeqs: plan.discard ? [] : plan.replayable.map(i => i.seq),
98
+ turnStep: { turn: plan.turnStep.turn, step },
99
+ })
100
+ return { kind: 'restore', win, plan, text, steps, finalStep: step }
101
+ }
102
+
103
+ /**
104
+ * 把语义脚本物化为磁盘事件 batch(seq/time 在此统一分配)。
105
+ *
106
+ * 时间口径与旧内联实现一致:preamble 从 baseTime 递增,notice/marker 紧随其后,
107
+ * 重放与 postamble 继续递增,保证同一批事件的 time 严格递增。
108
+ * @param {object} script buildCommitScript / buildRestoreScript 的结果
109
+ * @param {{startSeq:number, baseTime:number, version?:number}} env 起始 seq、基准时间、目标格式版本
110
+ * @returns {{batch:Array, markerSeq:(number|null), endStep:number}} 物化结果
111
+ */
112
+ export function materializeDisk(script, { startSeq, baseTime, version = 4 }) {
113
+ let cursor = startSeq
114
+ let time = baseTime
115
+ const batch = []
116
+ const push = (type, data) => {
117
+ batch.push({ type, seq: cursor++, time: time++, data })
118
+ }
119
+ for (const pre of noticeWindowPreamble(script.win)) push(pre.kind, pre.data)
120
+ let markerSeq = null
121
+ for (const step of script.steps) {
122
+ switch (step.form) {
123
+ case 'replace': {
124
+ const event = buildMarkerEvent({
125
+ seq: cursor++,
126
+ time: time++,
127
+ turnStep: step.turnStep,
128
+ text: script.text,
129
+ version,
130
+ startSeq: step.startSeq,
131
+ endSeq: step.endSeq,
132
+ shadowedSeqs: step.shadowedSeqs,
133
+ })
134
+ batch.push(event)
135
+ markerSeq = event.seq
136
+ break
137
+ }
138
+ case 'notice':
139
+ batch.push(
140
+ buildRestoreNoticeEvent({
141
+ seq: cursor++,
142
+ time: time++,
143
+ turnStep: step.turnStep,
144
+ version,
145
+ text: step.text,
146
+ restoreSeq: step.restoreSeq,
147
+ discard: step.discard,
148
+ restoredSourceSeqs: step.restoredSourceSeqs,
149
+ }),
150
+ )
151
+ break
152
+ case 'advance':
153
+ push('step/end', { turn: step.turn, step: step.fromStep })
154
+ push('step/start', { turn: step.turn, step: step.toStep })
155
+ break
156
+ case 'replay':
157
+ batch.push(buildReplayEvent({ seq: cursor++, time: time++, version, item: step.item, turnStep: step.turnStep }))
158
+ break
159
+ default:
160
+ throw new Error(`materializeDisk: unknown step form ${String(step.form)}`)
161
+ }
162
+ }
163
+ const endStep = script.kind === 'restore' ? script.finalStep : script.win.step
164
+ for (const post of noticeWindowPostamble({ ...script.win, step: endStep })) push(post.kind, post.data)
165
+ return { batch, markerSeq, endStep }
166
+ }
167
+
168
+
169
+ /**
170
+ * 把同一份语义脚本落到 live 引擎(0.34.2 M3)。
171
+ *
172
+ * 与 materializeDisk 的区别只有「怎么落地」:live 由引擎分配 seq/time,
173
+ * replace 必须走 applySurfaceReplace(写端 surfaceOp 拼写探测的唯一所有者),
174
+ * 其余步骤用 ops-core 的 builder 生成 data 再 `session.append`。
175
+ *
176
+ * 不变式:**要么没开窗口,要么窗口恰好闭合一次**。失败时内部先闭合再抛出,
177
+ * 调用方据 `state.windowOpened` 决定是否推进宿主 turn 游标。
178
+ * @param {object} session 宿主会话(append 接口)
179
+ * @param {object} script buildCommitScript / buildRestoreScript 的结果
180
+ * @param {{windowOpened?:boolean, closed?:boolean, emitted?:Array}} [state] 跨 catch 读取的落盘状态
181
+ * @returns {{windowOpened:boolean, closed:boolean, emitted:Array}} 状态(与入参同一对象)
182
+ */
183
+ export function applyScriptLive(session, script, state = {}) {
184
+ if (!state || typeof state !== 'object') throw new TypeError('applyScriptLive: state must be an object')
185
+ if (!Array.isArray(state.emitted)) state.emitted = []
186
+ if (typeof state.windowOpened !== 'boolean') state.windowOpened = false
187
+ if (typeof state.closed !== 'boolean') state.closed = false
188
+ // 0.35.2(BUG-1/2):记录**实际打开**的 step;失败时只能按它闭合。
189
+ // null = 没有打开的 step(preamble 未执行 / step/start 抛错 / advance 的 step/end 已写)。
190
+ if (!('stepOpened' in state)) state.stepOpened = null
191
+ // 0.39.5(srv-audit D2):postamble 被引擎拒绝时不能谎报 closed=true —— 日志会停在
192
+ // 「turn/step 开、无闭合」,宿主下一次真实轮次后整份日志不可加载。失败明细进
193
+ // state.closeFailures,调用方据此**不推进 turn 游标**并向上报 partial。
194
+ if (!Array.isArray(state.closeFailures)) state.closeFailures = []
195
+ // 0.40.0(srv-audit D3):记录**实际成功落盘**的重放源 seq —— 失败时据此补
196
+ // 记账 notice,进度才不会因为「按计划记账」而谎报全部恢复。
197
+ if (!Array.isArray(state.replayedSeqs)) state.replayedSeqs = []
198
+ if (!('accountingWritten' in state)) state.accountingWritten = false
199
+ const emit = (kind, data, opts) => {
200
+ const event = session.append(kind, data, opts)
201
+ if (event) state.emitted.push(event)
202
+ return event
203
+ }
204
+ const closeWindow = () => {
205
+ if (state.closed) return
206
+ // BUG-2:turn/start 都没写成功时绝不能闭合(否则落出无窗口的 step/end、turn/end)。
207
+ if (!state.windowOpened) {
208
+ state.closed = true
209
+ return
210
+ }
211
+ // BUG-1:只能用**实际打开的** step 闭合。写死 script.finalStep 会在
212
+ // 「notice/replay 抛错、advance 只走到一半」时落成 step/end@2 而日志只开到
213
+ // step 1,宿主判 `step/end does not match an open turn and step`(整份会话不可加载)。
214
+ const step = typeof state.stepOpened === 'number' ? state.stepOpened : null
215
+ const postamble = noticeWindowPostamble({ ...script.win, ...(step == null ? {} : { step }) })
216
+ for (const post of postamble) {
217
+ if (step == null && post.kind === 'step/end') continue
218
+ try {
219
+ emit(post.kind, post.data)
220
+ } catch (error) {
221
+ // 不让它覆盖已经成功的核心写入,但**必须记账**:窗口没闭合是真实状态。
222
+ state.closeFailures.push({ kind: post.kind, message: String((error && error.message) || error).slice(0, 200) })
223
+ }
224
+ }
225
+ state.closed = state.closeFailures.length === 0
226
+ }
227
+ try {
228
+ for (const pre of noticeWindowPreamble(script.win)) {
229
+ emit(pre.kind, pre.data)
230
+ if (pre.kind === 'turn/start') state.windowOpened = true
231
+ else if (pre.kind === 'step/start') state.stepOpened = pre.data && pre.data.step
232
+ }
233
+ for (const step of script.steps) {
234
+ switch (step.form) {
235
+ case 'replace': {
236
+ const event = applySurfaceReplace(session, step.startSeq, step.endSeq, step.shadowedSeqs, script.text, step.turnStep)
237
+ if (event) state.emitted.push(event)
238
+ break
239
+ }
240
+ case 'notice': {
241
+ const built = buildRestoreNoticeEvent({
242
+ seq: 0,
243
+ time: 0,
244
+ turnStep: step.turnStep,
245
+ version: 4,
246
+ text: step.text,
247
+ restoreSeq: step.restoreSeq,
248
+ discard: step.discard,
249
+ restoredSourceSeqs: step.restoredSourceSeqs,
250
+ })
251
+ emit(built.type, built.data, { surfaceOp: built.surfaceOp })
252
+ break
253
+ }
254
+ case 'advance':
255
+ emit('step/end', { turn: step.turn, step: step.fromStep })
256
+ state.stepOpened = null // step/end 已落,尚未开新 step
257
+ emit('step/start', { turn: step.turn, step: step.toStep })
258
+ state.stepOpened = step.toStep
259
+ break
260
+ case 'replay': {
261
+ const built = buildReplayEvent({ seq: 0, time: 0, version: 4, item: step.item, turnStep: step.turnStep })
262
+ emit(built.type, built.data, { surfaceOp: built.surfaceOp })
263
+ if (Number.isSafeInteger(step.item && step.item.seq)) state.replayedSeqs.push(step.item.seq)
264
+ break
265
+ }
266
+ default:
267
+ throw new Error(`applyScriptLive: unknown step form ${String(step.form)}`)
268
+ }
269
+ }
270
+ closeWindow()
271
+ return state
272
+ } catch (error) {
273
+ // 失败记账:重放已经落盘的副本必须被记录,否则进度会按「计划全部恢复」或
274
+ // 「全未恢复」两头都错(前者剩余轮永久 409,后者重试产生重复副本)。
275
+ const stepOpen = typeof state.stepOpened === 'number'
276
+ if (script.kind === 'restore' && stepOpen && state.replayedSeqs.length > 0 && !state.accountingWritten) {
277
+ try {
278
+ const pl = script.plan || {}
279
+ const partialText =
280
+ `[消息恢复] 恢复中断:已重放 ${state.replayedSeqs.length} 条,` +
281
+ `seq ${pl.startSeq}..${pl.endSeq} 区间其余消息仍可继续恢复`
282
+ const built = buildRestoreNoticeEvent({
283
+ seq: 0,
284
+ time: 0,
285
+ turnStep: { turn: script.win.turn, step: typeof state.stepOpened === 'number' ? state.stepOpened : script.win.step },
286
+ version: 4,
287
+ text: partialText,
288
+ restoreSeq: pl.restoreSeq,
289
+ discard: false,
290
+ restoredSourceSeqs: state.replayedSeqs.slice(),
291
+ })
292
+ emit(built.type, built.data, { surfaceOp: built.surfaceOp })
293
+ state.accountingWritten = true
294
+ } catch (accountingError) {
295
+ state.accountingFailed = String((accountingError && accountingError.message) || accountingError).slice(0, 200)
296
+ }
297
+ }
298
+ closeWindow()
299
+ throw error
300
+ }
301
+ }
@@ -18,6 +18,29 @@ import { constants, zstdCompressSync, zstdDecompressSync } from 'node:zlib'
18
18
 
19
19
  const ZSTD_MAGIC = 0xfd2fb528
20
20
 
21
+ /** 自有回撤/删除标记的正文前缀(legacy 身份;新事件另有 data.opsMarker)。 */
22
+ export const MARKER_TEXT_PREFIXES = ['[消息回滚]', '[消息删除]']
23
+
24
+ /**
25
+ * 事件是否**看起来像**本插件的回撤/删除标记(身份判定的共享单点)。
26
+ *
27
+ * 0.33.0(宿主契约):
28
+ * - 新事件带 `data.opsMarker === 'message-ops/v1'`(宿主透传额外 data 字段);
29
+ * - 旧事件靠正文前缀(legacy marker 的正文写在 message.content 里);
30
+ * - 宿主系统提示改写 / user rewind / compaction checkpoint 都没有这两个标记,
31
+ * 不得再被 `marker:true` 误分类(旧实现只看「有没有 replace」)。
32
+ *
33
+ * @param {object} e 单条事件
34
+ * @returns {boolean} 是否自有标记
35
+ */
36
+ export function looksLikeOwnMarker(e) {
37
+ if (!e || e.type !== 'system/message') return false
38
+ const d = e.data || {}
39
+ if (d.opsMarker === 'message-ops/v1') return true
40
+ const text = messageText(e) || (typeof d.text === 'string' ? d.text : '')
41
+ return MARKER_TEXT_PREFIXES.some(prefix => String(text).trimStart().startsWith(prefix))
42
+ }
43
+
21
44
  /** 带语义状态码的操作错误(单点:HTTP 直接映射 status,工具端转失败文本)。 */
22
45
  export class OpsError extends Error {
23
46
  constructor(message, status = 400) {
@@ -46,7 +69,11 @@ function textSegments(e) {
46
69
  /** 从 message 事件提取首个非空 text 块(listMessages / ops-core 共用单点)。 */
47
70
  export function messageText(e) {
48
71
  const segs = textSegments(e)
49
- return segs.length ? segs[0] : ''
72
+ if (segs.length) return segs[0]
73
+ // 0.33.0:插件把说明正文迁到 data.text(宿主把所有非空 system/message 当系统
74
+ // 提示更新,正文会进模型上下文并诱发重复 prompt)。读侧必须仍然能取到它。
75
+ if (e && e.type === 'system/message' && e.data && typeof e.data.text === 'string') return e.data.text
76
+ return ''
50
77
  }
51
78
 
52
79
  /**
@@ -60,7 +87,9 @@ export function messageText(e) {
60
87
  */
61
88
  export function messageTextFull(e) {
62
89
  const segs = textSegments(e)
63
- return segs.join('\n\n')
90
+ if (segs.length) return segs.join('\n\n')
91
+ if (e && e.type === 'system/message' && e.data && typeof e.data.text === 'string') return e.data.text
92
+ return ''
64
93
  }
65
94
 
66
95
  /** 与 DSH 宿主一致:帧带 checksum(ZSTD_c_checksumFlag=1)。 */
@@ -151,6 +180,7 @@ export function scanZstdFrames(buf) {
151
180
  */
152
181
  function collectHeaderAndEvents(text, events) {
153
182
  let header = null
183
+ let tornRecords = 0
154
184
  for (const line of text.split('\n')) {
155
185
  const t = line.trim()
156
186
  if (!t) continue
@@ -158,7 +188,8 @@ function collectHeaderAndEvents(text, events) {
158
188
  try {
159
189
  json = JSON.parse(t)
160
190
  } catch {
161
- continue /* torn record: skip */
191
+ tornRecords += 1 /* torn record: skip, but the writer must refuse to append */
192
+ continue
162
193
  }
163
194
  if (!header && json && typeof json === 'object' && json.type === 'session') {
164
195
  header = json
@@ -166,7 +197,7 @@ function collectHeaderAndEvents(text, events) {
166
197
  }
167
198
  events.push(json)
168
199
  }
169
- return header
200
+ return { header, tornRecords }
170
201
  }
171
202
 
172
203
  /**
@@ -175,26 +206,63 @@ function collectHeaderAndEvents(text, events) {
175
206
  */
176
207
  export function readSessionFile(file) {
177
208
  const buf = fs.readFileSync(file)
178
- const { frames } = scanZstdFrames(buf)
209
+ const { frames, tornStart } = scanZstdFrames(buf)
210
+ const tornTail = tornStart !== undefined
211
+ if (tornTail) {
212
+ // 0.32.0:尾部半帧(写入中被杀/断电)不是坏日志 —— 宿主把它当「未提交」丢弃并修复。
213
+ // 0.33.1:只有**真的从 tornStart 开始的半帧**才丢。完整帧之后只剩 1–3 字节残魔数时,
214
+ // 旧实现无条件 frames.pop() 会把最后一个**完整**帧也丢掉(读少一条),而宿主修复会保留它。
215
+ const last = frames[frames.length - 1]
216
+ if (last && last.start === tornStart && last.end === buf.length) frames.pop()
217
+ // 0.40.4(srv-audit D23):每次读盘都 warn 会在 GET 路径刷屏;按文件去重。
218
+ if (!tornTailWarned.has(file)) {
219
+ tornTailWarned.add(file)
220
+ console.warn('[message-ops] session log has a torn tail; ignoring the incomplete frame:', file)
221
+ }
222
+ }
179
223
  if (frames.length === 0) throw new Error('empty or header-less session log')
180
224
  const events = []
181
225
  let header = null
226
+ let tornRecords = 0
182
227
  for (const f of frames) {
183
228
  const text = zstdDecompressSync(buf.subarray(f.start, f.end)).toString('utf8')
184
229
  const found = collectHeaderAndEvents(text, events)
185
- if (!header) header = found
230
+ tornRecords += found.tornRecords
231
+ if (!header) header = found.header
186
232
  }
187
233
  if (!header) throw new Error(`session log ${file}: no {type:"session"} header line in any frame`)
188
- return { header, events }
234
+ return { header, events, tornTail, tornStart, tornRecords }
189
235
  }
190
236
 
191
237
  /** Read only the first zstd frame (header); a damaged body cannot block titles. */
192
238
  export function readSessionHeader(file) {
193
- const buf = fs.readFileSync(file)
239
+ // 0.33.4(perf-audit #4):只读前 64KB。标题解析每次 /messages 都会兜底调用,
240
+ // 旧实现 readFileSync 整份日志只为解压第 0 帧(15.8MB → 52.7ms,131MB 推算 430ms)。
241
+ // 头帧超过 64KB 或读不全时退回整份读(自愈,不改语义)。
242
+ const HEAD_BYTES = 64 * 1024
243
+ let buf
244
+ try {
245
+ const fd = fs.openSync(file, 'r')
246
+ try {
247
+ const size = fs.fstatSync(fd).size
248
+ const cap = Math.min(size, HEAD_BYTES)
249
+ buf = Buffer.allocUnsafe(cap)
250
+ const read = fs.readSync(fd, buf, 0, cap, 0)
251
+ buf = buf.subarray(0, read)
252
+ } finally {
253
+ fs.closeSync(fd)
254
+ }
255
+ } catch {
256
+ buf = fs.readFileSync(file)
257
+ }
194
258
  if (buf.length < 4 || buf.readUInt32LE(0) !== ZSTD_MAGIC) {
195
259
  throw new Error(`session log ${file}: no zstd header frame`)
196
260
  }
197
- const parsed = zstdFrameEnd(buf, 0)
261
+ let parsed = zstdFrameEnd(buf, 0)
262
+ if (parsed.error === 'truncated' && buf.length < fs.statSync(file).size) {
263
+ buf = fs.readFileSync(file)
264
+ parsed = zstdFrameEnd(buf, 0)
265
+ }
198
266
  if (parsed.error) throw new Error(`session log ${file}: ${parsed.error} header frame`)
199
267
  const text = zstdDecompressSync(buf.subarray(0, parsed.end)).toString('utf8')
200
268
  for (const line of text.split('\n')) {
@@ -258,7 +326,9 @@ export function findSessionDirs(sessionId) {
258
326
  for (const variant of variants) {
259
327
  const dir = path.join(root, slug.name, variant)
260
328
  try {
261
- if (!fs.statSync(dir).isDirectory()) continue
329
+ // 0.33.5(sec L4):拒绝符号链接目录,避免读/写到 sessions 根之外。
330
+ const st = fs.lstatSync(dir)
331
+ if (!st.isDirectory() || st.isSymbolicLink()) continue
262
332
  } catch {
263
333
  continue
264
334
  }
@@ -268,7 +338,8 @@ export function findSessionDirs(sessionId) {
268
338
  for (const name of ['session.v4.jsonl.zstd', 'session.v3.jsonl.zstd', 'session.jsonl.zstd']) {
269
339
  const candidate = path.join(dir, name)
270
340
  try {
271
- fs.statSync(candidate)
341
+ const st = fs.lstatSync(candidate)
342
+ if (!st.isFile() || st.isSymbolicLink()) continue
272
343
  logPath = candidate
273
344
  break
274
345
  } catch {
@@ -282,11 +353,6 @@ export function findSessionDirs(sessionId) {
282
353
  return found
283
354
  }
284
355
 
285
- /** 新建会话 id(与宿主同款 session-<uuid> 拼写)。 */
286
- export function newSessionId() {
287
- return `session-${crypto.randomUUID()}`
288
- }
289
-
290
356
  /** 从事件流提取消息级列表(user/assistant/system message + tool/call 摘要)。 */
291
357
  /**
292
358
  * turn 号 → 该 turn 首/末事件 seq 的映射。
@@ -346,7 +412,19 @@ export function listMessages(events) {
346
412
  // id:宿主持久化的消息身份(user 在 data.id、assistant 在 data.message.id),
347
413
  // 供 0.2.0 assistant-actions 槽(ownerProps={messageId})反查 seq。
348
414
  // marker:本事件是 revert/delete 落定的 replace 标记 → 对话框据此提供「恢复」模式。
349
- const isReplaceMarker = !!(e.surfaceOp && typeof e.surfaceOp === 'object' && e.surfaceOp.op === 'replace')
415
+ // 0.33.0:marker 只认**自有**回撤/删除标记。旧实现「任何 replace 都算 marker」,
416
+ // 把宿主系统提示改写(234 条/语料)、compaction checkpoint、甚至一条 user rewind
417
+ // 也算成活跃 marker;非自有 marker 的 restoreProgress 恒 null → 客户端渲染出
418
+ // 「点恢复必 409」的死行,并且会命中 /undo 的目标选择。
419
+ const isReplaceMarker =
420
+ e.type === 'system/message' &&
421
+ !!(e.surfaceOp && typeof e.surfaceOp === 'object' && e.surfaceOp.op === 'replace') &&
422
+ looksLikeOwnMarker(e)
423
+ const source = e.data && e.data.source
424
+ // 0.27.0:restore 重放写出的 user/message 带 `source.replayedFrom`(原消息 seq)。
425
+ // 它必须仍然渲染成用户消息(kind 仍是 'user'),但不能被当成「用户又说了话」
426
+ // —— markCommitted 据此把 marker 保持为未提交,dock 才不会一恢复就消失。
427
+ const replayed = e.type === 'user/message' && !!source && typeof source === 'object' && Object.hasOwn(source, 'replayedFrom')
350
428
  messages.push({
351
429
  seq: e.seq,
352
430
  type: e.type,
@@ -369,7 +447,9 @@ export function listMessages(events) {
369
447
  isReplaceMarker && e.surfaceOp.startSeq != null && e.surfaceOp.endSeq != null
370
448
  ? { start: e.surfaceOp.startSeq, end: e.surfaceOp.endSeq }
371
449
  : null,
372
- sourceKind: (e.data && e.data.source && e.data.source.kind) || null,
450
+ sourceKind: (source && source.kind) || null,
451
+ replayed,
452
+ replayedFrom: replayed && Number.isSafeInteger(source.replayedFrom) ? source.replayedFrom : null,
373
453
  // 0.4.2:恢复标记引用(restore 的 notice 事件带回它所恢复的标记 seq)
374
454
  restoresSeq: e.type === 'system/message' && e.data && typeof e.data.restoresSeq === 'number' ? e.data.restoresSeq : null,
375
455
  time: e.time ?? null,
@@ -446,7 +526,9 @@ export function readReplaceOp(e) {
446
526
  export function markCommitted(messages) {
447
527
  const realUserSeqs = []
448
528
  for (const m of messages) {
449
- if (m && m.type === 'user/message' && m.sourceKind === 'user') realUserSeqs.push(m.seq)
529
+ // 0.27.0:重放副本(source.replayedFrom)不是用户新说的话。把它算进来会让
530
+ // 「恢复」立刻提交 marker → dock 消失、也无法再继续按轮恢复。
531
+ if (m && m.type === 'user/message' && m.sourceKind === 'user' && m.replayed !== true) realUserSeqs.push(m.seq)
450
532
  }
451
533
  for (const m of messages) {
452
534
  if (!m || m.marker !== true) continue
@@ -493,8 +575,36 @@ export function computeShadowed(events) {
493
575
  return shadowed
494
576
  }
495
577
 
578
+ /** 已告警过撕裂尾的文件(0.40.4):读盘是热路径,同一文件只 warn 一次。 */
579
+ const tornTailWarned = new Set()
580
+
496
581
  const yieldToLoop = () => new Promise(resolve => setImmediate(resolve))
497
582
 
583
+ /**
584
+ * 只读日志**前缀**(0.39.2):给「未打开过、也没有投影标题」的会话取首条用户消息
585
+ * 做标题兜底。131MB/46480 事件的真实会话全量读要 +15–35s(审计实测),而首条用户
586
+ * 消息几乎总在头几帧 —— 逐帧解压,命中即停。
587
+ * @param {string} file 会话日志路径
588
+ * @param {{maxFrames?: number}} [options] 最多解压多少帧(默认 16),越界返回 `truncated: true`
589
+ * @returns {{header: object|null, events: object[], framesRead: number, truncated: boolean}}
590
+ * events 只含已解压帧里的事件(可能不完整,调用方不得据此算遮蔽/计数)
591
+ */
592
+ export function readSessionPrefix(file, { maxFrames = 16 } = {}) {
593
+ const buf = fs.readFileSync(file)
594
+ const { frames } = scanZstdFrames(buf)
595
+ if (frames.length === 0) throw new Error('empty or header-less session log')
596
+ const events = []
597
+ let header = null
598
+ let framesRead = 0
599
+ for (const f of frames) {
600
+ if (framesRead >= maxFrames) break
601
+ framesRead += 1
602
+ const found = collectHeaderAndEvents(zstdDecompressSync(buf.subarray(f.start, f.end)).toString('utf8'), events)
603
+ if (!header) header = found.header
604
+ }
605
+ return { header, events, framesRead, truncated: framesRead >= maxFrames }
606
+ }
607
+
498
608
  /**
499
609
  * readSessionFile 的异步变体:文件读取走 fs.promises.readFile(线程池,
500
610
  * 不阻塞事件循环——10.8MB 同步读是 19ms 的额外阻塞),逐帧解压循环每
@@ -507,15 +617,28 @@ const yieldToLoop = () => new Promise(resolve => setImmediate(resolve))
507
617
  */
508
618
  export async function readSessionFileAsync(file, { framesPerYield = 8, frameBudget = 500 } = {}) {
509
619
  const buf = await fs.promises.readFile(file)
510
- const { frames } = scanZstdFrames(buf)
620
+ const { frames, tornStart } = scanZstdFrames(buf)
621
+ const tornTail = tornStart !== undefined
622
+ if (tornTail) {
623
+ // 同 sync:只丢真正从 tornStart 开始的半帧;完整帧后的 1–3 字节残魔数保留全部帧。
624
+ const last = frames[frames.length - 1]
625
+ if (last && last.start === tornStart && last.end === buf.length) frames.pop()
626
+ // 0.40.4(srv-audit D23):每次读盘都 warn 会在 GET 路径刷屏;按文件去重。
627
+ if (!tornTailWarned.has(file)) {
628
+ tornTailWarned.add(file)
629
+ console.warn('[message-ops] session log has a torn tail; ignoring the incomplete frame:', file)
630
+ }
631
+ }
511
632
  if (frames.length === 0) throw new Error('empty or header-less session log')
512
633
  const events = []
513
634
  let header = null
635
+ let tornRecords = 0
514
636
  let framesSinceYield = 0
515
637
  for (const f of frames) {
516
638
  const text = zstdDecompressSync(buf.subarray(f.start, f.end)).toString('utf8')
517
639
  const found = collectHeaderAndEvents(text, events)
518
- if (!header) header = found
640
+ tornRecords += found.tornRecords
641
+ if (!header) header = found.header
519
642
  if (++framesSinceYield >= framesPerYield) {
520
643
  framesSinceYield = 0
521
644
  await yieldToLoop()
@@ -523,5 +646,5 @@ export async function readSessionFileAsync(file, { framesPerYield = 8, frameBudg
523
646
  }
524
647
  if (!header) throw new Error(`session log ${file}: no {type:"session"} header line in any frame`)
525
648
  const bodyFrames = frames.length - 1
526
- return { header, events, frameCount: bodyFrames, partial: bodyFrames > frameBudget }
649
+ return { header, events, frameCount: bodyFrames, partial: bodyFrames > frameBudget, tornTail, tornStart, tornRecords }
527
650
  }