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/contracts.js CHANGED
@@ -21,6 +21,7 @@ export const LAYER = {
21
21
  CONCURRENCY: 'concurrency', // 并发/写入者假设
22
22
  FRAMING: 'framing', // zstd 帧结构
23
23
  MIGRATION: 'migration', // 迁移预检层:官方 v0/v1/v2 → 当前格式的升级路径会不会拒(**独立维度**)
24
+ ARCHIVE: 'archive', // 归档层:外置内容的**结构化指针**能否在位还原(**独立维度**:要归档根目录才能评估)
24
25
  };
25
26
 
26
27
  export const SEVERITY = { ERROR: 'error', WARNING: 'warning', INFO: 'info' };
@@ -132,6 +133,14 @@ export const CONTRACT_RULES = [
132
133
  source: '2026-08-28 实锤(某真实会话):文件物理序出现回退(大→小→更大);单进程 appendCore 断言 seq==cursor+i 且按 id 串行化不可能写出',
133
134
  description: '按文件物理行序要求展开后事件 seq 严格单调递增。E2 在排序后检查(loadSessionLog 会 sort),物理序倒退被掩盖;S9 在排序前按行序检查,非单调 = 多写入者/旧光标回放交织的直接现场证据,加载会被拒。',
134
135
  },
136
+ {
137
+ id: 'S10',
138
+ title: 'sourceEventSeqs 元素必须是(解码后的)非负整数;存储形态只允许官方区间对',
139
+ layer: LAYER.PERSISTENCE,
140
+ severity: SEVERITY.ERROR,
141
+ source: '@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、解码后严格递增)',
142
+ description: '所有事件的 `sourceEventSeqs`(**含非 surface 类型与 ignorable 未知插件事件**)原始存储形态只允许两种元素:非负安全整数、或官方区间对 `[start,end]`;经官方 `decodeSeqRanges` 解码后必须全部是非负安全整数。解码后仍为数组/非整数 = 契约违规(投影层/restore/重写路径会把它静默当成 seq,实测 v4test 即如此)⇒ 判红并给出该事件的 seq/行号。注意:`[a,b]` 本身是 v3+ 的**合法存储形态**(本机 760 份真实会话里 265 处,全部可解码),不得误报;判红点是「解码后仍非整数」与「非官方区间对形态」。',
143
+ },
135
144
  {
136
145
  id: 'I1',
137
146
  sourceVerified: false,
@@ -141,6 +150,14 @@ export const CONTRACT_RULES = [
141
150
  source: '@deepseek-ai/dsh-agent lib/types/inbox.js:155-178 (apply/validate);2026-08-28 实锤(某两个真实会话):fork 边界 removedCount=1 孤儿',
142
151
  description: '从 header.seedLength 起重放 agent/inbox/spliced,next-turn/next-step 双队列;start+removedCount 不得超过队列长、不得产生重复 pending id。fork 时"移除父待处理提示词"的 splice 假设父会话 inbox,子会话 seed 相对空 inbox 上非法 → resume 被拒(invalid persisted inbox splice)。',
143
152
  },
153
+ {
154
+ id: 'I2',
155
+ title: 'seedLength = 继承事件条数(不是字节数);parentSession ∧ seedLength∈{缺失,0} 合法',
156
+ layer: LAYER.PERSISTENCE,
157
+ severity: SEVERITY.ERROR,
158
+ source: '@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\\"")',
159
+ description: '`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 例 `> 展开事件数`(判红分支是防"当字节数用"的护栏)。',
160
+ },
144
161
  {
145
162
  id: 'E3',
146
163
  title: 'type 必须在已知词汇表内(或带 ignorable 标记)',
@@ -378,6 +395,14 @@ export const CONTRACT_RULES = [
378
395
  source: 'retrace 插件 lib/client.js:393("event and never a surface node")',
379
396
  description: 'marker 的 sourceEventSeqs(= shadowedSeqs,驱动 CSS 隐藏)不得包含 marker 自身 seq——marker 节点由隐藏逻辑跳过,出现在 shadowed 集属于自指语义错误。',
380
397
  },
398
+ {
399
+ id: 'P5',
400
+ title: 'carrier 两段配对:第 2 段 sourceEventSeqs 首元素 = 第 1 段(审计段)seq',
401
+ layer: LAYER.PLUGIN,
402
+ severity: SEVERITY.ERROR,
403
+ source: '仓库既有两段载体形状(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 例),不属本条',
404
+ description: '两段载体(第 1 段 = `compaction/prune` 审计段,带 `data.shadowedRange`/`shadowedSeqs`;第 2 段 = 紧随其后的 surface replace 载体)的配对规则:第 2 段 `sourceEventSeqs[0]` 必须等于第 1 段的 seq(现役写法),其余元素覆盖被遮蔽节点。**读侧容错(两种写法都认)**:① 现役 `[审计段 seq, ...被遮蔽节点]`;② 早期 `[区间起点, ...被遮蔽节点]`(不引用审计段 seq——实测真实语料 1,519 个载体即此写法,若判红会全成"孤儿")。只有"审计段 seq 在中间位且首元素既非审计段也非区间起点"、或"紧邻审计段却既不引用它、首元素也不是区间起点"才报 error。**写侧**(prewrite)按现役写法严格校验:拟写载体若紧邻审计段,`sourceEventSeqs[0]` 必须是该审计段 seq,否则拒绝(早期写法在写侧被要求升级)。',
405
+ },
381
406
 
382
407
  // ── C · 并发 / 写入者假设 ───────────────────────────────────────────────
383
408
  {
@@ -473,6 +498,22 @@ export const CONTRACT_RULES = [
473
498
  source: '@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"',
474
499
  description: '文件版本 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 误报。',
475
500
  },
501
+ {
502
+ id: 'G4',
503
+ title: '未知历史事件声明式可忽略(ignorable:true + 白名单)——迁移不得硬拒',
504
+ layer: LAYER.MIGRATION,
505
+ severity: SEVERITY.WARNING,
506
+ source: '@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",未知类型按不透明事件保留的策略)',
507
+ description: '未知历史事件(不在本包 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,迁移不再被它阻断。',
508
+ },
509
+ {
510
+ id: 'A1',
511
+ title: '在位可还原只认结构化归档指针(archiveRef / archive / externalized.*)',
512
+ layer: LAYER.ARCHIVE,
513
+ severity: SEVERITY.ERROR,
514
+ source: '归档指针口径的外部实测(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 倍)',
515
+ description: '外置内容的"在位可还原"判定**只**从结构化字段取指针:`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。',
516
+ },
476
517
  ];
477
518
 
478
519
  /** 按 id 取规则。 */
package/lib/index.js CHANGED
@@ -11,5 +11,6 @@ export { repairSession, strictScanText, removeMarkersText, neutralizeMarkersText
11
11
  export { CONTRACT_RULES, LAYER, SEVERITY, ruleById } from './contracts.js';
12
12
  export { HOST_MAX_FILE_VERSION, hostPackageVersion, hostCapability, isAssessableFileVersion } from './vocab.js';
13
13
  export { TESTED_BASELINE, compareVersions, detectSupport, supportOfLog } from './version-support.js';
14
- export { tokenMeterViolations, tokenMeterSourceViolations, stepKeyViolations, nullTurnStepViolations, turnEndReasonViolations, ignorableTypeViolations, physicalOrderViolations, inboxReplayViolations } from './checks.js';
14
+ export { tokenMeterViolations, tokenMeterSourceViolations, stepKeyViolations, nullTurnStepViolations, turnEndReasonViolations, ignorableTypeViolations, physicalOrderViolations, inboxReplayViolations, sourceEventSeqElementViolations, rawSourceEventSeqViolations, isSeqRangePair, seedLengthViolations, carrierPairingViolations, carrierWriteViolations, isCarrierAuditSegment, carrierRangesMatch, surfaceReplaceRange, declarativeIgnorableViolations, isIgnorableRegistered, resolveIgnorableWhitelist, DEFAULT_IGNORABLE_WHITELIST } from './checks.js';
15
+ export { collectArchivePointers, verifyArchivePointers, archiveVerdict, archiveBasename, readArchiveLines, readArchiveIndex, ARCHIVE_POINTER_FIELDS, EXTERNALIZED_POINTER_FIELDS } from './archive.js';
15
16
  export { auditToolCalls, extractText, extractToolOutputs, indexToolCalls, toolCommandOf } from './archaeology.js';
package/lib/log-reader.js CHANGED
@@ -200,8 +200,8 @@ export function loadSessionLog(path) {
200
200
  };
201
201
  }
202
202
 
203
- const text = plain.toString('utf8');
204
- const lines = text.split('\n');
203
+ // 按行解码(Buffer 切分),避免整文件字符串化(>536MB 抛字符串上限)
204
+ const lines = (() => { const out = []; let s = 0, i; while ((i = plain.indexOf(0x0a, s)) !== -1) { out.push(plain.subarray(s, i).toString('utf8')); s = i + 1 } out.push(plain.subarray(s).toString('utf8')); return out })();
205
205
 
206
206
  // 第一行 = header
207
207
  const headerLine = 0;
package/lib/prewrite.js CHANGED
@@ -17,7 +17,7 @@
17
17
  * 所有判定复用 `lib/checks.js`(与离线体检同一套逻辑),
18
18
  * 保证"体检看到的问题 = 写入前拦下的问题"。
19
19
  */
20
- import { envelopeViolations, engineViolations, finalFold, isSafeInt, nullTurnStepViolations, pluginViolations, replaySurface, stepKeyViolations, tokenMeterViolations, turnEndReasonViolations, violation, wireViolations } from './checks.js';
20
+ import { carrierWriteViolations, declarativeIgnorableViolations, envelopeViolations, engineViolations, finalFold, isSafeInt, nullTurnStepViolations, pluginViolations, replaySurface, sourceEventSeqElementViolations, stepKeyViolations, tokenMeterViolations, turnEndReasonViolations, violation, wireViolations } from './checks.js';
21
21
  import { resolveFormatVersion, LEGACY_FORMAT_MAX_VERSION } from './vocab.js';
22
22
  import { normalizeEventSeqRanges } from './compat.js';
23
23
 
@@ -70,9 +70,10 @@ function normalizeCandidate(candidate, nextSeq) {
70
70
  * (`lib/prewrite-guard.js:166`),所以缺省时必须能自行推断,不能把 v3 输入按 0 处理
71
71
  * (否则首次调用即 10 条 E3/S2/S8 误报)。
72
72
  *
73
- * @param {{ events: Array<object>, baseSeq?: number, formatVersion?: number, header?: object|null }} input
73
+ * @param {{ events: Array<object>, baseSeq?: number, formatVersion?: number, header?: object|null, ignorableWhitelist?: string[] }} input
74
74
  * 当前日志的已解码事件(按日志顺序;无 seq 字段的事件按位置补 seq,用于窗口校验)。
75
75
  * `formatVersion`/`header` 二者其一优先决定被检文件的格式版本。
76
+ * `ignorableWhitelist`:G4 可忽略消费者白名单(精确 type 或以 `/` 结尾的前缀)。
76
77
  * @returns {{
77
78
  * events: Array, nextSeq: number, formatVersion: number,
78
79
  * validateAppend(candidate, opts?): { ok, violations, stateAfter },
@@ -80,7 +81,7 @@ function normalizeCandidate(candidate, nextSeq) {
80
81
  * }}
81
82
  */
82
83
  export function createPreWriter(input = {}) {
83
- const { baseSeq = 0, header = null } = input;
84
+ const { baseSeq = 0, header = null, ignorableWhitelist } = input;
84
85
  // C1:v3 storage-form 区间编码 → 内存稠密序列(与 log-reader 同一归一,覆盖"直接传 events"入口)
85
86
  let events = (input.events ?? []).map(normalizeEventSeqRanges);
86
87
  // C2:版本显式解析并固定在本次调用内(不读模块级全局)
@@ -117,6 +118,8 @@ export function createPreWriter(input = {}) {
117
118
  violations.push(...engineViolations(event, loc));
118
119
  violations.push(...pluginViolations(event, loc));
119
120
  }
121
+ // S10 —— sourceEventSeqs 元素硬断言(0.3.19 · 最小集 ②):解码后必须全为非负整数。
122
+ violations.push(...sourceEventSeqElementViolations(candidateEvents.map((event) => ({ event }))));
120
123
  // S1–S7 —— 与官方同语义的增量重放(含拟写事件)
121
124
  const replay = replaySurface(candidateEvents.map((event) => ({ event })), formatVersion);
122
125
  violations.push(...replay.violations);
@@ -177,6 +180,19 @@ export function createPreWriter(input = {}) {
177
180
  if (v.seq !== lastCandidate?.seq) continue;
178
181
  violations.push(v);
179
182
  }
183
+ // P5 —— carrier 两段配对(0.3.19 · 最小集 ④;**写侧按现役写法严格校验**)。
184
+ // 只在追加语境判(validateEdit 是"改后全量确认",由读侧容错口径负责)。
185
+ if (tailHint !== undefined) {
186
+ violations.push(...carrierWriteViolations(candidateEvents, { version: formatVersion }));
187
+ }
188
+ // G4 —— 未知历史事件声明式可忽略(0.3.19 · 最小集 ①):拟写事件带 ignorable:true 时
189
+ // **不得硬拒**;已登记白名单 ⇒ 静默接受(acceptedDrop),未登记 ⇒ warning(⛔ 不静默)。
190
+ if (formatVersion === 0) {
191
+ const subject = tailHint !== undefined && lastCandidate !== undefined
192
+ ? [{ event: lastCandidate }]
193
+ : candidateEvents.map((event) => ({ event }));
194
+ violations.push(...declarativeIgnorableViolations(subject, 0, { ignorableWhitelist }).violations);
195
+ }
180
196
  const bySeverity = { error: 0, warning: 0, info: 0 };
181
197
  for (const v of violations) bySeverity[v.severity] = (bySeverity[v.severity] ?? 0) + 1;
182
198
  // 「让降级可见」:把"本次写入沿用了历史 marker 形态(债)"作为**结构化字段**带出,
@@ -256,7 +272,7 @@ export function createPreWriter(input = {}) {
256
272
  * 一站式便利:加载会话日志 → 建立写前校验器。
257
273
  * @param {import('./log-reader.js').loadSessionLog} log `loadSessionLog()` 结果
258
274
  */
259
- export function preWriterFromLog(log) {
275
+ export function preWriterFromLog(log, opts = {}) {
260
276
  const events = (log.events ?? []).map((e) => e.event);
261
- return createPreWriter({ events, header: log?.header ?? null });
277
+ return createPreWriter({ events, header: log?.header ?? null, ignorableWhitelist: opts.ignorableWhitelist });
262
278
  }
package/lib/repair.js CHANGED
@@ -1135,6 +1135,31 @@ export function rebuildZstdText(text) {
1135
1135
  return out;
1136
1136
  }
1137
1137
 
1138
+ /**
1139
+ * 按官方 writer 帧格式重建 .jsonl.zstd(帧1=header,帧2..n=正文**分块多帧**,均带 checksum)。
1140
+ * 流式/分块版 —— 不构造整份大字符串(>536MB 会 ERR_STRING_TOO_LONG);逐帧 roundtrip 校验。
1141
+ * @param {string[]} lines - 按 \n 切开的行数组;末元素必须为 ''(单个换行结尾)。
1142
+ * @param {{chunkBytes?:number}} [opts]
1143
+ * @returns {Buffer}
1144
+ */
1145
+ export function rebuildZstdLines(lines, { chunkBytes = 64 * 1024 * 1024 } = {}) {
1146
+ if (!Array.isArray(lines) || lines.length === 0) throw new Error('repair: 无行可重建')
1147
+ if (lines[lines.length - 1] !== '') throw new Error('repair: JSONL 必须以单个换行结尾')
1148
+ if (lines.length === 1) throw new Error('repair: JSONL 缺 header 行')
1149
+ const headerLine = lines[0] + '\n'
1150
+ const opts = { params: { [constants.ZSTD_c_checksumFlag]: 1 } };
1151
+ const frames = [zstdCompressSync(Buffer.from(headerLine), opts)]
1152
+ let acc = []; let accBytes = 0
1153
+ const flush = () => { if (acc.length === 0) return; frames.push(zstdCompressSync(Buffer.concat(acc), opts)); acc = []; accBytes = 0 }
1154
+ for (let i = 1; i < lines.length - 1; i += 1) { const b = Buffer.from(lines[i] + '\n'); acc.push(b); accBytes += b.length; if (accBytes >= chunkBytes) flush() }
1155
+ flush()
1156
+ const out = Buffer.concat(frames)
1157
+ // 逐帧 roundtrip(不拼整串):帧1 == header;其余帧逐字节回读通过即可
1158
+ if (zstdDecompressSync(frames[0]).toString('utf8') !== headerLine) throw new Error('repair: 帧1 roundtrip 不一致')
1159
+ for (let i = 1; i < frames.length; i += 1) { const d = zstdDecompressSync(frames[i]); if (!Buffer.isBuffer(d) && typeof d !== 'string') throw new Error('repair: 正文帧 roundtrip 失败') }
1160
+ return out
1161
+ }
1162
+
1138
1163
  /**
1139
1164
  * 对单个会话日志执行诊断 +(可选)修复。
1140
1165
  * @param {string} file - .jsonl 或 .jsonl.zstd 路径。
package/lib/validate.js CHANGED
@@ -18,6 +18,8 @@ import { runHostProbes } from './host-probes.js';
18
18
  import { SOURCE_DRIFT } from './contracts.js';
19
19
  import {
20
20
  CHUNK_ROW_TYPES,
21
+ carrierPairingViolations,
22
+ declarativeIgnorableViolations,
21
23
  envelopeViolations,
22
24
  ignorableTypeViolations,
23
25
  engineViolations,
@@ -28,7 +30,10 @@ import {
28
30
  nullTurnStepViolations,
29
31
  physicalOrderViolations,
30
32
  pluginViolations,
33
+ rawSourceEventSeqViolations,
31
34
  replaySurface,
35
+ seedLengthViolations,
36
+ sourceEventSeqElementViolations,
32
37
  stepKeyViolations,
33
38
  turnEndReasonViolations,
34
39
  violation,
@@ -38,6 +43,7 @@ import {
38
43
  toolResultStructureViolations,
39
44
  wireViolations,
40
45
  } from './checks.js';
46
+ import { archiveVerdict } from './archive.js';
41
47
 
42
48
  /**
43
49
  * `header.cwd` 的"绝对路径"判据 —— **平台感知**(Issue #1)。
@@ -57,13 +63,16 @@ export function isAbsoluteLogPath(value) {
57
63
  }
58
64
 
59
65
  /** 宿主能力闸触发时**跳过**的规则(v3/被检版本语义相关)——报告里显式列出,避免"静默通过"。 */
60
- const VERSION_DEPENDENT_RULES = ['E3', 'E7', 'S1', 'S2', 'S3', 'S4', 'S5', 'S6', 'S7', 'S8', 'W1', 'W2', 'T1', 'T2', 'T3', 'T4', 'T5', 'G1', 'G2'];
66
+ const VERSION_DEPENDENT_RULES = ['E3', 'E7', 'S1', 'S2', 'S3', 'S4', 'S5', 'S6', 'S7', 'S8', 'W1', 'W2', 'T1', 'T2', 'T3', 'T4', 'T5', 'G1', 'G2', 'G4', 'P5'];
61
67
 
62
68
  /**
63
69
  * 对会话日志执行全量离线体检。
64
70
  *
65
71
  * @param {object} log `loadSessionLog()` 的返回值
66
- * @param {{ baseSeq?: number }} [opts]
72
+ * @param {{ baseSeq?: number, ignorableWhitelist?: string[], archiveRoots?: string[] }} [opts]
73
+ * - `ignorableWhitelist`:G4 可忽略消费者白名单(精确 type 或以 `/` 结尾的前缀;默认见
74
+ * `checks.js` 的 `DEFAULT_IGNORABLE_WHITELIST`);
75
+ * - `archiveRoots`:A1「在位可还原」的归档根目录;**不传 = 该维度不可判定**(不冒充通过)。
67
76
  * @returns {{
68
77
  * ok: boolean,
69
78
  * violations: Array,
@@ -72,7 +81,7 @@ const VERSION_DEPENDENT_RULES = ['E3', 'E7', 'S1', 'S2', 'S3', 'S4', 'S5', 'S6',
72
81
  * }}
73
82
  */
74
83
  export function validateSessionLog(log, opts = {}) {
75
- const { baseSeq = 0 } = opts;
84
+ const { baseSeq = 0, ignorableWhitelist, archiveRoots } = opts;
76
85
  const violations = [];
77
86
  const { header, headerLine, rows, frameInfo } = log;
78
87
  // C1 防御(多入口一致):即使调用方手搓 log 对象、未经 `loadSessionLog`,也在体检入口
@@ -89,7 +98,7 @@ export function validateSessionLog(log, opts = {}) {
89
98
  // `S8×1 + E3×40 / verdict=broken / loadable:false`),危险是用户以为日志坏了去跑
90
99
  // `fix --apply`。改为:只跑与版本无关的结构检查 + 显式"不可在本宿主评估"档。
91
100
  if (!isAssessableFileVersion(formatVersion)) {
92
- return unassessableResult({ header, headerLine, rows, events, frameInfo, baseSeq, formatVersion });
101
+ return unassessableResult({ header, headerLine, rows, events, frameInfo, baseSeq, formatVersion, ignorableWhitelist, archiveRoots });
93
102
  }
94
103
 
95
104
  // ── Z · 帧结构 ─────────────────────────────────────────────────────────
@@ -150,6 +159,17 @@ export function validateSessionLog(log, opts = {}) {
150
159
  }
151
160
  }
152
161
 
162
+ // ── S10 · sourceEventSeqs 元素类型硬断言(0.3.19 · 最小集 ②)───────────
163
+ // 两层:① 存储形态(rows[].value,官方区间对是合法存储形态);② 解码后形态(必须全是
164
+ // 非负整数)。覆盖面 = **所有事件**(含非 surface 与 ignorable 未知插件事件)。
165
+ violations.push(...rawSourceEventSeqViolations(rows));
166
+ violations.push(...sourceEventSeqElementViolations(events));
167
+
168
+ // ── I2 · seedLength = 继承事件条数(0.3.19 · 最小集 ③)─────────────────
169
+ // parentSession ∧ seedLength∈{缺失,0} 判**合法**(血缘 ≠ seeded);只有 seedLength 超过
170
+ // 展开后事件数、非法值、或 v4 头带该字段才判红。
171
+ violations.push(...seedLengthViolations(header, events.map((e) => e.event), formatVersion));
172
+
153
173
  // ── E · 事件信封 + seq 连续性 ──────────────────────────────────────────
154
174
  let expectedSeq = baseSeq;
155
175
  let seqBroken = false;
@@ -210,6 +230,10 @@ export function validateSessionLog(log, opts = {}) {
210
230
  violations.push(...pluginViolations(event, loc));
211
231
  }
212
232
 
233
+ // ── P5 · carrier 两段配对(0.3.19 · 最小集 ④;**读侧容错**)──────────────
234
+ // 读侧两种真实写法都认:① 现役 [审计段 seq, ...];② 早期 [区间起点, ...](不引用审计段)。
235
+ violations.push(...carrierPairingViolations(events, { version: formatVersion }));
236
+
213
237
  // ── C · 并发(仅当出现 seq 破坏时给出解释性告警)─────────────────────
214
238
  if (seqBroken) {
215
239
  violations.push(violation('C1', { lineNo: null }, 'seq 缺口/倒退是多写入者(≥2 个 Host 进程共享同一 session 目录)并发写的典型后果;离线体检无法观测竞态本身,但此痕迹需人工核查(N6)'));
@@ -218,7 +242,16 @@ export function validateSessionLog(log, opts = {}) {
218
242
  // ── G · 迁移预检(**独立维度**:官方升级路径会不会拒;不进 ok/verdict)──────
219
243
  // 官方把 v0/v1/v2 升到当前格式时的规则集比本工具的"读取/折叠"规则集更严:本工具判
220
244
  // ok/compactable **不代表**官方迁移会接受。这里只加 migration 层 warning(见 contracts G1/G2)。
221
- violations.push(...migrationPrecheckViolations(events, formatVersion));
245
+ violations.push(...migrationPrecheckViolations(events, formatVersion, { ignorableWhitelist }));
246
+ // G4(0.3.19 · 最小集 ①):未知历史事件 + ignorable:true = **声明式可忽略**。
247
+ // 已登记(白名单)⇒ 不报违规、进 acceptedDrops(迁移不硬拒);未登记 ⇒ warning(⛔ 不静默)。
248
+ const ignorableDrops = declarativeIgnorableViolations(events, formatVersion, { ignorableWhitelist });
249
+ violations.push(...ignorableDrops.violations);
250
+
251
+ // ── A1 · 在位可还原(0.3.19 · 最小集 ⑤;**独立维度**)────────────────────
252
+ // 只认结构化归档指针;未提供归档根目录 ⇒ verdict='unverifiable'(不冒充通过、不产生违规)。
253
+ const archive = archiveVerdict(events, { archiveRoots });
254
+ violations.push(...archive.violations);
222
255
 
223
256
  // ── 汇总 ───────────────────────────────────────────────────────────────
224
257
  violations.sort((a, b) => (a.seq ?? -1) - (b.seq ?? -1) || (a.lineNo ?? -1) - (b.lineNo ?? -1));
@@ -241,6 +274,10 @@ export function validateSessionLog(log, opts = {}) {
241
274
  fileVersion: formatVersion,
242
275
  hostMaxFileVersion: HOST_MAX_FILE_VERSION,
243
276
  assessable: true,
277
+ // 0.3.19:结构化读数(不进 ok,只供报告/机器判读)
278
+ seedLength: Object.hasOwn(header ?? {}, 'seedLength') ? header.seedLength : null,
279
+ ignorableDrops: { registered: ignorableDrops.registered.length, unregistered: ignorableDrops.unregistered.length },
280
+ archiveVerdict: archive.verdict,
244
281
  };
245
282
 
246
283
  const result = {
@@ -249,6 +286,10 @@ export function validateSessionLog(log, opts = {}) {
249
286
  violations,
250
287
  summary,
251
288
  surface: folded.surface ?? { nodes: replay.nodes, replacements: [] },
289
+ // A1 独立维度读数:没有归档根时 `verdict='unverifiable'`(不冒充通过)。
290
+ archive,
291
+ // G4 声明式可忽略:已登记(acceptedDrop,不阻断迁移)与未登记(warning + 仍阻断)。
292
+ ignorableDrops: { registered: ignorableDrops.registered, unregistered: ignorableDrops.unregistered },
252
293
  };
253
294
  // 版本支持面(2026-09-14 用户要求第 1 条):宿主版本 vs 测试基线 + 被检文件格式版本,
254
295
  // 给出 warnings/readOnly。只读档由入口(prewrite/fix)强制执行。
@@ -269,7 +310,7 @@ export function validateSessionLog(log, opts = {}) {
269
310
  * 里列出。**ok 固定 false**(不认证),但 `structuralOk` 单独给出结构层结论——
270
311
  * 语义是"本宿主评估不了",不是"日志坏了"。
271
312
  */
272
- function unassessableResult({ header, headerLine, rows, events, frameInfo, baseSeq, formatVersion }) {
313
+ function unassessableResult({ header, headerLine, rows, events, frameInfo, baseSeq, formatVersion, archiveRoots }) {
273
314
  const violations = [];
274
315
  const cap = hostCapability();
275
316
  const notAssessable = {
@@ -323,6 +364,12 @@ function unassessableResult({ header, headerLine, rows, events, frameInfo, baseS
323
364
  violations.push(...inboxReplayViolations(events, header));
324
365
  violations.push(...toolPairingViolations(events));
325
366
  violations.push(...toolResultStructureViolations(events));
367
+ // S10 / I2:版本无关的结构断言(0.3.19 最小集 ②③)。
368
+ violations.push(...rawSourceEventSeqViolations(rows));
369
+ violations.push(...sourceEventSeqElementViolations(events));
370
+ violations.push(...seedLengthViolations(header, events.map((e) => e.event), formatVersion));
371
+ const archive = archiveVerdict(events, { archiveRoots });
372
+ violations.push(...archive.violations);
326
373
  for (const { event, lineNo } of events) {
327
374
  const loc = { seq: event.seq, lineNo, eventType: event.type };
328
375
  violations.push(...engineViolations(event, loc));
@@ -356,8 +403,13 @@ function unassessableResult({ header, headerLine, rows, events, frameInfo, baseS
356
403
  fileVersion: formatVersion,
357
404
  hostMaxFileVersion: HOST_MAX_FILE_VERSION,
358
405
  assessable: false,
406
+ seedLength: Object.hasOwn(header ?? {}, 'seedLength') ? header.seedLength : null,
407
+ ignorableDrops: { registered: 0, unregistered: 0 },
408
+ archiveVerdict: archive.verdict,
359
409
  },
360
410
  surface: null,
411
+ archive,
412
+ ignorableDrops: { registered: [], unregistered: [] },
361
413
  };
362
414
  result.support = detectSupport({ header, events });
363
415
  result.probes = hostProbes();
@@ -423,6 +475,7 @@ export function migrationVerdict(result) {
423
475
  'G1 v0 源:subagent/descriptor.data.version !== 3',
424
476
  'G2 v0 源:事件类型不在官方 v0 dispositions 内(含 ignorable:true)',
425
477
  'G3 v0 源:session/title 系列 messageSeqs 必须引用更早的人类 user/message(含"空 ⟺ 用户标题")',
478
+ 'G4 v0 源:未知历史事件 + ignorable:true = 声明式可忽略(已登记白名单 ⇒ acceptedDrop,不硬拒;未登记 ⇒ warning 且仍阻断)',
426
479
  ],
427
480
  uncovered: [
428
481
  // 2026-09-15:`turn/start` 试做后在**真实语料**上被判定为"应用对象错"——
@@ -441,11 +494,26 @@ export function migrationVerdict(result) {
441
494
  note: '未覆盖 ≠ 通过:本维度只对 implemented 三条负责。官方判据版本:@deepseek-ai/dsh-session-format-v0-to-v1@0.1.5-rc.2 + v1-to-v2@0.1.5-rc.2',
442
495
  };
443
496
  if (result?.assessable === false) {
444
- return { assessable: false, applies: null, ready: null, fileVersion, blocked: [], coverage, assessmentScope: 'none', reason: result?.notAssessable?.reason ?? null };
497
+ return { assessable: false, applies: null, ready: null, fileVersion, blocked: [], acceptedDrops: { registered: [], unregistered: [] }, coverage, assessmentScope: 'none', reason: result?.notAssessable?.reason ?? null };
498
+ }
499
+ // G4(0.3.19):已登记的"声明式可忽略"未知历史事件 = acceptedDrop,**不阻断**迁移;
500
+ // G2 事实预检本身保留(仍在 violations 里,供人看"官方 v0→v1 会拒"),只是不再计入 blocked。
501
+ // 未登记 ⇒ 仍在 blocked(⛔ 不静默:新增插件事件必须显式登记一次)。
502
+ const registered = [];
503
+ const unregistered = [];
504
+ for (const v of violations) {
505
+ if (v.layer !== 'migration') continue;
506
+ if (v.id === 'G2' && v.ignorable === true) {
507
+ const drop = { id: v.id, seq: v.seq ?? null, eventType: v.eventType ?? null, message: v.message };
508
+ if (v.ignorableRegistered === true) registered.push(drop);
509
+ else unregistered.push(drop);
510
+ }
445
511
  }
446
- const blocked = violations.filter((v) => v.layer === 'migration');
512
+ const acceptedDrops = { registered, unregistered };
513
+ const blocked = violations.filter((v) => v.layer === 'migration'
514
+ && !(v.id === 'G2' && v.ignorable === true && v.ignorableRegistered === true));
447
515
  if (fileVersion !== null && fileVersion === MIGRATION_TARGET_VERSION) {
448
- return { assessable: true, applies: false, ready: null, fileVersion, targetFileVersion: MIGRATION_TARGET_VERSION, blocked, coverage, assessmentScope: 'full', reason: `被检文件已是当前官方格式(version=${fileVersion}),无需迁移` };
516
+ return { assessable: true, applies: false, ready: null, fileVersion, targetFileVersion: MIGRATION_TARGET_VERSION, blocked, acceptedDrops, coverage, assessmentScope: 'full', reason: `被检文件已是当前官方格式(version=${fileVersion}),无需迁移` };
449
517
  }
450
518
  const applies = fileVersion !== null && fileVersion < MIGRATION_TARGET_VERSION;
451
519
  return {
@@ -456,6 +524,7 @@ export function migrationVerdict(result) {
456
524
  targetFileVersion: MIGRATION_TARGET_VERSION,
457
525
  hostMaxFileVersion: HOST_MAX_FILE_VERSION,
458
526
  blocked,
527
+ acceptedDrops,
459
528
  coverage,
460
529
  // 2026-09-14:待迁移文件(applies=true)**只**被 2 条 G 规则覆盖,
461
530
  // 另有 6 类官方迁移规则未覆盖 ⇒ 评估范围只能是 "partial"。工具无法逐文件知道
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "dsh-log-contract",
3
3
  "description": "日志契约守护 — DSH session log contract guard: offline health check (CLI) + pre-write validation for DeepSeek Harness session logs",
4
- "version": "0.3.18",
4
+ "version": "0.3.20",
5
5
  "packageManager": "pnpm@11.7.0",
6
6
  "type": "module",
7
7
  "main": "lib/index.js",