dsh-log-contract 0.3.17 → 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.
@@ -53,21 +53,55 @@ export const PROBES = [
53
53
  })) === true,
54
54
  },
55
55
  {
56
- id: 'p3-system-message-plugin-source',
57
- title: 'system/message 是 surface 类型且必须 plugin source(kind=user 必须拒)',
56
+ id: 'p3-system-message-source',
57
+ title: 'system/message 是 surface 类型;source 按宿主格式:v3 plugin / v4 system-prompt(kind=user 必须拒)',
58
58
  rules: ['E6', 'E9'],
59
- expect: 'plugin source 通过;user source 被拒',
59
+ expect: 'v3 宿主:plugin 通过、system-prompt 被拒;v4 宿主:system-prompt 通过、plugin 被拒;user source 一律被拒',
60
60
  run: () => {
61
61
  const eligible = isSurfaceEligibleType('system/message') === true;
62
- const withPlugin = rejects(() => adoptSessionEvent({
62
+ const sys = (source) => rejects(() => adoptSessionEvent({
63
63
  type: 'system/message', seq: 0, time: 1, surfaceOp: 'append',
64
- data: { turn: 0, step: 0, message: { id: 's0', role: 'system', source: { kind: 'plugin', plugin: 'p' }, content: [] } },
64
+ data: { turn: 1, step: 1, message: { id: 's0', role: 'system', source, content: [] } },
65
65
  }));
66
- const withUser = rejects(() => adoptSessionEvent({
67
- type: 'system/message', seq: 0, time: 1, surfaceOp: 'append',
68
- data: { turn: 0, step: 0, message: { id: 's0', role: 'system', source: { kind: 'user' }, content: [] } },
66
+ const withPlugin = sys({ kind: 'plugin', plugin: 'p' });
67
+ const withSystemPrompt = sys({ kind: 'system-prompt' });
68
+ const withUser = sys({ kind: 'user' });
69
+ const expected = SESSION_FORMAT_VERSION >= 4
70
+ ? withSystemPrompt === false && withPlugin === true
71
+ : withPlugin === false;
72
+ return eligible && expected && withUser === true;
73
+ },
74
+ },
75
+ {
76
+ id: 'p7-tool-result-role',
77
+ title: 'tool/result 的 role 按宿主格式:v3 user + tool-result 包装块 / v4 tool + message.toolCallId',
78
+ rules: ['E6'],
79
+ expect: 'v3 宿主:包装形状通过、v4 形状被拒;v4 宿主:v4 形状通过、包装形状与 toolCallId 不匹配被拒',
80
+ run: () => {
81
+ const tool = (message) => rejects(() => adoptSessionEvent({
82
+ type: 'tool/result', seq: 2, time: 1, surfaceOp: 'append', data: { turn: 1, step: 1, message },
69
83
  }));
70
- return eligible && withPlugin === false && withUser === true;
84
+ const v4Shape = tool({ id: 't1', role: 'tool', toolCallId: 'c1', source: { kind: 'tool', callId: 'c1' }, content: [] });
85
+ const v4Mismatch = tool({ id: 't1', role: 'tool', toolCallId: 'c2', source: { kind: 'tool', callId: 'c1' }, content: [] });
86
+ const v3Shape = tool({ id: 't1', role: 'user', source: { kind: 'tool', callId: 'c1' }, content: [{ type: 'tool-result', toolCallId: 'c1', content: [] }] });
87
+ return SESSION_FORMAT_VERSION >= 4
88
+ ? v4Shape === false && v4Mismatch === true && v3Shape === true
89
+ : v3Shape === false && v4Shape === true;
90
+ },
91
+ },
92
+ {
93
+ id: 'p8-developer-message-surface',
94
+ title: 'developer/message 只在 v4 宿主是 surface 类型(role developer)',
95
+ rules: ['E6', 'S1', 'S2'],
96
+ expect: 'v4 宿主:surface-eligible 且 role developer 通过;v3 宿主:非 surface 类型',
97
+ run: () => {
98
+ const eligible = isSurfaceEligibleType('developer/message') === true;
99
+ if (SESSION_FORMAT_VERSION < 4) return eligible === false;
100
+ const accepted = rejects(() => adoptSessionEvent({
101
+ type: 'developer/message', seq: 3, time: 1, surfaceOp: 'append',
102
+ data: { turn: 1, step: 1, message: { id: 'd1', role: 'developer', source: { kind: 'tool-registry' }, content: [] } },
103
+ })) === false;
104
+ return eligible && accepted;
71
105
  },
72
106
  },
73
107
  {
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/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/validate.js CHANGED
@@ -9,6 +9,7 @@
9
9
  * 终验按**被检文件 header.version** 选:v3 → 运行时官方 `foldSurface`;
10
10
  * v0/v1/v2 → 本地等价实现 `legacyFoldSurface`(0.1.5 的 foldSurface 是 v3 语义,对旧格式会误报)。
11
11
  */
12
+ import { posix as posixPath, win32 as win32Path } from 'node:path';
12
13
  import { ruleById } from './contracts.js';
13
14
  import { normalizeEventSeqRanges } from './compat.js';
14
15
  import { HOST_MAX_FILE_VERSION, MIGRATION_TARGET_VERSION, hostCapability, isAssessableFileVersion } from './vocab.js';
@@ -17,6 +18,8 @@ import { runHostProbes } from './host-probes.js';
17
18
  import { SOURCE_DRIFT } from './contracts.js';
18
19
  import {
19
20
  CHUNK_ROW_TYPES,
21
+ carrierPairingViolations,
22
+ declarativeIgnorableViolations,
20
23
  envelopeViolations,
21
24
  ignorableTypeViolations,
22
25
  engineViolations,
@@ -27,7 +30,10 @@ import {
27
30
  nullTurnStepViolations,
28
31
  physicalOrderViolations,
29
32
  pluginViolations,
33
+ rawSourceEventSeqViolations,
30
34
  replaySurface,
35
+ seedLengthViolations,
36
+ sourceEventSeqElementViolations,
31
37
  stepKeyViolations,
32
38
  turnEndReasonViolations,
33
39
  violation,
@@ -37,15 +43,36 @@ import {
37
43
  toolResultStructureViolations,
38
44
  wireViolations,
39
45
  } from './checks.js';
46
+ import { archiveVerdict } from './archive.js';
47
+
48
+ /**
49
+ * `header.cwd` 的"绝对路径"判据 —— **平台感知**(Issue #1)。
50
+ *
51
+ * 旧实现只认 POSIX 的 `/` 前缀 ⇒ Windows 会话的 `C:\…` / `\\server\share\…` 全部误报 H2
52
+ * (体检是离线、跨机只读的:被检日志可能来自任意平台,不能按本机 `process.platform` 判)。
53
+ * 两种形态都接受:
54
+ * - POSIX:`/Users/x`、`/home/x`
55
+ * - Windows 盘符绝对:`C:\Users\x`、`C:/Users/x`
56
+ * - Windows UNC:`\\server\share\x`、`//server/share/x`
57
+ *
58
+ * 反例(仍报 H2):`C:relative`(盘符相对)、`Users/x`、`./x`、空串。
59
+ */
60
+ export function isAbsoluteLogPath(value) {
61
+ if (typeof value !== 'string' || value === '') return false;
62
+ return posixPath.isAbsolute(value) || win32Path.isAbsolute(value);
63
+ }
40
64
 
41
65
  /** 宿主能力闸触发时**跳过**的规则(v3/被检版本语义相关)——报告里显式列出,避免"静默通过"。 */
42
- 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'];
43
67
 
44
68
  /**
45
69
  * 对会话日志执行全量离线体检。
46
70
  *
47
71
  * @param {object} log `loadSessionLog()` 的返回值
48
- * @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「在位可还原」的归档根目录;**不传 = 该维度不可判定**(不冒充通过)。
49
76
  * @returns {{
50
77
  * ok: boolean,
51
78
  * violations: Array,
@@ -54,7 +81,7 @@ const VERSION_DEPENDENT_RULES = ['E3', 'E7', 'S1', 'S2', 'S3', 'S4', 'S5', 'S6',
54
81
  * }}
55
82
  */
56
83
  export function validateSessionLog(log, opts = {}) {
57
- const { baseSeq = 0 } = opts;
84
+ const { baseSeq = 0, ignorableWhitelist, archiveRoots } = opts;
58
85
  const violations = [];
59
86
  const { header, headerLine, rows, frameInfo } = log;
60
87
  // C1 防御(多入口一致):即使调用方手搓 log 对象、未经 `loadSessionLog`,也在体检入口
@@ -71,7 +98,7 @@ export function validateSessionLog(log, opts = {}) {
71
98
  // `S8×1 + E3×40 / verdict=broken / loadable:false`),危险是用户以为日志坏了去跑
72
99
  // `fix --apply`。改为:只跑与版本无关的结构检查 + 显式"不可在本宿主评估"档。
73
100
  if (!isAssessableFileVersion(formatVersion)) {
74
- return unassessableResult({ header, headerLine, rows, events, frameInfo, baseSeq, formatVersion });
101
+ return unassessableResult({ header, headerLine, rows, events, frameInfo, baseSeq, formatVersion, ignorableWhitelist, archiveRoots });
75
102
  }
76
103
 
77
104
  // ── Z · 帧结构 ─────────────────────────────────────────────────────────
@@ -99,8 +126,8 @@ export function validateSessionLog(log, opts = {}) {
99
126
  if (header.type !== 'session') {
100
127
  violations.push(violation('H1', { lineNo: headerLine }, `首行 type 必须为 "session"(实际 ${String(header.type)})`));
101
128
  }
102
- if (![0, 1, 2, 3].includes(header.version)) {
103
- violations.push(violation('H2', { lineNo: headerLine }, `header.version 未知(实际 ${String(header.version)})——已知 0/1/2/3;未知版本按 0 处理会误判,请先确认格式`));
129
+ if (![0, 1, 2, 3, 4].includes(header.version)) {
130
+ violations.push(violation('H2', { lineNo: headerLine }, `header.version 未知(实际 ${String(header.version)})——已知 0/1/2/3/4;未知版本按 0 处理会误判,请先确认格式`));
104
131
  }
105
132
  if (typeof header.id !== 'string' || header.id === '') {
106
133
  violations.push(violation('H2', { lineNo: headerLine }, 'header.id 必须为非空字符串'));
@@ -108,8 +135,8 @@ export function validateSessionLog(log, opts = {}) {
108
135
  if (!Number.isSafeInteger(header.createdAt) || header.createdAt < 0) {
109
136
  violations.push(violation('H2', { lineNo: headerLine }, 'header.createdAt 必须为非负安全整数'));
110
137
  }
111
- if (header.cwd !== undefined && (typeof header.cwd !== 'string' || !header.cwd.startsWith('/'))) {
112
- violations.push(violation('H2', { lineNo: headerLine }, 'header.cwd 若存在必须为绝对路径'));
138
+ if (header.cwd !== undefined && !isAbsoluteLogPath(header.cwd)) {
139
+ violations.push(violation('H2', { lineNo: headerLine }, 'header.cwd 若存在必须为绝对路径(POSIX 或 Windows 形态)'));
113
140
  }
114
141
  if (header.origin !== undefined && header.origin !== 'subagent') {
115
142
  violations.push(violation('H2', { lineNo: headerLine }, `header.origin 只能为 "subagent"(实际 ${String(header.origin)})`));
@@ -132,6 +159,17 @@ export function validateSessionLog(log, opts = {}) {
132
159
  }
133
160
  }
134
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
+
135
173
  // ── E · 事件信封 + seq 连续性 ──────────────────────────────────────────
136
174
  let expectedSeq = baseSeq;
137
175
  let seqBroken = false;
@@ -192,6 +230,10 @@ export function validateSessionLog(log, opts = {}) {
192
230
  violations.push(...pluginViolations(event, loc));
193
231
  }
194
232
 
233
+ // ── P5 · carrier 两段配对(0.3.19 · 最小集 ④;**读侧容错**)──────────────
234
+ // 读侧两种真实写法都认:① 现役 [审计段 seq, ...];② 早期 [区间起点, ...](不引用审计段)。
235
+ violations.push(...carrierPairingViolations(events, { version: formatVersion }));
236
+
195
237
  // ── C · 并发(仅当出现 seq 破坏时给出解释性告警)─────────────────────
196
238
  if (seqBroken) {
197
239
  violations.push(violation('C1', { lineNo: null }, 'seq 缺口/倒退是多写入者(≥2 个 Host 进程共享同一 session 目录)并发写的典型后果;离线体检无法观测竞态本身,但此痕迹需人工核查(N6)'));
@@ -200,7 +242,16 @@ export function validateSessionLog(log, opts = {}) {
200
242
  // ── G · 迁移预检(**独立维度**:官方升级路径会不会拒;不进 ok/verdict)──────
201
243
  // 官方把 v0/v1/v2 升到当前格式时的规则集比本工具的"读取/折叠"规则集更严:本工具判
202
244
  // ok/compactable **不代表**官方迁移会接受。这里只加 migration 层 warning(见 contracts G1/G2)。
203
- 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);
204
255
 
205
256
  // ── 汇总 ───────────────────────────────────────────────────────────────
206
257
  violations.sort((a, b) => (a.seq ?? -1) - (b.seq ?? -1) || (a.lineNo ?? -1) - (b.lineNo ?? -1));
@@ -223,6 +274,10 @@ export function validateSessionLog(log, opts = {}) {
223
274
  fileVersion: formatVersion,
224
275
  hostMaxFileVersion: HOST_MAX_FILE_VERSION,
225
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,
226
281
  };
227
282
 
228
283
  const result = {
@@ -231,6 +286,10 @@ export function validateSessionLog(log, opts = {}) {
231
286
  violations,
232
287
  summary,
233
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 },
234
293
  };
235
294
  // 版本支持面(2026-09-14 用户要求第 1 条):宿主版本 vs 测试基线 + 被检文件格式版本,
236
295
  // 给出 warnings/readOnly。只读档由入口(prewrite/fix)强制执行。
@@ -251,7 +310,7 @@ export function validateSessionLog(log, opts = {}) {
251
310
  * 里列出。**ok 固定 false**(不认证),但 `structuralOk` 单独给出结构层结论——
252
311
  * 语义是"本宿主评估不了",不是"日志坏了"。
253
312
  */
254
- function unassessableResult({ header, headerLine, rows, events, frameInfo, baseSeq, formatVersion }) {
313
+ function unassessableResult({ header, headerLine, rows, events, frameInfo, baseSeq, formatVersion, archiveRoots }) {
255
314
  const violations = [];
256
315
  const cap = hostCapability();
257
316
  const notAssessable = {
@@ -273,10 +332,10 @@ function unassessableResult({ header, headerLine, rows, events, frameInfo, baseS
273
332
  violations.push(violation('H1', { lineNo: headerLine }, '首行不是合法 JSON —— 整个会话不可读'));
274
333
  } else {
275
334
  if (header.type !== 'session') violations.push(violation('H1', { lineNo: headerLine }, `首行 type 必须为 "session"(实际 ${String(header.type)})`));
276
- if (![0, 1, 2, 3].includes(header.version)) violations.push(violation('H2', { lineNo: headerLine }, `header.version 未知(实际 ${String(header.version)})`));
335
+ if (![0, 1, 2, 3, 4].includes(header.version)) violations.push(violation('H2', { lineNo: headerLine }, `header.version 未知(实际 ${String(header.version)})`));
277
336
  if (typeof header.id !== 'string' || header.id === '') violations.push(violation('H2', { lineNo: headerLine }, 'header.id 必须为非空字符串'));
278
337
  if (!Number.isSafeInteger(header.createdAt) || header.createdAt < 0) violations.push(violation('H2', { lineNo: headerLine }, 'header.createdAt 必须为非负安全整数'));
279
- if (header.cwd !== undefined && (typeof header.cwd !== 'string' || !header.cwd.startsWith('/'))) violations.push(violation('H2', { lineNo: headerLine }, 'header.cwd 若存在必须为绝对路径'));
338
+ if (header.cwd !== undefined && !isAbsoluteLogPath(header.cwd)) violations.push(violation('H2', { lineNo: headerLine }, 'header.cwd 若存在必须为绝对路径(POSIX 或 Windows 形态)'));
280
339
  if (header.origin !== undefined && header.origin !== 'subagent') violations.push(violation('H2', { lineNo: headerLine }, `header.origin 只能为 "subagent"(实际 ${String(header.origin)})`));
281
340
  }
282
341
  if (header !== null && events.length === 0) violations.push(violation('Z3', { lineNo: headerLine }, '会话文件无任何事件(仅 header)——异常空会话'));
@@ -305,6 +364,12 @@ function unassessableResult({ header, headerLine, rows, events, frameInfo, baseS
305
364
  violations.push(...inboxReplayViolations(events, header));
306
365
  violations.push(...toolPairingViolations(events));
307
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);
308
373
  for (const { event, lineNo } of events) {
309
374
  const loc = { seq: event.seq, lineNo, eventType: event.type };
310
375
  violations.push(...engineViolations(event, loc));
@@ -338,8 +403,13 @@ function unassessableResult({ header, headerLine, rows, events, frameInfo, baseS
338
403
  fileVersion: formatVersion,
339
404
  hostMaxFileVersion: HOST_MAX_FILE_VERSION,
340
405
  assessable: false,
406
+ seedLength: Object.hasOwn(header ?? {}, 'seedLength') ? header.seedLength : null,
407
+ ignorableDrops: { registered: 0, unregistered: 0 },
408
+ archiveVerdict: archive.verdict,
341
409
  },
342
410
  surface: null,
411
+ archive,
412
+ ignorableDrops: { registered: [], unregistered: [] },
343
413
  };
344
414
  result.support = detectSupport({ header, events });
345
415
  result.probes = hostProbes();
@@ -405,6 +475,7 @@ export function migrationVerdict(result) {
405
475
  'G1 v0 源:subagent/descriptor.data.version !== 3',
406
476
  'G2 v0 源:事件类型不在官方 v0 dispositions 内(含 ignorable:true)',
407
477
  'G3 v0 源:session/title 系列 messageSeqs 必须引用更早的人类 user/message(含"空 ⟺ 用户标题")',
478
+ 'G4 v0 源:未知历史事件 + ignorable:true = 声明式可忽略(已登记白名单 ⇒ acceptedDrop,不硬拒;未登记 ⇒ warning 且仍阻断)',
408
479
  ],
409
480
  uncovered: [
410
481
  // 2026-09-15:`turn/start` 试做后在**真实语料**上被判定为"应用对象错"——
@@ -418,15 +489,31 @@ export function migrationVerdict(result) {
418
489
  'stored log corrupt(SessionFormatError)',
419
490
  'v0→v1 对其余事件的形状拒绝',
420
491
  'turn/end 无匹配 open turn / open step 穿越 / 未解析 tool / open compaction 穿越(官方同一状态机的其余分支)',
492
+ 'v3→v4 迁移(tool-result 提升为 role tool、plugin source 改名、父会话 subagent 目录补写、中断轮闭合;官方 dsh-session-format-v3-to-v4)',
421
493
  ],
422
494
  note: '未覆盖 ≠ 通过:本维度只对 implemented 三条负责。官方判据版本:@deepseek-ai/dsh-session-format-v0-to-v1@0.1.5-rc.2 + v1-to-v2@0.1.5-rc.2',
423
495
  };
424
496
  if (result?.assessable === false) {
425
- 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
+ }
426
511
  }
427
- 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));
428
515
  if (fileVersion !== null && fileVersion === MIGRATION_TARGET_VERSION) {
429
- 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}),无需迁移` };
430
517
  }
431
518
  const applies = fileVersion !== null && fileVersion < MIGRATION_TARGET_VERSION;
432
519
  return {
@@ -437,6 +524,7 @@ export function migrationVerdict(result) {
437
524
  targetFileVersion: MIGRATION_TARGET_VERSION,
438
525
  hostMaxFileVersion: HOST_MAX_FILE_VERSION,
439
526
  blocked,
527
+ acceptedDrops,
440
528
  coverage,
441
529
  // 2026-09-14:待迁移文件(applies=true)**只**被 2 条 G 规则覆盖,
442
530
  // 另有 6 类官方迁移规则未覆盖 ⇒ 评估范围只能是 "partial"。工具无法逐文件知道
@@ -11,7 +11,7 @@
11
11
  *
12
12
  * 三条运行时规则("不闷着按旧规则判"):
13
13
  * 1. 宿主 `@deepseek-ai/dsh-session` 版本**比基线新** ⇒ 明确告警(规则集未在该版本上验证);
14
- * 2. 被检**会话文件格式版本**不在已知集合 {0,1,2,3} 内 ⇒ 报"未验证格式"并**按只读处理**
14
+ * 2. 被检**会话文件格式版本**不在已知集合 {0,1,2,3,4} 内 ⇒ 报"未验证格式"并**按只读处理**
15
15
  * (不做写入前判定、不做修复);
16
16
  * 3. 两者都可解析时,给出一行可核对的摘要(宿主 / 文件格式 / 基线)。
17
17
  */
@@ -23,16 +23,17 @@ import { hostPackageVersion, resolveFormatVersionDetailed, HOST_MAX_FILE_VERSION
23
23
  */
24
24
  export const TESTED_BASELINE = Object.freeze({
25
25
  hostPackage: '@deepseek-ai/dsh-session',
26
- /** 开发机与 CI 实装宿主版本(devDependency 同值)。 */
27
- hostVersion: '0.1.5-rc.1',
26
+ /** 开发机与 CI 实装宿主版本(devDependency 同值;= DSH Desktop 0.2.0 内置版本)。 */
27
+ hostVersion: '0.2.0-rc.2',
28
28
  /** 声明的 peer 范围(允许安装,但未逐一验证)。 */
29
- peerRange: '^0.1.0-rc.7 || ^0.1.5-rc.1',
29
+ peerRange: '^0.1.0-rc.7 || ^0.1.5-rc.1 || ^0.2.0-rc.1',
30
30
  /** 会话格式版本基线(= 宿主 SESSION_FORMAT_VERSION)。 */
31
- sessionFormatVersion: 3,
31
+ sessionFormatVersion: 4,
32
32
  /** 已知/受支持的会话格式版本(0/1/2 由本包 vendored 词表 + 本地等价折叠支持)。 */
33
- knownFormatVersions: Object.freeze([0, 1, 2, 3]),
33
+ knownFormatVersions: Object.freeze([0, 1, 2, 3, 4]),
34
34
  note: '旧格式(0/1/2)由本包自带的 vendored 词表与 legacyFoldSurface 支持,与宿主版本无关;'
35
- + 'v3 用运行时词表/官方 foldSurface ⇒ 需要宿主 SESSION_FORMAT_VERSION ≥ 3。',
35
+ + 'v3/v4 用运行时词表/官方 foldSurface ⇒ 需要宿主 SESSION_FORMAT_VERSION ≥ 该版本;'
36
+ + 'v4 消息形状(tool/result role tool、system-prompt source、developer/message)按文件版本单独判定。',
36
37
  });
37
38
 
38
39
  /**
package/lib/vocab.js CHANGED
@@ -30,8 +30,8 @@
30
30
  * `RELEASED_V0_EVENT_DISPOSITIONS`,51 条,逐条比对零差异);
31
31
  * - 文件版本 2 → (v0 词表 − `assistant/chunk`) ∪ {`assistant/attempt`}(官方 v2 dispositions
32
32
  * 构造式实测:chunk 被显式剔除;见 `V2_EVENT_TYPES` 注释);
33
- * - 文件版本 3 → **运行时导出**的 `KNOWN_SESSION_EVENT_TYPES`;
34
- * - 折叠终验:v0/v1/v2 → `legacyFoldSurface`;v3 → 运行时 `foldSurface`。
33
+ * - 文件版本 3/4 → **运行时导出**的 `KNOWN_SESSION_EVENT_TYPES`(v4 需宿主 `SESSION_FORMAT_VERSION >= 4`);
34
+ * - 折叠终验:v0/v1/v2 → `legacyFoldSurface`;v3/v4 → 运行时 `foldSurface`。
35
35
  */
36
36
  import { foldSurface, KNOWN_SESSION_EVENT_TYPES, SESSION_FORMAT_VERSION } from '@deepseek-ai/dsh-session';
37
37
  import { createRequire } from 'node:module';
@@ -100,7 +100,9 @@ export function isLegacyFormat(version) {
100
100
  * 2. `system/message`:官方 v3 才有的 surface 类型(V0/V2 词表均无);
101
101
  * 3. `assistant/chunk`:顶层 chunk 行只在旧格式出现(v2 dispositions 已剔除它);
102
102
  * 4. `assistant/attempt`:v2 与 v3 都有(v0 无)⇒ 只能推出"≥2"。
103
- * 返回 3 / 2 / 0。**这是启发式**;有 `header.version` 或显式 `formatVersion` 时优先用它们。
103
+ * v4 判别特征(v3→v4 迁移逐项改写,v3 不可能出现)先于以上各条:`developer/message` 事件、
104
+ * role 为 `tool` 的 `tool/result`、source.kind 为 `system-prompt` 的 `system/message`。
105
+ * 返回 4 / 3 / 2 / 0。**这是启发式**;有 `header.version` 或显式 `formatVersion` 时优先用它们。
104
106
  */
105
107
  export function inferFormatVersion(events = []) {
106
108
  return inferFormatVersionDetailed(events) ?? 0;
@@ -109,7 +111,7 @@ export function inferFormatVersion(events = []) {
109
111
  /**
110
112
  * 同上,但**没有判别证据时返回 `null`**(而不是假装 0)——供版本支持面报"未验证格式"
111
113
  * (2026-09-14 用户要求第 1 条:无法识别格式 ⇒ 报未验证并按只读处理)。
112
- * @returns {3|2|0|null} 版本号;null = 事件里没有任何判别特征
114
+ * @returns {4|3|2|0|null} 版本号;null = 事件里没有任何判别特征
113
115
  */
114
116
  export function inferFormatVersionDetailed(events = []) {
115
117
  let sawLegacyReplace = false;
@@ -117,6 +119,7 @@ export function inferFormatVersionDetailed(events = []) {
117
119
  let sawSystemMessage = false;
118
120
  let sawChunk = false;
119
121
  let sawAttempt = false;
122
+ let sawV4Shape = false;
120
123
  for (const event of events) {
121
124
  if (!event || typeof event !== 'object') continue;
122
125
  const op = event.surfaceOp;
@@ -124,10 +127,15 @@ export function inferFormatVersionDetailed(events = []) {
124
127
  if (Object.hasOwn(op, 'startSeq') || Object.hasOwn(op, 'endSeq')) sawModernReplace = true;
125
128
  else if (Object.hasOwn(op, 'start') || Object.hasOwn(op, 'end')) sawLegacyReplace = true;
126
129
  }
127
- if (event.type === 'system/message') sawSystemMessage = true;
130
+ if (event.type === 'system/message') {
131
+ sawSystemMessage = true;
132
+ if (event.data?.message?.source?.kind === 'system-prompt') sawV4Shape = true;
133
+ } else if (event.type === 'developer/message') sawV4Shape = true;
134
+ else if (event.type === 'tool/result' && event.data?.message?.role === 'tool') sawV4Shape = true;
128
135
  else if (event.type === 'assistant/chunk') sawChunk = true;
129
136
  else if (event.type === 'assistant/attempt') sawAttempt = true;
130
137
  }
138
+ if (sawV4Shape) return 4;
131
139
  if (sawModernReplace || sawSystemMessage) return 3;
132
140
  if (sawLegacyReplace) return sawAttempt ? 2 : 0;
133
141
  if (sawAttempt) return 2;
@@ -149,7 +157,7 @@ export function resolveFormatVersionDetailed({ formatVersion, header, events } =
149
157
  }
150
158
  const inferred = inferFormatVersionDetailed(events ?? []);
151
159
  if (inferred !== null) {
152
- return { version: inferred, source: 'inferred', evidence: 'replace 字段名/system/message/assistant/{chunk,attempt} 形状' };
160
+ return { version: inferred, source: 'inferred', evidence: 'replace 字段名/system/message/developer/message/tool/result role/assistant/{chunk,attempt} 形状' };
153
161
  }
154
162
  return { version: 0, source: 'default', evidence: null };
155
163
  }
@@ -179,12 +187,13 @@ export const HOST_MAX_FILE_VERSION = Number.isSafeInteger(SESSION_FORMAT_VERSION
179
187
  : 0;
180
188
 
181
189
  /**
182
- * 官方迁移链的目标格式版本(固定 3)——**不是宿主版本**。
183
- * 依据:App 2.0.9 / `@deepseek-ai/dsh-session-format-*@0.1.5-rc.2` 的迁移链是 v0→v1→v2→v3,
184
- * `SESSION_FORMAT_VERSION = 3`。迁移预检问的是"升到目标格式会不会被拒",与当前宿主能不能
185
- * 评估 v3 **无关**(rc.7 宿主上同样可以预检一个 v0 文件将来能否升级)。
190
+ * 官方迁移链的目标格式版本——**下限 3,不随旧宿主降级**。
191
+ * 依据:App 2.0.9 / `@deepseek-ai/dsh-session-format-*@0.1.5-rc.2` 的迁移链是 v0→v1→v2→v3
192
+ * (`SESSION_FORMAT_VERSION = 3`);DSH 0.2.x 追加 `dsh-session-format-v3-to-v4`(`= 4`)。
193
+ * 迁移预检问的是"升到目标格式会不会被拒",与当前宿主能不能评估 v3 **无关**(rc.7 宿主上同样
194
+ * 可以预检一个 v0 文件将来能否升级),所以旧宿主仍按 3;带 v3→v4 迁移的宿主上目标随之为 4。
186
195
  */
187
- export const MIGRATION_TARGET_VERSION = 3;
196
+ export const MIGRATION_TARGET_VERSION = Math.max(3, HOST_MAX_FILE_VERSION);
188
197
 
189
198
  let hostVersionMemo;
190
199
  /** 宿主 `@deepseek-ai/dsh-session` 的包版本(用于输出/报告;不可解析时给未知标记,不抛)。 */
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.17",
4
+ "version": "0.3.19",
5
5
  "packageManager": "pnpm@11.7.0",
6
6
  "type": "module",
7
7
  "main": "lib/index.js",
@@ -59,10 +59,11 @@
59
59
  "node": ">=22"
60
60
  },
61
61
  "peerDependencies": {
62
- "@deepseek-ai/dsh-session": "^0.1.0-rc.7 || ^0.1.5-rc.1"
62
+ "@deepseek-ai/dsh-session": "^0.1.0-rc.7 || ^0.1.5-rc.1 || ^0.2.0-rc.1"
63
63
  },
64
64
  "devDependencies": {
65
- "@deepseek-ai/dsh-session": "0.1.5-rc.1",
65
+ "@deepseek-ai/cordis": "4.0.4",
66
+ "@deepseek-ai/dsh-session": "0.2.0-rc.2",
66
67
  "esbuild": "0.28.2",
67
68
  "vitest": "4.1.11"
68
69
  }