@240xu/dsh-message-ops 0.24.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.
package/src/index.js CHANGED
@@ -7,12 +7,14 @@
7
7
  */
8
8
 
9
9
  import { zstdCompressSync } from 'node:zlib'
10
+ import { constants as fsConstants } from 'node:fs'
10
11
  import { open as openFile, truncate as truncateFile, stat as statFile } from 'node:fs/promises'
11
12
  import {
12
13
  isSessionId,
13
14
  sessionIdVariants,
14
15
  findSessionDirs,
15
16
  readSessionFileAsync,
17
+ readSessionHeader,
16
18
  listMessages,
17
19
  computeShadowed,
18
20
  messageText,
@@ -22,33 +24,38 @@ import {
22
24
  readReplaceOp,
23
25
  } from './session-file.js'
24
26
  import {
25
- restoreNoticeText,
27
+ applyScriptLive,
28
+ buildCommitScript,
29
+ buildRestoreScript,
30
+ materializeDisk,
31
+ } from './ops-write.js'
32
+ import {
26
33
  planRevertFromEvents,
27
34
  planDeleteFromEvents,
28
35
  nextSeqFrom,
29
- buildMarkerEvent,
30
- buildRestoreNoticeEvent,
31
- buildReplayEvent,
32
36
  planNoticeWindow,
33
- noticeWindowPreamble,
34
- noticeWindowPostamble,
35
37
  sessionLogOf,
36
38
  alignLiveTurnCursor,
39
+ liveAgentOf,
40
+ livePhaseError,
37
41
  OpsError,
38
42
  planRevert,
39
43
  planDelete,
44
+ isMarkerEvent,
40
45
  planRestore,
41
- applyRestore,
42
- applySurfaceReplace,
43
46
  restoreProgress,
44
47
  pendingRestoreTurns,
45
48
  buildRestoreIndex,
46
49
  restoreProgressFromIndex,
47
50
  pendingRestoreTurnsFromIndex,
51
+ supersededMarkers,
48
52
  isTrustedApiRequest,
49
53
  isJsonContentType,
50
54
  webAuthGate,
51
55
  } from './ops-core.js'
56
+ import { captureServices, serviceOf, resetCapturedServicesForTests } from './host-services.js'
57
+ import { applyDerivedBatch, derivedTextsOf, primeDerivedIncremental, NotIncrementalError } from './derived-incremental.js'
58
+ import { withSessionLock, withWriteLock } from './write-lock.js'
52
59
  import { deleteSessionToTrash, listTrash, restoreTrash, purgeTrash, resolveSessionTitle } from './session-trash.js'
53
60
 
54
61
  export const name = 'dsh-message-ops'
@@ -57,9 +64,90 @@ export const name = 'dsh-message-ops'
57
64
  // apply 内部容错探测,见 registerToolTolerantly。
58
65
  export const inject = []
59
66
 
67
+ /**
68
+ * 判定错误该回什么 HTTP 状态(0.39.6)。
69
+ *
70
+ * srv-audit D13:路由此前只认 `OpsError`,其余一律 500 —— 但**引擎/宿主契约拒绝**
71
+ * (surface replace 溯源不全、turn/step 关系闸、消息形状)本就是「请求与当前状态
72
+ * 冲突」,README 承诺 409,且客户端凭状态码区分「可重试」与「已失效」。
73
+ * 损坏日志(D17)同理:应 409 并附修复指引而不是 500。
74
+ * @param {unknown} err 抛出的错误
75
+ * @returns {number} HTTP 状态码
76
+ */
77
+ function errorStatusOf(err) {
78
+ if (err instanceof OpsError) return err.status
79
+ const message = String((err && err.message) || err)
80
+ if (
81
+ /invalid replace surfaceOp|does not open the expected turn|does not match an open turn|does not match an open step|must include every shadowed|is not a surface event|lacks an identified message|invalid message role|mismatched tool call ids/i.test(
82
+ message,
83
+ )
84
+ ) {
85
+ return 409
86
+ }
87
+ // 0.47.0(srv-audit E20):宿主/读取层的「日志本身坏了」是**状态问题**(可打开宿主修复),
88
+ // 不是内部 500。旧实现只匹配 /session log has/,漏了宿主 workspace 校验器的
89
+ // `corrupt session log "<path>"`(E20 实测列表/全文/写三路都落 500 并被 0.43.2 脱敏)。
90
+ if (/empty or header-less session log|invalid zstd frame|unsupported session version|session log has|corrupt session log|unsupported session format/i.test(message)) {
91
+ return 409
92
+ }
93
+ return 500
94
+ }
95
+
96
+ /**
97
+ * 严格解析整数查询参数(0.41.2,srv-audit D18)。
98
+ *
99
+ * `Number.parseInt('3abc')` → 3、`'1e3'` → 1:旧实现会把明显非法的参数静默截断成
100
+ * 合法值并 200,与「seq=x → 400」的既有契约不一致。只接受纯十进制整数串。
101
+ * @param {string|null} raw 原始字符串
102
+ * @returns {number|undefined} 合法整数或 undefined
103
+ */
104
+ function strictIntParam(raw) {
105
+ if (raw === null || raw === undefined) return undefined
106
+ const text = String(raw).trim()
107
+ if (!/^-?\d+$/.test(text)) return undefined
108
+ const value = Number(text)
109
+ return Number.isSafeInteger(value) ? value : undefined
110
+ }
111
+
112
+ /**
113
+ * 把错误压成**可回给客户端**的文案(0.43.2,srv-audit P3 + D8 泄露面)。
114
+ *
115
+ * - 领域错误(OpsError):保留 message,但去掉尾部内部诊断 `[resolve: …]`
116
+ * (诊断仍进服务端日志,便于排障;不再出现在响应体/工具结果里)。
117
+ * - 其它错误(500):响应只说 internal error,**不泄露绝对路径/内部标识**;
118
+ * 完整信息走 console.error。
119
+ * @param {unknown} err 抛出值
120
+ * @param {string} status 已判定的 HTTP 状态
121
+ * @param {string} [where] 日志用路由标签
122
+ * @returns {{status:number, error:string}} 响应状态与文案
123
+ */
124
+ function publicErrorOf(err, status, where = 'route') {
125
+ const raw = String((err && err.message) || err)
126
+ const diagAt = raw.indexOf('[resolve:')
127
+ const message = diagAt === -1 ? raw : raw.slice(0, diagAt).trim()
128
+ if (diagAt !== -1) {
129
+ console.warn('[message-ops] internal resolve diagnostic (' + where + '):', raw.slice(diagAt))
130
+ }
131
+ // 0.47.0(E20):损坏日志的宿主文案带绝对路径 —— 409 也要脱敏(细节进日志)。
132
+ if (status === 409 && /corrupt session log|invalid zstd frame|unsupported session (version|format)/i.test(message)) {
133
+ console.warn('[message-ops] unreadable session log (' + where + '):', message)
134
+ return { status, error: 'session log is corrupt or unreadable; open it once in the dsh host to repair, then retry' }
135
+ }
136
+ if (status === 500) {
137
+ console.error('[message-ops] internal error (' + where + '):', raw, err && err.stack ? String(err.stack).split('\n').slice(1, 4).join(' | ') : '')
138
+ return { status, error: 'internal error (details in the dsh server log)' }
139
+ }
140
+ return { status, error: message || 'request failed' }
141
+ }
142
+
60
143
  function sendJson(res, status, body) {
61
144
  const payload = JSON.stringify(body)
62
- res.writeHead(status, { 'content-type': 'application/json; charset=utf-8' })
145
+ // 会话内容属敏感数据:禁止中间层/浏览器缓存,并阻止内容嗅探。
146
+ res.writeHead(status, {
147
+ 'content-type': 'application/json; charset=utf-8',
148
+ 'cache-control': 'no-store',
149
+ 'x-content-type-options': 'nosniff',
150
+ })
63
151
  res.end(payload)
64
152
  }
65
153
 
@@ -81,8 +169,65 @@ async function readJsonBody(req) {
81
169
  }
82
170
  }
83
171
 
84
- /** 统一入口围栏:全部 /api/message-ops/* 路由先过这一层(三层信任 + 宿主 BrowserAuth cookie)。 */
172
+ /**
173
+ * 统一入口围栏:全部 /api/message-ops/* 路由先过这一层。
174
+ *
175
+ * 0.33.2:优先复用宿主 Connection 的 `requestRejection`(Host/Origin + BrowserAuth
176
+ * cookie + trustedHosts),与宿主 `/api` 完全同一条判据 —— 自研围栏只认回环 Host,
177
+ * 经 `--trusted-host` 暴露的站点(如 dsh.sepic.space)会整站 403,与 README 的承诺
178
+ * 不符。老宿主没有该服务时退回原有三层信任 + webAuthGate。
179
+ */
85
180
  async function fence(targetCtx, req, res) {
181
+ let connection = null
182
+ try {
183
+ connection = targetCtx && typeof targetCtx.get === 'function' ? targetCtx.get('connection') : null
184
+ } catch {
185
+ connection = null
186
+ }
187
+ // 0.41.1(srv-audit D16):宿主 0.2.2-rc.2 起移除了 `requestRejection`,改为
188
+ // `admit(request)`(返回 `{rejection?:number}` 或 `{peer}`)。旧实现直接退回
189
+ // 「只认回环 Host」的自研围栏 → 经 `--trusted-host` 暴露的站点整站 403
190
+ // (README 承诺的 trustedHosts 复用失效)。
191
+ //
192
+ // 0.46.1(P0):宿主 0.2.3 的 cordis 服务隔离会在 **admit 内部**读
193
+ // `connection.authentication` 时按调用方 fiber 校验 inject —— 本插件 `inject` 为空
194
+ // (tools 是可选增强,不能声明硬依赖),于是 admit 抛
195
+ // `cannot get property "connection.authentication" without inject`。
196
+ // 旧实现把这个异常当 `{rejection:401}` → **全站 401(GET 也挂)**。
197
+ // 现在:admit 抛错(非业务拒绝)时**降级**到静态围栏,不把内部异常翻译成拒绝;
198
+ // 真拒绝仍走 `{rejection}` 正常映射。
199
+ if (connection && typeof connection.admit === 'function' && typeof connection.requestRejection !== 'function') {
200
+ let admission = null
201
+ let admitFailed = false
202
+ try {
203
+ admission = connection.admit({ headers: req.headers, method: req.method, url: req.url })
204
+ } catch (err) {
205
+ admitFailed = true
206
+ noteAdmitFallback(err)
207
+ }
208
+ if (!admitFailed) {
209
+ if (admission && admission.rejection !== undefined && admission.rejection !== null) {
210
+ const status = typeof admission.rejection === 'number' ? admission.rejection : 403
211
+ sendJson(res, status, { ok: false, error: status === 401 ? 'unauthorized' : 'untrusted request origin (host connection rejected)' })
212
+ return false
213
+ }
214
+ return true
215
+ }
216
+ }
217
+ if (connection && typeof connection.requestRejection === 'function') {
218
+ let rejection
219
+ try {
220
+ rejection = connection.requestRejection({ headers: req.headers, method: req.method, url: req.url })
221
+ } catch {
222
+ rejection = 401
223
+ }
224
+ if (rejection !== undefined && rejection !== null && rejection !== false) {
225
+ const status = typeof rejection === 'number' ? rejection : 403
226
+ sendJson(res, status, { ok: false, error: status === 401 ? 'unauthorized' : 'untrusted request origin (host connection rejected)' })
227
+ return false
228
+ }
229
+ return true
230
+ }
86
231
  if (!isTrustedApiRequest(req)) {
87
232
  sendJson(res, 403, { ok: false, error: 'untrusted request origin (loopback Host + same-origin only)' })
88
233
  return false
@@ -98,6 +243,22 @@ async function fence(targetCtx, req, res) {
98
243
  return true
99
244
  }
100
245
 
246
+ /**
247
+ * admit 不可用(宿主服务隔离未声明 inject)时的降级告警(进程内只告警一次)。
248
+ * @param {unknown} err 原始异常
249
+ * @returns {void}
250
+ */
251
+ function noteAdmitFallback(err) {
252
+ if (__admitFallbackWarned) return
253
+ __admitFallbackWarned = true
254
+ console.warn(
255
+ '[message-ops] connection.admit unavailable to this plugin fiber (' +
256
+ String((err && err.message) || err) +
257
+ '); falling back to the loopback/same-origin fence. --trusted-host sites may need the host to ' +
258
+ 'admit this plugin (see README compatibility notes).',
259
+ )
260
+ }
261
+
101
262
  /** 写操作围栏:入口信任 + Content-Type 必须 application/json(CSRF 纵深)。 */
102
263
  async function writeFence(targetCtx, req, res) {
103
264
  if (!(await fence(targetCtx, req, res))) return false
@@ -118,14 +279,32 @@ async function readFencedBody(req, res) {
118
279
  }
119
280
  }
120
281
 
121
- /** 从 sessions 注册表解析(两种 id 拼写都试)。 */
122
- let __resolveSource = null // 诊断:最近一次 resolveSession 的失败原因
123
- function resolveSession(ctx, sessionId) {
282
+ /**
283
+ * 从 sessions 注册表解析(两种 id 拼写都试)。
284
+ *
285
+ * @param ctx - 宿主 ctx
286
+ * @param sessionId - 会话 id(`uuid` / `session-<uuid>` 两种拼写都试)
287
+ * @param diag - 可选的诊断出参:`{ why: string }`。传了才会记录**为什么**成/败
288
+ * (只在需要把原因拼进错误信息的失败路径上传,成功路径零字符串开销)。
289
+ * @returns live SessionFace,或 `undefined`(未命中)
290
+ */
291
+ // 0.37.4:宿主 0.2.3 的 fiber 隔离让 `ctx.get('agents'|'sessions')` 在插件 fiber 上
292
+ // 可能恒为 undefined(真机日志:boot 期全 undefined,写合成 turn 时 agents 仍不可见)。
293
+ // cordis 的 `ctx.inject(deps, fn)` 回调拿到的是**注入命名空间**,服务一定在其同名属性
294
+ // 上 —— 用它把两个关键服务捕获一次,供 resolveSession / alignLiveTurnCursor 复用。
295
+ function resolveSession(ctx, sessionId, diag) {
124
296
  // 宿主自己的取法是 `this.ctx.sessions.get(id)`(api-session-controller 同款);
125
297
  // 实测 `ctx.get("sessions")` 在 inject 子 fiber 下解析到的注册表**查不到视图已
126
298
  // 加载的会话**(dock 已渲染但 get 双变体 miss —— agents.get 同 ctx 却命中),
127
299
  // 故属性优先、ctx.get 兜底,两处都试全变体。
128
300
  const candidates = []
301
+ // 诊断只写进调用方传进来的 diag 袋子(原先写进程级全局变量 → 0 读取方,
302
+ // 等于「排障线索被扔进黑洞」;现在由失败路径拼进 OpsError)。
303
+ const note = msg => {
304
+ if (diag) diag.why = msg
305
+ }
306
+ const capturedSessions = serviceOf(ctx, 'sessions')
307
+ if (capturedSessions) candidates.push(['captured', capturedSessions])
129
308
  try {
130
309
  if (ctx && ctx.sessions) candidates.push(['prop', ctx.sessions])
131
310
  } catch {
@@ -138,7 +317,7 @@ function resolveSession(ctx, sessionId) {
138
317
  /* absent */
139
318
  }
140
319
  if (candidates.length === 0) {
141
- __resolveSource = 'no-sessions-service'
320
+ note('no-sessions-service')
142
321
  return undefined
143
322
  }
144
323
  const variants = sessionIdVariants(sessionId)
@@ -151,7 +330,7 @@ function resolveSession(ctx, sessionId) {
151
330
  for (const variant of variants) {
152
331
  const s = svc.get(variant)
153
332
  if (s !== undefined) {
154
- __resolveSource = 'hit via ' + src + '.get ' + String(variant).slice(0, 24)
333
+ note('hit via ' + src + '.get ' + String(variant).slice(0, 24))
155
334
  return s
156
335
  }
157
336
  }
@@ -163,7 +342,7 @@ function resolveSession(ctx, sessionId) {
163
342
  if (Array.isArray(arr)) {
164
343
  const hit = arr.find(x => x && (variants.includes(x.id) || variants.includes(x.sessionId)))
165
344
  if (hit) {
166
- __resolveSource = 'hit via ' + src + '.list() n=' + arr.length
345
+ note('hit via ' + src + '.list() n=' + arr.length)
167
346
  return hit
168
347
  }
169
348
  tried.push(
@@ -186,7 +365,7 @@ function resolveSession(ctx, sessionId) {
186
365
  }
187
366
  tried.push(src + ':miss')
188
367
  }
189
- __resolveSource = tried.join(',') + ' tried=' + variants.length + ' first=' + String(variants[0]).slice(0, 30)
368
+ note(tried.join(',') + ' tried=' + variants.length + ' first=' + String(variants[0]).slice(0, 30))
190
369
  return undefined
191
370
  }
192
371
 
@@ -199,9 +378,13 @@ function resolveSession(ctx, sessionId) {
199
378
  * 会话 → 所有变更操作 404「not found in registry」。官方越界获取通道是
200
379
  * retain(target, {source}) → await ready → binding.session(ISessions 契约);
201
380
  * 引用在 mutation 完成后 release(final reference 触发 teardown,须先 flush)。
381
+ *
382
+ * @param diag - 可选诊断出参 `{ why }`:记录「live 面为什么没拿到」。原先这份
383
+ * 信息写在一个进程级诊断变量里,且**全仓 0 个读取方**(审计 §1.6)—— 等于每次
384
+ * 失败都重新拼一遍字符串却扔进黑洞。现在只由失败路径收集,并真的拼进错误信息。
202
385
  */
203
- async function acquireSession(ctx, sessionId) {
204
- const direct = resolveSession(ctx, sessionId)
386
+ async function acquireSession(ctx, sessionId, diag) {
387
+ const direct = resolveSession(ctx, sessionId, diag)
205
388
  if (direct !== undefined) return { session: direct, release() {} }
206
389
  const owners = []
207
390
  // reflect 层:api-session-controller 把 ISessions(ClientSessions,带 retain)经
@@ -229,7 +412,7 @@ async function acquireSession(ctx, sessionId) {
229
412
  owners.length === 0
230
413
  ? 'no-owner (prop-absent && get-absent)'
231
414
  : owners.map(([src, o]) => src + ':no-retain(' + (o == null ? 'null' : typeof o) + ')').join(',')
232
- __resolveSource = (__resolveSource || '') + ' | ISessions:' + why
415
+ if (diag) diag.why = (diag.why || '') + ' | ISessions:' + why
233
416
  return null
234
417
  }
235
418
  const isess = holders[0][1]
@@ -239,7 +422,7 @@ async function acquireSession(ctx, sessionId) {
239
422
  const binding = await ref.ready
240
423
  const face = binding && binding.session
241
424
  if (!face) {
242
- __resolveSource = 'retain-ready-no-session-face'
425
+ if (diag) diag.why = 'retain-ready-no-session-face'
243
426
  try {
244
427
  ref.release()
245
428
  } catch {
@@ -247,7 +430,6 @@ async function acquireSession(ctx, sessionId) {
247
430
  }
248
431
  return null
249
432
  }
250
- __resolveSource = 'acquired via ISessions.retain'
251
433
  return {
252
434
  session: face,
253
435
  release: () => {
@@ -259,7 +441,7 @@ async function acquireSession(ctx, sessionId) {
259
441
  },
260
442
  }
261
443
  } catch (e) {
262
- __resolveSource = 'retain-failed: ' + String(e && e.message).slice(0, 80)
444
+ if (diag) diag.why = 'retain-failed: ' + String(e && e.message).slice(0, 80)
263
445
  if (ref) {
264
446
  try {
265
447
  ref.release()
@@ -272,6 +454,8 @@ async function acquireSession(ctx, sessionId) {
272
454
  }
273
455
 
274
456
  let __runningSource = null // 诊断:最近一次 isRunning 的判定来源
457
+ /** admit 降级告警只打一次(0.46.1 P0:0.2.3 服务隔离下 admit 会抛)。 */
458
+ let __admitFallbackWarned = false
275
459
  /**
276
460
  * 用**宿主内存日志**补算 marker's committed(0.10.5 · R2 的根治)。
277
461
  *
@@ -314,7 +498,11 @@ function applyLiveCommitted(messages, live) {
314
498
  for (const e of log) {
315
499
  if (!e || typeof e.seq !== 'number' || e.seq <= maxUserSeq) continue
316
500
  if (e.type !== 'user/message') continue
317
- if (((e.data || {}).source || {}).kind !== 'user') continue
501
+ const source = (e.data || {}).source
502
+ if (!source || source.kind !== 'user') continue
503
+ // 0.27.0:restore 重放的 user/message 仍是 kind:'user'(否则界面上不可见),
504
+ // 用 replayedFrom 自识别;不算「真实用户输入」,否则恢复后 dock 立刻消失。
505
+ if (Object.hasOwn(source, 'replayedFrom')) continue
318
506
  maxUserSeq = e.seq
319
507
  }
320
508
  if (maxUserSeq < 0) return false
@@ -337,8 +525,13 @@ function isRunning(ctx, sessionId) {
337
525
  // running: this.ctx.agents.get(session.id)?.status === "running"
338
526
  // 原实现把「agents 注册表有条目」直接当 running —— 会话仅在视图中打开
339
527
  // 就有条目 → 打开即 409 锁死所有变更操作。必须再比对 status。
528
+ // 0.42.1(srv-audit D21):诊断变量是进程级的,旧实现不复位 → 一次请求的诊断会
529
+ // 串到下一次(跨会话运行中判定看似随机)。每个请求入口先清空。
530
+ __runningSource = ''
340
531
  try {
341
532
  const candidates = []
533
+ const fromCaptured = serviceOf(ctx, 'agents')
534
+ if (fromCaptured) candidates.push(fromCaptured)
342
535
  try {
343
536
  if (ctx && ctx.agents) candidates.push(ctx.agents)
344
537
  } catch {
@@ -382,7 +575,9 @@ async function diskAppend(logPath, newEvents) {
382
575
  if (!Array.isArray(newEvents) || newEvents.length === 0) throw new OpsError('diskAppend: empty batch', 400)
383
576
  const jsonl = newEvents.map(e => JSON.stringify(e)).join('\n') + '\n'
384
577
  const frame = zstdCompressSync(Buffer.from(jsonl, 'utf8'))
385
- const handle = await openFile(logPath, 'a')
578
+ // 0.33.5(sec L4):追加写不跟随符号链接(Windows 无 O_NOFOLLOW 时退回普通追加)。
579
+ const noFollow = fsConstants.O_NOFOLLOW | fsConstants.O_APPEND | fsConstants.O_CREAT | fsConstants.O_WRONLY
580
+ const handle = await openFile(logPath, Number.isSafeInteger(noFollow) ? noFollow : 'a')
386
581
  let closed = false
387
582
  const closeHandle = async () => {
388
583
  if (closed) return
@@ -397,7 +592,14 @@ async function diskAppend(logPath, newEvents) {
397
592
  } catch (error) {
398
593
  try {
399
594
  await closeHandle()
400
- await truncateFile(logPath, before)
595
+ // 0.33.1:只在「文件确实是 before + 我们这一帧」时才回滚。并发写者可能已在
596
+ // 之后追加了自己的帧,无条件 truncate(before) 会把对方的数据一并截掉。
597
+ const after = await statFile(logPath)
598
+ if (after.size === before + frame.length) {
599
+ await truncateFile(logPath, before)
600
+ } else {
601
+ throw new Error(`append rollback skipped: size ${after.size} != expected ${before + frame.length} (concurrent writer?)`)
602
+ }
401
603
  } catch (rollbackError) {
402
604
  throw new AggregateError([error, rollbackError], `failed to roll back append to "${logPath}"`)
403
605
  }
@@ -408,16 +610,153 @@ async function diskAppend(logPath, newEvents) {
408
610
  }
409
611
  }
410
612
 
411
- function flushSessions(ctx, session) {
412
- const sessions = ctx.get('sessions')
413
- if (sessions && typeof sessions.flush === 'function') {
414
- try {
415
- return sessions.flush(session)
416
- } catch {
417
- /* flush 失败不回滚已接受的事件 */
613
+ /**
614
+ * flush 宿主持久化并**吞掉失败**(不把已成功的写入改成失败)。
615
+ *
616
+ * 0.33.1:必须 await —— 旧实现只 catch 同步 throw,`sessions.flush()` 返回的
617
+ * rejected promise 被裸丢弃;Node 24 默认 `--unhandled-rejections=throw`,
618
+ * 一次 fsync EIO/磁盘满就会打死整个 dsh 进程。await 同时把「响应返回」放到
619
+ * 落盘之后,紧接的 restore 才能读到刚写的 marker。
620
+ * @param {object} ctx 插件上下文
621
+ * @param {object} session 目标会话
622
+ * @returns {Promise<void>} 无返回值;失败只告警
623
+ */
624
+ async function flushSessions(ctx, session) {
625
+ const sessions = serviceOf(ctx, 'sessions')
626
+ if (!sessions || typeof sessions.flush !== 'function') {
627
+ // 0.39.4:服务不可见时 flush 不会执行 —— 事件只留在内存(崩溃即丢 marker)。
628
+ // 原来是静默 return,现在留一行诊断(同 agents 的一次性警告口径)。
629
+ if (!flushMissingWarned) {
630
+ flushMissingWarned = true
631
+ console.warn('[message-ops] host sessions service is not visible to this plugin; writes are not flushed to the persist layer')
418
632
  }
633
+ return
634
+ }
635
+ try {
636
+ await sessions.flush(session)
637
+ } catch (error) {
638
+ console.warn('[message-ops] flush failed (events stay in memory):', error && error.message)
639
+ }
640
+ }
641
+
642
+ // ── 0.33.1 磁盘写硬化 ──────────────────────────────────────────────────────
643
+ // 同一 logPath 的 read→plan→append 必须串行:两个并发请求各自读到同一 maxSeq,
644
+ // 会各写一份 seq,宿主加载判 `event seq N is not dense` → 整份会话打不开
645
+ // (已用宿主 format catalog 复现)。跨进程仍需宿主 flock,这里是进程内第一道闸。
646
+
647
+ /**
648
+ * 在同一会话日志上串行执行一次写事务。
649
+ * @param {string} key 会话日志绝对路径
650
+ * @param {Function} task 事务体(内部必须重新读盘,不得复用锁外快照)
651
+ * @returns {Promise<any>} task 的返回值
652
+ */
653
+ /**
654
+ * 进程内「读自己刚写的」缓冲(0.40.2,srv-audit D4 第二层)。
655
+ *
656
+ * 宿主把 live append 异步批窗落盘;插件若在同一批窗内再次规划(只读盘兜底),
657
+ * 会看不到刚写的事件 → 同一 marker 被二次恢复(重复副本)。这里按 logPath 记录
658
+ * 最近一次写入的事件,读盘规划时按 seq 合并;一旦磁盘已包含这些 seq 即自动失效。
659
+ */
660
+ const pendingLiveWrites = new Map() // logPath -> { events: object[], at: number }
661
+ const PENDING_LIVE_TTL_MS = 30_000
662
+
663
+ function notePendingLiveWrite(logPath, events) {
664
+ if (!Array.isArray(events) || events.length === 0) return
665
+ const kept = (events || []).filter(e => e && Number.isSafeInteger(e.seq))
666
+ if (kept.length === 0) return
667
+ pendingLiveWrites.set(logPath, { events: kept.slice(), at: Date.now() })
668
+ }
669
+
670
+ function mergePendingLiveWrites(logPath, diskEvents) {
671
+ const entry = pendingLiveWrites.get(logPath)
672
+ const base = Array.isArray(diskEvents) ? diskEvents : []
673
+ if (!entry) return base
674
+ if (Date.now() - entry.at > PENDING_LIVE_TTL_MS) {
675
+ pendingLiveWrites.delete(logPath)
676
+ return base
677
+ }
678
+ const maxSeq = base.length > 0 ? base[base.length - 1].seq : -1
679
+ const fresh = entry.events.filter(e => e.seq > maxSeq)
680
+ if (fresh.length === 0) {
681
+ pendingLiveWrites.delete(logPath)
682
+ return base
683
+ }
684
+ return base.concat(fresh)
685
+ }
686
+
687
+
688
+
689
+ /**
690
+ * live 合成 turn 的 agents 服务探测(**告警,不阻断**)。
691
+ *
692
+ * 0.33.5 曾在这里 fail-closed(409),真机证明本机 profile 的插件上下文根本拿不到
693
+ * `agents`(`sessions/sessionController/...` 也多为 undefined)—— 一旦阻断,所有
694
+ * 回撤/删除/恢复都不可用。宿主在加载/唤醒时会从日志重建生命周期,实测照写不会
695
+ * 让日志不可加载,因此恢复 fail-open,只在首次缺失时告警一次。
696
+ *
697
+ * 残留风险(文档化):agents 缺失时既无法检测 maintenance 相位、也无法推进
698
+ * `lastTurn`;若宿主随后用旧游标开新 turn,可能出现重号。该风险在本机 profile
699
+ * 下不可消除(没有可用 seam),只能观察日志告警。
700
+ * @param {object} ctx 插件上下文
701
+ * @param {object} session 目标会话
702
+ * @param {{synthetic?:boolean}} win 窗口规划
703
+ * @returns {boolean} agents 服务是否可见
704
+ */
705
+ let agentsMissingWarned = false
706
+ let flushMissingWarned = false
707
+ function agentsServiceVisible(ctx, session, win) {
708
+ if (!win || win.synthetic !== true) return true
709
+ const agents = serviceOf(ctx, 'agents')
710
+ if (!agents && !agentsMissingWarned) {
711
+ agentsMissingWarned = true
712
+ console.warn(
713
+ '[message-ops] host agents service is not visible to this plugin; synthetic turns are written without advancing the host turn cursor',
714
+ )
715
+ }
716
+ return !!agents
717
+ }
718
+
719
+ /**
720
+ * 磁盘写前置闸:撕裂尾 / 完整帧内撕裂行 / 非 v4 一律拒绝。
721
+ *
722
+ * 撕裂尾后直接 append 会让新帧与残字节拼成非法帧界(宿主扫描器同样抛
723
+ * `invalid frame magic`),整份日志从此不可加载;正确做法是让宿主打开一次
724
+ * 会话完成修复,用户再重试。v3 的 system/message 必须带 plugin source,
725
+ * 而我们的 source 形状按 v4 写,写一次就会让 v3 校验器拒绝整份日志。
726
+ * @param {{header:object,tornTail:boolean,tornRecords:number}} read 读盘结果
727
+ * @param {string} logPath 会话日志路径(仅用于报错)
728
+ */
729
+ function assertWritableSessionLog(read, logPath) {
730
+ const raw = read && read.header ? read.header.version : undefined
731
+ // 0.41.0(srv-audit D14):旧实现只挡「整数且 ≠4」。header 无 version(旧单帧格式)
732
+ // 或 version 是字符串 "4" 时会被放行,并按「v3 形状」写出 marker(正文进
733
+ // message.content、无 opsMarker)—— 在 v4 宿主里会被当成系统提示注入模型。
734
+ // 磁盘写只接受**明确的数值 v4**;其它一律 409 并给出修复指引。
735
+ if (raw === undefined) {
736
+ throw new OpsError(
737
+ `session log ${logPath} has no numeric format version; disk writes only support v4 — open the session once in the host so it migrates, then retry`,
738
+ 409,
739
+ )
740
+ }
741
+ const version = Number.isSafeInteger(raw) ? raw : Number.NaN
742
+ if (!Number.isSafeInteger(version) || version !== 4) {
743
+ throw new OpsError(
744
+ `session log ${logPath} is format v${version}; disk writes only support v4 (v3 requires a plugin source shape). Open the session once in the host so it migrates, then retry`,
745
+ 409,
746
+ )
747
+ }
748
+ if (read && read.tornTail) {
749
+ throw new OpsError(
750
+ `session log ${logPath} has a torn tail (uncommitted write). Open the session once in the host to repair it, then retry`,
751
+ 409,
752
+ )
753
+ }
754
+ if (read && read.tornRecords > 0) {
755
+ throw new OpsError(
756
+ `session log ${logPath} contains ${read.tornRecords} torn record(s) inside complete frames; refusing to append until the host repairs it`,
757
+ 409,
758
+ )
419
759
  }
420
- return undefined
421
760
  }
422
761
 
423
762
  // ---------------------------------------------------------------------------
@@ -433,6 +772,24 @@ function pickSessionDir(sessionId) {
433
772
  return dirs[0]
434
773
  }
435
774
 
775
+ /**
776
+ * 把「live 面为什么没拿到」拼进 OpsError 消息(审计 §1.6 + §2.2)。
777
+ *
778
+ * 背景:0.5.6 排障期把原因拼进一个进程级诊断变量,但**全仓 0 个读取方** ——
779
+ * 于是 404/409 只剩 `not visible on current surface` / `session is running`,
780
+ * 排障者看不到「registry 是属性没读到、还是 get 双变体 miss、还是 retain 被拒」。
781
+ * 现在原因随 `diag` 一路带到失败点,只拼在**错误消息**里:
782
+ * · 不改 status —— 路由层仍按 `err.status` 映射 HTTP,工具端仍按 message 渲染;
783
+ * · 成功路径不产生任何字符串(diag 只在失败路径被读取);
784
+ * · 幂等 —— 同一条原因不会拼两遍(catch 里可能被重抛)。
785
+ */
786
+ function withResolveDiag(err, diag) {
787
+ const why = diag && diag.why
788
+ if (!why || !(err instanceof OpsError)) return err
789
+ if (err.message.indexOf(why) >= 0) return err
790
+ return new OpsError(`${err.message} [resolve: ${why}]`, err.status)
791
+ }
792
+
436
793
  // ---------------------------------------------------------------------------
437
794
  // 文件派生缓存(P0-1):mtime+size 失效 · 在途去重 · LRU 16
438
795
  // ---------------------------------------------------------------------------
@@ -456,6 +813,17 @@ function pickSessionDir(sessionId) {
456
813
  // - **绝不缓存 raw events**(实测 114MB/次的短命堆分配,388 会话不可控)。
457
814
  // 缓存的是**派生结果**:header / messages / shadowed / turnEndSeq /
458
815
  // marker 进度 —— 量级 = 响应体(最大约 1.8MB)× 16,上限几十 MB。
816
+ // 0.25.0 追加的「消息全文索引」(seq → messageTextFull,见 buildDerived)
817
+ // 也属于派生结果:实测 9.1MB 会话派生常驻 2.68MB、索引 3633 行再加 0.37MB
818
+ // (只索引 listMessages 的行;若改索引全量 events 文本会 +3.39MB → 6.07MB,
819
+ // 16 条 LRU 就是 54MB,不取)。
820
+ // - 0.25.0 起 **searchCache 已并入本缓存**(原先是同一 key 的第二张表):
821
+ // opsSearch 的语料完全可由 messages + 同一份全文索引重建(实测 3633 行
822
+ // 重建 2.0ms),因此删掉整层重复实现。收益是双份:
823
+ // · 第一次搜索不再**第二次全量读盘**(实测 809ms / 1 次读盘 → 4.8ms / 0 次);
824
+ // · 常驻内存反而下降(旧 dump 出的 search 语料 3633 行常驻 +3.64MB/条 × 8 条,
825
+ // 现在只有 0.37MB/条的全文索引 × 16 条)。
826
+ // /messages 与 /search 现在共享同一条 mtimeMs+size 失效路径。
459
827
  //
460
828
  // **刻意不进缓存、每请求重算**(放进缓存就是 0.9.6 那类事故):
461
829
  // - m.visible ← 依赖 live.surface.nodes(live 会话的 surface 会变)。
@@ -466,9 +834,26 @@ function pickSessionDir(sessionId) {
466
834
  // - m.shadowed ← 判据恒为 computeShadowed(纯文件派生,与 live 无关,
467
835
  // 0.9.6 起藏行判据就是它而不是 visible);但**写在每请求的浅拷贝上**,
468
836
  // 缓存对象本身永不被改写 —— 跨请求零串扰。
469
- const DERIVED_CACHE_MAX = 16
837
+ // 0.33.4(perf-audit #6):16 → 48。顺序浏览 20 个会话时 16 会 0% 命中
838
+ // (每次 miss 都把自己下次要用的条目挤出去),48 覆盖一次翻页。
839
+ const DERIVED_CACHE_MAX = 48
470
840
  const derivedCache = new Map() // logPath -> { mtimeMs, size, promise }
471
841
 
842
+ /**
843
+ * derived 对象 → 消息全文索引(seq → messageTextFull)。
844
+ *
845
+ * ⚠️ 为什么是 WeakMap 而不是 derived 的字段、也不是第二张缓存表(0.25.0 取舍):
846
+ * - **不能**做成 derived 的字段:`Object.keys(derived)` 是既有测试契约
847
+ * (test/derived-cache.test.js 断言它恰为 header/messages/shadowed/turnEndSeq),
848
+ * 且文本索引是内部细节,绝不该出现在任何 HTTP 响应里。
849
+ * - **不能**再建一张按 logPath 的缓存表:两张表的 key 相同却各自 stat/失效,
850
+ * 多一个「一边新一边旧」的窗口,且 0.25.0 已经把旧的 searchCache 并进来了
851
+ * (见上方缓存注释块)。
852
+ * - WeakMap 的生命周期与 derived 对象**严格同步**:缓存条目持 promise → derived
853
+ * 对象;条目被 LRU 淘汰/失效后 derived 与索引一起可回收,没有额外驻留。
854
+ */
855
+ const derivedTexts = new WeakMap() // derived -> Map<seq, string>
856
+
472
857
  /**
473
858
  * 真实计算:读日志 → 消息列表 → 遮蔽集 → marker 恢复进度 → turn 边界。
474
859
  * 返回的对象归缓存所有,**调用方不得原地修改**(opsList 用浅拷贝后再挂
@@ -476,7 +861,32 @@ const derivedCache = new Map() // logPath -> { mtimeMs, size, promise }
476
861
  */
477
862
  async function buildDerived(logPath) {
478
863
  // 大日志的逐帧解压走异步让出路径,避免阻塞 GUI 事件循环(评审 P1)。
479
- const { header, events } = await readSessionFileAsync(logPath)
864
+ const { header, events, frameCount, partial } = await readSessionFileAsync(logPath)
865
+ // 0.40.4(srv-audit D22):`partial`(>500 帧)此前计算了但无人消费 —— 大日志
866
+ // (实测 26363 帧 / 137MB)用户看不到任何提示。这里随派生结果带出,由 GET 响应
867
+ // 的 `frames`/`partial` 字段回给客户端。
868
+ // ⚠️ 必须**原地扩展**同一个对象:`deriveFromEvents` 把文本索引登记在 WeakMap
869
+ // (键就是返回对象),spread 出新对象会让每次请求都弱映射 miss → 重新读盘。
870
+ const derived = deriveFromEvents(header, events)
871
+ derived.frameCount = frameCount
872
+ derived.partial = partial
873
+ // 0.44.0(D6):把增量状态的建表(20k 事件约 32ms)摊进这次本来就要 19.5s 的读盘,
874
+ // 之后写后 apply 是稳态 ~1.5ms;失败返回 false 不影响读路径。
875
+ primeDerivedIncremental(derived, events)
876
+ return derived
877
+ }
878
+
879
+ /**
880
+ * 纯函数:事件数组 → 文件派生结果(消息 / 遮蔽集 / marker 进度 / turn 边界)。
881
+ *
882
+ * 0.35.0:从 buildDerived 拆出,供 live 会话复用 —— 写路径落盘后文件已变化,
883
+ * 但宿主内存里的 `session.log` 是权威,直接派生可跳过 131MB 的 zstd 解压+JSON 解析
884
+ * (实测 20–40s → 秒级)。
885
+ * @param {object} header 会话头(live 可能缺字段,调用方补齐)
886
+ * @param {Array} events 事件数组
887
+ * @returns {{header:object, messages:Array, shadowed:Set<number>, turnEndSeq:number}} 派生结果
888
+ */
889
+ function deriveFromEvents(header, events) {
480
890
  const messages = listMessages(events)
481
891
  const shadowed = computeShadowed(events)
482
892
  // 0.8.0 按轮步进:为每个回撤/删除标记附恢复进度与"待恢复轮"。
@@ -486,6 +896,8 @@ async function buildDerived(logPath) {
486
896
  // 本循环直接跳过,marker 循环体也一次都不会执行)。
487
897
  const seqText = messages.some(m => m.marker === true) ? new Map() : null
488
898
  const restoreIndex = seqText ? buildRestoreIndex(events) : null
899
+ // 0.27.0:一次折叠算出「已被后续回撤取代」的 marker(与 planRestore 的 409 闸同源)。
900
+ const superseded = seqText ? supersededMarkers(events) : null
489
901
  for (const e of seqText ? events : []) {
490
902
  if (!e || typeof e.seq !== 'number') continue
491
903
  if (e.type !== 'user/message' && e.type !== 'assistant/message') continue
@@ -510,6 +922,8 @@ async function buildDerived(logPath) {
510
922
  // —— 这正是 opencode 的 `messages.slice(0, boundaryIndex)`(边界自己也不显示)。
511
923
  for (const m of messages) {
512
924
  if (!m || m.marker !== true) continue
925
+ // 已被后续回撤取代 → dock 不再列出(恢复它等于绕过后来那次回撤)。
926
+ if (superseded && superseded.has(m.seq)) m.superseded = true
513
927
  const prog = restoreProgressFromIndex(restoreIndex, m.seq)
514
928
  if (!prog) {
515
929
  m.restoreComplete = false
@@ -529,7 +943,10 @@ async function buildDerived(logPath) {
529
943
  // 3721/3746 全是这么来的)。
530
944
  //
531
945
  // 正向修法:range 是 marker 的语义本体("我遮蔽了谁"),dock 只该用它。
532
- const range = readReplaceOp(events.find(x => x && x.seq === m.seq) || null)
946
+ // 0.33.4(perf-audit #3):用已建好的 restoreIndex.bySeq 查事件本体。
947
+ // 旧实现每个 marker 都对全部事件做一次 find → O(markers × events) 二次方,
948
+ // 实测 10 marker × 22k 事件 62ms、100 marker × 165k 事件 4–5s。
949
+ const range = readReplaceOp((restoreIndex && restoreIndex.bySeq.get(m.seq)) || null)
533
950
  if (range) m.range = range
534
951
  m.pendingTurns = pendingRestoreTurnsFromIndex(restoreIndex, m.seq, prog).map(t => ({
535
952
  upTo: t.seqs[t.seqs.length - 1],
@@ -612,7 +1029,85 @@ async function buildDerived(logPath) {
612
1029
  if (!m || typeof m.seq !== 'number') continue
613
1030
  m.turnStartSeq = enclosingTurnStart.get(m.seq) ?? null
614
1031
  }
615
- return { header, messages, shadowed, turnEndSeq }
1032
+ // ── 0.25.0 · 供 /text 与 /search 复用的「同一份」消息全文索引 ──────────────
1033
+ //
1034
+ // 实测取舍(样本 = 9.1MB / 12890 事件 / 3633 消息,见上方缓存注释块):
1035
+ // ① 索引**只覆盖 listMessages 的行**(user/assistant/system/developer +
1036
+ // tool/call),3633 条、常驻 0.37MB、构建 p50 2.1ms。listMessages 恰好就是
1037
+ // /text 的消费面(面板 pick / 铅笔编辑框都从这些行来),也恰好是
1038
+ // /search 语料的全部行(旧 buildSearchCorpus 也遍历同一批 rows)。
1039
+ // 逐行取 messageTextFull,与旧 /text 的 `messageTextFull(ev)` 逐字一致
1040
+ // (tool/call 恒为 '',与旧行为相同)。
1041
+ // ② **不索引非消息事件**(tool/result 最多 49930 字/条、1676 条共 1.5M 字符):
1042
+ // 「整个 events 全量文本」变体实测常驻 +3.39MB(2.68 → 6.07MB),16 条 LRU
1043
+ // 就是 54MB 纯浪费;这些 seq 界面取不到(面板/编辑框只认消息行),
1044
+ // 真被请求时走下面的「未命中按需读盘」分支。
1045
+ // ③ **不另建 search 语料表**:语料 = 本索引 + snippet 兜底,实测重建 2.0ms。
1046
+ // 旧 searchCache(同 key 的第二张表、常驻 +3.64MB/条 × 8)因此整个删除。
1047
+ const messageTexts = new Map() // seq -> 全文(仅 listMessages 行)
1048
+ const rowSeqs = new Set()
1049
+ for (const m of messages) if (m && typeof m.seq === 'number') rowSeqs.add(m.seq)
1050
+ for (const e of events) {
1051
+ if (!e || typeof e.seq !== 'number' || !rowSeqs.has(e.seq)) continue
1052
+ messageTexts.set(e.seq, messageTextFull(e))
1053
+ }
1054
+ // 0.43.0(srv-audit D24):宿主把「会话标题」落成 `session/title` 事件并由投影折叠
1055
+ // 最后一条(dsh-session-title:`events.findLast(type==='session/title')`)。
1056
+ // 插件此前只认投影行/header/首条用户消息 —— 未打开过的会话标题会与侧栏不一致。
1057
+ // 这里在已有遍历成本内折叠,零额外读盘。
1058
+ let sessionTitle = null
1059
+ for (const e of events) {
1060
+ if (e && e.type === 'session/title' && e.data && typeof e.data.title === 'string' && e.data.title.trim()) {
1061
+ sessionTitle = e.data.title.trim()
1062
+ }
1063
+ }
1064
+ const derived = { header, messages, shadowed, turnEndSeq, sessionTitle }
1065
+ derivedTexts.set(derived, messageTexts)
1066
+ return derived
1067
+ }
1068
+
1069
+ // 0.35.0:live 会话的派生结果按「事件数组引用 + 长度」缓存。宿主 append 会让
1070
+ // 长度变化,自动重算;surface replace 也追加事件,因此长度是足够的失效信号。
1071
+ const liveDerivedCache = new WeakMap() // events -> { length, derived }
1072
+
1073
+ /**
1074
+ * 从宿主内存事件派生(不读盘)。
1075
+ * @param {object} live 宿主会话
1076
+ * @param {Array} events live 事件数组
1077
+ * @param {string} sessionId 会话 id(header 缺 id 时兜底)
1078
+ * @returns {object} 派生结果
1079
+ */
1080
+ function deriveFromLive(live, events, sessionId) {
1081
+ const cached = liveDerivedCache.get(events)
1082
+ if (cached && cached.length === events.length) return cached.derived
1083
+ const length = events.length
1084
+ const liveHeader = (live && live.header) || {}
1085
+ const header = {
1086
+ ...liveHeader,
1087
+ id: liveHeader.id || sessionId,
1088
+ createdAt: typeof liveHeader.createdAt === 'number' ? liveHeader.createdAt : 0,
1089
+ }
1090
+ const derived = deriveFromEvents(header, events)
1091
+ liveDerivedCache.set(events, { length, derived })
1092
+ return derived
1093
+ }
1094
+
1095
+ /**
1096
+ * 取派生结果:live 有内存事件时优先(跳过读盘),否则走文件缓存。
1097
+ * @param {object|undefined} ctx 插件上下文(无 sessions 服务时为 undefined)
1098
+ * @param {string} sessionId 会话 id
1099
+ * @param {string} logPath 日志路径
1100
+ * @returns {Promise<{derived:object, live:object|null}>} 派生结果与 live 会话
1101
+ */
1102
+ async function derivedAndLive(ctx, sessionId, logPath) {
1103
+ const live = ctx ? resolveSession(ctx, sessionId) : null
1104
+ const events = live ? sessionLogOf(live) : null
1105
+ if (Array.isArray(events) && events.length > 0) {
1106
+ // 0.42.2(ui-0404 观察):live 派生不读盘,因此没有 frameCount —— 响应里
1107
+ // `frames` 缺失会让调用方误以为是契约不一致。用 `derivedFrom` 显式说明来源。
1108
+ return { derived: deriveFromLive(live, events, sessionId), live, derivedFrom: 'live' }
1109
+ }
1110
+ return { derived: await loadDerived(logPath), live, derivedFrom: 'disk' }
616
1111
  }
617
1112
 
618
1113
  /**
@@ -627,7 +1122,11 @@ async function loadDerived(logPath) {
627
1122
  derivedCache.set(logPath, hit) // LRU touch(Map 插入序 = LRU 序)
628
1123
  return hit.promise
629
1124
  }
630
- const entry = { mtimeMs: st.mtimeMs, size: st.size, promise: buildDerived(logPath) }
1125
+ const entry = { mtimeMs: st.mtimeMs, size: st.size, promise: null, value: null }
1126
+ entry.promise = buildDerived(logPath).then(derived => {
1127
+ entry.value = derived
1128
+ return derived
1129
+ })
631
1130
  derivedCache.delete(logPath)
632
1131
  derivedCache.set(logPath, entry)
633
1132
  while (derivedCache.size > DERIVED_CACHE_MAX) {
@@ -646,11 +1145,20 @@ async function opsList(targetCtx, sessionId, opts = {}) {
646
1145
  const { logPath } = pickSessionDir(sessionId)
647
1146
  // 文件派生段(读日志 → 消息 → 遮蔽集 → marker 进度 → turn 边界)走缓存:
648
1147
  // key = logPath、失效看读前 stat 的 mtimeMs+size,见 loadDerived 注释。
649
- const { header, messages: baseMessages, shadowed, turnEndSeq } = await loadDerived(logPath)
1148
+ const { derived, live, derivedFrom } = await derivedAndLive(targetCtx, sessionId, logPath)
1149
+ const { header, messages: baseMessages, shadowed, turnEndSeq } = derived
650
1150
  // 每请求**浅拷贝**一份再挂 per-request 字段:缓存对象永不被改写,
651
- // 并发请求之间零串扰(浅拷 5038 个小对象约 1~2ms)。
1151
+ // 并发请求之间零串扰(浅拷 3633 个小对象实测 0.56ms / 请求)。
1152
+ //
1153
+ // 0.25.0 评估结论:**保留浅拷,不做「只投影 compact 需要的字段」的特化**。
1154
+ // · 实测省下的量级 = 0.56ms(浅拷)→ 0.12ms(零浅拷 + 投影内联算),
1155
+ // 即约 0.4ms;而响应里 `JSON.stringify` 本身 9.9ms、网络/渲染是几十 ms。
1156
+ // · 代价却是**两套行语义**:full 视图仍要浅拷(它返回整行 + visible/shadowed),
1157
+ // compact 视图若改成「零浅拷」就多一条「不得再改行」的隐式约束;任何未来
1158
+ // 往 per-request 行上挂字段的改动都会静默只对 full 生效。这个风险 > 0.4ms。
1159
+ // · 可选的微优化(已评估、不采纳):把 `{...m}` 换成 `Object.assign({}, m)` 或
1160
+ // 预建模板 —— V8 上差异在噪声内(实测 0.5~0.6ms 区间抖动)。
652
1161
  const messages = baseMessages.map(m => ({ ...m }))
653
- const live = resolveSession(targetCtx, sessionId)
654
1162
  // R2 根治:磁盘派生可能还停在落盘批窗之前,用 live.log 补算 committed。
655
1163
  // 必须在 messages 浅拷贝之后(绝不改写 derivedCache 里的对象)。
656
1164
  applyLiveCommitted(messages, live)
@@ -704,6 +1212,8 @@ async function opsList(targetCtx, sessionId, opts = {}) {
704
1212
  // 客户端拿到 undefined 会把**已恢复完毕**的 marker 继续列在待恢复列表里。
705
1213
  restoreComplete: m.restoreComplete === true,
706
1214
  committed: m.committed === true,
1215
+ // 0.27.0:已被后续回撤取代的 marker —— dock 必须隐藏(同 planRestore 的 409 闸)
1216
+ superseded: m.superseded === true,
707
1217
  }))
708
1218
  : messages
709
1219
 
@@ -713,7 +1223,7 @@ async function opsList(targetCtx, sessionId, opts = {}) {
713
1223
  id: header.id,
714
1224
  createdAt: header.createdAt,
715
1225
  parentSession: header.parentSession ?? null,
716
- confirmTitle: resolveSessionTitle(targetCtx, sessionId) || header.id,
1226
+ confirmTitle: resolveSessionTitle(targetCtx, sessionId, { eventTitle: derived.sessionTitle }) || header.id,
717
1227
  },
718
1228
  running: isRunning(targetCtx, sessionId),
719
1229
  runningSource: __runningSource,
@@ -723,56 +1233,51 @@ async function opsList(targetCtx, sessionId, opts = {}) {
723
1233
  markerCount,
724
1234
  turnEndSeq,
725
1235
  messages: visibleMessages,
1236
+ // 0.40.4(srv-audit D22):大日志读取规模(>500 帧 partial=true),供客户端提示。
1237
+ // `frames` 只在磁盘派生时可算(live 派生不读盘);`derivedFrom` 显式说明来源。
1238
+ derivedFrom,
1239
+ ...(Number.isSafeInteger(derived.frameCount) ? { frames: derived.frameCount } : {}),
1240
+ ...(derived.partial === true ? { partial: true } : {}),
726
1241
  }
727
1242
  }
728
1243
 
729
1244
  // ---------------------------------------------------------------------------
730
1245
  // Per-session search (full text, beyond the 160-char snippet)
731
1246
  // ---------------------------------------------------------------------------
732
- const SEARCH_CACHE_MAX = 8
733
- const searchCache = new Map() // logPath -> { mtimeMs, size, promise }
1247
+ // 0.25.0:**不再有第二张 searchCache**。旧实现自带 SEARCH_CACHE_MAX=8 的
1248
+ // logPath/mtimeMs/size 表,与 derivedCache key 完全相同却互不复用 —— 后果是
1249
+ // 「先 /messages 再 /search」必然为同一份文件**再读一遍盘**(9.1MB 会话实测
1250
+ // 540ms 纯重复成本),而两张表各自失效还多一个「一边新一边旧」的窗口。
1251
+ // 现在语料由 loadDerived 的派生结果重建(实测 3633 行 2.0ms),共享同一条
1252
+ // mtimeMs+size 失效路径与 LRU 16;常驻内存同时下降(旧的语料副本 +3.64MB/条,
1253
+ // 现在只有 0.37MB/条的 messageTexts)。
734
1254
 
735
- /** Build the searchable corpus once per log revision (full text, lowercased lazily). */
736
- async function buildSearchCorpus(logPath) {
737
- const { events } = await readSessionFileAsync(logPath)
738
- const messages = listMessages(events)
739
- const shadowed = computeShadowed(events)
740
- const bySeq = new Map()
741
- for (const e of events) if (e && typeof e.seq === 'number') bySeq.set(e.seq, e)
1255
+ /** derived 的 messages → 可搜索语料(文本优先取 messageTexts,缺失退回 snippet)。 */
1256
+ // 0.33.12(perf-audit #5):语料只依赖 derived(shadowed 是该文件的纯派生),
1257
+ // 缓存到 WeakMap 后 /search 不再每次重建 + 逐行 toLowerCase(45k 行 140ms → ~10ms)。
1258
+ const searchCorpusCache = new WeakMap()
1259
+ function searchCorpusOf(derived) {
1260
+ const cached = searchCorpusCache.get(derived)
1261
+ if (cached) return cached
1262
+ const texts = derivedTexts.get(derived) || new Map()
1263
+ const { messages, shadowed } = derived
742
1264
  const corpus = []
743
1265
  for (const m of messages) {
744
- const ev = bySeq.get(m.seq)
745
- const text = ev ? messageTextFull(ev) : ''
1266
+ const text = texts.get(m.seq) || m.snippet || ''
746
1267
  corpus.push({
747
1268
  seq: m.seq,
748
1269
  type: m.type,
749
1270
  role: m.role,
750
1271
  marker: m.marker === true,
751
1272
  shadowed: shadowed.has(m.seq),
752
- text: text || m.snippet || '',
1273
+ text,
1274
+ lower: text.toLowerCase(),
753
1275
  })
754
1276
  }
1277
+ searchCorpusCache.set(derived, corpus)
755
1278
  return corpus
756
1279
  }
757
1280
 
758
- async function loadSearchCorpus(logPath) {
759
- const st = await statFile(logPath)
760
- const hit = searchCache.get(logPath)
761
- if (hit && hit.mtimeMs === st.mtimeMs && hit.size === st.size) {
762
- searchCache.delete(logPath)
763
- searchCache.set(logPath, hit)
764
- return hit.promise
765
- }
766
- const entry = { mtimeMs: st.mtimeMs, size: st.size, promise: buildSearchCorpus(logPath) }
767
- searchCache.delete(logPath)
768
- searchCache.set(logPath, entry)
769
- while (searchCache.size > SEARCH_CACHE_MAX) searchCache.delete(searchCache.keys().next().value)
770
- entry.promise.catch(() => {
771
- if (searchCache.get(logPath) === entry) searchCache.delete(logPath)
772
- })
773
- return entry.promise
774
- }
775
-
776
1281
  function searchSnippet(text, query, radius = 45) {
777
1282
  const lower = text.toLowerCase()
778
1283
  const at = lower.indexOf(query)
@@ -793,13 +1298,14 @@ async function opsSearch(targetCtx, sessionId, query, opts = {}) {
793
1298
  }
794
1299
  const limit = Number.isSafeInteger(opts && opts.limit) ? Math.max(1, Math.min(100, opts.limit)) : 50
795
1300
  const { logPath } = pickSessionDir(sessionId)
796
- const corpus = await loadSearchCorpus(logPath)
1301
+ // 与 /messages 共用同一条缓存:命中时为 0 读盘、语料重建 2.0ms。
1302
+ const corpus = searchCorpusOf((await derivedAndLive(targetCtx, sessionId, logPath)).derived)
797
1303
  const needle = q.toLowerCase()
798
1304
  const results = []
799
1305
  let total = 0
800
1306
  for (const row of corpus) {
801
1307
  if (role && row.role !== role) continue
802
- if (!row.text.toLowerCase().includes(needle)) continue
1308
+ if (!row.lower.includes(needle)) continue
803
1309
  total++
804
1310
  if (results.length >= limit) continue
805
1311
  results.push({
@@ -814,30 +1320,262 @@ async function opsSearch(targetCtx, sessionId, query, opts = {}) {
814
1320
  return { ok: true, query: q, role, limit, total, truncated: total > results.length, results }
815
1321
  }
816
1322
 
817
- /** 测试钩子(非公开 API):直接驱动 list / search 与文件派生缓存。 */
818
- export const _internals = { opsList, opsSearch, loadDerived, loadSearchCorpus, derivedCache, searchCache }
1323
+ /**
1324
+ * 单条消息全文(GET /api/message-ops/text 的唯一实现)。
1325
+ *
1326
+ * 0.25.0 修的就是这个绕路:旧路由每次 `readSessionFileAsync(logPath)` 全量重读
1327
+ * 日志(9.1MB 会话实测 550~1100ms/次),而面板每选一条消息就打一次 —— 绕过
1328
+ * 了 loadDerived 的 mtimeMs+size 缓存,等于把 /messages 刚付出的解压+解析
1329
+ * 成本再付一遍。现在命中缓存的成本 = 一次 Map.get(实测 0 读盘、<0.1ms)。
1330
+ *
1331
+ * 未命中(不在 messages 行里 / 缓存被 LRU 挤出 / 文件已变化):退回「按需
1332
+ * 现读」,语义与旧实现完全一致(旧实现本来就是 ev 不存在 → 404)。
1333
+ * @returns {Promise<string>} 全文(未索引的行返回 '')
1334
+ * @throws {OpsError} 404 = 该 seq 在日志里不存在;400 = 参数非法
1335
+ */
1336
+ async function opsText(sessionId, seq, targetCtx) {
1337
+ if (!isSessionId(sessionId)) throw new OpsError('invalid sessionId', 400)
1338
+ if (!Number.isSafeInteger(seq) || seq < 0) throw new OpsError('invalid seq', 400)
1339
+ // seq 0 在日志头里是结构事件区(permission/preset 等,实测恒非消息),
1340
+ // messageText 恒空串;引用按钮/编辑框不可能点它 —— 保持 404 而不是 200 {text:""}。
1341
+ if (seq === 0) throw new OpsError('no quotable message at seq 0', 404)
1342
+ const { logPath } = pickSessionDir(sessionId)
1343
+ const derived = (await derivedAndLive(targetCtx, sessionId, logPath)).derived
1344
+ const texts = derivedTexts.get(derived)
1345
+ if (texts && texts.has(seq)) return texts.get(seq)
1346
+ // 冷分支:缓存里没有这条 seq。两种可能 ——
1347
+ // a) 它压根不是消息事件(tool/result 之类):旧实现也会找到 event 并返回
1348
+ // messageTextFull 的结果(可能非空),所以这里同样按需读盘,**不改变** 404 语义;
1349
+ // b) 缓存条目刚被 LRU 淘汰/文件已变:读盘后就是最新真相。
1350
+ const { events } = await readSessionFileAsync(logPath)
1351
+ const ev = events.find(e => e && e.seq === seq)
1352
+ if (!ev) throw new OpsError('seq not found', 404)
1353
+ return messageTextFull(ev)
1354
+ }
1355
+
1356
+ /**
1357
+ * live 写入的统一落地与失败收尾(0.35.1 M4)。
1358
+ *
1359
+ * opsCommit / opsRestore 只在「怎么规划」上不同;落地后的三件事完全一致:
1360
+ * applyScriptLive → 推动宿主 turn 游标(失败告警)→ flush;失败时闭合窗口
1361
+ * (applyScriptLive 内部已完成,至多一次)并尽力推进游标,然后原样抛出。
1362
+ * @param {object} targetCtx 插件上下文
1363
+ * @param {object} session 宿主会话
1364
+ * @param {string} sessionId 会话 id(告警用)
1365
+ * @param {object} win 窗口规划(synthetic/turn/step)
1366
+ * @param {object} script buildCommitScript / buildRestoreScript 的结果
1367
+ * @param {object} diag 诊断收集器
1368
+ * @returns {Promise<{state:{windowOpened:boolean,closed:boolean,emitted:Array}, aligned:boolean}>} 落盘状态与对齐结果
1369
+ */
1370
+ async function runLiveScript(targetCtx, session, sessionId, win, script, diag) {
1371
+ const state = { windowOpened: false, closed: false, emitted: [] }
1372
+ try {
1373
+ applyScriptLive(session, script, state)
1374
+ // 0.39.5(srv-audit D2):闭合失败 = 窗口还开着。这时**不能推进宿主 turn 游标**
1375
+ // —— 宿主下一次真实轮次会用同一个 turn 号,加载端关系闸会拒绝整份日志
1376
+ // (`turn/start does not open the expected turn`)。
1377
+ if (state.closeFailures && state.closeFailures.length > 0) {
1378
+ const detail = state.closeFailures.map(f => f.kind + ': ' + f.message).join('; ')
1379
+ console.warn('[message-ops] synthetic turn left open (postamble rejected):', { session: sessionId, turn: win.turn, detail })
1380
+ await flushSessions(targetCtx, session)
1381
+ return { state, aligned: false, partial: true, warning: 'synthetic turn left open (' + detail + ')' }
1382
+ }
1383
+ const aligned = win.synthetic ? alignLiveTurnCursor(targetCtx, session, win.turn, serviceOf(targetCtx, 'agents')) : false
1384
+ if (win.synthetic && !aligned) {
1385
+ console.warn('[message-ops] synthetic turn written but agent cursor was not advanced', { session: sessionId, turn: win.turn })
1386
+ }
1387
+ await flushSessions(targetCtx, session)
1388
+ return { state, aligned }
1389
+ } catch (err) {
1390
+ if (win && win.synthetic && state.windowOpened) {
1391
+ try {
1392
+ alignLiveTurnCursor(targetCtx, session, win.turn, serviceOf(targetCtx, 'agents'))
1393
+ } catch {
1394
+ /* 尽力而为:对齐失败不覆盖原始错误 */
1395
+ }
1396
+ }
1397
+ throw withResolveDiag(err, diag)
1398
+ }
1399
+ }
1400
+
1401
+ /**
1402
+ * 磁盘写入的统一编排(0.35.3 M5):read→assert→plan→script→materialize→append。
1403
+ *
1404
+ * opsCommit / opsRestore 的磁盘分支原先各自复制这一串(含锁内重读、v4 断言、
1405
+ * seq/time 分配、错误诊断)。差异只有规划与响应字段,用三个回调表达。
1406
+ * @param {object} input 编排参数
1407
+ * @param {string} input.logPath 会话日志路径
1408
+ * @param {object} input.diag 诊断收集器
1409
+ * @param {(events:Array)=>object} input.plannedOf 由最新事件规划(返回任意计划对象)
1410
+ * @param {(planned:object)=>object} input.scriptOf 计划 → ops-write 语义脚本
1411
+ * @param {(planned:object, materialized:object, read:object)=>object} input.resultOf 构造响应
1412
+ * @returns {Promise<object>} resultOf 的返回值
1413
+ */
1414
+ /**
1415
+ * 写盘成功后把已知批次并进派生缓存(0.44.0,srv-audit D6)。
1416
+ *
1417
+ * 缓存按日志 mtimeMs+size 失效:本插件自己 append 一帧后,下一次 GET 会为同一份
1418
+ * 日志再全量读一次(137MB 会话实测 19.5s)。写批次的事件内容完全已知(materializeDisk
1419
+ * 的 batch),因此可以把旧派生 + 批次增量合并成新派生并直接替换缓存条目。
1420
+ *
1421
+ * 失败(NotIncrementalError / 缓存未命中 / stat 竞争)一律**放弃增量**,让下一次
1422
+ * GET 走原全量路径 —— 宁可慢也不能错。
1423
+ * @param {string} logPath 会话日志路径
1424
+ * @param {Array} preEvents 批次之前的全量事件(写路径锁内刚读过)
1425
+ * @param {Array} batch 本次写入的事件(diskAppend 的 batch)
1426
+ * @returns {void}
1427
+ */
1428
+ function adoptIncrementalCache(logPath, preEvents, batch, statBefore) {
1429
+ try {
1430
+ const entry = derivedCache.get(logPath)
1431
+ // 铁律 1:只有缓存派生与「本次读盘前的文件状态」一致才允许增量;
1432
+ // 不一致(宿主在缓存之后又写过)就删条目,让下一次 GET 全量重建。
1433
+ if (!statBefore || !entry || entry.mtimeMs !== statBefore.mtimeMs || entry.size !== statBefore.size || !entry.value) {
1434
+ if (entry) derivedCache.delete(logPath)
1435
+ return
1436
+ }
1437
+ const prev = entry.value
1438
+ const texts = derivedTexts.get(prev)
1439
+ const next = applyDerivedBatch(prev, batch, {
1440
+ events: preEvents,
1441
+ texts,
1442
+ framesAdded: 1,
1443
+ register: (derived, map) => {
1444
+ derivedTexts.set(derived, map)
1445
+ },
1446
+ })
1447
+ const registered = derivedTextsOf(next)
1448
+ if (registered && !derivedTexts.has(next)) derivedTexts.set(next, registered)
1449
+ statFile(logPath)
1450
+ .then(st => {
1451
+ derivedCache.delete(logPath)
1452
+ derivedCache.set(logPath, { mtimeMs: st.mtimeMs, size: st.size, promise: Promise.resolve(next), value: next })
1453
+ })
1454
+ .catch(() => {
1455
+ /* 拿不到新 stat 就不动缓存:下一次 GET 会因 mtime 不符而重建 */
1456
+ })
1457
+ } catch (error) {
1458
+ if (!(error instanceof NotIncrementalError)) {
1459
+ console.warn('[message-ops] incremental derived adoption failed:', error && error.message)
1460
+ }
1461
+ }
1462
+ }
1463
+
1464
+ async function runDiskWrite({ logPath, diag, plannedOf, scriptOf, resultOf }) {
1465
+ return withWriteLock(logPath, async () => {
1466
+ // 0.44.0(D6):读盘前 stat —— 增量接管缓存时用它证明「缓存派生与本次读到的是
1467
+ // 同一文件状态」,否则绝不拿陈旧派生做增量(三铁律之一)。
1468
+ const statBefore = await statFile(logPath).catch(() => null)
1469
+ const read = await readSessionFileAsync(logPath)
1470
+ assertWritableSessionLog(read, logPath)
1471
+ let planned
1472
+ try {
1473
+ planned = plannedOf(read.events)
1474
+ } catch (err) {
1475
+ throw withResolveDiag(err, diag)
1476
+ }
1477
+ const script = scriptOf(planned)
1478
+ const materialized = materializeDisk(script, {
1479
+ startSeq: nextSeqFrom(read.events),
1480
+ baseTime: Date.now(),
1481
+ version: read.header.version ?? 4,
1482
+ })
1483
+ await diskAppend(logPath, materialized.batch)
1484
+ // D6:写后增量更新派生缓存(失败静默退回全量)
1485
+ adoptIncrementalCache(logPath, read.events, materialized.batch, statBefore)
1486
+ return resultOf(planned, materialized, read)
1487
+ })
1488
+ }
1489
+
1490
+ /** 测试钩子(非公开 API):直接驱动 list / search / text 与文件派生缓存。 */
1491
+ export const _internals = {
1492
+ errorStatusOf,
1493
+ publicErrorOf,
1494
+ runningSourceOf: () => __runningSource,
1495
+ resetCapturedServicesForTests,
1496
+ registerToolTolerantly,
1497
+ runLiveScript,
1498
+ serviceOf,
1499
+ isRunning,
1500
+ captureServices,
1501
+ opsList,
1502
+ opsSearch,
1503
+ opsText,
1504
+ opsCommit,
1505
+ opsRestore,
1506
+ fence,
1507
+ diskAppend,
1508
+ loadDerived,
1509
+ derivedTexts,
1510
+ derivedCache,
1511
+ searchCorpusOf,
1512
+ }
819
1513
 
820
1514
  async function opsCommit(targetCtx, mode, sessionId, seq) {
821
1515
  if (!isSessionId(sessionId)) throw new OpsError('invalid sessionId', 400)
822
1516
  if (!Number.isSafeInteger(seq) || seq < 0) throw new OpsError('invalid seq', 400)
1517
+ // 0.40.3(srv-audit D7/D8):与回收站移动/purge 共用的按会话锁 —— 否则 delete 与
1518
+ // revert 并发时宿主持有 fd,日志写入丢失;两次 delete 会互相回滚 archive 墓碑。
1519
+ return withSessionLock(sessionId, () => commitUnderLock(targetCtx, mode, sessionId, seq))
1520
+ }
1521
+
1522
+ async function commitUnderLock(targetCtx, mode, sessionId, seq) {
823
1523
  if (isRunning(targetCtx, sessionId)) throw new OpsError('session is running; stop it first', 409)
824
1524
  const { logPath } = pickSessionDir(sessionId)
825
- const { header, events } = await readSessionFileAsync(logPath)
826
1525
  // 0.8.2:空闲会话(实测 340/364)没有打开的 turn/step → 用自足的**合成 turn**
827
1526
  // 承载 notice,而不是拒绝。引擎 append-only 插不进已有 step,但合成一整个 turn 合法
828
- //��已对官方校验闸实测:append 型 / 单节点 replace / 多节点 replace 全 PASS,遮蔽受保护头正确拒绝)。
1527
+ //(已对官方校验闸实测:append 型 / 单节点 replace / 多节点 replace 全 PASS,遮蔽受保护头正确拒绝)。
829
1528
  // 带 reason:"message-ops",UI 与审计可识别,不与真实模型轮次混淆。
830
- let win = planNoticeWindow(events)
831
1529
  const notice = mode === 'delete' ? `[消息删除] 已遮蔽 seq ${seq}` : null // revert 文案含 shadowed 数量,规划后拼
832
- const acq = await acquireSession(targetCtx, sessionId)
1530
+ // 审计 §1.6 + §2.2:live 面拿不到时会退回磁盘路径 —— 那是**正常**的 lazy-view 形态,
1531
+ // 但「为什么拿不到」以前被扔进没人读的全局变量。现在只在**真的失败**时把它
1532
+ // 拼进 OpsError(成功路径零字符串开销、也不改变任何控制流)。
1533
+ const diag = {}
1534
+ const acq = await acquireSession(targetCtx, sessionId, diag)
1535
+ let win = null
833
1536
  if (acq !== null && acq.session !== undefined) {
834
1537
  try {
835
- const session = acq.session
1538
+ // 0.40.1(srv-audit D4):live 分支与磁盘分支共用同一 per-logPath 串行队列。
1539
+ // 规划回退读盘(`liveEvents` 拿不到时 `await readSessionFileAsync`)是 await 点,
1540
+ // 旧实现没有互斥 → 两个并发 restore 基于同一份磁盘快照各写一遍(重复副本)。
1541
+ return await withWriteLock(logPath, async () => {
1542
+ const session = acq.session
836
1543
  const liveEvents = sessionLogOf(session)
837
- if (liveEvents) win = planNoticeWindow(liveEvents)
1544
+ // 0.33.1:live 面是权威;只有拿不到事件本体时才读盘做规划兜底(store 命中时
1545
+ // 磁盘可能落后于落盘批窗,先读盘会把「已存在的 marker」判成不存在)。
1546
+ const sourceEvents = liveEvents || mergePendingLiveWrites(logPath, (await readSessionFileAsync(logPath)).events)
1547
+ win = planNoticeWindow(sourceEvents)
838
1548
  const turnStep = { turn: win.turn, step: win.step }
839
1549
  // 0.5.4(P0):v4 准入要求 system/message 带正 turn/step——缺字段时持久层
840
1550
  // encodeEventBatch 的 SessionFormatError 未捕获会**打死整个 dsh 进程**。
1551
+ // 0.26.0(core-d 审计发现的最后一个自噬入口):
1552
+ // live 路径的 `planDelete/planRevert` 只拿得到 `session.surface.nodes`(没有事件
1553
+ // 本体),因此判不出「目标是不是一条 marker」。磁盘路径的
1554
+ // planDeleteFromEvents/planRevertFromEvents 早已有这道闸,live 路径原先漏了 →
1555
+ // 把 marker 自己当删除目标会写出一条 content 为空的新 replace(自噬 marker)。
1556
+ // 语料实测 40 条空 content 的 system/message replace(3424/3658/3689/3721/
1557
+ // 3746/7252/7524/7525/7526/8954…)全是这么来的。
1558
+ // 这里用 liveEvents(事件本体)补一次同判;判不了(无 liveEvents)就交给
1559
+ // planDelete/planRevert 自己的节点校验(保持原行为,不引入新的拒绝面)。
1560
+ if (liveEvents) {
1561
+ const target = liveEvents.find(e => e && e.seq === seq)
1562
+ if (target && isMarkerEvent(target))
1563
+ throw new OpsError(`seq ${seq} is a revert/delete marker and cannot be a ${mode} target (would create a self-eating marker)`, 409)
1564
+ }
1565
+ const liveLog = sessionLogOf(session) || []
1566
+ const targetEvent = liveLog.find(e => e && e.seq === seq)
1567
+ // 0.33.2(与磁盘路径同判):宿主的 surface 改写(compaction checkpoint、
1568
+ // 系统提示改写)不是对话消息。live 侧只查 isMarkerEvent(system/message)
1569
+ // 与 tool/result,会把 user/message + replace 的 checkpoint 放行 —— 遮蔽它
1570
+ // 等于把压缩后的整段上下文清空。
1571
+ if (targetEvent && readReplaceOp(targetEvent) !== null) {
1572
+ throw new OpsError(`seq ${seq} is a host surface rewrite, not a message — refusing to ${mode} it`, 409)
1573
+ }
1574
+ if (targetEvent && targetEvent.type === 'tool/result') {
1575
+ // 遮蔽 tool/result 会让 assistant 的 tool-call 失去配对 → 下一次模型请求被拒。
1576
+ // 磁盘路径靠 isSurfaceMessageType 过滤(tool/result 不在消息集),live 侧必须显式拦。
1577
+ throw new OpsError(`seq ${seq} is a tool result, not a message — refusing to ${mode} it`, 409)
1578
+ }
841
1579
  const plan = mode === 'delete' ? planDelete(session.surface, seq) : planRevert(session.surface, seq)
842
1580
  const text = mode === 'delete' ? notice : `[消息回滚] 已回滚到 seq ${seq}(含)之后的 ${plan.shadowedSeqs.length} 个节点`
843
1581
  // 0.8.2:会话 store 命中时走引擎路径 —— 同样要先开合成 turn 窗口,
@@ -856,80 +1594,61 @@ async function opsCommit(targetCtx, mode, sessionId, seq) {
856
1594
  // 日志落成 `step/end, turn/end, step/end, turn/end`。宿主读盘直接判
857
1595
  // `step/end does not match an open turn and step`,整份会话变 corrupt
858
1596
  // (实测 session-5b49db5b seq 806-809)。用 closed 标志保证闭环只发生一次。
859
- let closed = false
860
- const closeWindow = () => {
861
- if (closed) return
862
- closed = true
863
- for (const post of noticeWindowPostamble(win)) {
864
- try {
865
- session.append(post.kind, post.data)
866
- } catch {
867
- /* 引擎拒:维持原错误/继续 */
868
- }
869
- }
870
- }
871
- try {
872
- for (const pre of noticeWindowPreamble(win)) session.append(pre.kind, pre.data)
873
- const event = applySurfaceReplace(session, plan.startSeq, plan.endSeq, plan.shadowedSeqs, text, turnStep)
874
- // 必须闭合:否则引擎内存里 turn 永远开着 → isRunning 恒真 → 后续操作全被 409
875
- closeWindow()
876
- const aligned = win.synthetic ? alignLiveTurnCursor(targetCtx, session, win.turn) : false
877
- flushSessions(targetCtx, session)
878
- return {
879
- ok: true,
880
- mode,
881
- seq,
882
- syntheticTurn: win.synthetic === true,
883
- // 0.11.4:暴露对齐结果。live 路径必须 true;disk 路径(store-miss)没有
884
- // 内存 agent,false 属正常。若 live 也 false,下一条真实消息就会重号。
885
- turnAligned: aligned,
886
- shadowedCount: plan.shadowedSeqs.length,
887
- eventSeq: event && event.seq != null ? event.seq : null,
1597
+ // P0(0.32.0):宿主动机不在 idle(maintenance 也算 status 空闲)时禁止写合成窗口——
1598
+ // 写完无法推进 lastTurn,宿主下一轮会重号,整份日志被拒读。
1599
+ const phaseErr = livePhaseError(targetCtx, session, serviceOf(targetCtx, 'agents'))
1600
+ if (phaseErr) throw withResolveDiag(phaseErr, diag)
1601
+ // 0.33.10:agents 缺失只告警(本机 profile 恒缺失,硬拒绝会堵死所有写操作)。
1602
+ agentsServiceVisible(targetCtx, session, win)
1603
+ // 0.34.2(M3):live 与 disk 共用同一份语义脚本;落地方式由 applyScriptLive
1604
+ // 负责(引擎分配 seq/time、replace 走 applySurfaceReplace 的拼写探测)。
1605
+ const script = buildCommitScript({ mode, seq, win, plan })
1606
+ const live = await runLiveScript(targetCtx, session, sessionId, win, script, diag)
1607
+ notePendingLiveWrite(logPath, live.state.emitted)
1608
+ const markerEvent = live.state.emitted.find(e => e && e.type === 'system/message')
1609
+ return {
1610
+ ok: true,
1611
+ mode,
1612
+ seq,
1613
+ syntheticTurn: win.synthetic === true,
1614
+ turnAligned: live.aligned,
1615
+ shadowedCount: plan.shadowedSeqs.length,
1616
+ eventSeq: markerEvent && markerEvent.seq != null ? markerEvent.seq : null,
1617
+ ...(live.partial === true ? { partial: true, warning: live.warning } : {}),
888
1618
  }
889
- } catch (err) {
890
- // 只补闭合**尚未发生**的窗口;已闭合过就绝不再写第二遍。
891
- closeWindow()
892
- throw err
893
- }
1619
+ })
894
1620
  } finally {
895
1621
  acq.release()
896
1622
  }
897
1623
  }
898
- // store-miss(lazy-view 只读盘会话)→ 磁盘路径:镜像引擎字段直接追加 zstd 帧
899
- const plan = mode === 'delete' ? planDeleteFromEvents(events, seq) : planRevertFromEvents(events, seq)
900
- const text = mode === 'delete' ? notice : `[消息回滚] 已回滚到 seq ${seq}(含)之后的 ${plan.shadowedSeqs.length} 个节点`
901
- // 0.8.2:磁盘路径同样把 marker 包进合成 turn(裸 zstd 写、零校验,写错就是整份日志报废)
902
- const baseTime = Date.now()
903
- let cursor = nextSeqFrom(events)
904
- const batch = noticeWindowPreamble(win).map((e, i) => ({
905
- type: e.kind,
906
- seq: cursor++,
907
- time: baseTime + i,
908
- data: e.data,
909
- }))
910
- const marker = buildMarkerEvent({
911
- seq: cursor++,
912
- time: baseTime + batch.length,
913
- turnStep: { turn: win.turn, step: win.step },
914
- text,
915
- version: header?.version ?? 4,
916
- startSeq: plan.startSeq,
917
- endSeq: plan.endSeq,
918
- shadowedSeqs: plan.shadowedSeqs,
1624
+ // store-miss(lazy-view 只读盘会话)→ 磁盘路径:镜像引擎字段直接追加 zstd 帧。
1625
+ // 审计 §2.2:这条路径的失败(`start seq N not visible on current surface` 等)
1626
+ // 现在带上 diag —— 它正是「live 面也没拿到 + 磁盘面也拒」的最终现场。
1627
+ //
1628
+ // 0.33.1(P0):read→plan→append 整段进 per-logPath 串行队列。两个并发请求
1629
+ // 各自读到同一 maxSeq 会各写一份 seq,宿主加载判 `event seq N is not dense`,
1630
+ // 整份会话打不开(已用宿主 format catalog 复现)。
1631
+ // 0.8.2:磁盘路径同样把 marker 包进合成 turn(裸 zstd 写、零校验,写错就是整份日志报废)。
1632
+ // 0.34.0:事件序列由 ops-write 单一脚本层物化(与 live 共用同一份语义脚本)。
1633
+ return runDiskWrite({
1634
+ logPath,
1635
+ diag,
1636
+ plannedOf: events => {
1637
+ const plannedWin = planNoticeWindow(events)
1638
+ const plannedPlan = mode === 'delete' ? planDeleteFromEvents(events, seq) : planRevertFromEvents(events, seq)
1639
+ return { win: plannedWin, plan: plannedPlan }
1640
+ },
1641
+ scriptOf: ({ win: plannedWin, plan: plannedPlan }) => buildCommitScript({ mode, seq, win: plannedWin, plan: plannedPlan }),
1642
+ resultOf: ({ win: plannedWin, plan: plannedPlan }, { markerSeq }) => ({
1643
+ ok: true,
1644
+ mode,
1645
+ seq,
1646
+ disk: true,
1647
+ syntheticTurn: plannedWin.synthetic === true,
1648
+ shadowedCount: plannedPlan.shadowedSeqs.length,
1649
+ eventSeq: markerSeq,
1650
+ }),
919
1651
  })
920
- batch.push(marker)
921
- let tail = marker.time + 1
922
- for (const e of noticeWindowPostamble(win)) batch.push({ type: e.kind, seq: cursor++, time: tail++, data: e.data })
923
- await diskAppend(logPath, batch)
924
- return {
925
- ok: true,
926
- mode,
927
- seq,
928
- disk: true,
929
- syntheticTurn: win.synthetic === true,
930
- shadowedCount: plan.shadowedSeqs.length,
931
- eventSeq: marker.seq,
932
- }
933
1652
  }
934
1653
 
935
1654
  // 0.8.0:upToSeq 可选 —— 给定则按轮步进恢复(只重放到该 seq,后续仍遮蔽)。
@@ -938,109 +1657,143 @@ async function opsRestore(targetCtx, sessionId, restoreSeq, upToSeq, discard) {
938
1657
  if (!isSessionId(sessionId)) throw new OpsError('invalid sessionId', 400)
939
1658
  if (!Number.isSafeInteger(restoreSeq) || restoreSeq < 0) throw new OpsError('invalid seq', 400)
940
1659
  if (upToSeq !== undefined && (!Number.isSafeInteger(upToSeq) || upToSeq < 0)) throw new OpsError('invalid upToSeq', 400)
1660
+ return withSessionLock(sessionId, () => restoreUnderLock(targetCtx, sessionId, restoreSeq, upToSeq, discard))
1661
+ }
1662
+
1663
+ async function restoreUnderLock(targetCtx, sessionId, restoreSeq, upToSeq, discard) {
941
1664
  if (isRunning(targetCtx, sessionId)) throw new OpsError('session is running; stop it first', 409)
942
1665
  const { logPath } = pickSessionDir(sessionId)
943
- const { events } = await readSessionFileAsync(logPath)
1666
+ // ⚠️ 这里曾尝试用 `session.lock` 存在性判定「宿主仍持有写租约」,已撤回:
1667
+ // 宿主崩溃后锁文件会残留(文件在、flock 已释放),只查存在性会把磁盘写永久 409。
1668
+ // 0.33.1:磁盘写走进程内 per-logPath 串行队列(withWriteLock),并在锁内重读;
1669
+ // 跨进程仍依赖宿主 flock(插件不参与),文档已声明单宿主限制。
944
1670
  // 0.8.0(B1 修复):步进恢复必须排除先前轮次已重放的源 seq,
945
1671
  // 否则每轮从区间头重放 → 消息副本成倍出现。
946
1672
  // 合成 turn 承载 notice 的完整理由见 opsCommit() 处(0.8.2,实测 340/364 空闲会话)。
947
1673
  const buildPlan = sourceEvents => {
948
1674
  const window = planNoticeWindow(sourceEvents)
949
1675
  const progress = restoreProgress(sourceEvents, restoreSeq)
1676
+ // 0.33.2:只有「确实有可重放内容且全部恢复完」才拒绝。零候选 marker
1677
+ // (只遮蔽 tool/system/注入行)此前也被判 complete → restore 与 discard 永久
1678
+ // 409,而 dock 又按 restoreComplete 隐藏它 —— 标记再也清不掉(0.5.6 逃生路被封死)。
1679
+ if (progress && progress.complete && (progress.candidateCount ?? 0) > 0 && !discard) {
1680
+ throw new OpsError('restore: this marker has already been restored (no pending turns)', 409)
1681
+ }
1682
+ // 0.39.7(srv-audit D12):discard 此前不幂等 —— 每次重试都追加一个合成 turn + notice
1683
+ // (实测连续 5 次 = 5 条)。已丢弃过就明确 409,不写事件。
1684
+ if (discard && progress && progress.discarded) {
1685
+ throw new OpsError('restore: this marker was already discarded', 409)
1686
+ }
950
1687
  const restorePlan = planRestore(sourceEvents, restoreSeq, upToSeq, progress ? progress.restoredSeqs : null)
951
1688
  restorePlan.turnStep = { turn: window.turn, step: window.step }
952
- restorePlan.window = window
953
1689
  if (discard) restorePlan.discard = true
954
- if (restorePlan.replayable.length === 0 && progress && !progress.complete && progress.pendingSeqs.length > 0) {
955
- // 请求的 upTo 之前已全部重放过 → 只补一条进度 notice(不重复重放)
956
- restorePlan.upToSeq = upToSeq != null ? Math.min(upToSeq, restorePlan.endSeq) : restorePlan.endSeq
1690
+ // 0.39.7(srv-audit D11):请求的 upTo 之前已全部重放过、但后续轮仍 pending 时,
1691
+ // 旧实现「只补一条进度 notice」——文案却是「区间无可重放…该回撤标记就此停用」,
1692
+ // 与事实(marker 仍 pending)矛盾,还白白写一个合成 turn。改为 409 并指明出路。
1693
+ // 注意与「upTo 早于候选」区分:那种情况 progress.restoredSeqs 为空,写一条
1694
+ // `restoredSourceSeqs: []` 的 notice 是**有意**的(否则进度判 legacy → 永久 409,
1695
+ // 见 test/empty-replay-recovery.test.js)。这里只挡「已经恢复过、再要同一段」。
1696
+ if (
1697
+ !discard &&
1698
+ restorePlan.replayable.length === 0 &&
1699
+ progress &&
1700
+ !progress.complete &&
1701
+ progress.pendingSeqs.length > 0 &&
1702
+ progress.restoredSeqs.length > 0
1703
+ ) {
1704
+ throw new OpsError(
1705
+ 'restore: nothing to replay up to this point (already restored); restore the remaining turns by their own upToSeq, or use discard to stop restoring',
1706
+ 409,
1707
+ )
957
1708
  }
958
1709
  return { win: window, plan: restorePlan }
959
1710
  }
960
- let { win, plan } = buildPlan(events)
961
- const acq = await acquireSession(targetCtx, sessionId)
1711
+ // 与 opsCommit 同一诊断口径(审计 §1.6):restore 也走两条面,失败要把原因带上。
1712
+ const diag = {}
1713
+ let win = null
1714
+ let plan = null
1715
+ const acq = await acquireSession(targetCtx, sessionId, diag)
962
1716
  if (acq !== null && acq.session !== undefined) {
963
1717
  // 0.10.8 孤儿护栏(与 opsCommit 同型):planRestore/进度校验本就在 preamble
964
1718
  // 之前完成;applyRestore 里的引擎 append 若抛(如 replay 坐标错开),
965
1719
  // preamble 已落——闭合合成 turn 再原样抛出,不留常开孤儿窗口。
1720
+ // 0.29.x P0(与 opsCommit 0.11.3 同型):postamble 只能写一次,且只补**未写**的部分。
1721
+ // 旧实现把整段 postamble 同时放在成功路径和 catch 里;成功路径的第二个 postamble
1722
+ // 事件被引擎拒(或 flush 抛错)时,catch 会把已追加的 step/end 再写一遍 →
1723
+ // 日志落成 `step/end, turn/end, step/end, turn/end`,宿主读盘判
1724
+ // `step/end does not match an open turn and step`,整份会话 corrupt。
1725
+ // 注意:closeWindow 必须声明在 try 之外 —— catch 也要用它。
1726
+ // P0(0.32.0):与 opsCommit 同款前置闸 —— 非 idle phase 写合成窗口 = 重号风险。
1727
+ const phaseErr = livePhaseError(targetCtx, acq.session, serviceOf(targetCtx, 'agents'))
1728
+ if (phaseErr) {
1729
+ acq.release()
1730
+ throw withResolveDiag(phaseErr, diag)
1731
+ }
1732
+ let state = null
966
1733
  try {
1734
+ // 0.40.1(srv-audit D4):与磁盘分支共用同一 per-logPath 串行队列 —— 规划回退读盘
1735
+ // 的 await 点会让两个并发 restore 基于同一份快照各写一遍(重复副本)。
1736
+ return await withWriteLock(logPath, async () => {
967
1737
  const liveEvents = sessionLogOf(acq.session)
968
- if (liveEvents) ({ win, plan } = buildPlan(liveEvents))
969
- for (const pre of noticeWindowPreamble(win)) acq.session.append(pre.kind, pre.data)
970
- const result = applyRestore(acq.session, plan, {
971
- flush: () => {
972
- flushSessions(targetCtx, acq.session)
973
- },
974
- })
975
- for (const post of noticeWindowPostamble(win)) acq.session.append(post.kind, post.data)
976
- const aligned = win.synthetic ? alignLiveTurnCursor(targetCtx, acq.session, win.turn) : false
1738
+ // 0.33.1:live 面是权威;拿不到事件本体才读盘兜底。
1739
+ const sourceEvents = liveEvents || mergePendingLiveWrites(logPath, (await readSessionFileAsync(logPath)).events)
1740
+ ;({ win, plan } = buildPlan(sourceEvents))
1741
+ // 0.33.10:agents 缺失只告警,不阻断。
1742
+ agentsServiceVisible(targetCtx, acq.session, win)
1743
+ // 0.34.2(M3):与磁盘路径共用同一份语义脚本(notice / replay / advance / close)。
1744
+ const script = buildRestoreScript({ win, plan })
1745
+ const liveResult = await runLiveScript(targetCtx, acq.session, sessionId, win, script, diag)
1746
+ notePendingLiveWrite(logPath, liveResult.state.emitted)
1747
+ state = liveResult.state
1748
+ const aligned = liveResult.aligned
1749
+ // 0.34.3:与磁盘路径同口径 —— eventSeqs = 本次实际写入的**全部**事件
1750
+ // (含窗口开合)。旧 live 只返回 notice+replay,模型看到的进度与磁盘路径不一致。
1751
+ const eventSeqs = state.emitted.filter(e => e && e.seq != null).map(e => e.seq)
977
1752
  return {
978
1753
  ok: true,
979
- ...result,
1754
+ restoredCount: plan.discard ? 0 : plan.replayable.length,
1755
+ skipped: plan.skipped,
1756
+ eventSeqs,
980
1757
  turnAligned: aligned,
981
1758
  discarded: plan.discard === true,
982
1759
  upToSeq: plan.upToSeq,
983
- restoredSourceSeqs: plan.replayable.map(i => i.seq),
1760
+ restoredSourceSeqs: plan.discard ? [] : plan.replayable.map(i => i.seq),
984
1761
  range: { startSeq: plan.startSeq, endSeq: plan.endSeq },
1762
+ ...(liveResult.partial === true ? { partial: true, warning: liveResult.warning } : {}),
985
1763
  }
1764
+ })
986
1765
  } catch (err) {
987
- for (const post of noticeWindowPostamble(win)) {
988
- try {
989
- acq.session.append(post.kind, post.data)
990
- } catch {
991
- /* postamble 被引擎拒:维持原错误上抛 */
992
- }
993
- }
994
- throw err
1766
+ // 规划阶段失败时一个事件都没写;runLiveScript 已处理窗口闭合与失败对齐。
1767
+ throw withResolveDiag(err, diag)
995
1768
  } finally {
996
1769
  acq.release()
997
1770
  }
998
1771
  }
999
- // store-miss → 磁盘路径:说明事件 + 重放事件批量追加(一个帧)
1000
- let cursor = nextSeqFrom(events)
1001
- const baseTime = Date.now()
1002
- const version = (await readSessionFileAsync(logPath)).header?.version ?? 4
1003
- const batch = noticeWindowPreamble(win).map((e, i) => ({
1004
- type: e.kind,
1005
- seq: cursor++,
1006
- time: baseTime + i,
1007
- data: e.data,
1008
- }))
1009
- const noticeBase = baseTime + batch.length
1010
- batch.push(
1011
- buildRestoreNoticeEvent({
1012
- seq: cursor++,
1013
- time: noticeBase,
1014
- turnStep: plan.turnStep,
1015
- version,
1016
- text: plan.discard
1017
- ? `[消息操作] 回撤标记 seq ${plan.restoreSeq} 已停用(丢弃):区间内容保持遮蔽、未重放;日志原文仍在,可搜索`
1018
- : restoreNoticeText(plan),
1019
- restoreSeq: plan.restoreSeq,
1020
- discard: plan.discard === true,
1021
- // 0.11.4:把本轮实际重放的源 seq 落进 notice,restoreProgress 才能累计进度、
1022
- // 下一轮 excludeSeqs 才不会重复重放同一批消息(详见 ops-core 该函数注释)。
1023
- restoredSourceSeqs: plan.discard ? [] : plan.replayable.map(i => i.seq),
1772
+ // store-miss → 磁盘路径:说明事件 + 重放事件批量追加(一个帧)。
1773
+ // 0.33.1:read→plan→append 串行化,并在锁内重读重规划(并发 restore 会写出重复 seq)。
1774
+ // 0.34.0:notice / 多助手 step 分配 / postamble 由 ops-write 脚本统一物化。
1775
+ return runDiskWrite({
1776
+ logPath,
1777
+ diag,
1778
+ plannedOf: events => {
1779
+ const planned = buildPlan(events)
1780
+ return { win: planned.win, plan: planned.plan }
1781
+ },
1782
+ scriptOf: ({ win: plannedWin, plan: plannedPlan }) => buildRestoreScript({ win: plannedWin, plan: plannedPlan }),
1783
+ resultOf: ({ win: plannedWin, plan: plannedPlan }, { batch }) => ({
1784
+ ok: true,
1785
+ disk: true,
1786
+ // 与 live 路径同字段:discard 的语义要让调用方一眼可见。
1787
+ discarded: plannedPlan.discard === true,
1788
+ syntheticTurn: plannedWin.synthetic === true,
1789
+ restoredCount: plannedPlan.discard ? 0 : plannedPlan.replayable.length,
1790
+ upToSeq: plannedPlan.upToSeq,
1791
+ restoredSourceSeqs: plannedPlan.discard ? [] : plannedPlan.replayable.map(i => i.seq),
1792
+ skipped: plannedPlan.skipped,
1793
+ eventSeqs: batch.map(e => e.seq),
1794
+ range: { startSeq: plannedPlan.startSeq, endSeq: plannedPlan.endSeq },
1024
1795
  }),
1025
- )
1026
- let offset = 0
1027
- for (const item of plan.discard ? [] : plan.replayable) {
1028
- batch.push(buildReplayEvent({ seq: cursor++, time: noticeBase + ++offset, item, turnStep: plan.turnStep, version }))
1029
- }
1030
- let tail = noticeBase + offset + 1
1031
- for (const e of noticeWindowPostamble(win)) batch.push({ type: e.kind, seq: cursor++, time: tail++, data: e.data })
1032
- await diskAppend(logPath, batch)
1033
- return {
1034
- ok: true,
1035
- disk: true,
1036
- syntheticTurn: win.synthetic === true,
1037
- restoredCount: plan.replayable.length,
1038
- upToSeq: plan.upToSeq,
1039
- restoredSourceSeqs: plan.replayable.map(i => i.seq),
1040
- skipped: plan.skipped,
1041
- eventSeqs: batch.map(e => e.seq),
1042
- range: { startSeq: plan.startSeq, endSeq: plan.endSeq },
1043
- }
1796
+ })
1044
1797
  }
1045
1798
 
1046
1799
  // ---------------------------------------------------------------------------
@@ -1052,11 +1805,11 @@ async function opsRestore(targetCtx, sessionId, restoreSeq, upToSeq, discard) {
1052
1805
  * 这里保持零静态依赖、可在测试里用桩验证。ops 为核心操作表,签名:
1053
1806
  * (targetCtx, sessionId[, seq]) → 结果对象,失败抛 OpsError。
1054
1807
  */
1055
- export function createMessageOpsTool({ defineTool, ops, ctx }) {
1808
+ export function createMessageOpsTool({ defineTool, ops, ctx, authorizeTarget = authorizeToolTarget }) {
1056
1809
  return defineTool({
1057
1810
  name: 'message_ops',
1058
1811
  description:
1059
- 'Manage DSH conversation messages: list messages with visibility, revert to a seq (surface replace shadows the tail), delete a single message, restore (replay) messages shadowed by a previous revert. These are the message-level operations dsh does NOT provide natively (use the built-in session/fork for branching and /export for archives). Sessions must not be running for mutating actions.',
1812
+ 'Manage DSH conversation messages: list messages with visibility, revert to a seq (surface replace shadows the tail), delete a single message, restore (replay) messages shadowed by a previous revert. Listing excludes rolled-back (shadowed) message bodies; it only reports them as hidden. Sessions must not be running for mutating actions. The target session must belong to the caller workspace (same cwd).',
1060
1813
  parameters: {
1061
1814
  action: {
1062
1815
  type: 'string',
@@ -1075,6 +1828,7 @@ export function createMessageOpsTool({ defineTool, ops, ctx }) {
1075
1828
  },
1076
1829
  upToSeq: {
1077
1830
  type: 'integer',
1831
+ description: 'restore only: replay up to this seq (per-turn step); omitted = replay all pending turns.',
1078
1832
  },
1079
1833
  },
1080
1834
  output: {
@@ -1083,10 +1837,15 @@ export function createMessageOpsTool({ defineTool, ops, ctx }) {
1083
1837
  return [{ type: 'text', text: value }]
1084
1838
  },
1085
1839
  },
1086
- async execute(args) {
1840
+ async execute(args, exec) {
1087
1841
  const action = args.action
1088
1842
  const sessionId = String(args.sessionId || '').trim()
1089
1843
  try {
1844
+ // 0.33.2(安全 P0):模型工具必须与宿主自己的 session 工具**同口径**授权 ——
1845
+ // 调用者 cwd 必须等于目标会话 header.cwd(宿主 dsh-tool-session-query 的
1846
+ // authorizeTarget 就是这么做的)。旧实现 execute(args) 完全不看 exec,
1847
+ // 任何模型/子代理能跨 workspace 读改别人的会话,且 node:fs 写入绕过沙箱。
1848
+ await authorizeTarget(exec, sessionId)
1090
1849
  let result
1091
1850
  // 0.5.2(P1):ops 自 0.2.1 起为 async——不 await 会把 Promise 直接送进 renderResult,
1092
1851
  // list/restore 必抛 TypeError(测试桩曾是同步的故漏检)。
@@ -1101,12 +1860,15 @@ export function createMessageOpsTool({ defineTool, ops, ctx }) {
1101
1860
  result = await ops.delete(ctx, sessionId, args.seq)
1102
1861
  break
1103
1862
  case 'restore':
1104
- result = await ops.restore(ctx, sessionId, args.seq)
1863
+ // 0.36.0:upToSeq 是「按轮恢复」的唯一入口,旧实现声明了参数却没传。
1864
+ result = await ops.restore(ctx, sessionId, args.seq, args.upToSeq)
1105
1865
  break
1106
1866
  default:
1107
1867
  throw new OpsError(`unknown action: ${action}`, 400)
1108
1868
  }
1109
- return renderResult(action, result)
1869
+ // 0.33.2(安全):list 默认不把已回滚/删除的原文喂回模型 —— 回撤的产品语义
1870
+ // 就是从上下文移除;HTTP /messages 仍保留 shadowed 行给恢复 UI 用。
1871
+ return renderResult(action, action === 'list' ? withoutShadowed(result) : result)
1110
1872
  } catch (e) {
1111
1873
  return `${action} failed: ${e && e.message ? e.message : e}`
1112
1874
  }
@@ -1114,6 +1876,35 @@ export function createMessageOpsTool({ defineTool, ops, ctx }) {
1114
1876
  })
1115
1877
  }
1116
1878
 
1879
+ /** list 结果去掉 shadowed 行(模型不再看到已回滚内容)。 */
1880
+ function withoutShadowed(r) {
1881
+ if (!r || !Array.isArray(r.messages)) return r
1882
+ return { ...r, messages: r.messages.filter(m => m && m.shadowed !== true) }
1883
+ }
1884
+
1885
+ /**
1886
+ * 模型工具的目标授权:调用者 cwd 必须等于目标会话 header.cwd。
1887
+ *
1888
+ * 与宿主 `dsh-tool-session-query/src/workspace-access.ts` 的 authorizeTarget 同口径。
1889
+ * 读 header 只解第一帧,成本与标题读取同量级。
1890
+ * @param {object} exec 工具执行上下文(宿主传入)
1891
+ * @param {string} sessionId 目标会话
1892
+ * @returns {Promise<void>} 未通过时抛 403/404
1893
+ */
1894
+ async function authorizeToolTarget(exec, sessionId) {
1895
+ const caller =
1896
+ exec && exec.agent && exec.agent.session && exec.agent.session.header && typeof exec.agent.session.header.cwd === 'string'
1897
+ ? exec.agent.session.header.cwd
1898
+ : null
1899
+ if (!caller) throw new OpsError('message_ops requires a workspace-bound agent (no session cwd)', 403)
1900
+ if (!isSessionId(sessionId)) throw new OpsError('invalid sessionId', 400)
1901
+ const { logPath } = pickSessionDir(sessionId)
1902
+ const header = readSessionHeader(logPath)
1903
+ if (typeof header.cwd === 'string' && header.cwd !== caller) {
1904
+ throw new OpsError('target session belongs to another workspace', 403)
1905
+ }
1906
+ }
1907
+
1117
1908
  /** 工具结果 → 模型可读的多行文本。 */
1118
1909
  function renderResult(action, r) {
1119
1910
  switch (action) {
@@ -1138,20 +1929,33 @@ function renderResult(action, r) {
1138
1929
  * 容错工具注册:ctx 已带 tools 服务就直接注册;没有就等它出现
1139
1930
  * (ctx.inject 子 fiber,永不 fatal);dsh-tools 包解析失败也只跳过。
1140
1931
  */
1141
- function registerToolTolerantly(ctx) {
1142
- function tryRegister(targetCtx) {
1143
- const tools = targetCtx.get('tools')
1932
+ function registerToolTolerantly(ctx, loadDefineTool) {
1933
+ // 0.37.3(真机形态):cordis 的 `ctx.inject(deps, fn)` 回调收到的是**注入命名空间**
1934
+ // (服务挂在同名属性上),不一定有 `.get()`。旧实现 `sub.get('tools')` 在后到的
1935
+ // 分支会抛 `targetCtx.get is not a function`,把「等 tools 出现」的容错路径变成
1936
+ // apply 期异常。这里两种取值都接受。
1937
+ const toolsOf = scope =>
1938
+ scope && typeof scope.get === 'function' ? scope.get('tools') : scope && scope.tools
1939
+ function tryRegister(scope) {
1940
+ const tools = toolsOf(scope)
1144
1941
  if (!tools || typeof tools.register !== 'function') return false
1145
1942
  // 动态 import:包缺失时只跳过工具,不拖垮插件的 HTTP 面。
1146
- import('@deepseek-ai/dsh-tools')
1147
- .then(({ defineTool }) => {
1943
+ // loadDefineTool 只给测试注入;生产走真实包。
1944
+ const loader = loadDefineTool || (() => import('@deepseek-ai/dsh-tools').then(m => m.defineTool))
1945
+ loader()
1946
+ .then(defineTool => {
1148
1947
  const ops = {
1149
1948
  list: (c, id) => opsList(c, id),
1150
1949
  revert: (c, id, seq) => opsCommit(c, 'revert', id, seq),
1151
1950
  delete: (c, id, seq) => opsCommit(c, 'delete', id, seq),
1152
1951
  restore: (c, id, seq, upToSeq) => opsRestore(c, id, seq, upToSeq),
1153
1952
  }
1154
- tools.register(createMessageOpsTool({ defineTool, ops, ctx: targetCtx }))
1953
+ // ops 始终绑定 apply 期的 ctx(不是 inject 命名空间)—— 工具执行时要用
1954
+ // 它解析 sessions/agents;命名空间对象上没有这些解析能力。
1955
+ tools.register(createMessageOpsTool({ defineTool, ops, ctx }))
1956
+ // 0.37.3:一行成功日志 —— 真机上「工具到底registered 没有」此前只能靠猜
1957
+ // (失败有 warn,成功零输出)。
1958
+ console.log('[message-ops] tool registered: message_ops')
1155
1959
  })
1156
1960
  // 0.9.0:不再静默吞错。原先 catch(() => {}) 让「工具注册成功与否」完全无从诊断
1157
1961
  // (实测日志里 defineTool / ERR_MODULE_NOT_FOUND 零命中)。
@@ -1196,6 +2000,13 @@ export function apply(ctx) {
1196
2000
  } catch (e) {
1197
2001
  console.log('[message-ops] probe failed: ' + e)
1198
2002
  }
2003
+ try {
2004
+ const captured = captureServices(ctx)
2005
+ console.log('[message-ops] captured services: sessions=' + !!captured.sessions + ' agents=' + !!captured.agents)
2006
+ } catch (e) {
2007
+ console.log('[message-ops] capture failed: ' + e)
2008
+ }
2009
+
1199
2010
  function registerHttp(host, targetCtx) {
1200
2011
  // --- GET /api/message-ops/messages:消息列表(只读) ---------------------
1201
2012
  targetCtx.effect(
@@ -1216,10 +2027,8 @@ export function apply(ctx) {
1216
2027
  }),
1217
2028
  )
1218
2029
  } catch (err) {
1219
- return sendJson(res, err instanceof OpsError ? err.status : 500, {
1220
- ok: false,
1221
- error: String(err && err.message ? err.message : err),
1222
- })
2030
+ const pub = publicErrorOf(err, errorStatusOf(err))
2031
+ return sendJson(res, pub.status, { ok: false, error: pub.error })
1223
2032
  }
1224
2033
  },
1225
2034
  }),
@@ -1237,20 +2046,22 @@ export function apply(ctx) {
1237
2046
  if (!(await fence(targetCtx, req, res))) return
1238
2047
  try {
1239
2048
  const url = new URL(req.url, 'http://localhost')
1240
- const limitRaw = Number.parseInt(url.searchParams.get('limit') || '', 10)
2049
+ const limitRaw = url.searchParams.get('limit')
2050
+ const limit = strictIntParam(limitRaw)
2051
+ if (limitRaw !== null && limit === undefined) {
2052
+ return sendJson(res, 400, { ok: false, error: 'invalid limit' })
2053
+ }
1241
2054
  return sendJson(
1242
2055
  res,
1243
2056
  200,
1244
2057
  await opsSearch(targetCtx, url.searchParams.get('sessionId') || '', url.searchParams.get('q') || '', {
1245
2058
  role: url.searchParams.get('role') || null,
1246
- limit: Number.isSafeInteger(limitRaw) ? limitRaw : undefined,
2059
+ limit,
1247
2060
  }),
1248
2061
  )
1249
2062
  } catch (err) {
1250
- return sendJson(res, err instanceof OpsError ? err.status : 500, {
1251
- ok: false,
1252
- error: String(err && err.message ? err.message : err),
1253
- })
2063
+ const pub = publicErrorOf(err, errorStatusOf(err))
2064
+ return sendJson(res, pub.status, { ok: false, error: pub.error })
1254
2065
  }
1255
2066
  },
1256
2067
  }),
@@ -1258,7 +2069,8 @@ export function apply(ctx) {
1258
2069
  )
1259
2070
 
1260
2071
  // --- GET /api/message-ops/text:单条消息全文(0.5.2 引用按钮按需取) ----------
1261
- // assistant 消息的 fullText 不在 messages 列表里(载荷控制),quote 点击时单取。
2072
+ // assistant 消息的 fullText 不在 messages 列表里(载荷控制),quote/铅笔点击时单取。
2073
+ // 0.25.0:改走 opsText —— 复用 loadDerived 的派生缓存,不再每次全量重读日志。
1262
2074
  targetCtx.effect(
1263
2075
  () =>
1264
2076
  host.register({
@@ -1270,25 +2082,15 @@ export function apply(ctx) {
1270
2082
  try {
1271
2083
  const url = new URL(req.url, 'http://localhost')
1272
2084
  const sessionId = url.searchParams.get('sessionId') || ''
1273
- const seq = Number.parseInt(url.searchParams.get('seq') || '', 10)
1274
- if (!isSessionId(sessionId)) throw new OpsError('invalid sessionId', 400)
1275
- if (!Number.isSafeInteger(seq) || seq < 0) throw new OpsError('invalid seq', 400)
1276
- // seq 0 在日志头里是结构事件区(permission/preset 等,实测恒非消息),
1277
- // messageText 恒空串;引用按钮不可能引用它,直接 404 而不是 200 {text:""}。
1278
- if (seq === 0) throw new OpsError('no quotable message at seq 0', 404)
1279
- const { logPath } = pickSessionDir(sessionId)
1280
- const { events } = await readSessionFileAsync(logPath)
1281
- const ev = events.find(e => e && e.seq === seq)
1282
- if (!ev) throw new OpsError('seq not found', 404)
1283
- // 0.10.8:宿主会把长文本拆成多段 content(seq 6830 实测 321+7954+20),
1284
- // 只回首段 = 摘要拦腰截断。messageTextFull 与 messageText 同一条
1285
- // 「合格 text 段」口径,聚合改为全量拼接。
1286
- return sendJson(res, 200, { ok: true, seq, text: messageTextFull(ev) })
2085
+ const seqRaw = url.searchParams.get('seq')
2086
+ const seq = strictIntParam(seqRaw)
2087
+ if (seq === undefined) {
2088
+ return sendJson(res, 400, { ok: false, error: 'invalid seq' })
2089
+ }
2090
+ return sendJson(res, 200, { ok: true, seq, text: await opsText(sessionId, seq, targetCtx) })
1287
2091
  } catch (err) {
1288
- return sendJson(res, err instanceof OpsError ? err.status : 500, {
1289
- ok: false,
1290
- error: String(err && err.message ? err.message : err),
1291
- })
2092
+ const pub = publicErrorOf(err, errorStatusOf(err))
2093
+ return sendJson(res, pub.status, { ok: false, error: pub.error })
1292
2094
  }
1293
2095
  },
1294
2096
  }),
@@ -1305,10 +2107,8 @@ export function apply(ctx) {
1305
2107
  try {
1306
2108
  return sendJson(res, 200, await opsCommit(targetCtx, mode, body.sessionId, body.seq))
1307
2109
  } catch (err) {
1308
- return sendJson(res, err instanceof OpsError ? err.status : 500, {
1309
- ok: false,
1310
- error: String(err && err.message ? err.message : err),
1311
- })
2110
+ const pub = publicErrorOf(err, errorStatusOf(err))
2111
+ return sendJson(res, pub.status, { ok: false, error: pub.error })
1312
2112
  }
1313
2113
  }
1314
2114
 
@@ -1346,6 +2146,15 @@ export function apply(ctx) {
1346
2146
  if (!body || typeof body !== 'object') return sendJson(res, 400, { ok: false, error: 'invalid json' })
1347
2147
  try {
1348
2148
  // 0.8.0:body.upToSeq 存在 → 按轮步进恢复(只到该 seq)
2149
+ // 0.33.2:不得用 Number() 强转("2"/true/[] 都会被接受)。
2150
+ if (body.upToSeq !== undefined && body.upToSeq !== null && !Number.isSafeInteger(body.upToSeq)) {
2151
+ return sendJson(res, 400, { ok: false, error: 'invalid upToSeq' })
2152
+ }
2153
+ // 0.41.2(srv-audit D20):discard 只接受布尔。旧实现 `=== true` 把
2154
+ // "true"/1 静默当 false(用户以为丢弃了、实际执行了恢复)。
2155
+ if (body.discard !== undefined && typeof body.discard !== 'boolean') {
2156
+ return sendJson(res, 400, { ok: false, error: 'invalid discard (boolean expected)' })
2157
+ }
1349
2158
  return sendJson(
1350
2159
  res,
1351
2160
  200,
@@ -1353,15 +2162,13 @@ export function apply(ctx) {
1353
2162
  targetCtx,
1354
2163
  body.sessionId,
1355
2164
  body.seq,
1356
- body.upToSeq != null ? Number(body.upToSeq) : undefined,
2165
+ body.upToSeq === undefined || body.upToSeq === null ? undefined : body.upToSeq,
1357
2166
  body.discard === true,
1358
2167
  ),
1359
2168
  )
1360
2169
  } catch (err) {
1361
- return sendJson(res, err instanceof OpsError ? err.status : 500, {
1362
- ok: false,
1363
- error: String(err && err.message ? err.message : err),
1364
- })
2170
+ const pub = publicErrorOf(err, errorStatusOf(err))
2171
+ return sendJson(res, pub.status, { ok: false, error: pub.error })
1365
2172
  }
1366
2173
  },
1367
2174
  }),
@@ -1378,12 +2185,12 @@ export function apply(ctx) {
1378
2185
  if (req.method !== 'GET') return sendJson(res, 405, { ok: false, error: 'method not allowed' })
1379
2186
  if (!(await fence(targetCtx, req, res))) return
1380
2187
  try {
1381
- return sendJson(res, 200, { ok: true, entries: await listTrash(targetCtx, { purgeExpired: true }) })
2188
+ // 0.33.7(sec L2):GET 不得有删除副作用。过期条目的清理改在
2189
+ // 会话删除/回收站动作(POST)里做。
2190
+ return sendJson(res, 200, { ok: true, entries: await listTrash(targetCtx) })
1382
2191
  } catch (err) {
1383
- return sendJson(res, err instanceof OpsError ? err.status : 500, {
1384
- ok: false,
1385
- error: String(err && err.message ? err.message : err),
1386
- })
2192
+ const pub = publicErrorOf(err, errorStatusOf(err))
2193
+ return sendJson(res, pub.status, { ok: false, error: pub.error })
1387
2194
  }
1388
2195
  },
1389
2196
  }),
@@ -1405,21 +2212,34 @@ export function apply(ctx) {
1405
2212
  try {
1406
2213
  return sendJson(res, 200, await action(targetCtx, body))
1407
2214
  } catch (err) {
1408
- return sendJson(res, err instanceof OpsError ? err.status : 500, {
1409
- ok: false,
1410
- error: String(err && err.message ? err.message : err),
1411
- })
2215
+ const pub = publicErrorOf(err, errorStatusOf(err))
2216
+ return sendJson(res, pub.status, { ok: false, error: pub.error })
1412
2217
  }
1413
2218
  },
1414
2219
  }),
1415
2220
  'dsh-message-ops: ' + path,
1416
2221
  )
1417
2222
 
1418
- sessionAction('/api/message-ops/session/delete', (c, b) => deleteSessionToTrash(c, b.sessionId, b.confirmTitle))
2223
+ sessionAction('/api/message-ops/session/delete', async (c, b) => {
2224
+ const out = await deleteSessionToTrash(c, b.sessionId, b.confirmTitle)
2225
+ // 顺带清理过期回收站条目(GET 已改为只读)。
2226
+ try {
2227
+ await listTrash(c, { purgeExpired: true })
2228
+ } catch {
2229
+ /* 清理失败不影响删除结果 */
2230
+ }
2231
+ return out
2232
+ })
1419
2233
  sessionAction('/api/message-ops/session/restore', (c, b) => restoreTrash(c, b.trashId))
1420
2234
  sessionAction('/api/message-ops/session/purge', (c, b) => purgeTrash(c, b.trashId))
1421
2235
  }
1422
2236
 
2237
+ // 0.35.6:**不得**在 `workspace/session-unarchiving` 上注册 listener。
2238
+ // 真机 A/B 证明:只要注册(即使 listener 立即返回、不抛错),宿主的
2239
+ // unarchive RPC 就报 `gateway/internal`(诊断版 listener 内日志从未执行)。
2240
+ // 保护性拦截因此放弃;回收站恢复走插件自己的 Restore,宿主限制记录在
2241
+ // docs/revert-restore-audit.md。
2242
+
1423
2243
  const ws = ctx.get('webServer')
1424
2244
  if (ws !== undefined) registerHttp(ws, ctx)
1425
2245
  else ctx.inject(['webServer'], sub => registerHttp(sub.webServer, sub))