dsh-log-contract 0.3.18 → 0.3.20

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/archive.js ADDED
@@ -0,0 +1,309 @@
1
+ /**
2
+ * dsh-log-contract · lib/archive.js
3
+ *
4
+ * A1 —— 「在位可还原」只认结构化归档指针(0.3.19 · v4 契约补充最小集 ⑤)。
5
+ *
6
+ * 为什么单独成模块:这条判定需要读**归档文件**(外置内容的落盘副本),是文件系统维度,
7
+ * 不属于 `checks.js` 的纯事件判定;且它是**独立维度**(与 `migration` 同款):离线体检
8
+ * 只有在调用方提供归档根目录时才能回答"在位可还原",否则只能回答"不可判定"——
9
+ * **不许**把"没查"冒充成"通过"。
10
+ *
11
+ * 口径(外部评审一手实测,2026-10-20):
12
+ * - 只认**结构化字段**:`data.archiveRef` / `data.archive` /
13
+ * `data.externalized.archiveRef` / `data.externalized.archive`;
14
+ * 校验元数据取同级 `archiveLine` / `sha256`。
15
+ * - ⛔ **不得**从自由文本 grep 路径。实测两版文本口径全错:原版给 78.26%
16
+ * (正文模板/示例被算成引用)、改成"只认绝对路径"后 2.04%(正文里提到的真实路径示例
17
+ * 又虚低)。本机 763 份真实会话:结构化指针 273,571 个,自由文本 `archive 第 N 行`
18
+ * 出现在 144,391 个事件里——两种口径差近 20 倍,文本 grep 不可用。
19
+ *
20
+ * 判据:目标文件存在 + `archiveLine` 行存在 + `sha256`(若有)匹配 = 在位可还原;
21
+ * 目标缺失/行缺失/sha 不符 = A1 error;绝对路径失效但同名归档在归档根可解析 = relocated
22
+ * warning(re-home 未回写:内容可找回,但**不在位**)。
23
+ */
24
+ import fs from 'node:fs';
25
+ import path from 'node:path';
26
+ import crypto from 'node:crypto';
27
+ import { violation } from './checks.js';
28
+ import { decompressZstd } from './log-reader.js';
29
+
30
+ const ZSTD_MAGIC = 0xfd2fb528;
31
+
32
+ /** 结构化指针字段(只认这些;`content`/`pointer`/散文一律不碰)。 */
33
+ export const ARCHIVE_POINTER_FIELDS = Object.freeze(['archiveRef', 'archive']);
34
+
35
+ /** `data.externalized` 下认的键(等价指针字段)。 */
36
+ export const EXTERNALIZED_POINTER_FIELDS = Object.freeze(['archiveRef', 'archive']);
37
+
38
+ function isPlainRecord(value) {
39
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
40
+ }
41
+
42
+ function pushPointer(out, event, lineNo, field, ref, line, sha) {
43
+ if (typeof ref !== 'string' || ref === '') return;
44
+ out.push({
45
+ seq: Number.isSafeInteger(event.seq) ? event.seq : null,
46
+ lineNo: typeof lineNo === 'number' ? lineNo : null,
47
+ type: typeof event.type === 'string' ? event.type : null,
48
+ field,
49
+ ref,
50
+ archiveLine: Number.isSafeInteger(line) ? line : null,
51
+ sha256: typeof sha === 'string' && sha !== '' ? sha : null,
52
+ });
53
+ }
54
+
55
+ /**
56
+ * 从事件流提取**结构化**归档指针(纯函数,不读盘)。
57
+ *
58
+ * 入参既接受 `{event, lineNo}` 包装(`loadSessionLog().events` 的形状),也接受裸事件对象
59
+ * (手搓用例/第三方直接传事件数组)。
60
+ *
61
+ * @param {Array<{event:object,lineNo?:number}|object>} events
62
+ * @returns {Array<{seq:number|null,lineNo:number|null,type:string|null,field:string,ref:string,archiveLine:number|null,sha256:string|null}>}
63
+ */
64
+ export function collectArchivePointers(events) {
65
+ const out = [];
66
+ for (const item of events ?? []) {
67
+ const event = item && typeof item === 'object' && Object.hasOwn(item, 'event') ? item.event : item;
68
+ const lineNo = item && typeof item === 'object' ? item.lineNo : undefined;
69
+ if (!event || typeof event !== 'object') continue;
70
+ const data = event.data;
71
+ if (!isPlainRecord(data)) continue;
72
+ for (const field of ARCHIVE_POINTER_FIELDS) {
73
+ if (data[field] === undefined) continue;
74
+ pushPointer(out, event, lineNo, `data.${field}`, data[field], data.archiveLine, data.sha256 ?? data.archiveSha256);
75
+ }
76
+ const ext = data.externalized;
77
+ if (isPlainRecord(ext)) {
78
+ for (const field of EXTERNALIZED_POINTER_FIELDS) {
79
+ if (ext[field] === undefined) continue;
80
+ pushPointer(out, event, lineNo, `data.externalized.${field}`, ext[field], ext.archiveLine, ext.sha256 ?? ext.archiveSha256);
81
+ }
82
+ }
83
+ }
84
+ return out;
85
+ }
86
+
87
+ /** 归档引用 basename(用于在归档根里解析;不改变"在位"判据,只用于 relocated 判定)。 */
88
+ export function archiveBasename(ref) {
89
+ return typeof ref === 'string' ? path.basename(ref) : '';
90
+ }
91
+
92
+ /** 把指针的声明目标解析为文件路径:绝对路径优先;相对/basename 走归档根。 */
93
+ function findArchiveFile(pointer, { archiveRoots = [], index } = {}) {
94
+ const stated = typeof pointer.ref === 'string' && path.isAbsolute(pointer.ref) ? pointer.ref : null;
95
+ if (stated && fs.existsSync(stated)) return { target: stated, statedPath: stated, relocated: false };
96
+ const base = archiveBasename(pointer.ref);
97
+ if (!base) return { target: null, statedPath: stated, relocated: false };
98
+ let found = index?.get(base) ?? null;
99
+ if (!found) {
100
+ for (const root of archiveRoots) {
101
+ const hit = searchByBasename(root, base, 0, index);
102
+ if (hit) { found = hit; break; }
103
+ }
104
+ }
105
+ if (found) return { target: found, statedPath: stated, relocated: stated !== null && stated !== found };
106
+ return { target: null, statedPath: stated, relocated: false };
107
+ }
108
+
109
+ /** 在归档根下按 basename 找文件(深度 ≤3;找到即缓存)。 */
110
+ function searchByBasename(dir, base, depth, index) {
111
+ if (depth > 3 || !fs.existsSync(dir)) return null;
112
+ let entries;
113
+ try {
114
+ entries = fs.readdirSync(dir);
115
+ } catch {
116
+ return null;
117
+ }
118
+ for (const name of entries) {
119
+ const full = path.join(dir, name);
120
+ let st;
121
+ try {
122
+ st = fs.statSync(full);
123
+ } catch {
124
+ continue;
125
+ }
126
+ if (st.isDirectory()) {
127
+ const hit = searchByBasename(full, base, depth + 1, index);
128
+ if (hit) { index?.set(base, hit); return hit; }
129
+ } else if (name === base) {
130
+ index?.set(base, full);
131
+ return full;
132
+ }
133
+ }
134
+ return null;
135
+ }
136
+
137
+ /**
138
+ * 读归档文件的**行索引**(只保留请求的行;巨型归档不能整体 `toString`:
139
+ * >512MiB 明文会触发 V8 字符串上限——那是器具限制,不是内容缺失,必须避免把它误报成 A1)。
140
+ *
141
+ * @param {string} file 归档路径(.jsonl.zst 走多帧解压;.jsonl 直接 utf8)
142
+ * @param {Set<number>} [wantedLines] 需要的 1-based 行号
143
+ * @returns {{count:number, lineAt:(n:number)=>string}}
144
+ */
145
+ export function readArchiveIndex(file, wantedLines = new Set()) {
146
+ const buf = fs.readFileSync(file);
147
+ const isZstd = buf.length >= 4 && buf.readUInt32LE(0) === ZSTD_MAGIC;
148
+ const plain = isZstd ? decompressZstd(buf) : buf;
149
+ const lines = new Map();
150
+ let count = 0;
151
+ let start = 0;
152
+ for (let i = 0; i < plain.length; i++) {
153
+ if (plain[i] !== 0x0a) continue;
154
+ count++;
155
+ if (wantedLines.has(count)) lines.set(count, plain.subarray(start, i).toString('utf8'));
156
+ start = i + 1;
157
+ }
158
+ if (start < plain.length) {
159
+ count++;
160
+ if (wantedLines.has(count)) lines.set(count, plain.subarray(start).toString('utf8'));
161
+ }
162
+ return { count, lineAt: (n) => lines.get(n) ?? '' };
163
+ }
164
+
165
+ /** 读归档文件为明文行数组(.jsonl.zst 走多帧解压;.jsonl 直接 utf8)。 */
166
+ export function readArchiveLines(file) {
167
+ const buf = fs.readFileSync(file);
168
+ const isZstd = buf.length >= 4 && buf.readUInt32LE(0) === ZSTD_MAGIC;
169
+ const text = isZstd ? decompressZstd(buf).toString('utf8') : buf.toString('utf8');
170
+ const lines = text.split('\n');
171
+ if (lines.length > 0 && lines[lines.length - 1] === '') lines.pop();
172
+ return lines;
173
+ }
174
+
175
+ /** sha256(十六进制);匹配时允许 16 位前缀(深 H2 以 line16 为准,sha256 作对照)。 */
176
+ function sha256Hex(text) {
177
+ return crypto.createHash('sha256').update(text).digest('hex');
178
+ }
179
+
180
+ function shaMatches(line, want) {
181
+ if (typeof want !== 'string' || want.length < 16) return true; // 无/过短指纹 ⇒ 不做深校验(不猜)
182
+ const got = sha256Hex(line);
183
+ const w = want.toLowerCase();
184
+ if (w.length >= 64) return got === w.slice(0, 64);
185
+ return got.startsWith(w) || w.startsWith(got.slice(0, w.length));
186
+ }
187
+
188
+ /**
189
+ * 校验收到的结构化指针能否在位还原。
190
+ *
191
+ * @param {Array} pointers `collectArchivePointers()` 的结果
192
+ * @param {{archiveRoots?:string[], readLines?:Function}} [opts]
193
+ * @returns {{
194
+ * assessable: boolean,
195
+ * pointers: number, restorable: number, relocated: number, missing: number, unresolved: number,
196
+ * lineMissing: number, shaMismatch: number, restoredBytes: number,
197
+ * restorableRate: number, verdict: 'restorable'|'unrestorable'|'unverifiable',
198
+ * violations: Array, details: object,
199
+ * }}
200
+ */
201
+ export function verifyArchivePointers(pointers, { archiveRoots = [], readLines } = {}) {
202
+ const roots = Array.isArray(archiveRoots) ? archiveRoots.filter((r) => typeof r === 'string' && r !== '') : [];
203
+ const assessable = roots.length > 0;
204
+ const result = {
205
+ assessable,
206
+ pointers: pointers.length,
207
+ effectivePointers: 0,
208
+ restorable: 0,
209
+ relocated: 0,
210
+ missing: 0,
211
+ unresolved: 0,
212
+ lineMissing: 0,
213
+ shaMismatch: 0,
214
+ duplicated: 0,
215
+ restoredBytes: 0,
216
+ restorableRate: 0,
217
+ verdict: assessable ? 'restorable' : 'unverifiable',
218
+ violations: [],
219
+ details: { missing: [], relocated: [], unresolved: [], lineMissing: [], shaMismatch: [] },
220
+ };
221
+ if (!assessable) {
222
+ // 不可判定:没有归档根 ⇒ 不冒充通过、也不产生违规(独立维度)。
223
+ return result;
224
+ }
225
+ // ① 解析目标 + 按 (target, line) 去重:同一记录常同时带 `archiveRef`(basename) 与
226
+ // `archive`(绝对路径) 两个结构化指针,指向同一目标同一行——它们是**一条记录**,不能
227
+ // 算两次(否则"可还原率"会被双字段写法放大/缩小)。
228
+ const index = new Map();
229
+ const unique = [];
230
+ const seen = new Set();
231
+ for (const pointer of pointers) {
232
+ const { target, relocated } = findArchiveFile(pointer, { archiveRoots: roots, index });
233
+ if (!target) {
234
+ result.unresolved++;
235
+ if (result.details.unresolved.length < 20) result.details.unresolved.push({ seq: pointer.seq, field: pointer.field, ref: pointer.ref });
236
+ continue;
237
+ }
238
+ const dedupeKey = `${target}\u0000${pointer.archiveLine ?? ''}`;
239
+ if (seen.has(dedupeKey)) { result.duplicated++; continue; }
240
+ seen.add(dedupeKey);
241
+ unique.push({ pointer, target, relocated });
242
+ }
243
+ result.effectivePointers = unique.length;
244
+ // ② 按目标分组,一次扫描取回需要的行(巨型归档不能整体 toString:
245
+ // >512MiB 明文会触发 V8 字符串上限,那是器具限制、不是内容缺失)。
246
+ const byTarget = new Map();
247
+ for (const item of unique) {
248
+ if (!byTarget.has(item.target)) byTarget.set(item.target, []);
249
+ byTarget.get(item.target).push(item);
250
+ }
251
+ for (const [target, items] of byTarget) {
252
+ const wanted = new Set(items.map(({ pointer }) => pointer.archiveLine).filter((n) => Number.isSafeInteger(n) && n >= 1));
253
+ let archiveIndex;
254
+ try {
255
+ archiveIndex = (readLines ?? readArchiveIndex)(target, wanted);
256
+ if (Array.isArray(archiveIndex)) archiveIndex = { count: archiveIndex.length, lineAt: (n) => archiveIndex[n - 1] ?? '' };
257
+ } catch (err) {
258
+ const message = String(err?.message ?? err).slice(0, 120);
259
+ for (const { pointer } of items) {
260
+ result.missing++;
261
+ if (result.details.missing.length < 20) result.details.missing.push({ seq: pointer.seq, field: pointer.field, ref: pointer.ref, target, reason: message });
262
+ result.violations.push(violation('A1', { seq: pointer.seq, lineNo: pointer.lineNo, eventType: pointer.type }, `归档不可读:${pointer.field} → ${pointer.ref}(解析到 ${target})——在位可还原判定失败(${message})`));
263
+ }
264
+ continue;
265
+ }
266
+ for (const { pointer, relocated } of items) {
267
+ const loc = { seq: pointer.seq, lineNo: pointer.lineNo, eventType: pointer.type };
268
+ const lineNo = pointer.archiveLine;
269
+ if (!Number.isSafeInteger(lineNo) || lineNo < 1 || lineNo > archiveIndex.count) {
270
+ result.lineMissing++;
271
+ if (result.details.lineMissing.length < 20) result.details.lineMissing.push({ seq: pointer.seq, field: pointer.field, ref: pointer.ref, target, archiveLine: lineNo, lines: archiveIndex.count });
272
+ result.violations.push(violation('A1', loc, `归档行缺失:${pointer.field} → ${pointer.ref} 指向第 ${String(lineNo)} 行,但归档只有 ${archiveIndex.count} 行——内容不可在位还原(模板/示例文本不参与本判据)`));
273
+ continue;
274
+ }
275
+ const line = archiveIndex.lineAt(lineNo);
276
+ if (!shaMatches(line, pointer.sha256)) {
277
+ result.shaMismatch++;
278
+ if (result.details.shaMismatch.length < 20) result.details.shaMismatch.push({ seq: pointer.seq, field: pointer.field, ref: pointer.ref, target, archiveLine: lineNo, want: pointer.sha256?.slice(0, 16), got: sha256Hex(line).slice(0, 16) });
279
+ result.violations.push(violation('A1', loc, `归档内容指纹不符:${pointer.field} → ${pointer.ref} 第 ${lineNo} 行 sha256 期望 ${pointer.sha256?.slice(0, 16)}…,实际 ${sha256Hex(line).slice(0, 16)}…——归档已漂移,不可在位还原`));
280
+ continue;
281
+ }
282
+ if (relocated) {
283
+ result.relocated++;
284
+ const v = violation('A1', loc, `归档指针的绝对路径已失效(${pointer.ref}),但同名归档在归档根可解析(${target})——内容可找回,但**不在位**(re-home 未回写);按 relocated 记 warning`);
285
+ v.severity = 'warning';
286
+ result.violations.push(v);
287
+ if (result.details.relocated.length < 20) result.details.relocated.push({ seq: pointer.seq, field: pointer.field, ref: pointer.ref, target });
288
+ } else {
289
+ result.restorable++;
290
+ result.restoredBytes += Buffer.byteLength(line, 'utf8');
291
+ }
292
+ }
293
+ }
294
+ result.restorableRate = result.effectivePointers > 0 ? result.restorable / result.effectivePointers : 1;
295
+ result.verdict = result.missing === 0 && result.lineMissing === 0 && result.shaMismatch === 0 && result.unresolved === 0
296
+ ? 'restorable'
297
+ : 'unrestorable';
298
+ return result;
299
+ }
300
+
301
+ /**
302
+ * A1 一站式:事件流 → 结构化指针 → 在位可还原结论。
303
+ * @param {Array<{event:object,lineNo?:number}>} events
304
+ * @param {{archiveRoots?:string[]}} [opts]
305
+ */
306
+ export function archiveVerdict(events, { archiveRoots = [], readLines } = {}) {
307
+ const pointers = collectArchivePointers(events);
308
+ return verifyArchivePointers(pointers, { archiveRoots, readLines });
309
+ }
package/lib/checks.js CHANGED
@@ -8,7 +8,7 @@
8
8
  * 每条违规都挂 `lib/contracts.js` 中的规则 id 与官方源码出处。
9
9
  */
10
10
  import { isSurfaceEligibleType } from '@deepseek-ai/dsh-session';
11
- import { isJsonValue } from './compat.js';
11
+ import { isJsonValue, decodeSeqRanges } from './compat.js';
12
12
  import { currentVocabulary, currentFold, V0_EVENT_TYPES } from './vocab.js';
13
13
  import { ruleById } from './contracts.js';
14
14
 
@@ -948,9 +948,10 @@ export function wireViolations(events, version) {
948
948
  * @param {Array<{event:object, lineNo?:number}>} events 已展开事件(带 loc 包装)
949
949
  * @param {number} version 被检文件版本
950
950
  */
951
- export function migrationPrecheckViolations(events, version) {
951
+ export function migrationPrecheckViolations(events, version, opts = {}) {
952
952
  const out = [];
953
953
  if (version !== 0) return out;
954
+ const ignorableWhitelist = resolveIgnorableWhitelist(opts.ignorableWhitelist);
954
955
  for (const { event, lineNo } of events) {
955
956
  if (!event || typeof event !== 'object') continue;
956
957
  if (event.type === 'subagent/descriptor') {
@@ -963,8 +964,13 @@ export function migrationPrecheckViolations(events, version) {
963
964
  if (typeof event.type === 'string' && !V0_EVENT_TYPES.has(event.type)) {
964
965
  // 官方对"unknown historical event"一律拒(原文 even when ignorable);E3 的 ignorable
965
966
  // 豁免只作用于**读取路径**,这里不改它,只在迁移维度表达。
967
+ // 0.3.19(G4):把"是否声明可忽略 + 是否已登记"作为**机读字段**带出——事实预检(G2)
968
+ // 保留不变,但 migrationVerdict 据此把"已登记的可忽略事件"移入 acceptedDrops(不阻断)。
969
+ const ignorable = event.ignorable === true;
970
+ const ignorableRegistered = ignorable && isIgnorableRegistered(event.type, ignorableWhitelist);
966
971
  out.push(violation('G2', { seq: event.seq, lineNo, eventType: event.type },
967
- `type "${event.type}" 不在官方 v0 dispositions 内${event.ignorable === true ? '(即使 ignorable:true)' : ''}—— 官方迁移会拒:format v0 contains unknown historical event type`));
972
+ `type "${event.type}" 不在官方 v0 dispositions 内${ignorable ? '(即使 ignorable:true)' : ''}—— 官方迁移会拒:format v0 contains unknown historical event type`,
973
+ { ignorable, ignorableRegistered }));
968
974
  }
969
975
  }
970
976
  // ── G3 · session/title 系列 messageSeqs(官方 v0→v1 `assertTitleSources`,:2543-2556)──
@@ -1005,3 +1011,325 @@ export function migrationPrecheckViolations(events, version) {
1005
1011
  }
1006
1012
  return out;
1007
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
+ }