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.
package/lib/checks.js CHANGED
@@ -1,67 +1,1335 @@
1
1
  /**
2
2
  * dsh-log-contract · lib/checks.js
3
3
  *
4
- * 逐事件契约检查的**聚合面**:离线体检(validate.js)与写前校验(prewrite.js)
5
- * 复用同一套判定,保证"体检看到的问题 = 写入前拦下的问题"。
6
- *
7
- * 实现位置:
8
- * - 平台无关不变量 → contract/invariants.js
9
- * - DSH 事件形状 / 视图改写 / 版本路由与迁移 → adapters/dsh/
10
- *
11
- * 导出名与既有版本保持一致(公开面不变)。
12
- */
13
- export { violation } from '../contract/verdict.js';
14
- export { isSafeInt } from '../contract/invariants.js';
15
- export {
16
- envelopeViolations,
17
- messageShapeViolations,
18
- toolPairingViolations,
19
- toolResultStructureViolations,
20
- ignorableTypeViolations,
21
- sourceEventSeqElementViolations,
22
- rawSourceEventSeqViolations,
23
- isSeqRangePair,
24
- physicalOrderViolations,
25
- chunkRowMalformationViolations,
26
- physicalSequence,
27
- } from '../adapters/dsh/event-shapes.js';
28
- export {
29
- SURFACE_TYPES,
30
- MODERN_SURFACE_TYPES,
31
- V4_SURFACE_TYPES,
32
- currentSurfaceTypes,
33
- CHUNK_ROW_TYPES,
34
- MARKER_PREFIXES,
35
- ENVELOPE_ALLOWED_KEYS,
36
- DEFAULT_IGNORABLE_WHITELIST,
37
- resolveIgnorableWhitelist,
38
- isIgnorableRegistered,
39
- } from '../adapters/dsh/vocab.js';
40
- export {
41
- isReplaceOp,
42
- normalizeReplaceOp,
43
- replaySurface,
44
- provenanceViolations,
45
- toolResultRewriteViolations,
46
- engineViolations,
47
- pluginViolations,
48
- stepKeyViolations,
49
- nullTurnStepViolations,
50
- turnEndReasonViolations,
51
- tokenMeterViolations,
52
- tokenMeterSourceViolations,
53
- inboxReplayViolations,
54
- deriveWireMessage,
55
- wireViolations,
56
- isCarrierAuditSegment,
57
- surfaceReplaceRange,
58
- carrierRangesMatch,
59
- carrierPairingViolations,
60
- carrierWriteViolations,
61
- } from '../adapters/dsh/surface.js';
62
- export {
63
- finalFold,
64
- migrationPrecheckViolations,
65
- seedLengthViolations,
66
- declarativeIgnorableViolations,
67
- } from '../adapters/dsh/format-versions.js';
4
+ * 逐事件契约检查(共享层):离线体检(validate.js)与写前校验(prewrite.js)
5
+ * 复用同一套判定逻辑,保证"体检看到的问题 = 写入前拦下的问题"。
6
+ *
7
+ * 全部判定与 `@deepseek-ai/dsh-session@0.1.0-rc.7` 官方实现同语义,
8
+ * 每条违规都挂 `lib/contracts.js` 中的规则 id 与官方源码出处。
9
+ */
10
+ import { isSurfaceEligibleType } from '@deepseek-ai/dsh-session';
11
+ import { isJsonValue, decodeSeqRanges } from './compat.js';
12
+ import { currentVocabulary, currentFold, V0_EVENT_TYPES } from './vocab.js';
13
+ import { ruleById } from './contracts.js';
14
+
15
+ export const SURFACE_TYPES = new Set(['user/message', 'assistant/message', 'tool/result']);
16
+ /** v3 新增 `system/message`(官方 `SURFACE_EVENT_TYPES`,0.1.5 `lib/index.js:149-154`)。 */
17
+ export const MODERN_SURFACE_TYPES = new Set([...SURFACE_TYPES, 'system/message']);
18
+ /** v4 新增 `developer/message`(官方 `SURFACE_EVENT_TYPES`,dsh-session@0.2.0-rc.2 `src/surface.ts:50-56`)。 */
19
+ export const V4_SURFACE_TYPES = new Set([...MODERN_SURFACE_TYPES, 'developer/message']);
20
+ export const CHUNK_ROW_TYPES = new Set(['text-chunks', 'reasoning-chunks', 'tool-call-chunks']);
21
+
22
+ /** 当前文件版本适用的 surface 候选类型集(v3 起含 system/message,v4 起含 developer/message)。version = 被检文件版本。 */
23
+ export function currentSurfaceTypes(version) {
24
+ if (version >= 4) return V4_SURFACE_TYPES;
25
+ return version >= 3 ? MODERN_SURFACE_TYPES : SURFACE_TYPES;
26
+ }
27
+ export const MARKER_PREFIXES = ['retrace', 'message-editor'];
28
+
29
+ /** 构造一条违规记录。 */
30
+ export function violation(id, eventOrLoc, message, extra = {}) {
31
+ const rule = ruleById(id);
32
+ const loc = eventOrLoc ?? {};
33
+ return {
34
+ id,
35
+ severity: rule?.severity ?? 'error',
36
+ layer: rule?.layer ?? 'unknown',
37
+ seq: typeof loc.seq === 'number' ? loc.seq : null,
38
+ lineNo: typeof loc.lineNo === 'number' ? loc.lineNo : null,
39
+ eventType: loc.eventType ?? null,
40
+ message,
41
+ source: rule?.source ?? null,
42
+ ...extra,
43
+ };
44
+ }
45
+
46
+ export function isSafeInt(v) {
47
+ return typeof v === 'number' && Number.isSafeInteger(v) && v >= 0;
48
+ }
49
+
50
+ /** 事件信封 shape:seq/type/time/data(E1/E3/E4/E5/E6)。version = 被检文件版本。 */
51
+ export function envelopeViolations(event, loc, version) {
52
+ const out = [];
53
+ if (!isSafeInt(event.seq)) {
54
+ out.push(violation('E1', loc, `事件 seq 缺失或非法(${String(event.seq)}),必须为非负安全整数`));
55
+ }
56
+ if (typeof event.type !== 'string') {
57
+ out.push(violation('E3', loc, `事件缺少 type 字符串(${String(event.type)})`));
58
+ } else if (!currentVocabulary(version).has(event.type) && event.ignorable !== true) {
59
+ out.push(violation('E3', loc, `type "${event.type}" 不在已知词汇表内且未带 ignorable 标记(可能由更新版本的 harness 写入)`));
60
+ }
61
+ if (!isJsonValue(event.data)) {
62
+ out.push(violation('E4', loc, 'data 不是 lossless-JSON(函数/循环引用/非有限数等),写入热路径会拒绝'));
63
+ }
64
+ if (event.surfaceOp !== undefined && !isJsonValue(event.surfaceOp)) {
65
+ out.push(violation('E4', loc, 'surfaceOp 不是 lossless-JSON'));
66
+ }
67
+ if (event.sourceEventSeqs !== undefined && !isJsonValue(event.sourceEventSeqs)) {
68
+ out.push(violation('E4', loc, 'sourceEventSeqs 不是 lossless-JSON'));
69
+ }
70
+ if (event.type === 'request/header-delta') {
71
+ out.push(violation('E5', loc, '使用已删除的遗留格式 request/header-delta——写入会成功(宿主 append 不看 type)、下一次读取才炸;请改用当前格式'));
72
+ }
73
+ if (event.type === 'request/header' && event.data?.reason === 'fallback') {
74
+ out.push(violation('E5', loc, 'request/header 使用已删除的遗留 reason "fallback"'));
75
+ }
76
+ // ── 2026-09-14 实测:3 例确证漏检补成候选规则 ───────────────────────
77
+ // E8 信封键白名单:宿主 `assertSessionEventEnvelope`(@deepseek-ai/dsh-session@0.1.5-rc.1
78
+ // lib/index.js:852-861)逐键 switch,只认 7 个键,其余一律 `invalid event envelope`。
79
+ // 实测反例:宿主拒、旧契约 0 违规。
80
+ if (typeof event === 'object' && event !== null) {
81
+ const extra = Object.keys(event).filter((k) => !ENVELOPE_ALLOWED_KEYS.has(k));
82
+ if (extra.length > 0) {
83
+ out.push(violation('E8', loc, `事件信封含多余键 ${extra.join(', ')}——宿主只认 {${[...ENVELOPE_ALLOWED_KEYS].join(',')}}(dsh-session@0.1.5-rc.1 lib/index.js:852-861)`));
84
+ }
85
+ }
86
+ // E10 request/header 的 data 字段约束:宿主 `validateSessionEventData`
87
+ // (dsh-session@0.1.5-rc.1 lib/index.js:231-248)——`header.system` 必须省略、
88
+ // 空 tools / 空 adapterDefaults 必须省略。实测反例:宿主拒、旧契约 0 违规。
89
+ if (event.type === 'request/header') {
90
+ const header = event.data?.header;
91
+ if (typeof header !== 'object' || header === null || Array.isArray(header)) {
92
+ out.push(violation('E10', loc, 'request/header 的 data.header 必须是对象'));
93
+ } else {
94
+ if (Object.hasOwn(header, 'system')) out.push(violation('E10', loc, 'request/header 必须省略 header.system(系统提示改走 system/message)——宿主 lib/index.js:237'));
95
+ if (Array.isArray(header.tools) && header.tools.length === 0) out.push(violation('E10', loc, 'request/header 必须省略空 tools——宿主 lib/index.js:238'));
96
+ const defaults = header.adapterDefaults;
97
+ if (typeof defaults === 'object' && defaults !== null && !Array.isArray(defaults) && Object.keys(defaults).length === 0) {
98
+ out.push(violation('E10', loc, 'request/header 必须省略空 adapterDefaults——宿主 lib/index.js:239-240'));
99
+ }
100
+ }
101
+ }
102
+ out.push(...messageShapeViolations(event, loc, version));
103
+ return out;
104
+ }
105
+
106
+ /** 宿主信封键白名单(assertSessionEventEnvelope,dsh-session@0.1.5-rc.1 lib/index.js:852-861)。 */
107
+ export const ENVELOPE_ALLOWED_KEYS = new Set(['type', 'seq', 'time', 'data', 'surfaceOp', 'sourceEventSeqs', 'ignorable']);
108
+
109
+ /** v4 消息类事件 → 期望 role(dsh-session@0.2.0-rc.2 `MESSAGE_ROLE_BY_TYPE`,`src/index.ts:323-329`)。 */
110
+ const V4_MESSAGE_ROLE_BY_TYPE = {
111
+ 'system/message': 'system',
112
+ 'developer/message': 'developer',
113
+ 'user/message': 'user',
114
+ 'assistant/message': 'assistant',
115
+ 'tool/result': 'tool',
116
+ };
117
+
118
+ /**
119
+ * 镜像官方 assertMessageEventShape(lib/index.js:1242-1266)。**按被检文件版本**择路:
120
+ * v0–v3 → 旧形状(下方原逻辑);v4 → `v4MessageShapeViolations`。
121
+ */
122
+ export function messageShapeViolations(event, loc, version) {
123
+ if (version >= 4) return v4MessageShapeViolations(event, loc);
124
+ const type = event.type;
125
+ // 把 v3 新增的 `system/message` 纳入形状检查(MESSAGE_ROLE_BY_TYPE:system/message → system,
126
+ // dsh-session@0.1.5-rc.1 lib/index.js:917-926;source 要求 :942-944)。旧实现只查 user/assistant/tool
127
+ // ⇒ 实测反例(system/message 的 source.kind='user')宿主拒、旧契约 0 违规。
128
+ if (type !== 'user/message' && type !== 'assistant/message' && type !== 'tool/result' && type !== 'system/message') return [];
129
+ const out = [];
130
+ const data = event.data;
131
+ const record = typeof data === 'object' && data !== null ? data : undefined;
132
+ const message = type === 'user/message' ? record : record?.message;
133
+ const shape = () => `(seq ${event.seq})消息形状`;
134
+ if (typeof message !== 'object' || message === null) {
135
+ out.push(violation('E6', loc, `${shape()}:缺少 message 对象`));
136
+ return out;
137
+ }
138
+ if (typeof message.id !== 'string' || message.id === '') {
139
+ out.push(violation('E6', loc, `${shape()}:id 必须为非空字符串`));
140
+ }
141
+ const expectedRole = type === 'assistant/message' ? 'assistant' : (type === 'system/message' ? 'system' : 'user');
142
+ if (message.role !== expectedRole) {
143
+ out.push(violation('E6', loc, `${shape()}:role 必须为 "${expectedRole}",实际 ${String(message.role)}`));
144
+ }
145
+ const source = message.source;
146
+ if (typeof source !== 'object' || source === null || typeof source.kind !== 'string' || source.kind === '') {
147
+ out.push(violation('E6', loc, `${shape()}:source.kind 缺失或非法`));
148
+ }
149
+ if (!Array.isArray(message.content)) {
150
+ out.push(violation('E6', loc, `${shape()}:content 必须为数组`));
151
+ }
152
+ if (type === 'assistant/message') {
153
+ if (source?.kind !== 'model' || typeof source.provider !== 'string' || source.provider === '' || typeof source.model !== 'string' || source.model === '') {
154
+ out.push(violation('E6', loc, `${shape()}:assistant/message 必须带 model source(provider/model 非空)`));
155
+ }
156
+ }
157
+ if (type === 'system/message') {
158
+ // E9(候选规则):system/message 必须 plugin source(kind==='plugin' + plugin 非空)。
159
+ // 宿主依据:dsh-session@0.1.5-rc.1 lib/index.js:942-944("must have plugin source")。
160
+ if (source?.kind !== 'plugin' || typeof source.plugin !== 'string' || source.plugin === '') {
161
+ out.push(violation('E9', loc, `${shape()}:system/message 必须带 plugin source(kind==='plugin' 且 plugin 非空)——宿主 lib/index.js:942-944`));
162
+ }
163
+ }
164
+ if (type === 'tool/result') {
165
+ if (source?.kind !== 'tool' || typeof source.callId !== 'string' || source.callId === '') {
166
+ out.push(violation('E6', loc, `${shape()}:tool/result 必须带 tool source(callId 非空)`));
167
+ }
168
+ const content = message.content;
169
+ const block = Array.isArray(content) ? content[0] : undefined;
170
+ if (content?.length !== 1 || typeof block !== 'object' || block === null || block.type !== 'tool-result' || !Array.isArray(block.content)) {
171
+ out.push(violation('E6', loc, `${shape()}:必须恰含一个 tool-result block`));
172
+ } else if (block.toolCallId !== source?.callId) {
173
+ out.push(violation('E6', loc, `${shape()}:block.toolCallId 与 source.callId 不匹配`));
174
+ }
175
+ }
176
+ return out;
177
+ }
178
+
179
+ /**
180
+ * v4 消息形状。两层一手依据:
181
+ * - 运行时 load 路径:dsh-session@0.2.0-rc.2 `assertMessageEventShape`(`src/index.ts:331-381`)——
182
+ * role 表、system-prompt source、model source、tool source + `toolCallId` 匹配;
183
+ * - 文件读取路径:`dsh-session-format-v3-to-v4` 原生 v4 准入(`src/tool-role.ts:89-109`、
184
+ * `src/message-sources.ts:9`)——残留 `tool-result` 包装块、非布尔 `isError`、`data.error` 而
185
+ * `isError !== true`、`source.kind === 'plugin'` 一律 SessionFormatError ⇒ 会话从盘上读不回来。
186
+ * `adoptSessionEvent` 不查这几条,所以只看运行时会漏掉"写得进、读不回"的形状。
187
+ *
188
+ * 与 v3 的差异(v3→v4 迁移 `tool-role.ts` / `sources.ts` 的逐项改写):
189
+ * - 新增 `developer/message`(role `developer`);
190
+ * - `tool/result`:role `tool`;去掉 `tool-result` 包装块,content 直接是结果数组;
191
+ * `message.toolCallId` 必须等于 `source.callId`;`isError` 若存在必须为布尔;
192
+ * - `system/message`:source.kind 必须为 `system-prompt`(v3 是 plugin 包装);
193
+ * - 任何消息的 source.kind 都不得为 `plugin`(v4 把插件包装改写成生产者自有 kind)。
194
+ */
195
+ function v4MessageShapeViolations(event, loc) {
196
+ const type = event.type;
197
+ const expectedRole = V4_MESSAGE_ROLE_BY_TYPE[type];
198
+ if (expectedRole === undefined) return [];
199
+ const out = [];
200
+ const data = event.data;
201
+ const record = typeof data === 'object' && data !== null ? data : undefined;
202
+ const message = type === 'user/message' ? record : record?.message;
203
+ const shape = () => `(seq ${event.seq})消息形状`;
204
+ if (typeof message !== 'object' || message === null) {
205
+ out.push(violation('E6', loc, `${shape()}:缺少 message 对象`));
206
+ return out;
207
+ }
208
+ if (typeof message.id !== 'string' || message.id === '') {
209
+ out.push(violation('E6', loc, `${shape()}:id 必须为非空字符串`));
210
+ }
211
+ if (message.role !== expectedRole) {
212
+ out.push(violation('E6', loc, `${shape()}:role 必须为 "${expectedRole}",实际 ${String(message.role)}`));
213
+ }
214
+ const source = message.source;
215
+ if (typeof source !== 'object' || source === null || typeof source.kind !== 'string' || source.kind === '') {
216
+ out.push(violation('E6', loc, `${shape()}:source.kind 缺失或非法`));
217
+ } else if (source.kind === 'plugin') {
218
+ out.push(violation('E6', loc, `${shape()}:v4 不再接受 plugin source(kind==='plugin')——v3→v4 迁移把它改写为生产者自有 kind`));
219
+ }
220
+ if (!Array.isArray(message.content)) {
221
+ out.push(violation('E6', loc, `${shape()}:content 必须为数组`));
222
+ }
223
+ if (type === 'assistant/message') {
224
+ if (source?.kind !== 'model' || typeof source.provider !== 'string' || source.provider === '' || typeof source.model !== 'string' || source.model === '') {
225
+ out.push(violation('E6', loc, `${shape()}:assistant/message 必须带 model source(provider/model 非空)`));
226
+ }
227
+ }
228
+ if (type === 'system/message' && source?.kind !== 'system-prompt') {
229
+ out.push(violation('E9', loc, `${shape()}:system/message 必须带 system-prompt source(kind==='system-prompt')——dsh-session@0.2.0-rc.2 src/index.ts:360-364`));
230
+ }
231
+ if (type === 'tool/result') {
232
+ if (source?.kind !== 'tool' || typeof source.callId !== 'string' || source.callId === '') {
233
+ out.push(violation('E6', loc, `${shape()}:tool/result 必须带 tool source(callId 非空)`));
234
+ } else if (message.toolCallId !== source.callId) {
235
+ out.push(violation('E6', loc, `${shape()}:message.toolCallId 与 source.callId 不匹配`));
236
+ }
237
+ if (Array.isArray(message.content) && message.content.some((b) => typeof b === 'object' && b !== null && b.type === 'tool-result')) {
238
+ out.push(violation('E6', loc, `${shape()}:v4 tool/result 不得再含 tool-result 包装块(content 直接是结果数组)`));
239
+ }
240
+ if (message.isError !== undefined && typeof message.isError !== 'boolean') {
241
+ out.push(violation('E6', loc, `${shape()}:isError 若存在必须为布尔`));
242
+ }
243
+ if (record?.error !== undefined && message.isError !== true) {
244
+ out.push(violation('E6', loc, `${shape()}:带 data.error 时 message.isError 必须为 true`));
245
+ }
246
+ }
247
+ return out;
248
+ }
249
+
250
+ /** replace 操作数精确形状(镜像旧格式 isReplaceOp,lib/index.js:300-303)。 */
251
+ export function isReplaceOp(op) {
252
+ return (
253
+ typeof op === 'object' && op !== null &&
254
+ Object.keys(op).length === 3 &&
255
+ Object.hasOwn(op, 'op') && Object.hasOwn(op, 'start') && Object.hasOwn(op, 'end') &&
256
+ op.op === 'replace' && isSafeInt(op.start) && isSafeInt(op.end)
257
+ );
258
+ }
259
+
260
+ /**
261
+ * 按**被检文件版本**归一化 replace 操作数到内部 `{start,end}`。
262
+ *
263
+ * 一手依据:官方 replace 字段在 v3 改名——旧格式(v0/v1/v2)`{op,start,end}`,
264
+ * v3 `{op,startSeq,endSeq}`(`dsh-session-format-v2-to-v3/lib/index.js:361-371`)。
265
+ * 用错形状会得 null,由调用方归因为 S4(真实违规)。
266
+ *
267
+ * @param {unknown} op 待归一化的 surfaceOp
268
+ * @returns {{start:number,end:number}|null}
269
+ */
270
+ export function normalizeReplaceOp(op, version) {
271
+ if (typeof op !== 'object' || op === null || Array.isArray(op)) return null;
272
+ if (Object.keys(op).length !== 3 || op.op !== 'replace') return null;
273
+ if (version >= 3) {
274
+ return Object.hasOwn(op, 'startSeq') && Object.hasOwn(op, 'endSeq') && isSafeInt(op.startSeq) && isSafeInt(op.endSeq)
275
+ ? { start: op.startSeq, end: op.endSeq }
276
+ : null;
277
+ }
278
+ return Object.hasOwn(op, 'start') && Object.hasOwn(op, 'end') && isSafeInt(op.start) && isSafeInt(op.end)
279
+ ? { start: op.start, end: op.end }
280
+ : null;
281
+ }
282
+
283
+ /**
284
+ * S9 —— 文件物理序 seq 单调(2026-08-30 事故固化;交接书 L2)。
285
+ *
286
+ * 按**文件物理行序**(非 seq 排序)要求展开后的事件 seq 严格单调递增。
287
+ * 单进程 append 不可能写出非单调物理序(appendCore 断言 seq==cursor+i 且按
288
+ * id 串行化)——非单调 = 多写入者/旧光标回放交织的现场特征(某真实会话:物理序
289
+ * 734056→733539→735470)。E2 只查「排序后连续」,排序会掩盖物理序倒退;
290
+ * S9 补「物理序单调」盲区。
291
+ *
292
+ * @param rows - loadSessionLog 的 rows(物理行序,每行含 decoded 数组)。
293
+ * @returns S9 违规列表(error 级)。
294
+ */
295
+ export function physicalOrderViolations(rows) {
296
+ const out = [];
297
+ let prevSeq = -1;
298
+ let prevLineNo = null;
299
+ for (const row of rows) {
300
+ if (!Array.isArray(row.decoded) || row.decoded.length === 0) continue;
301
+ for (const event of row.decoded) {
302
+ if (typeof event.seq !== 'number' || !Number.isSafeInteger(event.seq) || event.seq < 0) continue; // E1 处理
303
+ if (event.seq < prevSeq) {
304
+ out.push(violation('S9', { seq: event.seq, lineNo: row.lineNo, eventType: event.type }, `文件物理序 seq 倒退:${prevSeq}(line ${prevLineNo})→ ${event.seq}(line ${row.lineNo})——非单调 = 多写入者/旧光标回放交织(单进程 append 不可能写出),会话加载会被拒`));
305
+ return out; // 首个倒退即现场特征,报一次足够(后续乱序都源自此)
306
+ }
307
+ prevSeq = event.seq;
308
+ prevLineNo = row.lineNo;
309
+ }
310
+ }
311
+ return out;
312
+ }
313
+
314
+ /**
315
+ * 与官方同语义的 surface 增量重放,逐事件归因 S1–S7。
316
+ * @param {Array<{event:object, lineNo?:number}>} events 按日志顺序的事件(带 loc 包装)
317
+ */
318
+ export function replaySurface(events, version) {
319
+ const violations = [];
320
+ const nodes = [];
321
+ let replaceGeneration = 0;
322
+
323
+ for (const { event, lineNo } of events) {
324
+ const loc = { seq: event.seq, lineNo, eventType: event.type };
325
+ const eligible = currentSurfaceTypes(version).has(event.type);
326
+ const op = event.surfaceOp;
327
+ const src = event.sourceEventSeqs;
328
+
329
+ if (!eligible) {
330
+ if (op !== undefined || src !== undefined) {
331
+ // ── 2026-09-14 实测:这里的 S2 是误报 ───────────────────────────────
332
+ // 宿主 `@deepseek-ai/dsh-session@0.1.5-rc.1` 是**刻意容忍**的:
333
+ // lib/index.js:270 `if (!KNOWN_SESSION_EVENT_TYPES.has(event.type) && event.ignorable === true) return;`
334
+ // 同一函数的契约注释 lib/index.js:305 —— "Unknown ignorable records retain opaque
335
+ // metadata and never change the surface."
336
+ // ⇒ **未知**类型且 `ignorable===true` 的事件带 surfaceOp/sourceEventSeqs 是合法的不透明
337
+ // 元数据(宿主收;实测反例:宿主收、旧契约 S2/error)。这里不再报 S2。
338
+ // "该未知类型有没有消费者"由 E7 以 **warning** 表达(策略层,非宿主契约)。
339
+ const unknownIgnorable = !currentVocabulary(version).has(event.type) && event.ignorable === true;
340
+ if (!unknownIgnorable) {
341
+ violations.push(violation('S2', loc, `非 surface 类型 "${event.type}" 不得携带 surfaceOp/sourceEventSeqs`));
342
+ }
343
+ }
344
+ continue;
345
+ }
346
+ if (op === undefined) {
347
+ violations.push(violation('S1', loc, `surface 候选类型 "${event.type}" 必须携带 surfaceOp 标记`));
348
+ continue;
349
+ }
350
+
351
+ if (op === 'append') {
352
+ violations.push(...provenanceViolations(event, loc, []));
353
+ nodes.push(event.seq);
354
+ continue;
355
+ }
356
+
357
+ const normalized = normalizeReplaceOp(op, version);
358
+ if (normalized === null) {
359
+ violations.push(violation('S4', loc, 'replace 操作数必须精确为 {op:"replace", start, end}(v0/v1/v2)或 {op:"replace", startSeq, endSeq}(v3),且端点为非负安全整数'));
360
+ continue;
361
+ }
362
+ const startIdx = nodes.indexOf(normalized.start);
363
+ const endIdx = nodes.indexOf(normalized.end);
364
+ if (startIdx === -1 || endIdx === -1) {
365
+ violations.push(violation('S4', loc, `replace 范围 ${normalized.start}..${normalized.end} 不在当前 surface 中(start 存在=${startIdx !== -1},end 存在=${endIdx !== -1})`));
366
+ continue;
367
+ }
368
+ if (startIdx > endIdx) {
369
+ violations.push(violation('S4', loc, `replace start ${normalized.start}(index ${startIdx})在 end ${normalized.end}(index ${endIdx})之后`));
370
+ continue;
371
+ }
372
+ const shadowedSeqs = nodes.slice(startIdx, endIdx + 1);
373
+ violations.push(...provenanceViolations(event, loc, shadowedSeqs));
374
+ violations.push(...toolResultRewriteViolations(event, loc, shadowedSeqs));
375
+ nodes.splice(startIdx, endIdx - startIdx + 1, event.seq);
376
+ replaceGeneration += 1;
377
+ }
378
+
379
+ return { violations, nodes, replaceGeneration };
380
+ }
381
+
382
+ /** 镜像官方 assertProvenance(lib/index.js:320-337)。 */
383
+ export function provenanceViolations(event, loc, shadowedSeqs) {
384
+ const out = [];
385
+ const raw = event.sourceEventSeqs;
386
+ const sources = new Set();
387
+ if (raw !== undefined) {
388
+ if (!Array.isArray(raw)) {
389
+ out.push(violation('S6', loc, `sourceEventSeqs 必须为数组(实际 ${typeof raw})`));
390
+ return out;
391
+ }
392
+ if (raw.length === 0 && event.type !== 'assistant/message') {
393
+ out.push(violation('S6', loc, 'sourceEventSeqs 不得为空(除 assistant/message 外)'));
394
+ }
395
+ let nonEarlier;
396
+ for (const source of raw) {
397
+ if (!isSafeInt(source)) {
398
+ out.push(violation('S6', loc, `sourceEventSeqs 必须稠密包含非负安全整数(非法值 ${String(source)})`));
399
+ continue;
400
+ }
401
+ if (sources.has(source)) {
402
+ out.push(violation('S6', loc, `sourceEventSeqs 不得重复(${source})`));
403
+ }
404
+ sources.add(source);
405
+ if (nonEarlier === undefined && source >= event.seq) nonEarlier = source;
406
+ }
407
+ if (nonEarlier !== undefined) {
408
+ out.push(violation('S6', loc, `sourceEventSeqs 必须引用更早事件:${nonEarlier} >= 当前 seq ${event.seq}`));
409
+ }
410
+ }
411
+ const missing = shadowedSeqs.filter((seq) => !sources.has(seq));
412
+ if (missing.length > 0) {
413
+ out.push(violation('S5', loc, `surface replace: sourceEventSeqs 必须覆盖每个被替换节点;缺失 ${missing.join(', ')}(共 ${missing.length} 个)`, { missingSeqs: missing }));
414
+ }
415
+ return out;
416
+ }
417
+
418
+ /** 镜像官方 assertToolResultRewrite(lib/index.js:369-395)的判定核心。 */
419
+ export function toolResultRewriteViolations(event, loc, shadowedSeqs) {
420
+ if (event.type !== 'tool/result') return [];
421
+ const out = [];
422
+ if (shadowedSeqs.length !== 1) {
423
+ out.push(violation('S7', loc, `tool/result 替换必须恰好重写 1 个当前节点(实际 ${shadowedSeqs.length} 个)`));
424
+ }
425
+ return out;
426
+ }
427
+
428
+ /** M1 —— 客户端引擎层:turn/step 缺失(null)的 assistant/message 只能 replace。 */
429
+ export function engineViolations(event, loc) {
430
+ const out = [];
431
+ if (event.type === 'assistant/message' && event.surfaceOp === 'append') {
432
+ // turn/step 位于 event.data 层(实证:正常消息 data.turn/data.step 为数字,
433
+ // 插件 marker data.turn/data.step 为 null —— 复盘事故第 2 次尝试)
434
+ const turn = event.data?.turn;
435
+ const step = event.data?.step;
436
+ if (turn == null || step == null) {
437
+ 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)`));
438
+ }
439
+ }
440
+ return out;
441
+ }
442
+
443
+ /** P 层 —— 插件 marker 语义(retrace 等以 assistant/message replace 承载的 marker)。 */
444
+ export function pluginViolations(event, loc) {
445
+ const out = [];
446
+ const isMarkerReplace = event.type === 'assistant/message' && event.surfaceOp && event.surfaceOp !== 'append' && event.data?.editor !== undefined;
447
+ if (!isMarkerReplace) return out;
448
+ const id = event.data?.message?.id;
449
+ const known = typeof id === 'string' && MARKER_PREFIXES.some((p) => id.startsWith(`${p}-`));
450
+ if (!known) {
451
+ out.push(violation('P1', loc, `marker id "${String(id)}" 前缀不在已知列表(${MARKER_PREFIXES.join('/')}-)——改名后未登记遗留前缀,旧 marker 隐藏语义将断裂(软兼容丢失)`));
452
+ }
453
+ const src = event.sourceEventSeqs;
454
+ if (Array.isArray(src) && src.includes(event.seq)) {
455
+ out.push(violation('P2', loc, `marker 自身 seq ${event.seq} 出现在自身 sourceEventSeqs(shadowed 集)——自指语义错误(marker 节点被隐藏逻辑跳过,不应被自己隐藏)`));
456
+ }
457
+ return out;
458
+ }
459
+
460
+ /** 折叠终验:**按文件版本**择路(2026-09-14 补强)。
461
+ *
462
+ * - v3 文件 → 运行时导出的官方 `foldSurface`(与运行时同语义);
463
+ * - v0/v1/v2 文件 → 本地 `legacyFoldSurface`(rc.7 `foldSurface` 逐条移植)。
464
+ *
465
+ * 为什么旧格式不能借用官方实现的 `violations` 字段:官方 `foldSurface` **只抛不报**,
466
+ * 旧口径下这里曾回退到 `replaySurface` 的 violations,但**没有任何调用方读它**
467
+ * (validate.js / prewrite.js 只看 `folded.error`)⇒ S8 在旧格式上永不触发——这正是
468
+ * 2026-09-14 六条失败里四条的真因。现在两条路径都是"抛错 = 拒绝"的同一种契约。 */
469
+ export function finalFold(events, version) {
470
+ const fold = currentFold(version);
471
+ try {
472
+ return { surface: fold(events) };
473
+ } catch (err) {
474
+ return { error: err };
475
+ }
476
+ }
477
+
478
+ /**
479
+ * T3 —— step 节点 key 冲突(2026-09-02 · 渲染层白屏事故真正根因固化)。
480
+ *
481
+ * 客户端渲染消息列表 = 从事件流构建节点,节点 key = `data.turn:data.step`
482
+ * (React 列表 key)。同 turn 内两个 step/start 的 step 号相同 → key 冲突 →
483
+ * React 渲染死循环 → 白屏/不展示(实测:同一 turn 内正常轮的 step 95/1 与
484
+ * 编辑块的 step 95/1 冲突;2026-09-02 全量扫描又发现多个同型冲突的会话,
485
+ * 均整块重编号修复)。
486
+ *
487
+ * 判定:扫 step/start,`data.turn:data.step` 组合重复 = error。
488
+ * - 无任何 step/start 的日志跳过(与 T1 同款宽松);
489
+ * - turn/step 为 null/undefined 的 step/start 不参与 key 判定(那是 T4 的域,
490
+ * 且 null 自身已是致命)。
491
+ *
492
+ * @param events - 行序事件流(`{event, lineNo}`)。
493
+ * @returns T3 违规列表。
494
+ */
495
+ export function stepKeyViolations(events) {
496
+ const out = []
497
+ if (!events.some(({ event }) => event.type === 'step/start')) return out
498
+ const seen = new Map() // `${turn}:${step}` → { seq, lineNo }
499
+ for (const { event, lineNo } of events) {
500
+ if (event.type !== 'step/start') continue
501
+ const turn = event.data?.turn
502
+ const step = event.data?.step
503
+ if (turn === null || turn === undefined || step === null || step === undefined) continue // T4 域
504
+ const key = `${String(turn)}:${String(step)}`
505
+ const prev = seen.get(key)
506
+ if (prev !== undefined) {
507
+ 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 递增,不得复用;整块重编号)`))
508
+ } else {
509
+ seen.set(key, { seq: event.seq, lineNo })
510
+ }
511
+ }
512
+ return out
513
+ }
514
+
515
+ /**
516
+ * T4 —— step/消息本体 turn 缺失(null/undefined)(2026-09-01 · D8 事故固化)。
517
+ *
518
+ * 客户端渲染状态机对 turn=null 的 step/消息**无法归属任何 turn** → 渲染死循环 →
519
+ * 白屏「载入历史」(实测:retrace 0.4.17 写的编辑块
520
+ * step/start+marker+step/end turn 全 null;离线自查脚本把 step
521
+ * 包裹/消息本体的 null-turn 判为致命)。
522
+ *
523
+ * 判定:`step/start|step/end|assistant/message` 的 `data.turn === null/undefined` = error。
524
+ * - user/message 天然不带 turn(坐标来自外层 step),不查;
525
+ * - assistant/chunk 坐标可能天然缺失,不查;
526
+ * - retrace/marker(neutralize 产物,ignorable)不查。
527
+ *
528
+ * @param events - 行序事件流(`{event, lineNo}`)。
529
+ * @returns T4 违规列表。
530
+ */
531
+ export function nullTurnStepViolations(events) {
532
+ const out = []
533
+ for (const { event, lineNo } of events) {
534
+ if (event.type !== 'step/start' && event.type !== 'step/end' && event.type !== 'assistant/message') continue
535
+ const turn = event.data?.turn
536
+ if (turn === null || turn === undefined) {
537
+ out.push(violation('T4', { seq: event.seq, lineNo, eventType: event.type }, `${event.type} 的 data.turn 为 ${String(turn)}(缺失)——客户端渲染状态机无法归属任何 turn → 渲染死循环白屏(D8 事故;step/消息本体必须带真实 turn 号)`))
538
+ }
539
+ }
540
+ return out
541
+ }
542
+
543
+ /**
544
+ * T5 —— turn/end 缺 reason.kind(2026-09-02 · malformed turn/end 固化)。
545
+ *
546
+ * 官方 agent-loop 写 turn/end 恒带 `reason: { kind }`(dsh-agent-loop/lib/index.js:620;
547
+ * kind ∈ completed|max-tokens|blocked|aborted|error|interrupted,中断恢复补
548
+ * interrupted,见 dsh-session interruptedTurnClosers)。官方 validation 强制
549
+ * reason.kind 存在——缺失 = malformed → 会话加载失败
550
+ * (SessionPersistenceCorruptionError "malformed pre-react-loop turn/end")。
551
+ *
552
+ * 判定:turn/end 的 `data.reason?.kind` 缺失/非字符串 = error。
553
+ *
554
+ * @param events - 行序事件流(`{event, lineNo}`)。
555
+ * @returns T5 违规列表。
556
+ */
557
+ export function turnEndReasonViolations(events) {
558
+ const out = []
559
+ for (const { event, lineNo } of events) {
560
+ if (event.type !== 'turn/end') continue
561
+ const reason = event.data?.reason
562
+ if (!reason || typeof reason.kind !== 'string') {
563
+ 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)`))
564
+ }
565
+ }
566
+ return out
567
+ }
568
+
569
+ /**
570
+ * E7 —— ignorable 未知 type 合法性(2026-09-09 T2 增量)。
571
+ *
572
+ * 盲区:E3 对"未知 type + ignorable:true"直接放行(容忍更新版本 harness 写入),
573
+ * 但 ignorable 标记无合法性校验 = 后门——被读路径接纳却无人消费的未知事件 =
574
+ * 静默垃圾(违 R3 精神)。补:未知 type + ignorable + **不在已知消费者白名单** →
575
+ * warning"有被忽略的未知事件"。
576
+ *
577
+ * 已知消费者(不算垃圾,排除):retrace 家族 marker(retrace/marker、retrace/goal-marker,
578
+ * neutralize/插件产物,retrace 客户端识别消费)与旧前缀 message-editor。
579
+ * 判定:type ∉ KNOWN && ignorable && 非已知插件前缀 → warning。
580
+ */
581
+ const KNOWN_IGNORABLE_CONSUMERS = new Set(['retrace/marker', 'retrace/goal-marker'])
582
+ function isKnownIgnorableType(type) {
583
+ if (typeof type !== 'string') return false
584
+ if (KNOWN_IGNORABLE_CONSUMERS.has(type)) return true
585
+ return type.startsWith('message-editor/') || type.startsWith('retrace/')
586
+ }
587
+ export function ignorableTypeViolations(events, version) {
588
+ const out = []
589
+ for (const { event, lineNo } of events) {
590
+ if (typeof event?.type !== 'string' || event.ignorable !== true) continue
591
+ if (currentVocabulary(version).has(event.type)) continue
592
+ if (isKnownIgnorableType(event.type)) continue
593
+ out.push(violation('E7', { seq: event.seq, lineNo, eventType: event.type }, `type "${event.type}" 不在已知词汇表且带 ignorable 标记、无已知消费者——被读路径接纳但无人消费 = 静默垃圾(ignorable 后门;若你的插件消费它,登记到 KNOWN_IGNORABLE_CONSUMERS)`))
594
+ }
595
+ return out
596
+ }
597
+
598
+ /**
599
+ * P3 —— tool/call ↔ tool/result 配对完整性(考古 B1)。
600
+ * 每个 tool/call 的 `data.callId` 必须能在 tool/result 的
601
+ * `data.message.source.callId` 中找到配对;孤儿 call(无 result)告警——
602
+ * 中断/失败轮次可能产生孤儿(合法但要审计)。warning 级:不破坏日志。
603
+ */
604
+ export function toolPairingViolations(events) {
605
+ const out = [];
606
+ const calls = new Map(); // callId → { command, loc }
607
+ const results = new Map(); // callId → loc(双向:孤儿 result 也要指认,2026-09-09 T1)
608
+ for (const { event, lineNo } of events) {
609
+ if (event.type === 'tool/call') {
610
+ const callId = event.data?.callId;
611
+ if (typeof callId === 'string' && callId !== '') {
612
+ let command = '';
613
+ try {
614
+ const args = typeof event.data?.arguments === 'string' ? JSON.parse(event.data.arguments) : event.data?.arguments;
615
+ command = typeof args?.command === 'string' ? args.command.slice(0, 120) : '';
616
+ } catch { /* 参数解析失败不阻断配对检查 */ }
617
+ calls.set(callId, { command, loc: { seq: event.seq, lineNo, eventType: event.type } });
618
+ }
619
+ } else if (event.type === 'tool/result') {
620
+ const callId = event.data?.message?.source?.callId;
621
+ if (typeof callId === 'string' && callId !== '') results.set(callId, { seq: event.seq, lineNo, eventType: event.type });
622
+ }
623
+ }
624
+ for (const [callId, { command, loc }] of calls) {
625
+ if (!results.has(callId)) {
626
+ out.push(violation('P3', loc, `tool/call ${callId}(命令 ${command || '(未知)'})没有配对的 tool/result——孤儿调用(中断/失败未落结果),考古提取将缺该输出`));
627
+ }
628
+ }
629
+ // 双向(T1 增量):孤儿 result = result 无对应 tool/call。
630
+ // 折叠后 wire 流中无主 tool 消息 = provider 拒绝风险(W1/W2 同族、不同层);
631
+ // 与孤儿 call 同为 warning 级——合法场景(中断/修复产物)不破坏日志。
632
+ for (const [callId, loc] of results) {
633
+ if (!calls.has(callId)) {
634
+ out.push(violation('P3', loc, `tool/result ${callId} 没有配对的 tool/call——孤儿结果(无主 tool 消息,wire 流 provider 拒绝风险;中断/修复产物合法但要审计),考古配对将无法归属`));
635
+ }
636
+ }
637
+ return out;
638
+ }
639
+
640
+ /**
641
+ * 递归检查 content 的可提取性:任意标量(string/number/boolean/null)都是合法
642
+ * 元数据(如 isError、toolCallId)——只有 "text 字段存在但值非 string" 才是
643
+ * 考古提取会漏数据的结构异常(extractText 依赖 text 为 string)。
644
+ */
645
+ function findUnparsableContent(node, path) {
646
+ if (typeof node === 'string' || typeof node === 'number' || typeof node === 'boolean' || node === null) return null;
647
+ if (Array.isArray(node)) {
648
+ for (let i = 0; i < node.length; i++) {
649
+ const r = findUnparsableContent(node[i], `${path}[${i}]`);
650
+ if (r !== null) return r;
651
+ }
652
+ return null;
653
+ }
654
+ if (typeof node === 'object') {
655
+ if (Object.prototype.hasOwnProperty.call(node, 'text') && typeof node.text !== 'string') {
656
+ return `${path}.text(${String(node.text)},非 string)`;
657
+ }
658
+ for (const key of Object.keys(node)) {
659
+ if (key === 'text') continue;
660
+ const r = findUnparsableContent(node[key], `${path}.${key}`);
661
+ if (r !== null) return r;
662
+ }
663
+ return null;
664
+ }
665
+ return `${path}(${String(node)})`;
666
+ }
667
+
668
+ /**
669
+ * P4 —— tool/result 输出结构契约(考古 B2)。
670
+ * `data.message.content` 必须可递归解析(list[dict{type:text,text}] 或等价);
671
+ * 不可解析片段 = 考古提取将漏数据。空 content(失败/无输出)合法。warning 级。
672
+ */
673
+ export function toolResultStructureViolations(events) {
674
+ const out = [];
675
+ for (const { event, lineNo } of events) {
676
+ if (event.type !== 'tool/result') continue;
677
+ const content = event.data?.message?.content;
678
+ if (!Array.isArray(content) || content.length === 0) continue;
679
+ const callId = event.data?.message?.source?.callId;
680
+ const loc = { seq: event.seq, lineNo, eventType: event.type };
681
+ const bad = findUnparsableContent(content, 'content');
682
+ if (bad !== null) {
683
+ out.push(violation('P4', loc, `tool/result ${callId ?? '?'} 的 content 含不可解析片段(${bad})——考古提取将漏数据`));
684
+ }
685
+ }
686
+ return out;
687
+ }
688
+
689
+ /**
690
+ * T1 —— token-meter 配对(复刻 @deepseek-ai/dsh-token-meter 的 _foldEvent 状态机,
691
+ * 2026-08-28 事故根因 3 固化):
692
+ * - `step/start` 打开一个 step(记录 turn/step);
693
+ * - `step/end` 必须匹配当前打开的 step/start,否则抛错;
694
+ * - `assistant/message` 必须匹配当前打开的 step/start(turn/step 完全一致),否则抛错;
695
+ * - `user/message` / `tool/result` 不检查(token meter 不配对)。
696
+ *
697
+ * 违反 = token meter 折叠抛错 → 该会话 `/compact` 与压力测量永久失败。
698
+ * 已知命中:retrace 的 turn/step=null 编辑/撤回 marker(空 assistant/message replace)——
699
+ * foldSurface 认可其合法性(M1 只约束 append 形态),但 token meter 崩溃。这是
700
+ * M1 规则的盲区:M1 没约束"replace 也必须过 token meter"。
701
+ *
702
+ * @param events - 行序事件流(`{event, lineNo}`)。
703
+ * @returns T1 违规列表。
704
+ */
705
+ export function tokenMeterViolations(events) {
706
+ const out = [];
707
+ // 无任何 step/start 的日志:现代 DSH 每个 assistant 回合必有 step/start,
708
+ // 完全没有说明是极早期格式或简化日志——token-meter 的 step 配对兼容性未
709
+ // 定义,不做配对检查(避免对旧结构误报;真实事故会话都是现代结构)。
710
+ if (!events.some(({ event }) => event.type === 'step/start')) return out;
711
+ let stepStart = undefined;
712
+ for (const { event, lineNo } of events) {
713
+ const loc = { seq: event.seq, lineNo, eventType: event.type };
714
+ if (event.type === 'step/start') {
715
+ if (stepStart !== undefined) {
716
+ out.push(violation('T1', loc, `step/start at seq ${event.seq} arrived before turn ${stepStart.turn}/step ${stepStart.step} ended——token meter 折叠会抛错`));
717
+ }
718
+ stepStart = { turn: event.data?.turn, step: event.data?.step };
719
+ } else if (event.type === 'step/end') {
720
+ if (stepStart === undefined || stepStart.turn !== event.data?.turn || stepStart.step !== event.data?.step) {
721
+ 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 折叠会抛错`));
722
+ }
723
+ stepStart = undefined;
724
+ } else if (event.type === 'assistant/message') {
725
+ const turn = event.data?.turn;
726
+ const step = event.data?.step;
727
+ if (stepStart === undefined || stepStart.turn !== turn || stepStart.step !== step) {
728
+ const open = stepStart === undefined ? '无打开的 step' : `打开的 step 为 turn ${stepStart.turn}/step ${stepStart.step}`;
729
+ 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 即命中此条)`));
730
+ }
731
+ }
732
+ }
733
+ return out;
734
+ }
735
+
736
+ /**
737
+ * T2 —— token-meter 的 sourceEventSeqs 引用必须同 turn/step(2026-08-30 第二类
738
+ * 刷屏事故固化)。
739
+ *
740
+ * 镜像官方 `_estimateProviderAssistant`(dsh-token-meter lib/index.js:634-650):
741
+ * `assistant/message` 的每个 `sourceEventSeqs` 若指向 `assistant/chunk`,其
742
+ * turn/step 必须与消息自身一致;跨 step 引用 → 官方抛
743
+ * `token meter: assistant/message at seq N source seq M belongs to another step`
744
+ * (lib/index.js:645)。
745
+ *
746
+ * 事故现场:DSH resend/regenerate 在 agent 仍开着 step 时被触发,会把旧 step 的
747
+ * chunk 全部引用进新 assistant/message(某真实会话的 chunk 源引用跨 step 7/8/9)→
748
+ * 离线 check(T1)全绿但实机 token-meter 崩溃 → 同样刷屏压垮 host。
749
+ *
750
+ * @param events - 行序事件流(`{event, lineNo}`)。
751
+ * @returns T2 违规列表(error 级,token-meter 实机必崩)。
752
+ */
753
+ export function tokenMeterSourceViolations(events) {
754
+ const out = [];
755
+ const bySeq = new Map();
756
+ for (const { event, lineNo } of events) bySeq.set(event.seq, { event, lineNo });
757
+ for (const { event, lineNo } of events) {
758
+ if (event.type !== 'assistant/message' || !Array.isArray(event.sourceEventSeqs) || event.sourceEventSeqs.length === 0) continue;
759
+ const turn = event.data?.turn;
760
+ const step = event.data?.step;
761
+ if (turn == null || step == null) continue; // turn-null marker 由 T1 覆盖
762
+ if (event.data?.usage === void 0) continue; // 无 usage 不触发 _estimateProviderAssistant(官方 :592 前提)——replace marker(S5 遮蔽语义,sourceEventSeqs 含非 chunk 节点)合法
763
+ const seen = new Set();
764
+ for (const s of event.sourceEventSeqs) {
765
+ if (s >= event.seq) {
766
+ 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)`));
767
+ break;
768
+ }
769
+ if (seen.has(s)) {
770
+ out.push(violation('T2', { seq: event.seq, lineNo, eventType: event.type }, `assistant/message at seq ${event.seq} repeats source seq ${s}——token meter 折叠会抛错`));
771
+ break;
772
+ }
773
+ seen.add(s);
774
+ const src = bySeq.get(s);
775
+ if (!src || src.event.type !== 'assistant/chunk') {
776
+ 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 与压力测量永久失败`));
777
+ break; // 官方抛一次即停(consumedEvents 不前进),只报首条
778
+ }
779
+ if (src.event.data?.turn !== turn || src.event.data?.step !== step) {
780
+ 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 引用)`));
781
+ break; // 官方抛一次即停(consumedEvents 不前进),只报首条
782
+ }
783
+ }
784
+ }
785
+ return out;
786
+ }
787
+
788
+ /**
789
+ * I1 —— inbox seed 相对重放(交接书 L1;镜像 dsh-agent lib/types/inbox.js)。
790
+ *
791
+ * 复刻官方 Inbox:从 `header.seedLength` 起重放 `agent/inbox/spliced`,
792
+ * next-turn/next-step 双队列;每条 splice 校验
793
+ * `start + removedCount <= 队列长` 且不产生重复 message id。违反 =
794
+ * `resume failed: invalid persisted inbox splice at seq N`(fork 边界孤儿:
795
+ * fork 时"移除父待处理提示词"的 removedCount=1 在子会话 seed 相对空 inbox 上非法)。
796
+ *
797
+ * @param events - 行序事件流(`{event, lineNo}`)。
798
+ * @param header - 日志 header(取 seedLength)。
799
+ * @returns I1 违规列表(error 级,resume 会被拒)。
800
+ */
801
+ export function inboxReplayViolations(events, header) {
802
+ const out = [];
803
+ const seedLength = header?.seedLength;
804
+ if (typeof seedLength !== 'number' || !Number.isSafeInteger(seedLength) || seedLength < 0) {
805
+ // 无 seedLength(非 fork 会话)→ Inbox 从 0 重放,语义等同全量;仍做队列校验
806
+ }
807
+ const state = { 'next-turn': [], 'next-step': [] };
808
+ const startSeq = seedLength ?? 0;
809
+ for (const { event, lineNo } of events) {
810
+ if (event.seq < startSeq) continue;
811
+ if (event.type !== 'agent/inbox/spliced') continue;
812
+ const loc = { seq: event.seq, lineNo, eventType: event.type };
813
+ const splice = event.data;
814
+ if (!splice || typeof splice.target !== 'string' || !['next-turn', 'next-step'].includes(splice.target)) {
815
+ out.push(violation('I1', loc, `spliced 缺合法 target(next-turn/next-step):${JSON.stringify(splice)?.slice(0, 80)}`));
816
+ continue;
817
+ }
818
+ const inbox = state[splice.target];
819
+ const removedCount = splice.removedCount ?? 0;
820
+ if (!Number.isSafeInteger(splice.start) || splice.start < 0 || splice.start > inbox.length
821
+ || !Number.isSafeInteger(removedCount) || removedCount < 0
822
+ || splice.start + removedCount > inbox.length) {
823
+ 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)`));
824
+ continue;
825
+ }
826
+ const inserted = Array.isArray(splice.inserted) ? splice.inserted : [];
827
+ const candidate = inbox.slice(0, splice.start).concat(inserted, inbox.slice(splice.start + removedCount));
828
+ const ids = new Set();
829
+ const other = splice.target === 'next-turn' ? state['next-step'] : state['next-turn'];
830
+ for (const message of [...candidate, ...other]) {
831
+ const id = message?.id ?? message?.message?.id;
832
+ if (id === undefined) continue;
833
+ if (ids.has(id)) {
834
+ out.push(violation('I1', loc, `message "${id}" 已在待处理队列中(target=${splice.target})——resume 会被拒(重复 pending id)`));
835
+ break;
836
+ }
837
+ ids.add(id);
838
+ }
839
+ inbox.splice(splice.start, removedCount, ...inserted);
840
+ }
841
+ return out;
842
+ }
843
+
844
+ /** 从事件推导 wire 消息(与 dsh-session deriveEventMessage 同语义)。 */
845
+ export function deriveWireMessage(event) {
846
+ if (event.type === 'user/message') {
847
+ return { role: 'user', content: event.data?.content ?? [] };
848
+ }
849
+ if (event.type === 'assistant/message') {
850
+ const m = event.data?.message;
851
+ if (!m || !Array.isArray(m.content) || m.content.length === 0) return null;
852
+ return { role: 'assistant', content: m.content };
853
+ }
854
+ if (event.type === 'tool/result') {
855
+ return { role: 'tool', content: event.data?.message?.content ?? [] };
856
+ }
857
+ return null;
858
+ }
859
+
860
+ /**
861
+ * Wire 级校验(W1/W2):按 surface 顺序展开模型请求消息流,
862
+ * 检查 tool 消息是否悬空(缺前置 assistant tool-call)以及 user 文本
863
+ * 是否插在 tool_calls 与结果之间。strict 端点(MiMo 等)直接 INVALID_REQUEST。
864
+ * @param events - 展开后的完整事件流(含 chunk 展开)。
865
+ * @returns 违规列表。
866
+ */
867
+ export function wireViolations(events, version) {
868
+ const out = [];
869
+ // 先折叠 surface(append 入列;replace 移除 [start..end] 并将 marker 自身入列)
870
+ const nodes = [];
871
+ const bySeq = new Map();
872
+ for (const { event, lineNo } of events) {
873
+ bySeq.set(event.seq, { event, lineNo });
874
+ if (!currentSurfaceTypes(version).has(event.type)) continue;
875
+ const op = event.surfaceOp;
876
+ if (op === 'append') {
877
+ nodes.push(event.seq);
878
+ } else if (op !== undefined) {
879
+ const normalized = normalizeReplaceOp(op, version);
880
+ const s = normalized === null ? -1 : nodes.indexOf(normalized.start);
881
+ const e = normalized === null ? -1 : nodes.indexOf(normalized.end);
882
+ if (s !== -1 && e !== -1 && s <= e) nodes.splice(s, e - s + 1, event.seq);
883
+ else nodes.push(event.seq);
884
+ }
885
+ }
886
+ // 展开 wire 流
887
+ const wire = [];
888
+ for (const seq of nodes) {
889
+ const rec = bySeq.get(seq);
890
+ if (!rec) continue;
891
+ const m = deriveWireMessage(rec.event);
892
+ if (m === null) continue;
893
+ if (m.role === 'assistant') {
894
+ wire.push({ role: 'assistant', tc: m.content.filter((b) => b.type === 'tool-call').length, seq, lineNo: rec.lineNo });
895
+ } else if (m.role === 'user') {
896
+ const text = m.content.some((b) => b.type === 'text');
897
+ const trs = m.content.filter((b) => b.type === 'tool-result').length;
898
+ if (text) wire.push({ role: 'user', seq, lineNo: rec.lineNo });
899
+ for (let i = 0; i < trs; i++) wire.push({ role: 'tool', seq, lineNo: rec.lineNo });
900
+ } else {
901
+ wire.push({ role: m.role, seq, lineNo: rec.lineNo });
902
+ }
903
+ }
904
+ let pending = 0;
905
+ let pendingSeq = null;
906
+ for (const w of wire) {
907
+ if (w.role === 'assistant') {
908
+ pending = w.tc;
909
+ pendingSeq = pending > 0 ? w.seq : null;
910
+ } else if (w.role === 'tool') {
911
+ if (pending <= 0) {
912
+ out.push(violation('W1', { seq: w.seq, lineNo: w.lineNo }, `wire: tool 消息 @seq ${w.seq} 悬空——surface 中没有未满足的 assistant tool-call(严格端点会 INVALID_REQUEST)`));
913
+ } else {
914
+ pending--;
915
+ if (pending === 0) pendingSeq = null;
916
+ }
917
+ } else if (w.role === 'user' && pending > 0) {
918
+ out.push(violation('W2', { seq: w.seq, lineNo: w.lineNo }, `wire: user 文本 @seq ${w.seq} 插在 assistant tool_calls(@seq ${pendingSeq})与其 tool 结果之间——严格端点会拒绝该序列`));
919
+ }
920
+ }
921
+ return out;
922
+ }
923
+
924
+ /**
925
+ * G · 迁移预检(payload 层 + 类型层)——**官方迁移会不会拒**,与"本工具能否读取/折叠"是
926
+ * **两个独立维度**(见 contracts.js 的 LAYER.MIGRATION 段)。
927
+ *
928
+ * 覆盖(每条都有一手出处,官方 `@0.1.5-rc.2`):
929
+ * - **G1** `subagent/descriptor.data.version !== 3`
930
+ * - **G2** 事件类型不在官方 v0 dispositions 内(含 `ignorable:true`)
931
+ * - **G3** `session/title` / `session/title-llm-request` 的 `messageSeqs`(`v0-to-v1/lib/index.js:2543-2556`)
932
+ *
933
+ * 仍未覆盖(由 `migrationVerdict().coverage.uncovered` 显式列出,**不许**当通过):
934
+ * `turn/start`(闭合/预期轮)、继承切点、`assistant/attempt` 配对、`stored log corrupt`、
935
+ * v0→v1 对其余事件的形状拒绝。
936
+ *
937
+ * **为什么 `turn/start` 不做(实测结论)**:官方那个状态机(`v0-to-v1:2270` 的
938
+ * `assertReleasedArtifactRelationships`)**不是**在原始 v0 事件上跑的——它由 **v1→v2**
939
+ * 以 `RELEASED_V2_RELATIONSHIP_EXTENSIONS` 调用在**变换后的 v1/v2 artifact** 上
940
+ * (`v1-to-v2/lib/index.js:104`),并带 `cut`(继承切点)处理。实测:在原始 v0 上照抄该
941
+ * 状态机会在**已 seed 的会话**上狂报(样本(某真实会话):v0→v1 官方并不以该规则拒绝,
942
+ * 而原始 v0 上会报 19 条),属"规则文本对、应用对象错"。要忠实复现必须先把 v0→v1→v2 的
943
+ * 变换做出来 ⇒ 记未覆盖。
944
+ *
945
+ * 范围:三条都只约束 **v0 源文件**(官方 v0→v1 迁移的规则;v1/v2 源走别的迁移代码)。
946
+ * severity 固定 warning、layer 固定 migration ⇒ 不进 ok / loadable / resumable / compactable。
947
+ *
948
+ * @param {Array<{event:object, lineNo?:number}>} events 已展开事件(带 loc 包装)
949
+ * @param {number} version 被检文件版本
950
+ */
951
+ export function migrationPrecheckViolations(events, version, opts = {}) {
952
+ const out = [];
953
+ if (version !== 0) return out;
954
+ const ignorableWhitelist = resolveIgnorableWhitelist(opts.ignorableWhitelist);
955
+ for (const { event, lineNo } of events) {
956
+ if (!event || typeof event !== 'object') continue;
957
+ if (event.type === 'subagent/descriptor') {
958
+ const dv = event.data?.version;
959
+ if (dv !== 3) {
960
+ out.push(violation('G1', { seq: event.seq, lineNo, eventType: event.type },
961
+ `subagent/descriptor data.version=${JSON.stringify(dv)}(官方 v0→v1 迁移要求 === 3)—— 升级到当前格式时官方会拒绝:subagent/descriptor ${event.seq} uses unsupported descriptor version ${String(dv)}`));
962
+ }
963
+ }
964
+ if (typeof event.type === 'string' && !V0_EVENT_TYPES.has(event.type)) {
965
+ // 官方对"unknown historical event"一律拒(原文 even when ignorable);E3 的 ignorable
966
+ // 豁免只作用于**读取路径**,这里不改它,只在迁移维度表达。
967
+ // 0.3.19(G4):把"是否声明可忽略 + 是否已登记"作为**机读字段**带出——事实预检(G2)
968
+ // 保留不变,但 migrationVerdict 据此把"已登记的可忽略事件"移入 acceptedDrops(不阻断)。
969
+ const ignorable = event.ignorable === true;
970
+ const ignorableRegistered = ignorable && isIgnorableRegistered(event.type, ignorableWhitelist);
971
+ out.push(violation('G2', { seq: event.seq, lineNo, eventType: event.type },
972
+ `type "${event.type}" 不在官方 v0 dispositions 内${ignorable ? '(即使 ignorable:true)' : ''}—— 官方迁移会拒:format v0 contains unknown historical event type`,
973
+ { ignorable, ignorableRegistered }));
974
+ }
975
+ }
976
+ // ── G3 · session/title 系列 messageSeqs(官方 v0→v1 `assertTitleSources`,:2543-2556)──
977
+ // 判据:每个被引 seq 必须解析到更早的 `user/message`,且 `data.source.kind === 'user'`;
978
+ // 另 `session/title` 的 `source.kind === 'user'` ⟺ `messageSeqs` 空。
979
+ //
980
+ // ⚠️ 应用面说明(实测 2026-09-15):官方 `assertTitleSources` 与 `turn/start` 状态机
981
+ // 同在 `assertReleasedArtifactRelationships` 里,而该函数被 **v1→v2** 以
982
+ // `RELEASED_V2_RELATIONSHIP_EXTENSIONS` 调用在**变换后的 v1/v2 artifact** 上
983
+ // (`dsh-session-format-v1-to-v2/lib/index.js:104`),不是原始 v0 事件。
984
+ // 对 `messageSeqs` 这类"按 seq 索引 + 事件类型/source 判定"的引用,变换保序保类型
985
+ // ⇒ 在原始 v0 上判是**必要条件的近似**;实测 281 个真实 v0 上 **0 误报**。
986
+ const bySeq = new Map();
987
+ for (const { event } of events) if (event && typeof event === 'object') bySeq.set(event.seq, event);
988
+ for (const { event, lineNo } of events) {
989
+ if (!event || typeof event !== 'object') continue;
990
+ if (event.type !== 'session/title' && event.type !== 'session/title-llm-request') continue;
991
+ const seqs = event.data?.messageSeqs;
992
+ if (!Array.isArray(seqs)) {
993
+ out.push(violation('G3', { seq: event.seq, lineNo, eventType: event.type },
994
+ `${event.type} ${event.seq} 的 messageSeqs 必须是数组 —— 官方迁移会拒`));
995
+ continue;
996
+ }
997
+ if (event.type === 'session/title') {
998
+ const kind = event.data?.source?.kind;
999
+ if ((seqs.length === 0) !== (kind === 'user')) {
1000
+ out.push(violation('G3', { seq: event.seq, lineNo, eventType: event.type },
1001
+ `session/title ${event.seq} messageSeqs must be empty exactly for a user title(官方原文;source.kind=${String(kind)},seqs=${seqs.length})`));
1002
+ }
1003
+ }
1004
+ for (const s of seqs) {
1005
+ const src = bySeq.get(s);
1006
+ if (!src || src.type !== 'user/message' || src.data?.source?.kind !== 'user') {
1007
+ out.push(violation('G3', { seq: event.seq, lineNo, eventType: event.type },
1008
+ `${event.type} ${event.seq} messageSeqs must cite earlier human user/message events(seq ${String(s)} 不是更早的人类 user/message)`));
1009
+ }
1010
+ }
1011
+ }
1012
+ return out;
1013
+ }
1014
+
1015
+ // ─────────────────────────────────────────────────────────────────────────────
1016
+ // 0.3.19 · v4 契约补充最小集(外部评审一手实测,2026-10-20)
1017
+ // 5 条硬规则:S10 / I2 / P5 / G4 / A1。判据只新增/收严,不改既有规则的判定。
1018
+ // ─────────────────────────────────────────────────────────────────────────────
1019
+
1020
+ /**
1021
+ * S10 —— `sourceEventSeqs` 元素类型硬断言(评审最小集 ②)。
1022
+ *
1023
+ * 实测(外部评审一手):化石里存在嵌套 `[a,b]`,`v4test`/投影层/`restore` **全部静默
1024
+ * 放过** ⇒ 契约层必须判红。但 `[a,b]` 本身是 v3+ 的**官方存储形态**(`encodeSeqRanges`
1025
+ * 把连续 ≥3 的 run 压成闭区间对;本机 760 份真实 v3/v4 里 265 处,全部可被官方
1026
+ * `decodeSeqRanges` 展开)⇒ 不能把合法的区间对当违规。判红点收严为两层:
1027
+ * ① **存储形态**(`rawSourceEventSeqViolations`,看 `log.rows[].value`):元素只能是
1028
+ * 非负安全整数或 `[start,end]`(start ≤ end),且必须能被官方 `decodeSeqRanges`
1029
+ * 解出且严格递增;否则 S10 error(解码层失败 = 投影/restore 会把它当 seq)。
1030
+ * ② **解码形态**(`sourceEventSeqElementViolations`,看已归一事件):解码后仍出现
1031
+ * 数组/非整数 = S10 error。
1032
+ * 覆盖面比 S6 宽:**所有事件**(含非 surface 类型与 `ignorable` 未知插件事件)都判——
1033
+ * 旧实现里非 surface 事件的 `sourceEventSeqs` 只在 S2 里被顺带提一句,`ignorable` 未知
1034
+ * 事件连 S2 都豁免 ⇒ 这类事件上的坏 provenance 是真空区。
1035
+ *
1036
+ * @param {Array<{event:object,lineNo?:number}>} events 已归一(区间已展开)的事件
1037
+ * @returns S10 违规列表
1038
+ */
1039
+ export function sourceEventSeqElementViolations(events) {
1040
+ const out = [];
1041
+ for (const { event, lineNo } of events ?? []) {
1042
+ if (!event || typeof event !== 'object') continue;
1043
+ const src = event.sourceEventSeqs;
1044
+ if (src === undefined) continue;
1045
+ const loc = { seq: event.seq, lineNo, eventType: event.type };
1046
+ if (!Array.isArray(src)) {
1047
+ out.push(violation('S10', loc, `sourceEventSeqs 必须是数组(实际 ${typeof src})——元素必须是非负整数`));
1048
+ continue;
1049
+ }
1050
+ for (let i = 0; i < src.length; i++) {
1051
+ const v = src[i];
1052
+ if (isSafeInt(v)) continue;
1053
+ if (Array.isArray(v)) {
1054
+ out.push(violation('S10', loc, `sourceEventSeqs[${i}] 解码后仍是嵌套数组 ${JSON.stringify(v).slice(0, 80)}——元素必须是非负整数(投影/restore/重写路径会把它静默当成 seq;实测 v4test 放过)`));
1055
+ } else {
1056
+ out.push(violation('S10', loc, `sourceEventSeqs[${i}] 不是非负安全整数(${String(v)},${typeof v})——元素必须是非负整数`));
1057
+ }
1058
+ }
1059
+ }
1060
+ return out;
1061
+ }
1062
+
1063
+ /** 单个元素是否为官方区间对 `[start,end]`(`decodeSeqRanges` 的存储形态,start ≤ end)。 */
1064
+ export function isSeqRangePair(value) {
1065
+ return Array.isArray(value) && value.length === 2 && isSafeInt(value[0]) && isSafeInt(value[1]) && value[0] <= value[1];
1066
+ }
1067
+
1068
+ /**
1069
+ * S10 · 存储形态层(见上)。只读 `loadSessionLog()` 的 `rows`(`value` = JSON.parse 原文)。
1070
+ * @param {Array<{lineNo:number,value:object|null}>} rows
1071
+ * @returns S10 违规列表
1072
+ */
1073
+ export function rawSourceEventSeqViolations(rows) {
1074
+ const out = [];
1075
+ for (const row of rows ?? []) {
1076
+ const value = row?.value;
1077
+ if (!value || typeof value !== 'object' || Array.isArray(value)) continue;
1078
+ const src = value.sourceEventSeqs;
1079
+ if (src === undefined) continue;
1080
+ const loc = { seq: Number.isSafeInteger(value.seq) ? value.seq : null, lineNo: row.lineNo, eventType: value.type };
1081
+ if (!Array.isArray(src)) {
1082
+ out.push(violation('S10', loc, `sourceEventSeqs 必须是数组(实际 ${typeof src})`));
1083
+ continue;
1084
+ }
1085
+ let bad = null;
1086
+ for (let i = 0; i < src.length; i++) {
1087
+ const v = src[i];
1088
+ if (isSafeInt(v) || isSeqRangePair(v)) continue;
1089
+ bad = { i, v };
1090
+ break;
1091
+ }
1092
+ if (bad !== null) {
1093
+ const shape = Array.isArray(bad.v) ? `嵌套数组 ${JSON.stringify(bad.v).slice(0, 80)}` : `${String(bad.v)}(${typeof bad.v})`;
1094
+ out.push(violation('S10', loc, `sourceEventSeqs[${bad.i}] 存储形态非法:${shape}——只允许非负安全整数或官方区间对 [start,end](start ≤ end)`));
1095
+ continue;
1096
+ }
1097
+ // 形态合法但官方解码器解不出(区间对逆序 / 越界 / 非严格递增)⇒ 同样是契约违规。
1098
+ try {
1099
+ decodeSeqRanges(src);
1100
+ } catch (err) {
1101
+ out.push(violation('S10', loc, `sourceEventSeqs 无法按官方区间编码解码:${err.message}——投影/restore 会把它静默当成 seq`));
1102
+ }
1103
+ }
1104
+ return out;
1105
+ }
1106
+
1107
+ /**
1108
+ * I2 —— `seedLength` 语义钉死 + `parentSession ∧ seedLength∈{缺失,0}` 合法(评审最小集 ③)。
1109
+ *
1110
+ * 一手依据(`@deepseek-ai/dsh-session-format-v0-to-v1@0.2.0-rc.2`):
1111
+ * - `package/lib/index.js:1707` `seedLength` → `inheritedEventCount`(缺省 0);
1112
+ * - `:1720` `isSeeded = record["seedLength"] !== undefined`(是否 seeded **只由字段是否存在决定**);
1113
+ * - `:1517-1520` `inheritedEventCount > events.length` → "Session inheritedEventCount exceeds its event count";`!isSeeded && inheritedEventCount !== 0` → "unseeded Session inheritedEventCount must be 0"。
1114
+ *
1115
+ * 结论(不再猜):
1116
+ * - **`parentSession` 有值 ≠ seeded**:血缘关系与继承计数是两件事。本机 712/760 份真实
1117
+ * v3/v4 头带 `parentSession` 且**无** `seedLength`(`isSeeded:false`)仍正常加载 ⇒
1118
+ * `parentSession ∧ seedLength∈{缺失,0}` 判 **合法**(不告警、不拒)。
1119
+ * - `seedLength` 超过**展开后**事件数 ⇒ error(本机 16 份 v0 化石命中:153113/531084/683896
1120
+ * vs 34841/12973/20268 —— 这些值明显是字节数/其它口径,官方迁移必拒)。
1121
+ * - v4 运行时头**禁** `seedLength`(dsh-session@0.2.0-rc.2 lib/index.js:1040)⇒ v4 文件带该字段 error。
1122
+ *
1123
+ * @param {object|null} header
1124
+ * @param {Array<object>} events 展开后事件(chunk 行已展开),用于比较继承条数
1125
+ * @param {number} version 被检文件版本
1126
+ * @returns I2 违规列表
1127
+ */
1128
+ export function seedLengthViolations(header, events, version) {
1129
+ const out = [];
1130
+ if (!header || typeof header !== 'object') return out;
1131
+ const has = Object.hasOwn(header, 'seedLength');
1132
+ if (version >= 4) {
1133
+ if (has) {
1134
+ out.push(violation('I2', {}, `v4 会话头不得带 seedLength(实际 ${String(header.seedLength)})——宿主 header 校验直接拒:"session header has invalid field \\"seedLength\\""(dsh-session@0.2.0-rc.2 lib/index.js:1040);v4 用 isSeeded + 构造器 inheritedEventCount,不落盘该字段`));
1135
+ }
1136
+ return out;
1137
+ }
1138
+ if (!has) return out;
1139
+ const seedLength = header.seedLength;
1140
+ if (!isSafeInt(seedLength)) {
1141
+ out.push(violation('I2', {}, `header.seedLength 必须是非负安全整数(实际 ${String(seedLength)})——语义 = 继承事件条数(官方 inheritedEventCount),不是字节数`));
1142
+ return out;
1143
+ }
1144
+ const count = Array.isArray(events) ? events.length : 0;
1145
+ if (seedLength > count) {
1146
+ out.push(violation('I2', {}, `header.seedLength=${seedLength} 大于展开后事件数 ${count}——seedLength 语义是**继承事件条数**(官方 inheritedEventCount),不是字节数/行数;官方解码/迁移会抛 "Session inheritedEventCount exceeds its event count"(dsh-session-format-v0-to-v1@0.2.0-rc.2 :1517-1520)`));
1147
+ }
1148
+ return out;
1149
+ }
1150
+
1151
+ // ── P5 · carrier 两段配对(评审最小集 ④)─────────────────────────────────
1152
+
1153
+ /** 第 1 段(审计段):`compaction/prune` + `data.shadowedRange`/`shadowedSeqs`(插件两段载体)。 */
1154
+ export function isCarrierAuditSegment(event) {
1155
+ if (!event || event.type !== 'compaction/prune') return false;
1156
+ const data = event.data;
1157
+ if (!data || typeof data !== 'object') return false;
1158
+ const range = data.shadowedRange;
1159
+ return typeof range === 'object' && range !== null && isSafeInt(range.start) && isSafeInt(range.end) && Array.isArray(data.shadowedSeqs);
1160
+ }
1161
+
1162
+ /** 从 surfaceOp 取 replace 的 [start,end](按文件版本择路:v3+ startSeq/endSeq)。 */
1163
+ export function surfaceReplaceRange(op, version) {
1164
+ if (!op || typeof op !== 'object' || op.op !== 'replace') return null;
1165
+ if (version >= 3) {
1166
+ return isSafeInt(op.startSeq) && isSafeInt(op.endSeq) ? { start: op.startSeq, end: op.endSeq } : null;
1167
+ }
1168
+ return isSafeInt(op.start) && isSafeInt(op.end) ? { start: op.start, end: op.end } : null;
1169
+ }
1170
+
1171
+ /** 审计段与载体的区间是否一致(配对的结构证据)。 */
1172
+ export function carrierRangesMatch(audit, carrier, version) {
1173
+ const range = audit?.data?.shadowedRange;
1174
+ const op = surfaceReplaceRange(carrier?.surfaceOp, version);
1175
+ return Boolean(range && op && range.start === op.start && range.end === op.end);
1176
+ }
1177
+
1178
+ /**
1179
+ * P5 —— carrier 两段配对(评审最小集 ④;读侧)。
1180
+ *
1181
+ * 现役写法(实测 888/888 真实载体):`sourceEventSeqs = [审计段 seq, ...被遮蔽节点]`;
1182
+ * 第 2 段 = 紧随审计段的 surface replace。规则:
1183
+ * - 审计段 seq 在 **首元素** ⇒ 通过(现役);
1184
+ * - 在 **末元素** ⇒ 通过(旧顺序,读侧容错),给 warning(不静默);
1185
+ * - 在中间位 / 载体紧邻审计段却**完全没引用**它 ⇒ error(配对失败 / 孤儿审计段)。
1186
+ * 官方 compaction 的 `compaction/summary` 引用是另一形状(`[compaction/start, summary, …]`),
1187
+ * 审计段类型限定 `compaction/prune` 天然不误报(本机 15 例实测)。
1188
+ *
1189
+ * @param {Array<{event:object,lineNo?:number}>} events 行序事件
1190
+ * @param {{version?:number}} [opts] 被检文件版本(决定 replace 字段名)
1191
+ * @returns P5 违规列表
1192
+ */
1193
+ export function carrierPairingViolations(events, { version = 0 } = {}) {
1194
+ const out = [];
1195
+ const list = events ?? [];
1196
+ const audits = new Map();
1197
+ for (const { event, lineNo } of list) {
1198
+ if (isCarrierAuditSegment(event) && isSafeInt(event.seq)) audits.set(event.seq, { event, lineNo });
1199
+ }
1200
+ if (audits.size === 0) return out;
1201
+ for (let idx = 0; idx < list.length; idx++) {
1202
+ const { event, lineNo } = list[idx];
1203
+ if (!event || !event.surfaceOp || typeof event.surfaceOp !== 'object' || event.surfaceOp.op !== 'replace') continue;
1204
+ const loc = { seq: event.seq, lineNo, eventType: event.type };
1205
+ const src = event.sourceEventSeqs;
1206
+ if (!Array.isArray(src)) continue; // S6/S10 负责
1207
+ const refs = [];
1208
+ for (let i = 0; i < src.length; i++) {
1209
+ const audit = audits.get(src[i]);
1210
+ if (audit && src[i] < event.seq) refs.push({ audit, pos: i });
1211
+ }
1212
+ // 读侧**两种写法都认**(外部评审要求;两种都在真实语料里出现过):
1213
+ // ① 现役:`[审计段 seq, ...被遮蔽节点]`(审计段 seq 在首位);
1214
+ // ② 早期:`[区间起点, ...被遮蔽节点]`(**不引用**审计段 seq;"区间起点"= replace 范围
1215
+ // 起点:实测真实语料 1,519 个载体即此写法)。
1216
+ // 两种都不报;其余(审计段 seq 在中间位、或首元素既非审计段也非区间起点)= 配对失败。
1217
+ const range = surfaceReplaceRange(event.surfaceOp, version);
1218
+ const legacyStartFirst = range !== null && src[0] === range.start;
1219
+ if (refs.length > 0) {
1220
+ for (const { audit, pos } of refs) {
1221
+ if (pos === 0 || legacyStartFirst) continue; // 现役 / 早期写法
1222
+ out.push(violation('P5', loc, `carrier 两段配对:审计段 seq ${audit.event.seq} 出现在 sourceEventSeqs 第 ${pos} 位,且首元素既不是审计段 seq 也不是区间起点(${String(src[0])} ≠ ${String(range?.start)})——读侧只认两种写法:[审计段, ...](现役)或 [区间起点, ...](早期)`));
1223
+ }
1224
+ continue;
1225
+ }
1226
+ const prev = idx > 0 ? list[idx - 1] : undefined;
1227
+ if (prev && isCarrierAuditSegment(prev.event) && carrierRangesMatch(prev.event, event, version)) {
1228
+ if (legacyStartFirst) continue; // 早期写法:区间起点开头、不引用审计段 ⇒ 读侧容错
1229
+ 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(现役)或区间起点(早期写法)`));
1230
+ }
1231
+ }
1232
+ return out;
1233
+ }
1234
+
1235
+ /**
1236
+ * P5 —— 写侧(现役写法严格校验)。`events` = 已存在事件 + 拟写事件(拟写事件在最后)。
1237
+ * 判据:拟写载体若紧邻审计段,`sourceEventSeqs[0]` 必须等于该审计段 seq;任何被引用的
1238
+ * 审计段 seq 都必须出现在首元素。
1239
+ * @param {Array<object>} events 完整事件列表(拟写事件在末尾)
1240
+ * @param {{version?:number}} [opts]
1241
+ * @returns P5 违规列表(error 级 = 写入被拒)
1242
+ */
1243
+ export function carrierWriteViolations(events, { version = 3 } = {}) {
1244
+ const out = [];
1245
+ const list = events ?? [];
1246
+ if (list.length === 0) return out;
1247
+ const candidate = list[list.length - 1];
1248
+ if (!candidate || !candidate.surfaceOp || typeof candidate.surfaceOp !== 'object' || candidate.surfaceOp.op !== 'replace') return out;
1249
+ const src = candidate.sourceEventSeqs;
1250
+ if (!Array.isArray(src)) return out; // S6/S10 负责
1251
+ const loc = { seq: candidate.seq, lineNo: null, eventType: candidate.type };
1252
+ const audits = new Map();
1253
+ for (const event of list) if (isCarrierAuditSegment(event) && isSafeInt(event.seq)) audits.set(event.seq, event);
1254
+ // ① 紧邻审计段(最强的配对证据):首元素必须就是它。
1255
+ const prev = list[list.length - 2];
1256
+ if (isCarrierAuditSegment(prev) && carrierRangesMatch(prev, candidate, version)) {
1257
+ if (src[0] !== prev.seq) {
1258
+ out.push(violation('P5', loc, `carrier 两段配对(写侧):紧邻审计段 seq ${prev.seq}(compaction/prune),第 2 段 sourceEventSeqs 首元素必须是它(实际首元素 ${String(src[0])})——写入被拒`));
1259
+ }
1260
+ return out;
1261
+ }
1262
+ // ② 其余情况:任何被引用的审计段 seq 都必须在首元素(写侧严格)。
1263
+ for (let i = 1; i < src.length; i++) {
1264
+ const audit = audits.get(src[i]);
1265
+ if (audit && src[i] < candidate.seq) {
1266
+ out.push(violation('P5', loc, `carrier 两段配对(写侧):审计段 seq ${audit.seq} 出现在 sourceEventSeqs 第 ${i} 位,但现役写法要求首元素 = 第 1 段 seq——写入被拒`));
1267
+ break;
1268
+ }
1269
+ }
1270
+ return out;
1271
+ }
1272
+
1273
+ // ── G4 · 未知历史事件声明式可忽略 + 白名单(评审最小集 ①)────────────────
1274
+
1275
+ /** 默认可忽略消费者白名单(与 E7 的已知插件前缀对齐;可被 opts/env 注入扩展)。 */
1276
+ export const DEFAULT_IGNORABLE_WHITELIST = Object.freeze(['retrace/', 'message-editor/']);
1277
+
1278
+ /**
1279
+ * 解析注入的白名单:数组,元素为精确 type 或以 `/` 结尾的前缀。
1280
+ * @param {string[]|undefined} extra
1281
+ * @returns {readonly string[]}
1282
+ */
1283
+ export function resolveIgnorableWhitelist(extra) {
1284
+ if (!Array.isArray(extra) || extra.length === 0) return DEFAULT_IGNORABLE_WHITELIST;
1285
+ return Object.freeze([...DEFAULT_IGNORABLE_WHITELIST, ...extra.filter((x) => typeof x === 'string' && x !== '')]);
1286
+ }
1287
+
1288
+ /** 未知 type 是否已被登记为"可忽略消费者"。 */
1289
+ export function isIgnorableRegistered(type, whitelist = DEFAULT_IGNORABLE_WHITELIST) {
1290
+ if (typeof type !== 'string' || type === '') return false;
1291
+ for (const entry of whitelist ?? []) {
1292
+ if (typeof entry !== 'string' || entry === '') continue;
1293
+ if (entry.endsWith('/')) {
1294
+ if (type.startsWith(entry)) return true;
1295
+ } else if (type === entry) {
1296
+ return true;
1297
+ }
1298
+ }
1299
+ return false;
1300
+ }
1301
+
1302
+ /**
1303
+ * G4 —— 未知历史事件的"声明式可忽略"策略(**迁移维度**,仅 v0 源文件)。
1304
+ *
1305
+ * 规则(评审原文):`未知类型 ∧ ignorable:true ⇒ 允许按声明丢弃并登记`(⛔ 不静默)。
1306
+ * - **已登记**(白名单命中)⇒ **不报违规**,进 `registered`(acceptedDrop)——迁移不再因它硬拒;
1307
+ * - **未登记** ⇒ G4 warning(仍阻断迁移:⛔ 不静默),提示登记到白名单;
1308
+ * - 未知且**无** ignorable ⇒ 不归本条(E3 读路径 error;G2 迁移事实预检)。
1309
+ *
1310
+ * 只作用于 v0(G 层是 v0→v1 迁移预检维度);v3/v4 的 ignorable 语义由 E3 表达,不改。
1311
+ *
1312
+ * @param {Array<{event:object,lineNo?:number}>} events
1313
+ * @param {number} version 被检文件版本
1314
+ * @param {{ignorableWhitelist?:string[]}} [opts]
1315
+ * @returns {{violations:Array, registered:Array, unregistered:Array}}
1316
+ */
1317
+ export function declarativeIgnorableViolations(events, version, { ignorableWhitelist } = {}) {
1318
+ const whitelist = resolveIgnorableWhitelist(ignorableWhitelist);
1319
+ const registered = [];
1320
+ const unregistered = [];
1321
+ const violations = [];
1322
+ if (version !== 0) return { violations, registered, unregistered };
1323
+ for (const { event, lineNo } of events ?? []) {
1324
+ if (typeof event?.type !== 'string' || event.ignorable !== true) continue;
1325
+ if (V0_EVENT_TYPES.has(event.type)) continue; // 已知历史事件,不属本条
1326
+ const loc = { seq: event.seq, lineNo, eventType: event.type };
1327
+ if (isIgnorableRegistered(event.type, whitelist)) {
1328
+ registered.push({ type: event.type, seq: typeof event.seq === 'number' ? event.seq : null, lineNo: typeof lineNo === 'number' ? lineNo : null });
1329
+ continue;
1330
+ }
1331
+ unregistered.push({ type: event.type, seq: typeof event.seq === 'number' ? event.seq : null, lineNo: typeof lineNo === 'number' ? lineNo : null });
1332
+ violations.push(violation('G4', loc, `type "${event.type}" 是未知历史事件且带 ignorable:true,但不在可忽略白名单——按声明丢弃会被静默吞掉(⛔ 不静默);登记到 opts.ignorableWhitelist / DSH_LOG_CONTRACT_IGNORABLE_WHITELIST(精确 type 或以 / 结尾的前缀)后才移出迁移阻断`));
1333
+ }
1334
+ return { violations, registered, unregistered };
1335
+ }