dsh-log-contract 0.3.17 → 0.3.18

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/docs/CONTRACTS.md CHANGED
@@ -14,8 +14,8 @@
14
14
  > T3/T4 = 渲染层白屏事故复盘,T5 = malformed turn/end 事故复盘。
15
15
  >
16
16
  > **版本支持基线(本规则集验证过的版本;权威常量见 `lib/version-support.js` 的 TESTED_BASELINE)**:
17
- > 宿主 `@deepseek-ai/dsh-session@0.1.5-rc.1` | 会话格式 **v3**(`SESSION_FORMAT_VERSION = 3`)|
18
- > 声明范围 `^0.1.0-rc.7 || ^0.1.5-rc.1`(可安装 ≠ 逐个验证)| 已知格式 0/1/2/3
17
+ > 宿主 `@deepseek-ai/dsh-session@0.2.0-rc.2` | 会话格式 **v4**(`SESSION_FORMAT_VERSION = 4`)|
18
+ > 声明范围 `^0.1.0-rc.7 || ^0.1.5-rc.1 || ^0.2.0-rc.1`(可安装 ≠ 逐个验证)| 已知格式 0/1/2/3/4
19
19
  > (0–2 由本包自带 vendored 词表 + `legacyFoldSurface` 支持,与宿主版本无关)。
20
20
  > **未验证版本**:宿主比基线新 → 运行时告警;文件格式未知/无法识别 → 报"未验证格式"并**按只读处理**
21
21
  > (`prewrite`/`fix` 拒绝,退出码 3);文件版本 > 宿主上限 → `not-assessable`(不是 broken)。
@@ -54,7 +54,7 @@
54
54
  | T5 | error | engine | turn/end 必须带 data.reason.kind |
55
55
  | E7 | warning | persistence | ignorable 未知 type 合法性(带被忽略标记的未知事件须有消费者) |
56
56
  | E8 | warning | persistence | 事件信封键白名单(多余键:seed/restore 路径会拒) |
57
- | E9 | error | persistence | system/message 必须带 plugin source |
57
+ | E9 | error | persistence | system/message 的 source 契约(v3 plugin / v4 system-prompt) |
58
58
  | E10 | error | persistence | request/header 的 data.header 字段约束 |
59
59
  | Z3 | warning | framing | 空会话文件(有 header 无事件)显式报出 |
60
60
  | P3 | warning | plugin | tool/call ↔ tool/result 配对完整性(考古 B1) |
@@ -84,8 +84,8 @@
84
84
  ### H2 — header 版本与必填字段
85
85
 
86
86
  - **层级**: persistence | **严重度**: error
87
- - **出处**: @deepseek-ai/dsh-session lib/index.js:1110-1125;已知格式版本 0/1/2/3(App 2.0.9 内置 v0→v1→v2→v3 迁移,SESSION_FORMAT_VERSION=3)
88
- - **契约**: header.version 必须为已知受支持版本(0/1/2/3);未知版本报 H2。id 为字符串;createdAt 为非负安全整数;cwd 若存在必须为绝对路径;origin 只能为 "subagent"。
87
+ - **出处**: @deepseek-ai/dsh-session lib/index.js:1110-1125;已知格式版本 0/1/2/3/4(App 2.0.9 内置 v0→v1→v2→v3 迁移,SESSION_FORMAT_VERSION=3;DSH 0.2.x 追加 v3→v4,SESSION_FORMAT_VERSION=4)
88
+ - **契约**: header.version 必须为已知受支持版本(0/1/2/3/4);未知版本报 H2。id 为字符串;createdAt 为非负安全整数;cwd 若存在必须为绝对路径(POSIX 与 Windows 盘符/UNC 形态均接受);origin 只能为 "subagent"。
89
89
 
90
90
  ### R1 — 每行必须是合法 JSON
91
91
 
@@ -150,14 +150,14 @@
150
150
  ### E6 — 消息类事件消息形状
151
151
 
152
152
  - **层级**: persistence | **严重度**: error
153
- - **出处**: @deepseek-ai/dsh-session lib/index.js:1242-1266 (assertMessageEventShape)
154
- - **契约**: user/message、assistant/message、tool/result 必须携带具名 message(非空 id、正确 role、合法 source、content 数组;assistant 需 model source,tool/result 需 tool source 且 toolCallId 匹配)。
153
+ - **出处**: @deepseek-ai/dsh-session lib/index.js:1242-1266 (assertMessageEventShape);v4:dsh-session@0.2.0-rc.2 src/index.ts:331-381
154
+ - **契约**: user/message、assistant/message、tool/result 必须携带具名 message(非空 id、正确 role、合法 source、content 数组;assistant 需 model source,tool/result 需 tool source 且 toolCallId 匹配)。v0–v3:tool/result role 为 user 且恰含一个 tool-result 块;v4:tool/result role 为 tool、不得含 tool-result 包装块、message.toolCallId 等于 source.callId,新增 developer/message(role developer),且任何消息 source.kind 不得为 plugin。
155
155
 
156
156
  ### S1 — surface 候选类型必须携带 surfaceOp
157
157
 
158
158
  - **层级**: persistence | **严重度**: error
159
159
  - **出处**: @deepseek-ai/dsh-session lib/index.js:312-317 (surfaceOpOf)
160
- - **契约**: user/message、assistant/message、tool/result 是 surface-eligible 类型,缺 surfaceOp 即违反契约。
160
+ - **契约**: user/message、assistant/message、tool/result(v3 起含 system/message,v4 起含 developer/message)是 surface-eligible 类型,缺 surfaceOp 即违反契约。
161
161
 
162
162
  ### S2 — 非 surface 类型不得携带 surface 元数据
163
163
 
@@ -175,7 +175,7 @@
175
175
 
176
176
  - **层级**: persistence | **严重度**: error
177
177
  - **出处**: @deepseek-ai/dsh-session lib/index.js:300-303 (isReplaceOp)、:339-350 (replacementRange)
178
- - **契约**: replace 必须是精确的 {op:"replace", start, end};start/end 必须存在于当前 surface 节点且 startIdx ≤ endIdx。
178
+ - **契约**: replace 必须是精确的 {op:"replace", start, end}(v0–v2)或 {op:"replace", startSeq, endSeq}(v3/v4);端点必须存在于当前 surface 节点且 startIdx ≤ endIdx。
179
179
 
180
180
  ### S5 — replace 的 sourceEventSeqs 必须完整覆盖被替换节点
181
181
 
@@ -243,11 +243,11 @@
243
243
  - **出处**: @deepseek-ai/dsh-session@0.1.5-rc.1 lib/index.js:849-861(assertSessionEventEnvelope)+ :1063-1068(唯一调用点=seed 路径);load 路径容忍见行为探针 p5
244
244
  - **契约**: 事件对象只允许 7 个信封键(type/seq/time/data/surfaceOp/sourceEventSeqs/ignorable)。实测反例指出"宿主拒、旧契约 0 违规";行为探针进一步订正口径:**load 路径容忍、seed/restore 路径拒** ⇒ warning。
245
245
 
246
- ### E9 — system/message 必须带 plugin source
246
+ ### E9 — system/message 的 source 契约(v3 plugin / v4 system-prompt)
247
247
 
248
248
  - **层级**: persistence | **严重度**: error
249
- - **出处**: @deepseek-ai/dsh-session@0.1.5-rc.1 lib/index.js:942-944("must have plugin source");角色表 :917-926
250
- - **契约**: v3 新增的 system/message:role 必须为 system,source.kind 必须为 plugin 且 plugin 非空。实测(反例):source.kind='user' 宿主拒、旧契约 0 违规 ⇒ 漏检。
249
+ - **出处**: @deepseek-ai/dsh-session@0.1.5-rc.1 lib/index.js:942-944("must have plugin source");角色表 :917-926;v4:dsh-session@0.2.0-rc.2 src/index.ts:360-364("must have system-prompt source")
250
+ - **契约**: v3 新增的 system/message:role 必须为 system,source.kind 必须为 plugin 且 plugin 非空。实测(反例):source.kind='user' 宿主拒、旧契约 0 违规 ⇒ 漏检。v4(v3→v4 迁移把 @deepseek-ai/dsh-system-prompt 改写为生产者自有 kind):source.kind 必须为 system-prompt。
251
251
 
252
252
  ### E10 — request/header 的 data.header 字段约束
253
253
 
package/lib/checks.js CHANGED
@@ -15,10 +15,13 @@ import { ruleById } from './contracts.js';
15
15
  export const SURFACE_TYPES = new Set(['user/message', 'assistant/message', 'tool/result']);
16
16
  /** v3 新增 `system/message`(官方 `SURFACE_EVENT_TYPES`,0.1.5 `lib/index.js:149-154`)。 */
17
17
  export const MODERN_SURFACE_TYPES = new Set([...SURFACE_TYPES, 'system/message']);
18
+ /** v4 新增 `developer/message`(官方 `SURFACE_EVENT_TYPES`,dsh-session@0.2.0-rc.2 `src/surface.ts:50-56`)。 */
19
+ export const V4_SURFACE_TYPES = new Set([...MODERN_SURFACE_TYPES, 'developer/message']);
18
20
  export const CHUNK_ROW_TYPES = new Set(['text-chunks', 'reasoning-chunks', 'tool-call-chunks']);
19
21
 
20
- /** 当前文件版本适用的 surface 候选类型集(v3 起含 system/message)。version = 被检文件版本。 */
22
+ /** 当前文件版本适用的 surface 候选类型集(v3 起含 system/message,v4 起含 developer/message)。version = 被检文件版本。 */
21
23
  export function currentSurfaceTypes(version) {
24
+ if (version >= 4) return V4_SURFACE_TYPES;
22
25
  return version >= 3 ? MODERN_SURFACE_TYPES : SURFACE_TYPES;
23
26
  }
24
27
  export const MARKER_PREFIXES = ['retrace', 'message-editor'];
@@ -96,15 +99,28 @@ export function envelopeViolations(event, loc, version) {
96
99
  }
97
100
  }
98
101
  }
99
- out.push(...messageShapeViolations(event, loc));
102
+ out.push(...messageShapeViolations(event, loc, version));
100
103
  return out;
101
104
  }
102
105
 
103
106
  /** 宿主信封键白名单(assertSessionEventEnvelope,dsh-session@0.1.5-rc.1 lib/index.js:852-861)。 */
104
107
  export const ENVELOPE_ALLOWED_KEYS = new Set(['type', 'seq', 'time', 'data', 'surfaceOp', 'sourceEventSeqs', 'ignorable']);
105
108
 
106
- /** 镜像官方 assertMessageEventShape(lib/index.js:1242-1266)。 */
107
- export function messageShapeViolations(event, loc) {
109
+ /** v4 消息类事件 → 期望 role(dsh-session@0.2.0-rc.2 `MESSAGE_ROLE_BY_TYPE`,`src/index.ts:323-329`)。 */
110
+ const V4_MESSAGE_ROLE_BY_TYPE = {
111
+ 'system/message': 'system',
112
+ 'developer/message': 'developer',
113
+ 'user/message': 'user',
114
+ 'assistant/message': 'assistant',
115
+ 'tool/result': 'tool',
116
+ };
117
+
118
+ /**
119
+ * 镜像官方 assertMessageEventShape(lib/index.js:1242-1266)。**按被检文件版本**择路:
120
+ * v0–v3 → 旧形状(下方原逻辑);v4 → `v4MessageShapeViolations`。
121
+ */
122
+ export function messageShapeViolations(event, loc, version) {
123
+ if (version >= 4) return v4MessageShapeViolations(event, loc);
108
124
  const type = event.type;
109
125
  // 把 v3 新增的 `system/message` 纳入形状检查(MESSAGE_ROLE_BY_TYPE:system/message → system,
110
126
  // dsh-session@0.1.5-rc.1 lib/index.js:917-926;source 要求 :942-944)。旧实现只查 user/assistant/tool
@@ -160,6 +176,77 @@ export function messageShapeViolations(event, loc) {
160
176
  return out;
161
177
  }
162
178
 
179
+ /**
180
+ * v4 消息形状。两层一手依据:
181
+ * - 运行时 load 路径:dsh-session@0.2.0-rc.2 `assertMessageEventShape`(`src/index.ts:331-381`)——
182
+ * role 表、system-prompt source、model source、tool source + `toolCallId` 匹配;
183
+ * - 文件读取路径:`dsh-session-format-v3-to-v4` 原生 v4 准入(`src/tool-role.ts:89-109`、
184
+ * `src/message-sources.ts:9`)——残留 `tool-result` 包装块、非布尔 `isError`、`data.error` 而
185
+ * `isError !== true`、`source.kind === 'plugin'` 一律 SessionFormatError ⇒ 会话从盘上读不回来。
186
+ * `adoptSessionEvent` 不查这几条,所以只看运行时会漏掉"写得进、读不回"的形状。
187
+ *
188
+ * 与 v3 的差异(v3→v4 迁移 `tool-role.ts` / `sources.ts` 的逐项改写):
189
+ * - 新增 `developer/message`(role `developer`);
190
+ * - `tool/result`:role `tool`;去掉 `tool-result` 包装块,content 直接是结果数组;
191
+ * `message.toolCallId` 必须等于 `source.callId`;`isError` 若存在必须为布尔;
192
+ * - `system/message`:source.kind 必须为 `system-prompt`(v3 是 plugin 包装);
193
+ * - 任何消息的 source.kind 都不得为 `plugin`(v4 把插件包装改写成生产者自有 kind)。
194
+ */
195
+ function v4MessageShapeViolations(event, loc) {
196
+ const type = event.type;
197
+ const expectedRole = V4_MESSAGE_ROLE_BY_TYPE[type];
198
+ if (expectedRole === undefined) return [];
199
+ const out = [];
200
+ const data = event.data;
201
+ const record = typeof data === 'object' && data !== null ? data : undefined;
202
+ const message = type === 'user/message' ? record : record?.message;
203
+ const shape = () => `(seq ${event.seq})消息形状`;
204
+ if (typeof message !== 'object' || message === null) {
205
+ out.push(violation('E6', loc, `${shape()}:缺少 message 对象`));
206
+ return out;
207
+ }
208
+ if (typeof message.id !== 'string' || message.id === '') {
209
+ out.push(violation('E6', loc, `${shape()}:id 必须为非空字符串`));
210
+ }
211
+ if (message.role !== expectedRole) {
212
+ out.push(violation('E6', loc, `${shape()}:role 必须为 "${expectedRole}",实际 ${String(message.role)}`));
213
+ }
214
+ const source = message.source;
215
+ if (typeof source !== 'object' || source === null || typeof source.kind !== 'string' || source.kind === '') {
216
+ out.push(violation('E6', loc, `${shape()}:source.kind 缺失或非法`));
217
+ } else if (source.kind === 'plugin') {
218
+ out.push(violation('E6', loc, `${shape()}:v4 不再接受 plugin source(kind==='plugin')——v3→v4 迁移把它改写为生产者自有 kind`));
219
+ }
220
+ if (!Array.isArray(message.content)) {
221
+ out.push(violation('E6', loc, `${shape()}:content 必须为数组`));
222
+ }
223
+ if (type === 'assistant/message') {
224
+ if (source?.kind !== 'model' || typeof source.provider !== 'string' || source.provider === '' || typeof source.model !== 'string' || source.model === '') {
225
+ out.push(violation('E6', loc, `${shape()}:assistant/message 必须带 model source(provider/model 非空)`));
226
+ }
227
+ }
228
+ if (type === 'system/message' && source?.kind !== 'system-prompt') {
229
+ out.push(violation('E9', loc, `${shape()}:system/message 必须带 system-prompt source(kind==='system-prompt')——dsh-session@0.2.0-rc.2 src/index.ts:360-364`));
230
+ }
231
+ if (type === 'tool/result') {
232
+ if (source?.kind !== 'tool' || typeof source.callId !== 'string' || source.callId === '') {
233
+ out.push(violation('E6', loc, `${shape()}:tool/result 必须带 tool source(callId 非空)`));
234
+ } else if (message.toolCallId !== source.callId) {
235
+ out.push(violation('E6', loc, `${shape()}:message.toolCallId 与 source.callId 不匹配`));
236
+ }
237
+ if (Array.isArray(message.content) && message.content.some((b) => typeof b === 'object' && b !== null && b.type === 'tool-result')) {
238
+ out.push(violation('E6', loc, `${shape()}:v4 tool/result 不得再含 tool-result 包装块(content 直接是结果数组)`));
239
+ }
240
+ if (message.isError !== undefined && typeof message.isError !== 'boolean') {
241
+ out.push(violation('E6', loc, `${shape()}:isError 若存在必须为布尔`));
242
+ }
243
+ if (record?.error !== undefined && message.isError !== true) {
244
+ out.push(violation('E6', loc, `${shape()}:带 data.error 时 message.isError 必须为 true`));
245
+ }
246
+ }
247
+ return out;
248
+ }
249
+
163
250
  /** replace 操作数精确形状(镜像旧格式 isReplaceOp,lib/index.js:300-303)。 */
164
251
  export function isReplaceOp(op) {
165
252
  return (
package/lib/contracts.js CHANGED
@@ -75,8 +75,8 @@ export const CONTRACT_RULES = [
75
75
  title: 'header 版本与必填字段',
76
76
  layer: LAYER.PERSISTENCE,
77
77
  severity: SEVERITY.ERROR,
78
- source: '@deepseek-ai/dsh-session lib/index.js:1110-1125;已知格式版本 0/1/2/3(App 2.0.9 内置 v0→v1→v2→v3 迁移,SESSION_FORMAT_VERSION=3)',
79
- description: 'header.version 必须为已知受支持版本(0/1/2/3);未知版本报 H2。id 为字符串;createdAt 为非负安全整数;cwd 若存在必须为绝对路径;origin 只能为 "subagent"。',
78
+ source: '@deepseek-ai/dsh-session lib/index.js:1110-1125;已知格式版本 0/1/2/3/4(App 2.0.9 内置 v0→v1→v2→v3 迁移,SESSION_FORMAT_VERSION=3;DSH 0.2.x 追加 v3→v4,SESSION_FORMAT_VERSION=4)',
79
+ description: 'header.version 必须为已知受支持版本(0/1/2/3/4);未知版本报 H2。id 为字符串;createdAt 为非负安全整数;cwd 若存在必须为绝对路径(POSIX 与 Windows 盘符/UNC 形态均接受);origin 只能为 "subagent"。',
80
80
  },
81
81
 
82
82
  // ── R · 存储行 ──────────────────────────────────────────────────────────
@@ -172,8 +172,8 @@ export const CONTRACT_RULES = [
172
172
  title: '消息类事件消息形状',
173
173
  layer: LAYER.PERSISTENCE,
174
174
  severity: SEVERITY.ERROR,
175
- source: '@deepseek-ai/dsh-session lib/index.js:1242-1266 (assertMessageEventShape)',
176
- description: 'user/message、assistant/message、tool/result 必须携带具名 message(非空 id、正确 role、合法 source、content 数组;assistant 需 model source,tool/result 需 tool source 且 toolCallId 匹配)。',
175
+ source: '@deepseek-ai/dsh-session lib/index.js:1242-1266 (assertMessageEventShape);v4:dsh-session@0.2.0-rc.2 src/index.ts:331-381',
176
+ description: 'user/message、assistant/message、tool/result 必须携带具名 message(非空 id、正确 role、合法 source、content 数组;assistant 需 model source,tool/result 需 tool source 且 toolCallId 匹配)。v0–v3:tool/result role 为 user 且恰含一个 tool-result 块;v4:tool/result role 为 tool、不得含 tool-result 包装块、message.toolCallId 等于 source.callId,新增 developer/message(role developer),且任何消息 source.kind 不得为 plugin。',
177
177
  },
178
178
 
179
179
  // ── S · surface 不变量(事故核心层)────────────────────────────────────
@@ -183,7 +183,7 @@ export const CONTRACT_RULES = [
183
183
  layer: LAYER.PERSISTENCE,
184
184
  severity: SEVERITY.ERROR,
185
185
  source: '@deepseek-ai/dsh-session lib/index.js:312-317 (surfaceOpOf)',
186
- description: 'user/message、assistant/message、tool/result 是 surface-eligible 类型,缺 surfaceOp 即违反契约。',
186
+ description: 'user/message、assistant/message、tool/result(v3 起含 system/message,v4 起含 developer/message)是 surface-eligible 类型,缺 surfaceOp 即违反契约。',
187
187
  },
188
188
  {
189
189
  id: 'S2',
@@ -207,7 +207,7 @@ export const CONTRACT_RULES = [
207
207
  layer: LAYER.PERSISTENCE,
208
208
  severity: SEVERITY.ERROR,
209
209
  source: '@deepseek-ai/dsh-session lib/index.js:300-303 (isReplaceOp)、:339-350 (replacementRange)',
210
- description: 'replace 必须是精确的 {op:"replace", start, end};start/end 必须存在于当前 surface 节点且 startIdx ≤ endIdx。',
210
+ description: 'replace 必须是精确的 {op:"replace", start, end}(v0–v2)或 {op:"replace", startSeq, endSeq}(v3/v4);端点必须存在于当前 surface 节点且 startIdx ≤ endIdx。',
211
211
  },
212
212
  {
213
213
  id: 'S5',
@@ -307,11 +307,11 @@ export const CONTRACT_RULES = [
307
307
  },
308
308
  {
309
309
  id: 'E9',
310
- title: 'system/message 必须带 plugin source',
310
+ title: 'system/message 的 source 契约(v3 plugin / v4 system-prompt)',
311
311
  layer: LAYER.PERSISTENCE,
312
312
  severity: SEVERITY.ERROR,
313
- source: '@deepseek-ai/dsh-session@0.1.5-rc.1 lib/index.js:942-944("must have plugin source");角色表 :917-926',
314
- description: 'v3 新增的 system/message:role 必须为 system,source.kind 必须为 plugin 且 plugin 非空。实测(反例):source.kind=\'user\' 宿主拒、旧契约 0 违规 ⇒ 漏检。',
313
+ source: '@deepseek-ai/dsh-session@0.1.5-rc.1 lib/index.js:942-944("must have plugin source");角色表 :917-926;v4:dsh-session@0.2.0-rc.2 src/index.ts:360-364("must have system-prompt source")',
314
+ description: 'v3 新增的 system/message:role 必须为 system,source.kind 必须为 plugin 且 plugin 非空。实测(反例):source.kind=\'user\' 宿主拒、旧契约 0 违规 ⇒ 漏检。v4(v3→v4 迁移把 @deepseek-ai/dsh-system-prompt 改写为生产者自有 kind):source.kind 必须为 system-prompt。',
315
315
  candidate: true,
316
316
  },
317
317
  {
@@ -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/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';
@@ -38,6 +39,23 @@ import {
38
39
  wireViolations,
39
40
  } from './checks.js';
40
41
 
42
+ /**
43
+ * `header.cwd` 的"绝对路径"判据 —— **平台感知**(Issue #1)。
44
+ *
45
+ * 旧实现只认 POSIX 的 `/` 前缀 ⇒ Windows 会话的 `C:\…` / `\\server\share\…` 全部误报 H2
46
+ * (体检是离线、跨机只读的:被检日志可能来自任意平台,不能按本机 `process.platform` 判)。
47
+ * 两种形态都接受:
48
+ * - POSIX:`/Users/x`、`/home/x`
49
+ * - Windows 盘符绝对:`C:\Users\x`、`C:/Users/x`
50
+ * - Windows UNC:`\\server\share\x`、`//server/share/x`
51
+ *
52
+ * 反例(仍报 H2):`C:relative`(盘符相对)、`Users/x`、`./x`、空串。
53
+ */
54
+ export function isAbsoluteLogPath(value) {
55
+ if (typeof value !== 'string' || value === '') return false;
56
+ return posixPath.isAbsolute(value) || win32Path.isAbsolute(value);
57
+ }
58
+
41
59
  /** 宿主能力闸触发时**跳过**的规则(v3/被检版本语义相关)——报告里显式列出,避免"静默通过"。 */
42
60
  const VERSION_DEPENDENT_RULES = ['E3', 'E7', 'S1', 'S2', 'S3', 'S4', 'S5', 'S6', 'S7', 'S8', 'W1', 'W2', 'T1', 'T2', 'T3', 'T4', 'T5', 'G1', 'G2'];
43
61
 
@@ -99,8 +117,8 @@ export function validateSessionLog(log, opts = {}) {
99
117
  if (header.type !== 'session') {
100
118
  violations.push(violation('H1', { lineNo: headerLine }, `首行 type 必须为 "session"(实际 ${String(header.type)})`));
101
119
  }
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 处理会误判,请先确认格式`));
120
+ if (![0, 1, 2, 3, 4].includes(header.version)) {
121
+ violations.push(violation('H2', { lineNo: headerLine }, `header.version 未知(实际 ${String(header.version)})——已知 0/1/2/3/4;未知版本按 0 处理会误判,请先确认格式`));
104
122
  }
105
123
  if (typeof header.id !== 'string' || header.id === '') {
106
124
  violations.push(violation('H2', { lineNo: headerLine }, 'header.id 必须为非空字符串'));
@@ -108,8 +126,8 @@ export function validateSessionLog(log, opts = {}) {
108
126
  if (!Number.isSafeInteger(header.createdAt) || header.createdAt < 0) {
109
127
  violations.push(violation('H2', { lineNo: headerLine }, 'header.createdAt 必须为非负安全整数'));
110
128
  }
111
- if (header.cwd !== undefined && (typeof header.cwd !== 'string' || !header.cwd.startsWith('/'))) {
112
- violations.push(violation('H2', { lineNo: headerLine }, 'header.cwd 若存在必须为绝对路径'));
129
+ if (header.cwd !== undefined && !isAbsoluteLogPath(header.cwd)) {
130
+ violations.push(violation('H2', { lineNo: headerLine }, 'header.cwd 若存在必须为绝对路径(POSIX 或 Windows 形态)'));
113
131
  }
114
132
  if (header.origin !== undefined && header.origin !== 'subagent') {
115
133
  violations.push(violation('H2', { lineNo: headerLine }, `header.origin 只能为 "subagent"(实际 ${String(header.origin)})`));
@@ -273,10 +291,10 @@ function unassessableResult({ header, headerLine, rows, events, frameInfo, baseS
273
291
  violations.push(violation('H1', { lineNo: headerLine }, '首行不是合法 JSON —— 整个会话不可读'));
274
292
  } else {
275
293
  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)})`));
294
+ if (![0, 1, 2, 3, 4].includes(header.version)) violations.push(violation('H2', { lineNo: headerLine }, `header.version 未知(实际 ${String(header.version)})`));
277
295
  if (typeof header.id !== 'string' || header.id === '') violations.push(violation('H2', { lineNo: headerLine }, 'header.id 必须为非空字符串'));
278
296
  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 若存在必须为绝对路径'));
297
+ if (header.cwd !== undefined && !isAbsoluteLogPath(header.cwd)) violations.push(violation('H2', { lineNo: headerLine }, 'header.cwd 若存在必须为绝对路径(POSIX 或 Windows 形态)'));
280
298
  if (header.origin !== undefined && header.origin !== 'subagent') violations.push(violation('H2', { lineNo: headerLine }, `header.origin 只能为 "subagent"(实际 ${String(header.origin)})`));
281
299
  }
282
300
  if (header !== null && events.length === 0) violations.push(violation('Z3', { lineNo: headerLine }, '会话文件无任何事件(仅 header)——异常空会话'));
@@ -418,6 +436,7 @@ export function migrationVerdict(result) {
418
436
  'stored log corrupt(SessionFormatError)',
419
437
  'v0→v1 对其余事件的形状拒绝',
420
438
  'turn/end 无匹配 open turn / open step 穿越 / 未解析 tool / open compaction 穿越(官方同一状态机的其余分支)',
439
+ 'v3→v4 迁移(tool-result 提升为 role tool、plugin source 改名、父会话 subagent 目录补写、中断轮闭合;官方 dsh-session-format-v3-to-v4)',
421
440
  ],
422
441
  note: '未覆盖 ≠ 通过:本维度只对 implemented 三条负责。官方判据版本:@deepseek-ai/dsh-session-format-v0-to-v1@0.1.5-rc.2 + v1-to-v2@0.1.5-rc.2',
423
442
  };
@@ -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.18",
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
  }