dsh-log-contract 0.3.21 → 0.3.22

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,66 @@
1
+ /**
2
+ * dsh-log-contract · adapters/dsh/vocab.js
3
+ *
4
+ * DSH 专属:词表与形状常量(事件类型表、可见面类型表、存储行类型、标记前缀、
5
+ * 信封键集、可忽略消费者白名单、归档指针字段名),以及按文件版本选词表的路由。
6
+ *
7
+ * 契约层不持有任何具体词表:需要判定「种类是否已知」时由本适配器提供词表与白名单。
8
+ * 版本路由与词表数据由 format-versions 适配器提供。
9
+ */
10
+
11
+
12
+
13
+ // ── 归档指针字段名(结构化指针语义)────────────────────────────────────────
14
+ /** 结构化指针字段(只认这些;自由文本一律不碰)。 */
15
+ export const ARCHIVE_POINTER_FIELDS = Object.freeze(['archiveRef', 'archive']);
16
+
17
+ /** `data.externalized` 下认的键(等价指针字段)。 */
18
+ export const EXTERNALIZED_POINTER_FIELDS = Object.freeze(['archiveRef', 'archive']);
19
+
20
+ export const SURFACE_TYPES = new Set(['user/message', 'assistant/message', 'tool/result']);
21
+ /** v3 新增 `system/message`(官方 `SURFACE_EVENT_TYPES`,0.1.5 `lib/index.js:149-154`)。 */
22
+ export const MODERN_SURFACE_TYPES = new Set([...SURFACE_TYPES, 'system/message']);
23
+ /** v4 新增 `developer/message`(官方 `SURFACE_EVENT_TYPES`,dsh-session@0.2.0-rc.2 `src/surface.ts:50-56`)。 */
24
+ export const V4_SURFACE_TYPES = new Set([...MODERN_SURFACE_TYPES, 'developer/message']);
25
+ export const CHUNK_ROW_TYPES = new Set(['text-chunks', 'reasoning-chunks', 'tool-call-chunks']);
26
+
27
+ /** 当前文件版本适用的 surface 候选类型集(v3 起含 system/message,v4 起含 developer/message)。version = 被检文件版本。 */
28
+ export function currentSurfaceTypes(version) {
29
+ if (version >= 4) return V4_SURFACE_TYPES;
30
+ return version >= 3 ? MODERN_SURFACE_TYPES : SURFACE_TYPES;
31
+ }
32
+ export const MARKER_PREFIXES = ['retrace', 'message-editor'];
33
+
34
+
35
+ /** 宿主信封键白名单(assertSessionEventEnvelope,dsh-session@0.1.5-rc.1 lib/index.js:852-861)。 */
36
+ export const ENVELOPE_ALLOWED_KEYS = new Set(['type', 'seq', 'time', 'data', 'surfaceOp', 'sourceEventSeqs', 'ignorable']);
37
+
38
+
39
+ // ── G4 · 未知历史事件声明式可忽略 + 白名单 ────────────────────────────────
40
+
41
+ /** 默认可忽略消费者白名单(与 E7 的已知插件前缀对齐;可被 opts/env 注入扩展)。 */
42
+ export const DEFAULT_IGNORABLE_WHITELIST = Object.freeze(['retrace/', 'message-editor/']);
43
+
44
+ /**
45
+ * 解析注入的白名单:数组,元素为精确 type 或以 `/` 结尾的前缀。
46
+ * @param {string[]|undefined} extra
47
+ * @returns {readonly string[]}
48
+ */
49
+ export function resolveIgnorableWhitelist(extra) {
50
+ if (!Array.isArray(extra) || extra.length === 0) return DEFAULT_IGNORABLE_WHITELIST;
51
+ return Object.freeze([...DEFAULT_IGNORABLE_WHITELIST, ...extra.filter((x) => typeof x === 'string' && x !== '')]);
52
+ }
53
+
54
+ /** 未知 type 是否已被登记为"可忽略消费者"。 */
55
+ export function isIgnorableRegistered(type, whitelist = DEFAULT_IGNORABLE_WHITELIST) {
56
+ if (typeof type !== 'string' || type === '') return false;
57
+ for (const entry of whitelist ?? []) {
58
+ if (typeof entry !== 'string' || entry === '') continue;
59
+ if (entry.endsWith('/')) {
60
+ if (type.startsWith(entry)) return true;
61
+ } else if (type === entry) {
62
+ return true;
63
+ }
64
+ }
65
+ return false;
66
+ }
@@ -42,7 +42,7 @@ const USAGE = `dsh-log-contract —— 日志契约守护(DSH session log cont
42
42
  用法:
43
43
  dsh-log-contract check <session-log> [--json] [--max-details N] [--resume] [--fail-on-migration] [--no-fail-on-migration] [--archive-root DIR] [--ignorable-whitelist a,b]
44
44
  离线体检 + **迁移预检** + **在位可还原(A1,独立维度)**。session-log 支持 .jsonl 与 .jsonl.zstd。
45
- ⚠️ 口径边界:本工具只判定它实现的规则集。「ok」/「可加载」/「可继续」/「可压缩」
45
+ ⚠️ 判据边界:本工具只判定它实现的规则集。「ok」/「可加载」/「可继续」/「可压缩」
46
46
  **不代表**会话"可用",**不代表**可安全编辑,也**不代表**官方升级路径会接受
47
47
  (迁移是独立维度,覆盖边界见 contracts 输出与 lib/contracts.js 的 G 段)。
48
48
  --json 输出机器可读 JSON 报告(含 host / assessable / assessmentScope / migration 字段)
@@ -73,14 +73,14 @@ const USAGE = `dsh-log-contract —— 日志契约守护(DSH session log cont
73
73
  --no-fail-on-migration 退出该档)。
74
74
 
75
75
  dsh-log-contract fix <session-log> [--remove-markers] [--neutralize] [--neutralize-legacy-markers] [--clip-crossstep] [--drop-failed-turns] [--trim-last N] [--compact-last N] [--tail-renumber D] [--neutralize-orphan] [--extract-turn N] [--keep-ranges a-b,c-d] [--apply] [--backup-dir DIR] [--json]
76
- 诊断 + 修复(2026-08 事故固化方案)。先做严格 seq 连续扫描 + 契约体检
76
+ 诊断 + 修复。先做严格 seq 连续扫描 + 契约体检
77
77
  (含 W1/W2 wire 级悬空 tool 检查),再按需修复:
78
78
  --remove-markers 移除 retrace/message-editor marker 并全量重编号
79
79
  (用于大范围遮蔽历史 / marker 漏盖 tool/result)
80
80
  --clip-crossstep 裁剪 assistant/message 的跨 step sourceEventSeqs(token-meter 不再抛 belongs to another step)
81
81
  --neutralize 原地中和 turn-null marker(type→retrace/marker +
82
82
  ignorable:true,删 surfaceOp/sourceEventSeqs,seq/行数不变)
83
- —— token-meter 不再刷屏,会话驻留也安全(2026-08-30 事故)
83
+ —— token-meter 不再刷屏,会话驻留也安全
84
84
  --neutralize-legacy-markers
85
85
  **一次性根治历史载体债**:只中和
86
86
  assistant/message + data.editor 形态的历史 retrace marker
@@ -447,7 +447,7 @@ function cmdPrewrite(args) {
447
447
  }
448
448
 
449
449
  function cmdContracts() {
450
- out('dsh-log-contract 契约规则目录(spec:官方源码逐行核对 + 实测事故固化)\n\n');
450
+ out('dsh-log-contract 契约规则目录(spec:官方源码逐行核对)\n\n');
451
451
  for (const r of CONTRACT_RULES) {
452
452
  const flags = [
453
453
  r.candidate ? '候选规则' : null,
@@ -0,0 +1,17 @@
1
+ /**
2
+ * contract/index.js
3
+ *
4
+ * 契约层(platform-neutral)公开面。
5
+ *
6
+ * 两层边界:
7
+ * - contract/ 平台无关:判定模型、不变量目录、规则描述符与注册表、记录 schema
8
+ * - adapters/<platform>/ 平台专属:事件形状、格式版本、帧结构、视图推导、词表
9
+ *
10
+ * 依赖方向固定为 adapters → contract,契约层不得反向依赖任何适配器。
11
+ * 各模块为契约层自有实现;平台专属内容由适配器提供(adapters → contract 单向)。
12
+ */
13
+
14
+ export * from './verdict.js';
15
+ export * from './invariants.js';
16
+ export * from './rules.js';
17
+ export * from './registry.js';
@@ -0,0 +1,478 @@
1
+ /**
2
+ * contract/invariants.js
3
+ *
4
+ * 平台无关的不变量目录 + 判定原语。
5
+ *
6
+ * 「不变量」= 与具体运行时无关、必须始终成立的性质。适配器负责把平台记录
7
+ * **规范化**成这里的输入形状,再交给这些判定;契约层不反向依赖任何适配器。
8
+ *
9
+ * 判定输入是**规范化记录视图**(不绑定任何平台的字段命名习惯):
10
+ *
11
+ * record = { seq, lineNo?, eventType?, ... } 一条逻辑记录(序号 + 定位)
12
+ * row = { lineNo, value, error } 一条物理存储行(解析结果或解析错误)
13
+ * pointer = { seq, lineNo?, type?, field, ref, 一条外置内容指针(目标 + 行 + 指纹)
14
+ * archiveLine, sha256 }
15
+ *
16
+ * 平台适配器负责把原始记录翻译成上述视图;本文件只判断不变量是否成立,
17
+ * 并构造与注册表一致的判定记录(severity/layer 由规则 id 解析)。
18
+ */
19
+
20
+ import fs from 'node:fs';
21
+ import path from 'node:path';
22
+ import crypto from 'node:crypto';
23
+ import { violation } from './verdict.js';
24
+
25
+ /**
26
+ * 不变量标识目录。每个标识对应一类跨平台成立的性质;
27
+ * 具体协议/格式相关的判定由 adapters/<platform>/ 提供。
28
+ */
29
+ export const INVARIANTS = Object.freeze({
30
+ // 记录与存储
31
+ RECORD_PARSABLE: 'record.parsable',
32
+ RECORD_HEAD_DECLARED: 'record.head-declared',
33
+ ENVELOPE_CLOSED: 'envelope.closed',
34
+ VALUE_JSON_LOSSLESS: 'value.json-lossless',
35
+ EMPTY_CONTAINER_EXPLICIT: 'container.empty-explicit',
36
+ // 序号与写入者
37
+ SEQ_PRESENT: 'seq.present',
38
+ SEQ_CONTIGUOUS: 'seq.contiguous',
39
+ SEQ_MONOTONIC: 'seq.monotonic',
40
+ SINGLE_WRITER: 'seq.single-writer',
41
+ // 种类与引用
42
+ TYPE_KNOWN_OR_DECLARED: 'type.known-or-declared',
43
+ REFERENCE_CLOSURE: 'reference.closure',
44
+ REFERENCE_SAME_SCOPE: 'reference.same-scope',
45
+ PAIRING_COMPLETE: 'pairing.complete',
46
+ // 视图推导与改写
47
+ VIEW_REPLAYABLE: 'view.replayable',
48
+ VIEW_KEY_UNIQUE: 'view.key-unique',
49
+ VIEW_SCOPE_ATTRIBUTABLE: 'view.scope-attributable',
50
+ REWRITE_NODE_BOUNDED: 'rewrite.node-bounded',
51
+ REWRITE_COVERAGE_COMPLETE: 'rewrite.coverage-complete',
52
+ REWRITE_CONTENT_ONLY: 'rewrite.content-only',
53
+ DERIVED_SCOPE_MATCH: 'derived.scope-match',
54
+ // 帧与容器
55
+ FRAME_DECODABLE: 'frame.decodable',
56
+ FRAME_TAIL_INTACT: 'frame.tail-intact',
57
+ FRAME_FIRST_RECORD_ALONE: 'frame.first-record-alone',
58
+ FRAME_LAYOUT_PRESERVED: 'frame.layout-preserved',
59
+ // 版本迁移
60
+ MIGRATION_KNOWN_TYPES: 'migration.known-types',
61
+ MIGRATION_REFERENCE_SOUND: 'migration.reference-sound',
62
+ MIGRATION_DECLARED_SKIP: 'migration.declared-skip',
63
+ // 外置内容
64
+ EXTERNALIZED_RESTORABLE: 'externalized.restorable',
65
+ });
66
+
67
+ // ── 通用原语 ────────────────────────────────────────────────────────────────
68
+
69
+ /** 非负安全整数。 */
70
+ export function isSafeInt(value) {
71
+ return typeof value === 'number' && Number.isSafeInteger(value) && value >= 0;
72
+ }
73
+
74
+ /** 普通记录(对象、非 null、非数组)。 */
75
+ export function isPlainRecord(value) {
76
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
77
+ }
78
+
79
+ //#region lossless-JSON 判定(拒绝稀疏数组、非有限数、-0、循环引用、非普通原型、symbol/不可枚举键)
80
+ /** 原型是否为本 realm 的普通对象原型(跨 realm 也认)。 */
81
+ function isIntrinsicObjectPrototype(prototype) {
82
+ return prototype === null || Object.getPrototypeOf(prototype) === null;
83
+ }
84
+
85
+ /** 对象是否来自普通/空原型(任意 realm)。 */
86
+ function hasPlainObjectPrototype(value) {
87
+ const prototype = Object.getPrototypeOf(value);
88
+ return prototype === null || (typeof prototype === 'object' && isIntrinsicObjectPrototype(prototype));
89
+ }
90
+
91
+ /** 数组是否为普通数组(拒绝子类/异形)。 */
92
+ function hasPlainArrayPrototype(value) {
93
+ const prototype = Object.getPrototypeOf(value);
94
+ if (prototype === Array.prototype) return true;
95
+ return typeof prototype === 'object' && prototype !== null && Object.getPrototypeOf(prototype) === Object.prototype && Object.getPrototypeOf(Object.getPrototypeOf(prototype)) === null;
96
+ }
97
+
98
+ /** 取所有 JSON 可见键;含 JSON 会丢弃的键 ⇒ 拒绝。 */
99
+ function enumerableStringKeys(value) {
100
+ const keys = Reflect.ownKeys(value);
101
+ if (keys.some((key) => typeof key !== 'string' || !Object.prototype.propertyIsEnumerable.call(value, key))) return undefined;
102
+ return keys;
103
+ }
104
+
105
+ /**
106
+ * 判断值是否可无损 JSON 序列化(迭代实现,避免深递归栈溢出)。
107
+ * @param {unknown} value
108
+ * @returns {boolean}
109
+ */
110
+ export function isJsonValue(value) {
111
+ const ancestors = new Set();
112
+ const tasks = [{ kind: 'visit', value }];
113
+ for (let task = tasks.pop(); task !== undefined; task = tasks.pop()) {
114
+ if (task.kind === 'leave') {
115
+ ancestors.delete(task.source);
116
+ continue;
117
+ }
118
+ if (task.kind === 'array-item') {
119
+ if (!Object.prototype.hasOwnProperty.call(task.source, task.index)) return false;
120
+ tasks.push({ kind: 'visit', value: task.source[task.index] });
121
+ continue;
122
+ }
123
+ if (task.kind === 'object-property') {
124
+ tasks.push({ kind: 'visit', value: task.source[task.key] });
125
+ continue;
126
+ }
127
+ const current = task.value;
128
+ if (current === null) continue;
129
+ if (typeof current === 'boolean' || typeof current === 'string') continue;
130
+ if (typeof current === 'number') {
131
+ if (!Number.isFinite(current) || Object.is(current, -0)) return false;
132
+ continue;
133
+ }
134
+ if (typeof current !== 'object') return false;
135
+ if (ancestors.has(current)) return false;
136
+ if (Array.isArray(current)) {
137
+ if (!hasPlainArrayPrototype(current)) return false;
138
+ const length = current.length;
139
+ if (Reflect.ownKeys(current).length !== length + 1) return false;
140
+ ancestors.add(current);
141
+ tasks.push({ kind: 'leave', source: current });
142
+ for (let index = length - 1; index >= 0; index--) tasks.push({ kind: 'array-item', source: current, index });
143
+ continue;
144
+ }
145
+ if (!hasPlainObjectPrototype(current)) return false;
146
+ const keys = enumerableStringKeys(current);
147
+ if (keys === undefined) return false;
148
+ ancestors.add(current);
149
+ tasks.push({ kind: 'leave', source: current });
150
+ for (let index = keys.length - 1; index >= 0; index--) {
151
+ const key = keys[index];
152
+ if (key === undefined) return false;
153
+ tasks.push({ kind: 'object-property', source: current, key });
154
+ }
155
+ }
156
+ return true;
157
+ }
158
+ //#endregion
159
+
160
+ // ── 记录 / 容器不变量 ──────────────────────────────────────────────────────
161
+
162
+ /**
163
+ * 记录头(容器的首条记录)。
164
+ *
165
+ * @param {object|null} head 首条记录的解析结果(解析失败为 null)
166
+ * @param {number} lineNo 首条记录的物理行号
167
+ * @param {{expectedFamily?: string, familyField?: string}} [opts]
168
+ * `expectedFamily`:该容器要求的记录族取值;`familyField`:声明记录族的字段名。
169
+ * @returns {Array<object>} H1 判定(记录头不可解析 / 未声明期望的记录族)
170
+ */
171
+ export function recordHeadViolations(head, lineNo, { expectedFamily, familyField = 'type' } = {}) {
172
+ if (head === null) {
173
+ return [violation('H1', { lineNo }, '首行不是合法 JSON —— 整个会话不可读')];
174
+ }
175
+ if (expectedFamily !== undefined && head?.[familyField] !== expectedFamily) {
176
+ return [violation('H1', { lineNo }, `首行 ${familyField} 必须为 "${expectedFamily}"(实际 ${String(head?.[familyField])})`)];
177
+ }
178
+ return [];
179
+ }
180
+
181
+ /**
182
+ * 物理存储行可解析性:非空行必须能解析成 JSON(解析失败且无值 = 损坏行)。
183
+ * @param {Array<{lineNo:number, value:unknown, error:Error|null}>} rows
184
+ * @returns {Array<object>} R1 判定
185
+ */
186
+ export function recordParsabilityViolations(rows) {
187
+ const out = [];
188
+ for (const row of rows ?? []) {
189
+ if (!row?.error || row.value !== null) continue;
190
+ out.push(violation('R1', { lineNo: row.lineNo }, '该行不是合法 JSON(损坏行)'));
191
+ }
192
+ return out;
193
+ }
194
+
195
+ /**
196
+ * 有头无记录 = 异常空容器(显式报出,不静默通过)。
197
+ * @param {boolean} hasHead
198
+ * @param {number} recordCount
199
+ * @param {number} lineNo
200
+ * @returns {Array<object>} Z3 判定
201
+ */
202
+ export function emptyContainerViolation(hasHead, recordCount, lineNo) {
203
+ if (!hasHead || recordCount !== 0) return [];
204
+ return [violation('Z3', { lineNo }, '会话文件无任何事件(仅 header)——异常空会话(新建即空或写入未落盘);空态不在任何有内容规则的覆盖下,显式报出供人判断')];
205
+ }
206
+
207
+ // ── 序号 / 写入者不变量 ────────────────────────────────────────────────────
208
+
209
+ /**
210
+ * 每条逻辑记录必须携带非负安全整数序号。
211
+ * @param {Array<{seq:unknown, lineNo?:number, eventType?:string}>} records 规范化记录视图
212
+ * @returns {Array<object>} E1 判定
213
+ */
214
+ export function ordinalViolations(records) {
215
+ const out = [];
216
+ for (const record of records ?? []) {
217
+ if (isSafeInt(record?.seq)) continue;
218
+ out.push(violation('E1', { seq: null, lineNo: record?.lineNo ?? null, eventType: record?.eventType ?? null }, `事件 seq 缺失或非法(${String(record?.seq)}),必须为非负安全整数`));
219
+ }
220
+ return out;
221
+ }
222
+
223
+ /**
224
+ * 单写入者假设:序号从落点起严格连续(相等步长 1)。
225
+ *
226
+ * @param {Array<{seq:unknown, lineNo?:number, eventType?:string}>} records 按逻辑顺序排列的记录
227
+ * @param {{baseSeq?: number}} [opts]
228
+ * @returns {{violations: Array<object>, broken: boolean}} E2 判定 + 是否出现缺口/倒退
229
+ */
230
+ export function sequenceContinuityViolations(records, { baseSeq = 0 } = {}) {
231
+ const violations = [];
232
+ let broken = false;
233
+ let expected = baseSeq;
234
+ for (const record of records ?? []) {
235
+ const seq = record?.seq;
236
+ if (!isSafeInt(seq)) continue; // 缺失/非法序号由序号存在性不变量负责
237
+ if (seq !== expected) {
238
+ const kind = seq < expected ? '倒退(backward)' : '缺口(gap)';
239
+ violations.push(violation('E2', { seq, lineNo: record.lineNo ?? null, eventType: record.eventType ?? null }, `seq ${seq} 不连续:${kind},期望 ${expected} —— 违反单写入者假设`));
240
+ broken = true;
241
+ }
242
+ expected = seq + 1;
243
+ }
244
+ return { violations, broken };
245
+ }
246
+
247
+ /**
248
+ * 物理顺序与逻辑序号一致:按**物理顺序**逐条比较,出现倒退即多写入者/回放交织特征。
249
+ *
250
+ * @param {Array<{seq:unknown, lineNo?:number, eventType?:string}>} entries 按物理顺序展开后的记录
251
+ * @returns {Array<object>} S9 判定(首个倒退即报,后续乱序皆源于此)
252
+ */
253
+ export function physicalOrderViolations(entries) {
254
+ const out = [];
255
+ let prevSeq = -1;
256
+ let prevLineNo = null;
257
+ for (const entry of entries ?? []) {
258
+ const seq = entry?.seq;
259
+ if (!isSafeInt(seq)) continue; // 序号非法由序号存在性不变量负责
260
+ if (seq < prevSeq) {
261
+ out.push(violation('S9', { seq, lineNo: entry.lineNo ?? null, eventType: entry.eventType ?? null },
262
+ `文件物理序 seq 倒退:${prevSeq}(line ${prevLineNo})→ ${seq}(line ${entry.lineNo ?? null})——非单调 = 多写入者/旧光标回放交织(单进程 append 不可能写出),会话加载会被拒`));
263
+ return out;
264
+ }
265
+ prevSeq = seq;
266
+ prevLineNo = entry.lineNo ?? null;
267
+ }
268
+ return out;
269
+ }
270
+
271
+ /**
272
+ * 并发诊断:序号破坏出现时给出解释性告警(不替代 E2/S9,只解释原因)。
273
+ * @param {boolean} broken 是否出现序号缺口/倒退
274
+ * @param {string} message 人读说明
275
+ * @returns {Array<object>} C1 判定
276
+ */
277
+ export function singleWriterDiagnostic(broken, message) {
278
+ if (!broken) return [];
279
+ return [violation('C1', { lineNo: null }, message)];
280
+ }
281
+
282
+ // ── 负载不变量 ─────────────────────────────────────────────────────────────
283
+
284
+ /**
285
+ * 记录负载必须可无损 JSON 序列化。
286
+ *
287
+ * @param {object} record 规范化记录(原始记录对象)
288
+ * @param {{lineNo?:number, seq?:number, eventType?:string}} loc 定位
289
+ * @param {{required?: string[], optional?: string[]}} [fields]
290
+ * `required`:无论是否存在都必须判定的负载字段;`optional`:存在时才判定。
291
+ * @returns {Array<object>} E4 判定
292
+ */
293
+ export function payloadLosslessViolations(record, loc, { required = [], optional = [] } = {}) {
294
+ const out = [];
295
+ for (const field of required) {
296
+ if (isJsonValue(record?.[field])) continue;
297
+ out.push(violation('E4', loc, `${field} 不是 lossless-JSON(函数/循环引用/非有限数等),写入热路径会拒绝`));
298
+ }
299
+ for (const field of optional) {
300
+ if (record?.[field] === undefined || isJsonValue(record[field])) continue;
301
+ out.push(violation('E4', loc, `${field} 不是 lossless-JSON`));
302
+ }
303
+ return out;
304
+ }
305
+
306
+ // ── 外置内容不变量(在位可还原)─────────────────────────────────────────────
307
+
308
+ /** 读明文行索引(无平台帧格式时的兜底读法)。 */
309
+ function readPlainLineIndex(file, wantedLines = new Set()) {
310
+ const text = fs.readFileSync(file, 'utf8');
311
+ const lines = text.split('\n');
312
+ if (lines.length > 0 && lines[lines.length - 1] === '') lines.pop();
313
+ return { count: lines.length, lineAt: (n) => lines[n - 1] ?? '' };
314
+ }
315
+
316
+ /** 把声明目标解析为文件路径:绝对路径优先;相对/basename 走归档根。 */
317
+ function findExternalizedFile(pointer, { archiveRoots = [], index } = {}) {
318
+ const stated = typeof pointer.ref === 'string' && path.isAbsolute(pointer.ref) ? pointer.ref : null;
319
+ if (stated && fs.existsSync(stated)) return { target: stated, statedPath: stated, relocated: false };
320
+ const base = typeof pointer.ref === 'string' ? path.basename(pointer.ref) : '';
321
+ if (!base) return { target: null, statedPath: stated, relocated: false };
322
+ let found = index?.get(base) ?? null;
323
+ if (!found) {
324
+ for (const root of archiveRoots) {
325
+ const hit = searchByBasename(root, base, 0, index);
326
+ if (hit) { found = hit; break; }
327
+ }
328
+ }
329
+ if (found) return { target: found, statedPath: stated, relocated: stated !== null && stated !== found };
330
+ return { target: null, statedPath: stated, relocated: false };
331
+ }
332
+
333
+ /** 在根目录下按 basename 找文件(深度 ≤3;找到即缓存)。 */
334
+ function searchByBasename(dir, base, depth, index) {
335
+ if (depth > 3 || !fs.existsSync(dir)) return null;
336
+ let entries;
337
+ try {
338
+ entries = fs.readdirSync(dir);
339
+ } catch {
340
+ return null;
341
+ }
342
+ for (const name of entries) {
343
+ const full = path.join(dir, name);
344
+ let st;
345
+ try {
346
+ st = fs.statSync(full);
347
+ } catch {
348
+ continue;
349
+ }
350
+ if (st.isDirectory()) {
351
+ const hit = searchByBasename(full, base, depth + 1, index);
352
+ if (hit) { index?.set(base, hit); return hit; }
353
+ } else if (name === base) {
354
+ index?.set(base, full);
355
+ return full;
356
+ }
357
+ }
358
+ return null;
359
+ }
360
+
361
+ /** sha256(十六进制)。 */
362
+ function sha256Hex(text) {
363
+ return crypto.createHash('sha256').update(text).digest('hex');
364
+ }
365
+
366
+ /** 指纹匹配:允许 16 位前缀(深校验以较长指纹为准;过短/缺失不猜)。 */
367
+ function shaMatches(line, want) {
368
+ if (typeof want !== 'string' || want.length < 16) return true;
369
+ const got = sha256Hex(line);
370
+ const w = want.toLowerCase();
371
+ if (w.length >= 64) return got === w.slice(0, 64);
372
+ return got.startsWith(w) || w.startsWith(got.slice(0, w.length));
373
+ }
374
+
375
+ /**
376
+ * 校验收到的外置内容指针能否在位还原。
377
+ *
378
+ * 判据:目标文件存在 + 指针行存在 + 指纹(若有)匹配 = 在位可还原;
379
+ * 目标缺失/行缺失/指纹不符 = error;绝对路径失效但同名文件在归档根可解析 = relocated warning。
380
+ * 同一(目标, 行)被多个指针引用时按一条记录计(去重)。
381
+ *
382
+ * @param {Array<{seq:number|null, lineNo:number|null, type:string|null, field:string, ref:string, archiveLine:number|null, sha256:string|null}>} pointers
383
+ * @param {{archiveRoots?: string[], readLines?: (file:string, wanted:Set<number>) => ({count:number, lineAt:(n:number)=>string}|string[])}} [opts]
384
+ * @returns {object} 结论(restorable/unrestorable/unverifiable + 逐项读数与判定)
385
+ */
386
+ export function verifyExternalizedPointers(pointers, { archiveRoots = [], readLines } = {}) {
387
+ const roots = Array.isArray(archiveRoots) ? archiveRoots.filter((r) => typeof r === 'string' && r !== '') : [];
388
+ const assessable = roots.length > 0;
389
+ const result = {
390
+ assessable,
391
+ pointers: pointers.length,
392
+ effectivePointers: 0,
393
+ restorable: 0,
394
+ relocated: 0,
395
+ missing: 0,
396
+ unresolved: 0,
397
+ lineMissing: 0,
398
+ shaMismatch: 0,
399
+ duplicated: 0,
400
+ restoredBytes: 0,
401
+ restorableRate: 0,
402
+ verdict: assessable ? 'restorable' : 'unverifiable',
403
+ violations: [],
404
+ details: { missing: [], relocated: [], unresolved: [], lineMissing: [], shaMismatch: [] },
405
+ };
406
+ if (!assessable) return result; // 不可判定:不冒充通过、也不产生判定
407
+ // ① 解析目标 + 按 (target, line) 去重
408
+ const index = new Map();
409
+ const unique = [];
410
+ const seen = new Set();
411
+ for (const pointer of pointers) {
412
+ const { target, relocated } = findExternalizedFile(pointer, { archiveRoots: roots, index });
413
+ if (!target) {
414
+ result.unresolved++;
415
+ if (result.details.unresolved.length < 20) result.details.unresolved.push({ seq: pointer.seq, field: pointer.field, ref: pointer.ref });
416
+ continue;
417
+ }
418
+ const dedupeKey = `${target}\u0000${pointer.archiveLine ?? ''}`;
419
+ if (seen.has(dedupeKey)) { result.duplicated++; continue; }
420
+ seen.add(dedupeKey);
421
+ unique.push({ pointer, target, relocated });
422
+ }
423
+ result.effectivePointers = unique.length;
424
+ // ② 按目标分组,一次扫描取回需要的行(巨型归档不能整体字符串化)
425
+ const byTarget = new Map();
426
+ for (const item of unique) {
427
+ if (!byTarget.has(item.target)) byTarget.set(item.target, []);
428
+ byTarget.get(item.target).push(item);
429
+ }
430
+ for (const [target, items] of byTarget) {
431
+ const wanted = new Set(items.map(({ pointer }) => pointer.archiveLine).filter((n) => Number.isSafeInteger(n) && n >= 1));
432
+ let lineIndex;
433
+ try {
434
+ lineIndex = (readLines ?? readPlainLineIndex)(target, wanted);
435
+ if (Array.isArray(lineIndex)) lineIndex = { count: lineIndex.length, lineAt: (n) => lineIndex[n - 1] ?? '' };
436
+ } catch (err) {
437
+ const message = String(err?.message ?? err).slice(0, 120);
438
+ for (const { pointer } of items) {
439
+ result.missing++;
440
+ if (result.details.missing.length < 20) result.details.missing.push({ seq: pointer.seq, field: pointer.field, ref: pointer.ref, target, reason: message });
441
+ result.violations.push(violation('A1', { seq: pointer.seq, lineNo: pointer.lineNo, eventType: pointer.type }, `归档不可读:${pointer.field} → ${pointer.ref}(解析到 ${target})——在位可还原判定失败(${message})`));
442
+ }
443
+ continue;
444
+ }
445
+ for (const { pointer, relocated } of items) {
446
+ const loc = { seq: pointer.seq, lineNo: pointer.lineNo, eventType: pointer.type };
447
+ const lineNo = pointer.archiveLine;
448
+ if (!Number.isSafeInteger(lineNo) || lineNo < 1 || lineNo > lineIndex.count) {
449
+ result.lineMissing++;
450
+ if (result.details.lineMissing.length < 20) result.details.lineMissing.push({ seq: pointer.seq, field: pointer.field, ref: pointer.ref, target, archiveLine: lineNo, lines: lineIndex.count });
451
+ result.violations.push(violation('A1', loc, `归档行缺失:${pointer.field} → ${pointer.ref} 指向第 ${String(lineNo)} 行,但归档只有 ${lineIndex.count} 行——内容不可在位还原(模板/示例文本不参与本判据)`));
452
+ continue;
453
+ }
454
+ const line = lineIndex.lineAt(lineNo);
455
+ if (!shaMatches(line, pointer.sha256)) {
456
+ result.shaMismatch++;
457
+ 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) });
458
+ result.violations.push(violation('A1', loc, `归档内容指纹不符:${pointer.field} → ${pointer.ref} 第 ${lineNo} 行 sha256 期望 ${pointer.sha256?.slice(0, 16)}…,实际 ${sha256Hex(line).slice(0, 16)}…——归档已漂移,不可在位还原`));
459
+ continue;
460
+ }
461
+ if (relocated) {
462
+ result.relocated++;
463
+ const v = violation('A1', loc, `归档指针的绝对路径已失效(${pointer.ref}),但同名归档在归档根可解析(${target})——内容可找回,但**不在位**(re-home 未回写);按 relocated 记 warning`);
464
+ v.severity = 'warning';
465
+ result.violations.push(v);
466
+ if (result.details.relocated.length < 20) result.details.relocated.push({ seq: pointer.seq, field: pointer.field, ref: pointer.ref, target });
467
+ } else {
468
+ result.restorable++;
469
+ result.restoredBytes += Buffer.byteLength(line, 'utf8');
470
+ }
471
+ }
472
+ }
473
+ result.restorableRate = result.effectivePointers > 0 ? result.restorable / result.effectivePointers : 1;
474
+ result.verdict = result.missing === 0 && result.lineMissing === 0 && result.shaMismatch === 0 && result.unresolved === 0
475
+ ? 'restorable'
476
+ : 'unrestorable';
477
+ return result;
478
+ }
@@ -0,0 +1,77 @@
1
+ /**
2
+ * contract/registry.js
3
+ *
4
+ * 规则注册表:层枚举 + 注册与读取接口。
5
+ *
6
+ * 平台无关:本文件只定义「规则如何登记、如何按 id 读取」,
7
+ * **不持有任何具体规则内容**——规则描述符由适配器在加载时登记(adapters → contract 单向)。
8
+ *
9
+ * 登记是幂等的纯数据操作:按 `id` 建索引并冻结目录;重复 id、非数组、
10
+ * 或调用方提供的描述符校验失败时**立即抛错**(fail-loud,不静默跳过)。
11
+ */
12
+
13
+ /**
14
+ * 规则所属层(契约维度)枚举。层名描述「这条规则守的是哪一类性质」,
15
+ * 与具体平台无关:一个平台适配器可以只填其中若干层。
16
+ */
17
+ export const LAYER = Object.freeze({
18
+ PERSISTENCE: 'persistence', // 持久化层:记录能被解码器完整重放
19
+ ENGINE: 'engine', // 引擎层:记录形状匹配客户端状态机
20
+ PLUGIN: 'plugin', // 插件语义层:命名/标记的隐藏语义
21
+ CONCURRENCY: 'concurrency', // 并发 / 写入者假设
22
+ FRAMING: 'framing', // 容器帧结构
23
+ MIGRATION: 'migration', // 迁移预检层(独立维度:升级路径会不会拒)
24
+ ARCHIVE: 'archive', // 归档层(独立维度:外置内容能否在位还原)
25
+ });
26
+
27
+ /** 已登记的规则目录(按登记顺序冻结)。 */
28
+ let catalog = Object.freeze([]);
29
+ /** id → 规则描述符。 */
30
+ const index = new Map();
31
+
32
+ /**
33
+ * 登记规则目录。
34
+ *
35
+ * @param {ReadonlyArray<object>} rules 规则描述符列表(按展示顺序)
36
+ * @param {{ validate?: (rule: unknown) => boolean }} [opts]
37
+ * `validate`:调用方提供的描述符形状校验;返回 false 即拒绝整批登记。
38
+ * @returns {ReadonlyArray<object>} 冻结后的目录
39
+ */
40
+ export function installRuleCatalog(rules, { validate } = {}) {
41
+ if (!Array.isArray(rules)) {
42
+ throw new TypeError('规则目录必须为数组');
43
+ }
44
+ if (typeof validate === 'function') {
45
+ for (const rule of rules) {
46
+ if (validate(rule)) continue;
47
+ const id = rule !== null && typeof rule === 'object' && 'id' in rule ? String(rule.id) : '<unknown>';
48
+ throw new TypeError(`规则描述符非法:${id}`);
49
+ }
50
+ }
51
+ const next = new Map();
52
+ for (const rule of rules) {
53
+ const id = rule?.id;
54
+ if (typeof id !== 'string' || id === '') throw new TypeError('规则描述符缺少非空 id');
55
+ if (next.has(id)) throw new TypeError(`规则 id 重复:${id}`);
56
+ next.set(id, rule);
57
+ }
58
+ catalog = Object.freeze([...rules]);
59
+ index.clear();
60
+ for (const [id, rule] of next) index.set(id, rule);
61
+ return catalog;
62
+ }
63
+
64
+ /** 当前已登记的规则目录(冻结副本,顺序 = 登记顺序)。 */
65
+ export function contractRules() {
66
+ return catalog;
67
+ }
68
+
69
+ /** 按 id 取规则;未登记 ⇒ undefined。 */
70
+ export function ruleById(id) {
71
+ return index.get(id);
72
+ }
73
+
74
+ /** 按目录顺序渲染规则索引行(`| id | severity | layer | title |`)。 */
75
+ export function ruleTableRows() {
76
+ return catalog.map((r) => `| ${r.id} | ${r.severity} | ${r.layer} | ${r.title} |`).join('\n');
77
+ }