dsh-log-contract 0.3.22 → 0.3.24

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,792 +0,0 @@
1
- /**
2
- * dsh-log-contract · adapters/dsh/surface.js
3
- *
4
- * DSH 专属:模型可见面(surface)的推导与改写语义。
5
- *
6
- * 契约层的不变量是「视图必须可重放、改写必须完整覆盖被遮蔽节点、改写必须单节点内容级、
7
- * 引用必须闭合且同作用域、视图节点键唯一」;DSH 的 replace 操作数形状、遮蔽集合、
8
- * 按文件版本的折叠择路、载体两段配对、wire 请求序列与 token 计量配对全部落在本文件。
9
- *
10
- * 客户端投影缓存(projcache)是渲染层缓存,不是落盘判定对象:本包不为它造判定,
11
- * 仅在适配器元数据里登记其归属(见 ADAPTER.projcache)。
12
- */
13
- import { violation } from '../../contract/verdict.js';
14
- import { isSafeInt } from '../../contract/invariants.js';
15
- import {
16
- SURFACE_TYPES,
17
- MODERN_SURFACE_TYPES,
18
- V4_SURFACE_TYPES,
19
- currentSurfaceTypes,
20
- MARKER_PREFIXES,
21
- } from './vocab.js';
22
- import { currentVocabulary } from './format-versions.js';
23
-
24
- // ── v0/v1/v2 旧格式的视图终验(运行时折叠是 v3 语义,旧格式必须用等价实现)──────
25
- /** v0/v1/v2 的 surface 候选类型(官方 rc.7 `SURFACE_EVENT_TYPES`,3 条)。 */
26
- const SURFACE_EVENT_TYPES = new Set(['user/message', 'assistant/message', 'tool/result']);
27
-
28
- /** Whether an event type can join the model-visible surface(rc.7 `isSurfaceEligibleType`)。 */
29
- export function isLegacySurfaceEligibleType(type) {
30
- return SURFACE_EVENT_TYPES.has(type);
31
- }
32
-
33
- /** Whether a runtime value is a non-negative safe event sequence(rc.7 `isEventSeq`)。 */
34
- function isEventSeq(value) {
35
- return typeof value === 'number' && Number.isSafeInteger(value) && value >= 0;
36
- }
37
-
38
- /** Whether a runtime value is the exact positional-replacement shape(rc.7 `isLegacyReplaceOpShape`:start/end)。 */
39
- function isLegacyReplaceOpShape(value) {
40
- if (value === null || typeof value !== 'object' || Array.isArray(value)) return false;
41
- const op = value;
42
- return (
43
- Object.keys(op).length === 3 &&
44
- Object.hasOwn(op, 'op') && Object.hasOwn(op, 'start') && Object.hasOwn(op, 'end') &&
45
- op.op === 'replace' && isEventSeq(op.start) && isEventSeq(op.end)
46
- );
47
- }
48
-
49
- /** Validate event-local surface eligibility and return its operation(rc.7 `surfaceOpOf`)。 */
50
- function surfaceOpOf(event) {
51
- if (!SURFACE_EVENT_TYPES.has(event.type)) {
52
- if (event.surfaceOp !== undefined) throw new Error(`session event "${event.type}" is not surface-eligible and cannot carry surfaceOp`);
53
- if (event.sourceEventSeqs !== undefined) throw new Error(`session event "${event.type}" is not surface-eligible and cannot carry sourceEventSeqs`);
54
- return undefined;
55
- }
56
- const op = event.surfaceOp;
57
- if (op === undefined) throw new Error(`session event "${event.type}" is surface-eligible and requires a surfaceOp marker`);
58
- if (op === 'append') return op;
59
- if (op === null || typeof op !== 'object' || Array.isArray(op)) throw new Error(`session event "${event.type}" carries an invalid surfaceOp`);
60
- if (!isLegacyReplaceOpShape(op)) throw new Error(`session event "${event.type}" carries an invalid replace surfaceOp`);
61
- return op;
62
- }
63
-
64
- /** Validate cited source-event seqs against prior log entries and the replacement range(rc.7 `assertProvenance`)。 */
65
- function assertProvenance(event, shadowedSeqs) {
66
- const raw = event.sourceEventSeqs;
67
- const sources = new Set();
68
- if (raw !== undefined) {
69
- if (!Array.isArray(raw)) throw new Error(`sourceEventSeqs on event at seq ${event.seq} must be an array when present`);
70
- if (raw.length === 0 && event.type !== 'assistant/message') throw new Error('sourceEventSeqs must not be empty except on assistant/message');
71
- let nonEarlierSource;
72
- for (const source of raw) {
73
- if (!isEventSeq(source)) throw new Error(`session event "${event.type}" sourceEventSeqs must densely contain non-negative safe integers`);
74
- sources.add(source);
75
- if (nonEarlierSource === undefined && source >= event.seq) nonEarlierSource = source;
76
- }
77
- if (sources.size !== raw.length) throw new Error('sourceEventSeqs must not contain duplicates');
78
- if (nonEarlierSource !== undefined) throw new Error(`sourceEventSeqs must reference earlier events: ${nonEarlierSource} >= current seq ${event.seq}`);
79
- }
80
- const missing = shadowedSeqs.filter((seq) => !sources.has(seq));
81
- if (missing.length > 0) throw new Error(`surface replace: sourceEventSeqs must include every shadowed surface node; missing ${missing.join(', ')}`);
82
- }
83
-
84
- /** Locate one replacement range without mutating the current fold state(rc.7 `replacementRange`)。 */
85
- function replacementRange(state, op) {
86
- const startIdx = state.nodes.indexOf(op.start);
87
- if (startIdx === -1) throw new Error(`surface replace: start seq ${op.start} not found in surface`);
88
- const endIdx = state.nodes.indexOf(op.end);
89
- if (endIdx === -1) throw new Error(`surface replace: end seq ${op.end} not found in surface`);
90
- if (startIdx > endIdx) throw new Error(`surface replace: start seq ${op.start} (index ${startIdx}) is after end seq ${op.end} (index ${endIdx})`);
91
- return { startIdx, endIdx, shadowedSeqs: state.nodes.slice(startIdx, endIdx + 1) };
92
- }
93
-
94
- /** Deep structural equality over the session-event JSON value domain(rc.7 `isDeepEqualJson`)。 */
95
- function isDeepEqualJson(a, b) {
96
- if (a === b) return true;
97
- if (Array.isArray(a) || Array.isArray(b)) {
98
- if (!Array.isArray(a) || !Array.isArray(b) || a.length !== b.length) return false;
99
- return a.every((item, i) => isDeepEqualJson(item, b[i]));
100
- }
101
- if (typeof a !== 'object' || typeof b !== 'object' || a === null || b === null) return false;
102
- const aKeys = Object.keys(a);
103
- if (aKeys.length !== Object.keys(b).length) return false;
104
- return aKeys.every((key) => Object.hasOwn(b, key) && isDeepEqualJson(a[key], b[key]));
105
- }
106
-
107
- /** Restrict a tool-result replacement to one current result's content(rc.7 `assertToolResultRewrite`)。 */
108
- function assertToolResultRewrite(event, shadowedSeqs, events, baseSeq) {
109
- if (event.type !== 'tool/result') return;
110
- if (shadowedSeqs.length !== 1) throw new Error('tool/result surface replacement must rewrite exactly one current node');
111
- for (const originalSeq of shadowedSeqs) {
112
- const original = events[originalSeq - baseSeq];
113
- if (original?.type !== 'tool/result') throw new Error('tool/result surface replacement must target a current tool/result');
114
- const originalRest = { ...original.data };
115
- const replacementRest = { ...event.data };
116
- const originalResult = original.data.message.content[0];
117
- const replacementResult = event.data.message.content[0];
118
- originalRest.message = { ...original.data.message, content: [{ ...originalResult, content: null }] };
119
- replacementRest.message = { ...event.data.message, content: [{ ...replacementResult, content: null }] };
120
- if (!isDeepEqualJson(originalRest, replacementRest)) throw new Error('tool/result surface replacement may change only content');
121
- }
122
- }
123
-
124
- /** Validate one event at its replay boundary and prepare its atomic fold transition(rc.7 `planSurfaceEvent`)。 */
125
- function planSurfaceEvent(state, event, expectedSeq, events, baseSeq) {
126
- if (event.seq !== expectedSeq) throw new Error(`session event seq ${event.seq} is not contiguous; expected ${expectedSeq}`);
127
- const surfaceOp = surfaceOpOf(event);
128
- if (surfaceOp === undefined) return undefined;
129
- if (surfaceOp === 'append') {
130
- assertProvenance(event, []);
131
- return { kind: 'append', seq: event.seq };
132
- }
133
- const range = replacementRange(state, surfaceOp);
134
- assertProvenance(event, range.shadowedSeqs);
135
- assertToolResultRewrite(event, range.shadowedSeqs, events, baseSeq);
136
- return { kind: 'replace', seq: event.seq, start: surfaceOp.start, end: surfaceOp.end, ...range };
137
- }
138
-
139
- /** Commit one previously validated surface transition(rc.7 `applySurfacePlan`)。 */
140
- function applySurfacePlan(state, plan) {
141
- if (plan?.kind === 'append') state.nodes.push(plan.seq);
142
- else if (plan?.kind === 'replace') {
143
- state.nodes.splice(plan.startIdx, plan.endIdx - plan.startIdx + 1, plan.seq);
144
- state.replaceGeneration += 1;
145
- }
146
- if (plan?.kind !== 'replace') return undefined;
147
- return { seq: plan.seq, start: plan.start, end: plan.end, shadowedSeqs: plan.shadowedSeqs };
148
- }
149
-
150
- /** Apply one event and return replacement metadata only when one occurred(rc.7 `applySurfaceEvent`)。 */
151
- function applySurfaceEvent(state, event, expectedSeq, events, baseSeq) {
152
- return applySurfacePlan(state, planSurfaceEvent(state, event, expectedSeq, events, baseSeq));
153
- }
154
-
155
- /**
156
- * Replay a complete session log through the **v0/v1/v2** canonical surface fold.
157
- *
158
- * @param events - session events in contiguous seq order(seq 从 0 起,与官方 `foldSurface` 同约定)。
159
- * @returns {{ nodes: number[], replacements: Array<{seq:number,start:number,end:number,shadowedSeqs:number[]}> }}
160
- * @throws when an event violates surface metadata, source-event references, range, or tool-result rewrite rules.
161
- */
162
- export function legacyFoldSurface(events) {
163
- const state = { nodes: [], replaceGeneration: 0 };
164
- const replacements = [];
165
- for (const [index, event] of events.entries()) {
166
- const replacement = applySurfaceEvent(state, event, index, events, 0);
167
- if (replacement !== undefined) replacements.push(replacement);
168
- }
169
- return { nodes: [...state.nodes], replacements };
170
- }
171
-
172
- // ── 视图改写与引擎/插件/wire 语义 ────────────────────────────────────────────
173
- /** replace 操作数精确形状(镜像旧格式 isReplaceOp,lib/index.js:300-303)。 */
174
- export function isReplaceOp(op) {
175
- return (
176
- typeof op === 'object' && op !== null &&
177
- Object.keys(op).length === 3 &&
178
- Object.hasOwn(op, 'op') && Object.hasOwn(op, 'start') && Object.hasOwn(op, 'end') &&
179
- op.op === 'replace' && isSafeInt(op.start) && isSafeInt(op.end)
180
- );
181
- }
182
-
183
- /**
184
- * 按**被检文件版本**归一化 replace 操作数到内部 `{start,end}`。
185
- *
186
- * 一手依据:官方 replace 字段在 v3 改名——旧格式(v0/v1/v2)`{op,start,end}`,
187
- * v3 `{op,startSeq,endSeq}`(`dsh-session-format-v2-to-v3/lib/index.js:361-371`)。
188
- * 用错形状会得 null,由调用方归因为 S4(真实违规)。
189
- *
190
- * @param {unknown} op 待归一化的 surfaceOp
191
- * @returns {{start:number,end:number}|null}
192
- */
193
- export function normalizeReplaceOp(op, version) {
194
- if (typeof op !== 'object' || op === null || Array.isArray(op)) return null;
195
- if (Object.keys(op).length !== 3 || op.op !== 'replace') return null;
196
- if (version >= 3) {
197
- return Object.hasOwn(op, 'startSeq') && Object.hasOwn(op, 'endSeq') && isSafeInt(op.startSeq) && isSafeInt(op.endSeq)
198
- ? { start: op.startSeq, end: op.endSeq }
199
- : null;
200
- }
201
- return Object.hasOwn(op, 'start') && Object.hasOwn(op, 'end') && isSafeInt(op.start) && isSafeInt(op.end)
202
- ? { start: op.start, end: op.end }
203
- : null;
204
- }
205
-
206
- /**
207
- * 与官方同语义的 surface 增量重放,逐事件归因 S1–S7。
208
- * @param {Array<{event:object, lineNo?:number}>} events 按日志顺序的事件(带 loc 包装)
209
- */
210
- export function replaySurface(events, version) {
211
- const violations = [];
212
- const nodes = [];
213
- let replaceGeneration = 0;
214
-
215
- for (const { event, lineNo } of events) {
216
- const loc = { seq: event.seq, lineNo, eventType: event.type };
217
- const eligible = currentSurfaceTypes(version).has(event.type);
218
- const op = event.surfaceOp;
219
- const src = event.sourceEventSeqs;
220
-
221
- if (!eligible) {
222
- if (op !== undefined || src !== undefined) {
223
- // 宿主 `@deepseek-ai/dsh-session@0.1.5-rc.1` 对该形状是**刻意容忍**的:
224
- // lib/index.js:270 `if (!KNOWN_SESSION_EVENT_TYPES.has(event.type) && event.ignorable === true) return;`
225
- // 同一函数的契约注释 lib/index.js:305 —— "Unknown ignorable records retain opaque
226
- // metadata and never change the surface."
227
- // ⇒ **未知**类型且 `ignorable===true` 的事件带 surfaceOp/sourceEventSeqs 是合法的不透明
228
- // 元数据(宿主接受,不报 S2)。
229
- // "该未知类型有没有消费者"由 E7 以 **warning** 表达(策略层,非宿主契约)。
230
- const unknownIgnorable = !currentVocabulary(version).has(event.type) && event.ignorable === true;
231
- if (!unknownIgnorable) {
232
- violations.push(violation('S2', loc, `非 surface 类型 "${event.type}" 不得携带 surfaceOp/sourceEventSeqs`));
233
- }
234
- }
235
- continue;
236
- }
237
- if (op === undefined) {
238
- violations.push(violation('S1', loc, `surface 候选类型 "${event.type}" 必须携带 surfaceOp 标记`));
239
- continue;
240
- }
241
-
242
- if (op === 'append') {
243
- violations.push(...provenanceViolations(event, loc, []));
244
- nodes.push(event.seq);
245
- continue;
246
- }
247
-
248
- const normalized = normalizeReplaceOp(op, version);
249
- if (normalized === null) {
250
- violations.push(violation('S4', loc, 'replace 操作数必须精确为 {op:"replace", start, end}(v0/v1/v2)或 {op:"replace", startSeq, endSeq}(v3),且端点为非负安全整数'));
251
- continue;
252
- }
253
- const startIdx = nodes.indexOf(normalized.start);
254
- const endIdx = nodes.indexOf(normalized.end);
255
- if (startIdx === -1 || endIdx === -1) {
256
- violations.push(violation('S4', loc, `replace 范围 ${normalized.start}..${normalized.end} 不在当前 surface 中(start 存在=${startIdx !== -1},end 存在=${endIdx !== -1})`));
257
- continue;
258
- }
259
- if (startIdx > endIdx) {
260
- violations.push(violation('S4', loc, `replace start ${normalized.start}(index ${startIdx})在 end ${normalized.end}(index ${endIdx})之后`));
261
- continue;
262
- }
263
- const shadowedSeqs = nodes.slice(startIdx, endIdx + 1);
264
- violations.push(...provenanceViolations(event, loc, shadowedSeqs));
265
- violations.push(...toolResultRewriteViolations(event, loc, shadowedSeqs));
266
- nodes.splice(startIdx, endIdx - startIdx + 1, event.seq);
267
- replaceGeneration += 1;
268
- }
269
-
270
- return { violations, nodes, replaceGeneration };
271
- }
272
-
273
- /** 镜像官方 assertProvenance(lib/index.js:320-337)。 */
274
- export function provenanceViolations(event, loc, shadowedSeqs) {
275
- const out = [];
276
- const raw = event.sourceEventSeqs;
277
- const sources = new Set();
278
- if (raw !== undefined) {
279
- if (!Array.isArray(raw)) {
280
- out.push(violation('S6', loc, `sourceEventSeqs 必须为数组(实际 ${typeof raw})`));
281
- return out;
282
- }
283
- if (raw.length === 0 && event.type !== 'assistant/message') {
284
- out.push(violation('S6', loc, 'sourceEventSeqs 不得为空(除 assistant/message 外)'));
285
- }
286
- let nonEarlier;
287
- for (const source of raw) {
288
- if (!isSafeInt(source)) {
289
- out.push(violation('S6', loc, `sourceEventSeqs 必须稠密包含非负安全整数(非法值 ${String(source)})`));
290
- continue;
291
- }
292
- if (sources.has(source)) {
293
- out.push(violation('S6', loc, `sourceEventSeqs 不得重复(${source})`));
294
- }
295
- sources.add(source);
296
- if (nonEarlier === undefined && source >= event.seq) nonEarlier = source;
297
- }
298
- if (nonEarlier !== undefined) {
299
- out.push(violation('S6', loc, `sourceEventSeqs 必须引用更早事件:${nonEarlier} >= 当前 seq ${event.seq}`));
300
- }
301
- }
302
- const missing = shadowedSeqs.filter((seq) => !sources.has(seq));
303
- if (missing.length > 0) {
304
- out.push(violation('S5', loc, `surface replace: sourceEventSeqs 必须覆盖每个被替换节点;缺失 ${missing.join(', ')}(共 ${missing.length} 个)`, { missingSeqs: missing }));
305
- }
306
- return out;
307
- }
308
-
309
- /** 镜像官方 assertToolResultRewrite(lib/index.js:369-395)的判定核心。 */
310
- export function toolResultRewriteViolations(event, loc, shadowedSeqs) {
311
- if (event.type !== 'tool/result') return [];
312
- const out = [];
313
- if (shadowedSeqs.length !== 1) {
314
- out.push(violation('S7', loc, `tool/result 替换必须恰好重写 1 个当前节点(实际 ${shadowedSeqs.length} 个)`));
315
- }
316
- return out;
317
- }
318
-
319
- /** M1 —— 客户端引擎层:turn/step 缺失(null)的 assistant/message 只能 replace。 */
320
- export function engineViolations(event, loc) {
321
- const out = [];
322
- if (event.type === 'assistant/message' && event.surfaceOp === 'append') {
323
- // turn/step 位于 event.data 层(正常消息 data.turn/data.step 为数字,
324
- // 插件 marker data.turn/data.step 为 null)
325
- const turn = event.data?.turn;
326
- const step = event.data?.step;
327
- if (turn == null || step == null) {
328
- out.push(violation('M1', loc, `assistant/message 以 append 进入 surface 但 data.turn/data.step 缺失(turn=${String(turn)}, step=${String(step)})——只能以 replace 承载(插件 marker 定义),append 会触发客户端引擎崩溃(rt.js:6816)`));
329
- }
330
- }
331
- return out;
332
- }
333
-
334
- /** P 层 —— 插件 marker 语义(retrace 等以 assistant/message replace 承载的 marker)。 */
335
- export function pluginViolations(event, loc) {
336
- const out = [];
337
- const isMarkerReplace = event.type === 'assistant/message' && event.surfaceOp && event.surfaceOp !== 'append' && event.data?.editor !== undefined;
338
- if (!isMarkerReplace) return out;
339
- const id = event.data?.message?.id;
340
- const known = typeof id === 'string' && MARKER_PREFIXES.some((p) => id.startsWith(`${p}-`));
341
- if (!known) {
342
- out.push(violation('P1', loc, `marker id "${String(id)}" 前缀不在已知列表(${MARKER_PREFIXES.join('/')}-)——改名后未登记遗留前缀,旧 marker 隐藏语义将断裂(软兼容丢失)`));
343
- }
344
- const src = event.sourceEventSeqs;
345
- if (Array.isArray(src) && src.includes(event.seq)) {
346
- out.push(violation('P2', loc, `marker 自身 seq ${event.seq} 出现在自身 sourceEventSeqs(shadowed 集)——自指语义错误(marker 节点被隐藏逻辑跳过,不应被自己隐藏)`));
347
- }
348
- return out;
349
- }
350
-
351
- /**
352
- * T3 —— step 节点 key 冲突。
353
- *
354
- * 客户端渲染消息列表 = 从事件流构建节点,节点 key = `data.turn:data.step`
355
- * (React 列表 key)。同 turn 内两个 step/start 的 step 号相同 → key 冲突 →
356
- * React 渲染死循环 → 空白渲染(正常轮与编辑块复用同一 step 号即可触发;
357
- * 同类冲突可成批出现在同一日志,修复方式为整块重编号)。
358
- *
359
- * 判定:扫 step/start,`data.turn:data.step` 组合重复 = error。
360
- * - 无任何 step/start 的日志跳过(与 T1 同款宽松);
361
- * - turn/step 为 null/undefined 的 step/start 不参与 key 判定(那是 T4 的域,
362
- * 且 null 自身已是致命)。
363
- *
364
- * @param events - 行序事件流(`{event, lineNo}`)。
365
- * @returns T3 违规列表。
366
- */
367
- export function stepKeyViolations(events) {
368
- const out = []
369
- if (!events.some(({ event }) => event.type === 'step/start')) return out
370
- const seen = new Map() // `${turn}:${step}` → { seq, lineNo }
371
- for (const { event, lineNo } of events) {
372
- if (event.type !== 'step/start') continue
373
- const turn = event.data?.turn
374
- const step = event.data?.step
375
- if (turn === null || turn === undefined || step === null || step === undefined) continue // T4 域
376
- const key = `${String(turn)}:${String(step)}`
377
- const prev = seen.get(key)
378
- if (prev !== undefined) {
379
- out.push(violation('T3', { seq: event.seq, lineNo, eventType: event.type }, `step 节点 key ${key} 冲突:seq ${prev.seq} 与 seq ${event.seq} 的 step/start 同 turn 同 step——客户端 React 渲染死循环空白渲染(渲染层失败;修复:同 turn 内 step 递增,不得复用;整块重编号)`))
380
- } else {
381
- seen.set(key, { seq: event.seq, lineNo })
382
- }
383
- }
384
- return out
385
- }
386
-
387
- /**
388
- * T4 —— step/消息本体 turn 缺失(null/undefined)。
389
- *
390
- * 客户端渲染状态机对 turn=null 的 step/消息**无法归属任何 turn** → 渲染死循环 →
391
- * 空白渲染「载入历史」(编辑块的 step/start+marker+step/end turn 全 null 即触发;
392
- * step 包裹/消息本体的 null-turn 判为致命)。
393
- *
394
- * 判定:`step/start|step/end|assistant/message` 的 `data.turn === null/undefined` = error。
395
- * - user/message 天然不带 turn(坐标来自外层 step),不查;
396
- * - assistant/chunk 坐标可能天然缺失,不查;
397
- * - retrace/marker(neutralize 产物,ignorable)不查。
398
- *
399
- * @param events - 行序事件流(`{event, lineNo}`)。
400
- * @returns T4 违规列表。
401
- */
402
- export function nullTurnStepViolations(events) {
403
- const out = []
404
- for (const { event, lineNo } of events) {
405
- if (event.type !== 'step/start' && event.type !== 'step/end' && event.type !== 'assistant/message') continue
406
- const turn = event.data?.turn
407
- if (turn === null || turn === undefined) {
408
- out.push(violation('T4', { seq: event.seq, lineNo, eventType: event.type }, `${event.type} 的 data.turn 为 ${String(turn)}(缺失)——客户端渲染状态机无法归属任何 turn → 渲染死循环空白渲染(step/消息本体必须带真实 turn 号)`))
409
- }
410
- }
411
- return out
412
- }
413
-
414
- /**
415
- * T5 —— turn/end 缺 reason.kind(malformed turn/end)。
416
- *
417
- * 官方 agent-loop 写 turn/end 恒带 `reason: { kind }`(dsh-agent-loop/lib/index.js:620;
418
- * kind ∈ completed|max-tokens|blocked|aborted|error|interrupted,中断恢复补
419
- * interrupted,见 dsh-session interruptedTurnClosers)。官方 validation 强制
420
- * reason.kind 存在——缺失 = malformed → 会话加载失败
421
- * (SessionPersistenceCorruptionError "malformed pre-react-loop turn/end")。
422
- *
423
- * 判定:turn/end 的 `data.reason?.kind` 缺失/非字符串 = error。
424
- *
425
- * @param events - 行序事件流(`{event, lineNo}`)。
426
- * @returns T5 违规列表。
427
- */
428
- export function turnEndReasonViolations(events) {
429
- const out = []
430
- for (const { event, lineNo } of events) {
431
- if (event.type !== 'turn/end') continue
432
- const reason = event.data?.reason
433
- if (!reason || typeof reason.kind !== 'string') {
434
- out.push(violation('T5', { seq: event.seq, lineNo, eventType: event.type }, `turn/end 缺 data.reason.kind(reason=${JSON.stringify(reason)})——官方 validation 拒绝 → 会话加载失败(malformed turn/end;turn/end 必须带 reason.kind,镜像 dsh-agent-loop:620)`))
435
- }
436
- }
437
- return out
438
- }
439
-
440
- /**
441
- * T1 —— token-meter 配对(复刻 @deepseek-ai/dsh-token-meter 的 _foldEvent 状态机):
442
- * - `step/start` 打开一个 step(记录 turn/step);
443
- * - `step/end` 必须匹配当前打开的 step/start,否则抛错;
444
- * - `assistant/message` 必须匹配当前打开的 step/start(turn/step 完全一致),否则抛错;
445
- * - `user/message` / `tool/result` 不检查(token meter 不配对)。
446
- *
447
- * 违反 = token meter 折叠抛错 → 该会话 `/compact` 与压力测量永久失败。
448
- * 已知命中:retrace 的 turn/step=null 编辑/撤回 marker(空 assistant/message replace)——
449
- * foldSurface 认可其合法性(M1 只约束 append 形态),但 token meter 崩溃。这是
450
- * M1 规则的盲区:M1 没约束"replace 也必须过 token meter"。
451
- *
452
- * @param events - 行序事件流(`{event, lineNo}`)。
453
- * @returns T1 违规列表。
454
- */
455
- export function tokenMeterViolations(events) {
456
- const out = [];
457
- // 无任何 step/start 的日志:现代 DSH 每个 assistant 回合必有 step/start,
458
- // 完全没有说明是极早期格式或简化日志——token-meter 的 step 配对兼容性未
459
- // 定义,不做配对检查(避免对旧结构误报;现代会话均有 step/start)。
460
- if (!events.some(({ event }) => event.type === 'step/start')) return out;
461
- let stepStart = undefined;
462
- for (const { event, lineNo } of events) {
463
- const loc = { seq: event.seq, lineNo, eventType: event.type };
464
- if (event.type === 'step/start') {
465
- if (stepStart !== undefined) {
466
- out.push(violation('T1', loc, `step/start at seq ${event.seq} arrived before turn ${stepStart.turn}/step ${stepStart.step} ended——token meter 折叠会抛错`));
467
- }
468
- stepStart = { turn: event.data?.turn, step: event.data?.step };
469
- } else if (event.type === 'step/end') {
470
- if (stepStart === undefined || stepStart.turn !== event.data?.turn || stepStart.step !== event.data?.step) {
471
- out.push(violation('T1', loc, `step/end at seq ${event.seq} has no matching step/start event(turn=${String(event.data?.turn)}, step=${String(event.data?.step)})——token meter 折叠会抛错`));
472
- }
473
- stepStart = undefined;
474
- } else if (event.type === 'assistant/message') {
475
- const turn = event.data?.turn;
476
- const step = event.data?.step;
477
- if (stepStart === undefined || stepStart.turn !== turn || stepStart.step !== step) {
478
- const open = stepStart === undefined ? '无打开的 step' : `打开的 step 为 turn ${stepStart.turn}/step ${stepStart.step}`;
479
- out.push(violation('T1', loc, `assistant/message at seq ${event.seq} has no matching step/start event(turn=${String(turn)}, step=${String(step)};${open})——token meter 折叠会抛错,/compact 与压力测量永久失败(retrace 的 turn-null 编辑/撤回 marker 即命中此条)`));
480
- }
481
- }
482
- }
483
- return out;
484
- }
485
-
486
- /**
487
- * T2 —— token-meter 的 sourceEventSeqs 引用必须同 turn/step。
488
- *
489
- * 镜像官方 `_estimateProviderAssistant`(dsh-token-meter lib/index.js:634-650):
490
- * `assistant/message` 的每个 `sourceEventSeqs` 若指向 `assistant/chunk`,其
491
- * turn/step 必须与消息自身一致;跨 step 引用 → 官方抛
492
- * `token meter: assistant/message at seq N source seq M belongs to another step`
493
- * (lib/index.js:645)。
494
- *
495
- * 成因:DSH resend/regenerate 在 agent 仍开着 step 时被触发,会把旧 step 的
496
- * chunk 全部引用进新 assistant/message(chunk 源引用跨 step)→
497
- * 离线 check(T1)全绿但实机 token-meter 崩溃 → 同样刷屏压垮 host。
498
- *
499
- * @param events - 行序事件流(`{event, lineNo}`)。
500
- * @returns T2 违规列表(error 级,token-meter 实机必崩)。
501
- */
502
- export function tokenMeterSourceViolations(events) {
503
- const out = [];
504
- const bySeq = new Map();
505
- for (const { event, lineNo } of events) bySeq.set(event.seq, { event, lineNo });
506
- for (const { event, lineNo } of events) {
507
- if (event.type !== 'assistant/message' || !Array.isArray(event.sourceEventSeqs) || event.sourceEventSeqs.length === 0) continue;
508
- const turn = event.data?.turn;
509
- const step = event.data?.step;
510
- if (turn == null || step == null) continue; // turn-null marker 由 T1 覆盖
511
- if (event.data?.usage === void 0) continue; // 无 usage 不触发 _estimateProviderAssistant(官方 :592 前提)——replace marker(S5 遮蔽语义,sourceEventSeqs 含非 chunk 节点)合法
512
- const seen = new Set();
513
- for (const s of event.sourceEventSeqs) {
514
- if (s >= event.seq) {
515
- out.push(violation('T2', { seq: event.seq, lineNo, eventType: event.type }, `assistant/message at seq ${event.seq} source seq ${s} is not earlier——token meter 折叠会抛错(_estimateProviderAssistant)`));
516
- break;
517
- }
518
- if (seen.has(s)) {
519
- out.push(violation('T2', { seq: event.seq, lineNo, eventType: event.type }, `assistant/message at seq ${event.seq} repeats source seq ${s}——token meter 折叠会抛错`));
520
- break;
521
- }
522
- seen.add(s);
523
- const src = bySeq.get(s);
524
- if (!src || src.event.type !== 'assistant/chunk') {
525
- out.push(violation('T2', { seq: event.seq, lineNo, eventType: event.type }, `assistant/message at seq ${event.seq} source seq ${s} is not assistant/chunk(实际 ${src ? src.event.type : 'MISSING'})——token meter 折叠会抛错(_estimateProviderAssistant :644 对非 chunk 引用直接 throw),/compact 与压力测量永久失败`));
526
- break; // 官方抛一次即停(consumedEvents 不前进),只报首条
527
- }
528
- if (src.event.data?.turn !== turn || src.event.data?.step !== step) {
529
- out.push(violation('T2', { seq: event.seq, lineNo, eventType: event.type }, `assistant/message at seq ${event.seq} source seq ${s} belongs to another step(消息 turn ${turn}/step ${step},源 turn ${String(src.event.data?.turn)}/step ${String(src.event.data?.step)})——token meter 折叠会抛错,/compact 与压力测量永久失败(DSH resend 在 step 未关时跨 step 引用)`));
530
- break; // 官方抛一次即停(consumedEvents 不前进),只报首条
531
- }
532
- }
533
- }
534
- return out;
535
- }
536
-
537
- /**
538
- * I1 —— inbox seed 相对重放(交接书 L1;镜像 dsh-agent lib/types/inbox.js)。
539
- *
540
- * 复刻官方 Inbox:从 `header.seedLength` 起重放 `agent/inbox/spliced`,
541
- * next-turn/next-step 双队列;每条 splice 校验
542
- * `start + removedCount <= 队列长` 且不产生重复 message id。违反 =
543
- * `resume failed: invalid persisted inbox splice at seq N`(fork 边界孤儿:
544
- * fork 时"移除父待处理提示词"的 removedCount=1 在子会话 seed 相对空 inbox 上非法)。
545
- *
546
- * @param events - 行序事件流(`{event, lineNo}`)。
547
- * @param header - 日志 header(取 seedLength)。
548
- * @returns I1 违规列表(error 级,resume 会被拒)。
549
- */
550
- export function inboxReplayViolations(events, header) {
551
- const out = [];
552
- const seedLength = header?.seedLength;
553
- if (typeof seedLength !== 'number' || !Number.isSafeInteger(seedLength) || seedLength < 0) {
554
- // 无 seedLength(非 fork 会话)→ Inbox 从 0 重放,语义等同全量;仍做队列校验
555
- }
556
- const state = { 'next-turn': [], 'next-step': [] };
557
- const startSeq = seedLength ?? 0;
558
- for (const { event, lineNo } of events) {
559
- if (event.seq < startSeq) continue;
560
- if (event.type !== 'agent/inbox/spliced') continue;
561
- const loc = { seq: event.seq, lineNo, eventType: event.type };
562
- const splice = event.data;
563
- if (!splice || typeof splice.target !== 'string' || !['next-turn', 'next-step'].includes(splice.target)) {
564
- out.push(violation('I1', loc, `spliced 缺合法 target(next-turn/next-step):${JSON.stringify(splice)?.slice(0, 80)}`));
565
- continue;
566
- }
567
- const inbox = state[splice.target];
568
- const removedCount = splice.removedCount ?? 0;
569
- if (!Number.isSafeInteger(splice.start) || splice.start < 0 || splice.start > inbox.length
570
- || !Number.isSafeInteger(removedCount) || removedCount < 0
571
- || splice.start + removedCount > inbox.length) {
572
- out.push(violation('I1', loc, `invalid inbox splice @seq ${event.seq}:target=${splice.target} start=${splice.start} removedCount=${removedCount} 但队列长 ${inbox.length}(seedLength=${seedLength})——resume 会被拒(fork 边界孤儿 spliced 即此形态,removedCount 指向 seed 相对空 inbox)`));
573
- continue;
574
- }
575
- const inserted = Array.isArray(splice.inserted) ? splice.inserted : [];
576
- const candidate = inbox.slice(0, splice.start).concat(inserted, inbox.slice(splice.start + removedCount));
577
- const ids = new Set();
578
- const other = splice.target === 'next-turn' ? state['next-step'] : state['next-turn'];
579
- for (const message of [...candidate, ...other]) {
580
- const id = message?.id ?? message?.message?.id;
581
- if (id === undefined) continue;
582
- if (ids.has(id)) {
583
- out.push(violation('I1', loc, `message "${id}" 已在待处理队列中(target=${splice.target})——resume 会被拒(重复 pending id)`));
584
- break;
585
- }
586
- ids.add(id);
587
- }
588
- inbox.splice(splice.start, removedCount, ...inserted);
589
- }
590
- return out;
591
- }
592
-
593
- /** 从事件推导 wire 消息(与 dsh-session deriveEventMessage 同语义)。 */
594
- export function deriveWireMessage(event) {
595
- if (event.type === 'user/message') {
596
- return { role: 'user', content: event.data?.content ?? [] };
597
- }
598
- if (event.type === 'assistant/message') {
599
- const m = event.data?.message;
600
- if (!m || !Array.isArray(m.content) || m.content.length === 0) return null;
601
- return { role: 'assistant', content: m.content };
602
- }
603
- if (event.type === 'tool/result') {
604
- return { role: 'tool', content: event.data?.message?.content ?? [] };
605
- }
606
- return null;
607
- }
608
-
609
- /**
610
- * Wire 级校验(W1/W2):按 surface 顺序展开模型请求消息流,
611
- * 检查 tool 消息是否悬空(缺前置 assistant tool-call)以及 user 文本
612
- * 是否插在 tool_calls 与结果之间。strict 端点(MiMo 等)直接 INVALID_REQUEST。
613
- * @param events - 展开后的完整事件流(含 chunk 展开)。
614
- * @returns 违规列表。
615
- */
616
- export function wireViolations(events, version) {
617
- const out = [];
618
- // 先折叠 surface(append 入列;replace 移除 [start..end] 并将 marker 自身入列)
619
- const nodes = [];
620
- const bySeq = new Map();
621
- for (const { event, lineNo } of events) {
622
- bySeq.set(event.seq, { event, lineNo });
623
- if (!currentSurfaceTypes(version).has(event.type)) continue;
624
- const op = event.surfaceOp;
625
- if (op === 'append') {
626
- nodes.push(event.seq);
627
- } else if (op !== undefined) {
628
- const normalized = normalizeReplaceOp(op, version);
629
- const s = normalized === null ? -1 : nodes.indexOf(normalized.start);
630
- const e = normalized === null ? -1 : nodes.indexOf(normalized.end);
631
- if (s !== -1 && e !== -1 && s <= e) nodes.splice(s, e - s + 1, event.seq);
632
- else nodes.push(event.seq);
633
- }
634
- }
635
- // 展开 wire 流
636
- const wire = [];
637
- for (const seq of nodes) {
638
- const rec = bySeq.get(seq);
639
- if (!rec) continue;
640
- const m = deriveWireMessage(rec.event);
641
- if (m === null) continue;
642
- if (m.role === 'assistant') {
643
- wire.push({ role: 'assistant', tc: m.content.filter((b) => b.type === 'tool-call').length, seq, lineNo: rec.lineNo });
644
- } else if (m.role === 'user') {
645
- const text = m.content.some((b) => b.type === 'text');
646
- const trs = m.content.filter((b) => b.type === 'tool-result').length;
647
- if (text) wire.push({ role: 'user', seq, lineNo: rec.lineNo });
648
- for (let i = 0; i < trs; i++) wire.push({ role: 'tool', seq, lineNo: rec.lineNo });
649
- } else {
650
- wire.push({ role: m.role, seq, lineNo: rec.lineNo });
651
- }
652
- }
653
- let pending = 0;
654
- let pendingSeq = null;
655
- for (const w of wire) {
656
- if (w.role === 'assistant') {
657
- pending = w.tc;
658
- pendingSeq = pending > 0 ? w.seq : null;
659
- } else if (w.role === 'tool') {
660
- if (pending <= 0) {
661
- out.push(violation('W1', { seq: w.seq, lineNo: w.lineNo }, `wire: tool 消息 @seq ${w.seq} 悬空——surface 中没有未满足的 assistant tool-call(严格端点会 INVALID_REQUEST)`));
662
- } else {
663
- pending--;
664
- if (pending === 0) pendingSeq = null;
665
- }
666
- } else if (w.role === 'user' && pending > 0) {
667
- out.push(violation('W2', { seq: w.seq, lineNo: w.lineNo }, `wire: user 文本 @seq ${w.seq} 插在 assistant tool_calls(@seq ${pendingSeq})与其 tool 结果之间——严格端点会拒绝该序列`));
668
- }
669
- }
670
- return out;
671
- }
672
-
673
- // ── P5 · carrier 两段配对 ──────────────────────────────────────────────
674
-
675
- /** 第 1 段(审计段):`compaction/prune` + `data.shadowedRange`/`shadowedSeqs`(插件两段载体)。 */
676
- export function isCarrierAuditSegment(event) {
677
- if (!event || event.type !== 'compaction/prune') return false;
678
- const data = event.data;
679
- if (!data || typeof data !== 'object') return false;
680
- const range = data.shadowedRange;
681
- return typeof range === 'object' && range !== null && isSafeInt(range.start) && isSafeInt(range.end) && Array.isArray(data.shadowedSeqs);
682
- }
683
-
684
- /** 从 surfaceOp 取 replace 的 [start,end](按文件版本择路:v3+ startSeq/endSeq)。 */
685
- export function surfaceReplaceRange(op, version) {
686
- if (!op || typeof op !== 'object' || op.op !== 'replace') return null;
687
- if (version >= 3) {
688
- return isSafeInt(op.startSeq) && isSafeInt(op.endSeq) ? { start: op.startSeq, end: op.endSeq } : null;
689
- }
690
- return isSafeInt(op.start) && isSafeInt(op.end) ? { start: op.start, end: op.end } : null;
691
- }
692
-
693
- /** 审计段与载体的区间是否一致(配对的结构证据)。 */
694
- export function carrierRangesMatch(audit, carrier, version) {
695
- const range = audit?.data?.shadowedRange;
696
- const op = surfaceReplaceRange(carrier?.surfaceOp, version);
697
- return Boolean(range && op && range.start === op.start && range.end === op.end);
698
- }
699
-
700
- /**
701
- * P5 —— carrier 两段配对(读侧)。
702
- *
703
- * 现行写法:`sourceEventSeqs = [审计段 seq, ...被遮蔽节点]`;
704
- * 第 2 段 = 紧随审计段的 surface replace。规则:
705
- * - 审计段 seq 在 **首元素** ⇒ 通过(现役);
706
- * - 在 **末元素** ⇒ 通过(旧顺序,读侧容错),给 warning(不静默);
707
- * - 在中间位 / 载体紧邻审计段却**完全没引用**它 ⇒ error(配对失败 / 孤儿审计段)。
708
- * 官方 compaction 的 `compaction/summary` 引用是另一形状(`[compaction/start, summary, …]`),
709
- * 审计段类型限定 `compaction/prune` 天然不误报。
710
- *
711
- * @param {Array<{event:object,lineNo?:number}>} events 行序事件
712
- * @param {{version?:number}} [opts] 被检文件版本(决定 replace 字段名)
713
- * @returns P5 违规列表
714
- */
715
- export function carrierPairingViolations(events, { version = 0 } = {}) {
716
- const out = [];
717
- const list = events ?? [];
718
- const audits = new Map();
719
- for (const { event, lineNo } of list) {
720
- if (isCarrierAuditSegment(event) && isSafeInt(event.seq)) audits.set(event.seq, { event, lineNo });
721
- }
722
- if (audits.size === 0) return out;
723
- for (let idx = 0; idx < list.length; idx++) {
724
- const { event, lineNo } = list[idx];
725
- if (!event || !event.surfaceOp || typeof event.surfaceOp !== 'object' || event.surfaceOp.op !== 'replace') continue;
726
- const loc = { seq: event.seq, lineNo, eventType: event.type };
727
- const src = event.sourceEventSeqs;
728
- if (!Array.isArray(src)) continue; // S6/S10 负责
729
- const refs = [];
730
- for (let i = 0; i < src.length; i++) {
731
- const audit = audits.get(src[i]);
732
- if (audit && src[i] < event.seq) refs.push({ audit, pos: i });
733
- }
734
- // 读侧**两种写法都认**(两种都在真实日志中出现过):
735
- // ① 现役:`[审计段 seq, ...被遮蔽节点]`(审计段 seq 在首位);
736
- // ② 早期:`[区间起点, ...被遮蔽节点]`(**不引用**审计段 seq;"区间起点"= replace 范围起点)。
737
- // 两种都不报;其余(审计段 seq 在中间位、或首元素既非审计段也非区间起点)= 配对失败。
738
- const range = surfaceReplaceRange(event.surfaceOp, version);
739
- const legacyStartFirst = range !== null && src[0] === range.start;
740
- if (refs.length > 0) {
741
- for (const { audit, pos } of refs) {
742
- if (pos === 0 || legacyStartFirst) continue; // 现役 / 早期写法
743
- out.push(violation('P5', loc, `carrier 两段配对:审计段 seq ${audit.event.seq} 出现在 sourceEventSeqs 第 ${pos} 位,且首元素既不是审计段 seq 也不是区间起点(${String(src[0])} ≠ ${String(range?.start)})——读侧只认两种写法:[审计段, ...](现役)或 [区间起点, ...](早期)`));
744
- }
745
- continue;
746
- }
747
- const prev = idx > 0 ? list[idx - 1] : undefined;
748
- if (prev && isCarrierAuditSegment(prev.event) && carrierRangesMatch(prev.event, event, version)) {
749
- if (legacyStartFirst) continue; // 早期写法:区间起点开头、不引用审计段 ⇒ 读侧容错
750
- out.push(violation('P5', loc, `carrier 两段配对失败(孤儿审计段):紧邻的审计段 seq ${prev.event.seq}(compaction/prune,区间 ${prev.event.data.shadowedRange.start}..${prev.event.data.shadowedRange.end})既未被本载体 sourceEventSeqs 引用,首元素也不是区间起点(${String(src[0])} ≠ ${prev.event.data.shadowedRange.start})——第 2 段首元素必须是第 1 段 seq(现役)或区间起点(早期写法)`));
751
- }
752
- }
753
- return out;
754
- }
755
-
756
- /**
757
- * P5 —— 写侧(现役写法严格校验)。`events` = 已存在事件 + 拟写事件(拟写事件在最后)。
758
- * 判据:拟写载体若紧邻审计段,`sourceEventSeqs[0]` 必须等于该审计段 seq;任何被引用的
759
- * 审计段 seq 都必须出现在首元素。
760
- * @param {Array<object>} events 完整事件列表(拟写事件在末尾)
761
- * @param {{version?:number}} [opts]
762
- * @returns P5 违规列表(error 级 = 写入被拒)
763
- */
764
- export function carrierWriteViolations(events, { version = 3 } = {}) {
765
- const out = [];
766
- const list = events ?? [];
767
- if (list.length === 0) return out;
768
- const candidate = list[list.length - 1];
769
- if (!candidate || !candidate.surfaceOp || typeof candidate.surfaceOp !== 'object' || candidate.surfaceOp.op !== 'replace') return out;
770
- const src = candidate.sourceEventSeqs;
771
- if (!Array.isArray(src)) return out; // S6/S10 负责
772
- const loc = { seq: candidate.seq, lineNo: null, eventType: candidate.type };
773
- const audits = new Map();
774
- for (const event of list) if (isCarrierAuditSegment(event) && isSafeInt(event.seq)) audits.set(event.seq, event);
775
- // ① 紧邻审计段(最强的配对证据):首元素必须就是它。
776
- const prev = list[list.length - 2];
777
- if (isCarrierAuditSegment(prev) && carrierRangesMatch(prev, candidate, version)) {
778
- if (src[0] !== prev.seq) {
779
- out.push(violation('P5', loc, `carrier 两段配对(写侧):紧邻审计段 seq ${prev.seq}(compaction/prune),第 2 段 sourceEventSeqs 首元素必须是它(实际首元素 ${String(src[0])})——写入被拒`));
780
- }
781
- return out;
782
- }
783
- // ② 其余情况:任何被引用的审计段 seq 都必须在首元素(写侧严格)。
784
- for (let i = 1; i < src.length; i++) {
785
- const audit = audits.get(src[i]);
786
- if (audit && src[i] < candidate.seq) {
787
- out.push(violation('P5', loc, `carrier 两段配对(写侧):审计段 seq ${audit.seq} 出现在 sourceEventSeqs 第 ${i} 位,但现役写法要求首元素 = 第 1 段 seq——写入被拒`));
788
- break;
789
- }
790
- }
791
- return out;
792
- }