dsh-log-contract 0.3.18 → 0.3.19

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.
@@ -13,6 +13,7 @@
13
13
  * contracts 列出内置契约规则目录
14
14
  */
15
15
  import fs from 'node:fs';
16
+ import { delimiter as pathDelimiter } from 'node:path';
16
17
  import { loadSessionLog, validateSessionLog, resumeVerdict, migrationVerdict, assessmentScope, createPreWriter, repairSession, readSessionHeader, CONTRACT_RULES, ruleById, extractToolOutputs, auditToolCalls, hostCapability, HOST_MAX_FILE_VERSION, detectSupport } from '../lib/index.js';
17
18
 
18
19
  /**
@@ -39,8 +40,8 @@ const errOut = (text) => writeAllSync(2, text);
39
40
  const USAGE = `dsh-log-contract —— 日志契约守护(DSH session log contract guard)
40
41
 
41
42
  用法:
42
- dsh-log-contract check <session-log> [--json] [--max-details N] [--resume] [--fail-on-migration] [--no-fail-on-migration]
43
- 离线体检 + **迁移预检**(两个**独立维度**,互不蕴含)。session-log 支持 .jsonl 与 .jsonl.zstd。
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
+ 离线体检 + **迁移预检** + **在位可还原(A1,独立维度)**。session-log 支持 .jsonl 与 .jsonl.zstd。
44
45
  ⚠️ 口径边界:本工具只判定它实现的规则集。「ok」/「可加载」/「可继续」/「可压缩」
45
46
  **不代表**会话"可用",**不代表**可安全编辑,也**不代表**官方升级路径会接受
46
47
  (迁移是独立维度,覆盖边界见 contracts 输出与 lib/contracts.js 的 G 段)。
@@ -59,6 +60,13 @@ const USAGE = `dsh-log-contract —— 日志契约守护(DSH session log cont
59
60
  'partial' = **需要迁移**(version<3):迁移维度只覆盖 2 条规则,另有 6 类未覆盖 ⇒
60
61
  **不构成"官方升级会接受"**;'none' = 本宿主能力不足以评估(文件版本 > 宿主上限)。
61
62
  机器应判 assessmentScope == "full" 才可把绿读作完整评估(partial/none 都不该)。
63
+ --archive-root DIR A1「在位可还原」的归档根目录(可重复;也可用 env
64
+ DSH_LOG_CONTRACT_ARCHIVE_ROOTS,按路径分隔符分隔)。**不提供 = 该维度
65
+ 不可判定(unverifiable),不冒充通过**。只认结构化指针
66
+ (archiveRef/archive/externalized.*),⛔ 不从自由文本 grep 路径。
67
+ --ignorable-whitelist a,b
68
+ G4 可忽略消费者白名单(精确 type 或以 / 结尾的前缀;也可用 env
69
+ DSH_LOG_CONTRACT_IGNORABLE_WHITELIST)。已登记 ⇒ acceptedDrop 不阻断迁移。
62
70
  退出码:0 本工具认为可加载且无迁移阻断;1 有 error 级违规;3 不可在本宿主评估
63
71
  (被检文件版本 > 宿主支持上限,如 rc.7 宿主的 v3 文件——**不是** broken);
64
72
  4 迁移预检 blocked(assessmentScope=partial 且 migration.ready=false;可用
@@ -202,6 +210,16 @@ function migrationLine(mig, partial = false) {
202
210
  s += ` [${v.id}] seq ${v.seq ?? '-'}${v.eventType ? ` (${v.eventType})` : ''} — ${String(v.message).slice(0, 130)}\n`;
203
211
  }
204
212
  if (n > 5) s += ` …另有 ${n - 5} 项\n`;
213
+ const drops = mig.acceptedDrops ?? { registered: [], unregistered: [] };
214
+ if (drops.registered.length > 0) {
215
+ s += ` 声明式可忽略(G4 · 已登记 acceptedDrop,不阻断迁移):${drops.registered.length} 项`;
216
+ const types = [...new Set(drops.registered.map((d) => d.eventType).filter(Boolean))];
217
+ if (types.length > 0) s += `(${types.slice(0, 5).join('、')}${types.length > 5 ? ' 等' : ''})`;
218
+ s += '\n';
219
+ }
220
+ if (drops.unregistered.length > 0) {
221
+ s += ` ⛔ 声明可忽略但**未登记**(G4 warning,仍阻断迁移):${drops.unregistered.length} 项——登记到 opts.ignorableWhitelist / DSH_LOG_CONTRACT_IGNORABLE_WHITELIST 后才移出阻断\n`;
222
+ }
205
223
  s += ` 覆盖边界:已覆盖 ${mig.coverage.implemented.length} 条;未覆盖 ${mig.coverage.uncovered.length} 类官方迁移规则(未覆盖 ≠ 通过;判据 ${mig.coverage.note})\n`;
206
224
  // 规格 (iii):把未覆盖类名直接列出来,人不必开 --json 才知道边界。
207
225
  if (partial) {
@@ -210,6 +228,23 @@ function migrationLine(mig, partial = false) {
210
228
  return s;
211
229
  }
212
230
 
231
+ /**
232
+ * A1「在位可还原」独立维度(0.3.19 · 最小集 ⑤)。
233
+ * 未提供归档根 ⇒ `unverifiable`(不冒充通过);提供后才给读数与违规。
234
+ */
235
+ function archiveLines(archive) {
236
+ if (!archive) return '';
237
+ if (archive.verdict === 'unverifiable') {
238
+ return ' 在位可还原(A1,独立维度):— 未提供归档根目录(不可判定;加 `--archive-root DIR` 或 env DSH_LOG_CONTRACT_ARCHIVE_ROOTS 才评估)\n';
239
+ }
240
+ const rate = (archive.restorableRate * 100).toFixed(2);
241
+ let s = ` 在位可还原(A1,独立维度,只认结构指针):${archive.verdict === 'restorable' ? '✅' : '❌'} ${rate}%`
242
+ + `(指针 ${archive.pointers},去重后 ${archive.effectivePointers ?? archive.pointers}:可还原 ${archive.restorable}`
243
+ + ` / relocated ${archive.relocated} / 缺失 ${archive.missing} / 行缺失 ${archive.lineMissing} / sha 不符 ${archive.shaMismatch} / 无法解析 ${archive.unresolved})\n`;
244
+ if (archive.relocated > 0) s += ' ⚠️ relocated:绝对路径已失效但同名归档在归档根可解析(内容可找回,但不在位;re-home 未回写)\n';
245
+ return s;
246
+ }
247
+
213
248
  function cmdCheck(args) {
214
249
  const json = args.includes('--json');
215
250
  const resume = args.includes('--resume');
@@ -220,7 +255,32 @@ function cmdCheck(args) {
220
255
  const noFailOnMigration = args.includes('--no-fail-on-migration');
221
256
  const maxDetailsIdx = args.indexOf('--max-details');
222
257
  const maxDetails = maxDetailsIdx >= 0 && args[maxDetailsIdx + 1] ? Number(args[maxDetailsIdx + 1]) : 8;
223
- const file = args.find((a) => !a.startsWith('-'));
258
+ // 0.3.19:G4 白名单 / A1 归档根(可重复 `--archive-root DIR`,或 env 用 path.delimiter 分隔)。
259
+ const flagValues = (flag) => {
260
+ const vals = [];
261
+ for (let i = 0; i < args.length; i++) if (args[i] === flag && args[i + 1] !== undefined && !args[i + 1].startsWith('-')) vals.push(args[i + 1]);
262
+ return vals;
263
+ };
264
+ const archiveRoots = [
265
+ ...flagValues('--archive-root'),
266
+ ...(process.env.DSH_LOG_CONTRACT_ARCHIVE_ROOTS ? process.env.DSH_LOG_CONTRACT_ARCHIVE_ROOTS.split(pathDelimiter).filter(Boolean) : []),
267
+ ];
268
+ const whitelistRaw = [
269
+ ...flagValues('--ignorable-whitelist'),
270
+ ...(process.env.DSH_LOG_CONTRACT_IGNORABLE_WHITELIST ? [process.env.DSH_LOG_CONTRACT_IGNORABLE_WHITELIST] : []),
271
+ ];
272
+ const ignorableWhitelist = whitelistRaw.length > 0
273
+ ? whitelistRaw.flatMap((v) => String(v).split(',')).map((s) => s.trim()).filter(Boolean)
274
+ : undefined;
275
+ // 取位置参数时排除所有带值开关的值(否则 `--archive-root /x` 的 /x 会被当成被检文件)。
276
+ const valuedFlags = new Set(['--max-details', '--archive-root', '--ignorable-whitelist']);
277
+ const positional = [];
278
+ for (let i = 0; i < args.length; i++) {
279
+ const a = args[i];
280
+ if (a.startsWith('-')) { if (valuedFlags.has(a)) i++; continue; }
281
+ positional.push(a);
282
+ }
283
+ const file = positional[0];
224
284
  if (!file) fail(USAGE);
225
285
 
226
286
  let log;
@@ -229,7 +289,7 @@ function cmdCheck(args) {
229
289
  } catch (err) {
230
290
  fail(`读取失败:${err.message}`);
231
291
  }
232
- const result = validateSessionLog(log);
292
+ const result = validateSessionLog(log, { archiveRoots, ignorableWhitelist });
233
293
  const { summary, violations, ok } = result;
234
294
  const notAssessable = result.assessable === false;
235
295
  const migration = result.migration ?? migrationVerdict(result);
@@ -244,7 +304,7 @@ function cmdCheck(args) {
244
304
  const exitCode = notAssessable ? 3 : (!ok ? 1 : (migGate ? 4 : 0));
245
305
 
246
306
  if (json) {
247
- const payload = { file, ok, assessable: !notAssessable, assessmentScope: scope, host: hostCapability(), support: result.support ?? null, probes: result.probes ?? null, drift: result.drift ?? null, migration, summary, violations };
307
+ const payload = { file, ok, assessable: !notAssessable, assessmentScope: scope, host: hostCapability(), support: result.support ?? null, probes: result.probes ?? null, drift: result.drift ?? null, migration, summary, violations, archive: result.archive ?? null, ignorableDrops: result.ignorableDrops ?? null };
248
308
  if (notAssessable) payload.notAssessable = result.notAssessable;
249
309
  if (resume) payload.resume = resumeVerdict(result);
250
310
  out(JSON.stringify(payload, null, 2) + '\n');
@@ -280,6 +340,7 @@ function cmdCheck(args) {
280
340
  out(supportLines(result.support));
281
341
  out(driftLines(result.drift, result.probes));
282
342
  out(migrationLine(migration, partial));
343
+ out(archiveLines(result.archive));
283
344
  out(`\n 结论: ${icons[tier]}${migBlocked
284
345
  ? '(本工具规则集内)—— 但**迁移预检 blocked**:不得据此宣称"可升级"'
285
346
  : partial
@@ -295,6 +356,7 @@ function cmdCheck(args) {
295
356
  out(supportLines(result.support));
296
357
  out(driftLines(result.drift, result.probes));
297
358
  out(migrationLine(migration, partial));
359
+ out(archiveLines(result.archive));
298
360
  out('\n');
299
361
  printViolations(violations, maxDetails);
300
362
  out(`\n${ok
@@ -327,7 +389,10 @@ function cmdPrewrite(args) {
327
389
  } catch (err) {
328
390
  fail(`会话日志读取失败:${err.message}`);
329
391
  }
330
- const baseline = validateSessionLog(log);
392
+ const prewriteWhitelist = process.env.DSH_LOG_CONTRACT_IGNORABLE_WHITELIST
393
+ ? process.env.DSH_LOG_CONTRACT_IGNORABLE_WHITELIST.split(',').map((x) => x.trim()).filter(Boolean)
394
+ : undefined;
395
+ const baseline = validateSessionLog(log, { ignorableWhitelist: prewriteWhitelist });
331
396
  // 版本支持面(2026-09-14 用户要求第 1 条):**未验证格式 ⇒ 只读**,不得给出写入结论。
332
397
  if (baseline.support?.readOnly) {
333
398
  fail(`未验证的会话格式(来源 ${baseline.support.file.source},版本 v${baseline.support.file.version})——按只读处理,写前校验无法给出可信结论。`
@@ -343,7 +408,7 @@ function cmdPrewrite(args) {
343
408
  }
344
409
 
345
410
  // C2:把被检文件的 header 显式交给 prewriter(版本不再靠模块级全局;缺省也能自行推断)
346
- const prewriter = createPreWriter({ events: log.events.map((e) => e.event), header: log.header });
411
+ const prewriter = createPreWriter({ events: log.events.map((e) => e.event), header: log.header, ignorableWhitelist: prewriteWhitelist });
347
412
  let result;
348
413
  if (Object.hasOwn(plan, 'append')) {
349
414
  result = prewriter.validateAppend(plan.append);
package/docs/CONTRACTS.md CHANGED
@@ -22,7 +22,7 @@
22
22
  >
23
23
  > 严重度:**error** = 违反即会话不可加载/写入被拒(fail-loud);**warning** = 合法但可疑。
24
24
 
25
- ## 规则索引(共 46 条)
25
+ ## 规则索引(共 51 条)
26
26
 
27
27
  | id | 严重度 | 层级 | 规则 |
28
28
  |---|---|---|---|
@@ -34,7 +34,9 @@
34
34
  | E1 | error | persistence | 每个事件携带非负安全整数 seq |
35
35
  | E2 | error | persistence | seq 严格连续(单写入者假设) |
36
36
  | S9 | error | persistence | 文件物理序 seq 单调(多写入者交织现场特征) |
37
+ | S10 | error | persistence | sourceEventSeqs 元素必须是(解码后的)非负整数;存储形态只允许官方区间对 |
37
38
  | I1 | error | engine | inbox seed 相对重放(fork 边界孤儿 spliced) |
39
+ | I2 | error | persistence | seedLength = 继承事件条数(不是字节数);parentSession ∧ seedLength∈{缺失,0} 合法 |
38
40
  | E3 | error | persistence | type 必须在已知词汇表内(或带 ignorable 标记) |
39
41
  | E4 | error | persistence | data 与 surface 元数据必须 JSON 无损 |
40
42
  | E5 | error | persistence | 禁用遗留词汇 |
@@ -62,6 +64,7 @@
62
64
  | M1 | error | engine | turn/step 为 null 的 assistant/message 只能 replace,不能 append |
63
65
  | P1 | warning | plugin | marker id 前缀必须被识别 |
64
66
  | P2 | error | plugin | marker 自身 seq 不得出现在自身 shadowed 集 |
67
+ | P5 | error | plugin | carrier 两段配对:第 2 段 sourceEventSeqs 首元素 = 第 1 段(审计段)seq |
65
68
  | C1 | warning | concurrency | seq 缺口/倒退提示多写入者 |
66
69
  | Z1 | warning | framing | zstd 尾帧撕裂 |
67
70
  | Z2 | error | framing | zstd 帧解码失败 = 单帧全损 |
@@ -72,6 +75,8 @@
72
75
  | G1 | warning | migration | 迁移预检:v0 源文件的 subagent/descriptor.data.version 必须为 3 |
73
76
  | G2 | warning | migration | 迁移预检:v0 源文件不得含词表外的历史事件类型(含 ignorable) |
74
77
  | G3 | warning | migration | 迁移预检:v0 源 session/title 系列的 messageSeqs 必须引用更早的人类 user/message |
78
+ | G4 | warning | migration | 未知历史事件声明式可忽略(ignorable:true + 白名单)——迁移不得硬拒 |
79
+ | A1 | error | archive | 在位可还原只认结构化归档指针(archiveRef / archive / externalized.*) |
75
80
 
76
81
  ## 详细规则
77
82
 
@@ -123,12 +128,24 @@
123
128
  - **出处**: 2026-08-28 实锤(某真实会话):文件物理序出现回退(大→小→更大);单进程 appendCore 断言 seq==cursor+i 且按 id 串行化不可能写出
124
129
  - **契约**: 按文件物理行序要求展开后事件 seq 严格单调递增。E2 在排序后检查(loadSessionLog 会 sort),物理序倒退被掩盖;S9 在排序前按行序检查,非单调 = 多写入者/旧光标回放交织的直接现场证据,加载会被拒。
125
130
 
131
+ ### S10 — sourceEventSeqs 元素必须是(解码后的)非负整数;存储形态只允许官方区间对
132
+
133
+ - **层级**: persistence | **严重度**: error
134
+ - **出处**: @deepseek-ai/dsh-session@0.2.0-rc.2 lib/index.js:963-999(encodeSeqRanges:连续 ≥3 才压缩成 `[start,end]`,即 v3+ JSONL 的存储形态)、:1000-1026(decodeSeqRanges/assertSeq:元素必须是非负安全整数,区间对只允许 `[start,end]` 且 start ≤ end、解码后严格递增)
135
+ - **契约**: 所有事件的 `sourceEventSeqs`(**含非 surface 类型与 ignorable 未知插件事件**)原始存储形态只允许两种元素:非负安全整数、或官方区间对 `[start,end]`;经官方 `decodeSeqRanges` 解码后必须全部是非负安全整数。解码后仍为数组/非整数 = 契约违规(投影层/restore/重写路径会把它静默当成 seq,实测 v4test 即如此)⇒ 判红并给出该事件的 seq/行号。注意:`[a,b]` 本身是 v3+ 的**合法存储形态**(本机 760 份真实会话里 265 处,全部可解码),不得误报;判红点是「解码后仍非整数」与「非官方区间对形态」。
136
+
126
137
  ### I1 — inbox seed 相对重放(fork 边界孤儿 spliced)
127
138
 
128
139
  - **层级**: engine | **严重度**: error
129
140
  - **出处**: @deepseek-ai/dsh-agent lib/types/inbox.js:155-178 (apply/validate);2026-08-28 实锤(某两个真实会话):fork 边界 removedCount=1 孤儿
130
141
  - **契约**: 从 header.seedLength 起重放 agent/inbox/spliced,next-turn/next-step 双队列;start+removedCount 不得超过队列长、不得产生重复 pending id。fork 时"移除父待处理提示词"的 splice 假设父会话 inbox,子会话 seed 相对空 inbox 上非法 → resume 被拒(invalid persisted inbox splice)。
131
142
 
143
+ ### I2 — seedLength = 继承事件条数(不是字节数);parentSession ∧ seedLength∈{缺失,0} 合法
144
+
145
+ - **层级**: persistence | **严重度**: error
146
+ - **出处**: @deepseek-ai/dsh-session-format-v0-to-v1@0.2.0-rc.2 package/lib/index.js:1707(`seedLength` → `inheritedEventCount`,缺省 0)、:1720(`isSeeded = seedLength !== undefined`)、:1517-1520("Session inheritedEventCount exceeds its event count" / "unseeded Session inheritedEventCount must be 0");v4 运行时头禁该字段:dsh-session@0.2.0-rc.2 lib/index.js:1040("session header has invalid field \"seedLength\"")
147
+ - **契约**: `header.seedLength` 的语义被钉死为**继承事件条数**(官方 `inheritedEventCount`),不是字节数、不是行数。判据:① 若存在必须是非负安全整数;② `seedLength > 展开后事件数` ⇒ error(官方解码/迁移直接抛 "inheritedEventCount exceeds its event count");③ 文件版本 ≥4 时该字段必须不存在(v4 运行时 header 校验拒)。**`parentSession` 有值 ∧ `seedLength` 缺失或 0 ⇒ 合法**:`parentSession` 只记血缘,是否 seeded 由 `seedLength` 字段是否存在决定(`isSeeded = seedLength !== undefined`;只有 unseeded 才要求 inheritedEventCount === 0)——实测本机 712/760 份真实 v3/v4 头带 `parentSession` 且无 `seedLength`(`isSeeded:false`)仍正常加载,不能判违规。真实读数(本机 29 份 v0 化石):19 份带 `seedLength`(15 万/53 万/68 万/28 万/67 万量级),**全部 ≤ 展开后事件数**(约 69 万/59 万/72 万/39 万/317 万条),而同一文件的明文体积是 20.3–105.4 MB ⇒ `seedLength` 既不可能是字节数(差 1–2 个数量级),也不可能是行数(行数仅 1.3–7 万)⇒ 真实数据与"继承事件条数"一致,本机命中 0 例 `> 展开事件数`(判红分支是防"当字节数用"的护栏)。
148
+
132
149
  ### E3 — type 必须在已知词汇表内(或带 ignorable 标记)
133
150
 
134
151
  - **层级**: persistence | **严重度**: error
@@ -291,6 +308,12 @@
291
308
  - **出处**: retrace 插件 lib/client.js:393("event and never a surface node")
292
309
  - **契约**: marker 的 sourceEventSeqs(= shadowedSeqs,驱动 CSS 隐藏)不得包含 marker 自身 seq——marker 节点由隐藏逻辑跳过,出现在 shadowed 集属于自指语义错误。
293
310
 
311
+ ### P5 — carrier 两段配对:第 2 段 sourceEventSeqs 首元素 = 第 1 段(审计段)seq
312
+
313
+ - **层级**: plugin | **严重度**: error
314
+ - **出处**: 仓库既有两段载体形状(test/semantics-v4.test.js:108-121:`compaction/prune` 审计段 + `user/message` replace 载体);2026-10-20 本机实测 760 份真实 v3/v4:884 个载体按现役写法(审计段 seq 在 `sourceEventSeqs[0]`,全部 user/message);另有 1,519 个载体按**早期写法**(首元素 = 区间起点、不引用审计段 seq;user/message 1,022 + tool/result 497)⇒ 读侧必须两种都认;对照官方 compaction 的 `compaction/summary` 引用是另一形状(`[compaction/start, compaction/summary, …]`,15 例),不属本条
315
+ - **契约**: 两段载体(第 1 段 = `compaction/prune` 审计段,带 `data.shadowedRange`/`shadowedSeqs`;第 2 段 = 紧随其后的 surface replace 载体)的配对规则:第 2 段 `sourceEventSeqs[0]` 必须等于第 1 段的 seq(现役写法),其余元素覆盖被遮蔽节点。**读侧容错(两种写法都认)**:① 现役 `[审计段 seq, ...被遮蔽节点]`;② 早期 `[区间起点, ...被遮蔽节点]`(不引用审计段 seq——实测真实语料 1,519 个载体即此写法,若判红会全成"孤儿")。只有"审计段 seq 在中间位且首元素既非审计段也非区间起点"、或"紧邻审计段却既不引用它、首元素也不是区间起点"才报 error。**写侧**(prewrite)按现役写法严格校验:拟写载体若紧邻审计段,`sourceEventSeqs[0]` 必须是该审计段 seq,否则拒绝(早期写法在写侧被要求升级)。
316
+
294
317
  ### C1 — seq 缺口/倒退提示多写入者
295
318
 
296
319
  - **层级**: concurrency | **严重度**: warning
@@ -351,3 +374,15 @@
351
374
  - **出处**: @deepseek-ai/dsh-session-format-v0-to-v1@0.1.5-rc.2 lib/index.js:2543-2556(assertTitleSources):`session/title` 的 messageSeqs 为空 ⟺ source.kind === "user";每个被引 seq 必须解析到 `user/message` 且其 `data.source.kind === "user"`,否则 "messageSeqs must cite earlier human user/message events" / "must be empty exactly for a user title"
352
375
  - **契约**: 文件版本 0 且事件为 session/title 或 session/title-llm-request:messageSeqs 必须是数组;session/title 的"空数组 ⟺ 用户标题"必须成立;每个被引 seq 必须是更早的 user/message 且 source.kind === "user"。违反 → 官方升级到当前格式时拒绝。**应用面说明**:官方 `assertTitleSources` 与 turn/start 状态机同在 `assertReleasedArtifactRelationships`,由 v1→v2 在**变换后的 v1/v2 artifact** 上调用(`dsh-session-format-v1-to-v2/lib/index.js:104`);对 messageSeqs 这类按 seq 索引 + 类型/source 判定的引用,变换保序保类型 ⇒ 在原始 v0 上判是必要条件的近似,实测 281 真实 v0 上 0 误报。
353
376
 
377
+ ### G4 — 未知历史事件声明式可忽略(ignorable:true + 白名单)——迁移不得硬拒
378
+
379
+ - **层级**: migration | **严重度**: warning
380
+ - **出处**: @deepseek-ai/dsh-session-format-v0-to-v1@0.2.0-rc.2 package/lib/index.js:1513-1535(assertReleasedArtifactCoordinates:`ignorableCurrent` 分支只在 allowLegacySteering=false 时生效;:1531 原文 "migration refuses unknown historical events even when ignorable")、同处 `vocabularyNeutral` 参数("whether unknown event types remain opaque",未知类型按不透明事件保留的策略)
381
+ - **契约**: 未知历史事件(不在本包 vendored v0 词表内)若带信封级 `ignorable:true`,契约层按**声明式可忽略**处置:允许按声明丢弃并登记为 `acceptedDrop`,**不得**让整条迁移硬拒(这正是"每新增一类插件事件就卡死整条迁移"的根因)。消费者白名单可注入:`opts.ignorableWhitelist` / `createPreWriter({ignorableWhitelist})` / 环境变量 `DSH_LOG_CONTRACT_IGNORABLE_WHITELIST`(逗号分隔;元素为精确 type 或以 `/` 结尾的前缀),默认 = 已知插件消费者 `retrace/`、`message-editor/`。**未登记**的未知 ignorable 事件仍报 G4 warning(⛔ 不静默),且保持迁移阻断。G2 仍**原样保留**为"官方 v0→v1 会拒"的事实预检,不放宽;本规则只把"已声明可忽略且已登记"的事件从迁移阻断移入 `acceptedDrops`。实测:本机 2 份真实 v0 化石含 `retrace/goal-marker`(ignorable),默认白名单命中 ⇒ acceptedDrops,迁移不再被它阻断。
382
+
383
+ ### A1 — 在位可还原只认结构化归档指针(archiveRef / archive / externalized.*)
384
+
385
+ - **层级**: archive | **严重度**: error
386
+ - **出处**: 归档指针口径的外部实测(2026-10-20):只认 `archiveRef`/`archive`/`externalized.*`,⛔ 不得从自由文本 grep 路径;两版文本口径实测全错(原版 78.26%、只认绝对路径 2.04%);本机 763 份真实会话实测:结构化指针 273,571 个 → 按(目标,行)去重后 271,538 条记录,**可还原 271,538(100%)**、真实落空 0、行缺失 0、sha 不符 0;同批数据自由文本 `archive 第 N 行` 出现在 144,391 个事件里(口径差近 20 倍)
387
+ - **契约**: 外置内容的"在位可还原"判定**只**从结构化字段取指针:`data.archiveRef` / `data.archive` / `data.externalized.archiveRef` / `data.externalized.archive`(校验元数据取同级 `archiveLine`/`sha256`);⛔ **永不**从 `content`/`pointer`/散文模板等自由文本 grep 路径(实测两版全错:模板/示例会被算成引用,真实路径示例又被误计)。判据:目标文件存在 + `archiveLine` 行存在 + `sha256` 匹配 = 在位可还原;目标缺失/行缺失/sha 不符 = error;绝对路径失效但同名归档在归档根可解析 = `relocated` warning(re-home 未回写)。**按记录去重**:同一事件同时带 `archiveRef`(basename) 与 `archive`(绝对路径) 时按(目标,行)算一条记录——本机 2,033 个双字段指针即此类(其中 `/tmp` 绝对路径已失效者由 `archiveRef` 解析回 history 根,故真实落空 0,而不是把工具限制或旧路径算成内容缺失)。**独立维度**:需要归档根目录才能评估(`opts.archiveRoots` / `check --archive-root DIR`),未提供时结论为 `unverifiable`(不冒充通过,也不产生违规)。启用本维度后,真实缺失/行缺失/sha 不符是 **error**(红判据:在位可还原须 100%),会进 `ok` 与三档结论;`relocated` 只是 warning。
388
+
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
+ }