dsh-log-contract 0.3.21 → 0.3.23

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 CHANGED
@@ -1,309 +1,19 @@
1
1
  /**
2
2
  * dsh-log-contract · lib/archive.js
3
3
  *
4
- * A1 —— 「在位可还原」只认结构化归档指针(0.3.19 · v4 契约补充最小集 ⑤)。
4
+ * 外置内容(归档)判定公开面(实现层):
5
+ * - 判定核心(在位可还原)→ contract/invariants.js
6
+ * - DSH 结构化指针提取与归档读取 → adapters/dsh/archive.js
5
7
  *
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]
8
+ * 导出名与既有版本保持一致(公开面不变)。
305
9
  */
306
- export function archiveVerdict(events, { archiveRoots = [], readLines } = {}) {
307
- const pointers = collectArchivePointers(events);
308
- return verifyArchivePointers(pointers, { archiveRoots, readLines });
309
- }
10
+ export {
11
+ ARCHIVE_POINTER_FIELDS,
12
+ EXTERNALIZED_POINTER_FIELDS,
13
+ collectArchivePointers,
14
+ archiveBasename,
15
+ readArchiveIndex,
16
+ readArchiveLines,
17
+ verifyArchivePointers,
18
+ archiveVerdict,
19
+ } from '../adapters/dsh/archive.js';