dsh-log-contract 0.3.35 → 0.3.37

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/README.md CHANGED
@@ -36,7 +36,7 @@ plugin marker semantics).
36
36
  - **`fix` / `extract` / `audit-report`** — repair primitives and read-only
37
37
  session archaeology.
38
38
 
39
- **Capabilities at a glance**: session formats **v0–v4** · 57 contract rules ·
39
+ **Capabilities at a glance**: session formats **v0–v4** · **63 contract rules (57 log-contract + 6 error-expression)** ·
40
40
  exit-code contract `0/1/3/4` · three-tier verdicts · pre-write validation ·
41
41
  per-rule negative-control tests + rules self-test · tolerant reading (a single
42
42
  damaged file degrades to structured results and is counted, never thrown).
@@ -76,8 +76,10 @@ line-by-line verification against the official Host source (each rule carries it
76
76
  ---
77
77
 
78
78
  ## Three-layer contract (the model)
79
- > 57 rules across the layers below (`contracts` lists them all, each with its
80
- > official source reference).
79
+ > **63 rules in two families**: **57 log-contract rules** across the layers below
80
+ > (each with its official source reference) + **6 error-expression rules** (E1–E6, see
81
+ > §1.1). `contracts` lists the 57 log-contract rules; the error-expression catalogue is
82
+ > returned by `check --json` under `errorContract`, and `error-contract` scans source text for it.
81
83
 
82
84
  | Layer | Rules | What it guards |
83
85
  |---|---|---|
@@ -160,7 +162,7 @@ rather than by relaxing the format gate:
160
162
  - validation for v3 and earlier is **unchanged** (identical verdicts on 408 real v3 sessions before/after)
161
163
  - the format gate still rejects **unknown** future versions (`readOnly`); v5+ remains unassessable by design
162
164
 
163
- **Rules (55 as of 0.3.28, 57 as of 0.3.32):** the five rules below were added in the
165
+ **Rules (55 as of 0.3.28, 57 as of 0.3.32; 63 total as of 0.3.36 — 57 log-contract + 6 error-expression):** the five rules below were added in the
164
166
  0.3.18 – 0.3.24 window (see above for the 0.3.28 additions):
165
167
 
166
168
  | Rule | Checks |
@@ -269,11 +271,11 @@ when the host cannot judge the file.
269
271
  read* are self-consistent — see the `tailStatus` note in the 0.3.28 section above.
270
272
 
271
273
  **Report structure versioning (`schemaVersion`)**: every `check --json` report
272
- carries a top-level `schemaVersion` (currently `"1"`) that versions the **report
274
+ carries a top-level `schemaVersion` (currently `"2"`) that versions the **report
273
275
  structure** itself — field set / types / meanings — not the tool version and not
274
276
  the log format version. Within one version, reports are additive only (existing
275
277
  top-level keys are never removed, renamed or redefined); a report **without** the
276
- field is to be read as `"1"`. Full compatibility promise and bump rules:
278
+ field is to be read as `"1"`. `"2"` adds S9 diagnosis fields (`category`/`confidence`/`hint`/`basis`) without changing the S9 verdict. Full compatibility promise and bump rules:
277
279
  [docs/interface-versioning.md](./docs/interface-versioning.md).
278
280
 
279
281
  `check` adds **W1/W2 wire-level checks** since 0.2.0: expand the model request
@@ -284,7 +286,8 @@ results" — tolerated by some endpoints, `INVALID_REQUEST` on strict ones
284
286
 
285
287
  ### 1.1 Error-expression contract scan (`error-contract`)
286
288
 
287
- Static scan of *how errors are raised* (source text; no AST):
289
+ Static scan of *how errors are raised* (source text; no AST). This is the **6-rule
290
+ error-expression family** (E1–E6; 63 = 57 log-contract + 6 here):
288
291
  E1 one code with many causes · E2 constant message · E3 terminal word on a non-terminal
289
292
  cause · E4 `cause` not surfaced · E5 unconditional success (candidate) · E6 claims with no
290
293
  enforcement point (candidate).
package/README.zh.md CHANGED
@@ -28,7 +28,7 @@
28
28
  - **`check --resume`** —— 三档结论(`loadable` / `resumable` / `compactable`,宿主判不了时另有 `not-assessable`)。
29
29
  - **`fix` / `extract` / `audit-report`** —— 修复原语 + 只读会话考古。
30
30
 
31
- **能力一览**:会话格式 **v0–v4** · 契约规则 **57 条** · 退出码契约 `0/1/3/4` · 三档结论 ·
31
+ **能力一览**:会话格式 **v0–v4** · 契约规则 **63 条(日志契约 57 + 错误表达契约 6)** · 退出码契约 `0/1/3/4` · 三档结论 ·
32
32
  写前校验 · 每条规则都有负对照用例 + 规则自检 · 读取容错(单文件损坏降级为结构化结果并计数,不抛出)。
33
33
 
34
34
  ---
@@ -58,7 +58,9 @@ dsh-retrace 的「日志体检与修复」能力——与 dsh-retrace 一起构
58
58
  ---
59
59
 
60
60
  ## 三层契约(判定模型)
61
- > 57 条规则,覆盖以下各层(`contracts` 列出全部,每条附官方源码出处)。
61
+ > **63 条规则分两族**:以下各层的**日志契约 57 条**(每条附官方源码出处)+ **错误表达契约 6 条**
62
+ > (E1–E6,见 §1.1)。`contracts` 列出日志契约 57 条;错误表达规则目录由 `check --json` 的
63
+ > `errorContract` 返回,`error-contract` 子命令对源码做第二族扫描。
62
64
 
63
65
  | 层 | 规则 | 守护什么 |
64
66
  |---|---|---|
@@ -132,7 +134,7 @@ dsh-retrace 的「日志体检与修复」能力——与 dsh-retrace 一起构
132
134
  - **v3 及更早的判据零改动**(多份真实语料 v3 会话前后判定完全一致)
133
135
  - 格式闸门仍**拒绝未知的未来版本**(`readOnly`);v5+ 按设计保持"不可评估"
134
136
 
135
- **规则(0.3.28 起 55 条;0.3.32 起 57 条)**:下表五条是 0.3.18 – 0.3.24 窗口新增
137
+ **规则(0.3.28 起 55 条;0.3.32 起 57 条;0.3.36 起共 63 条 = 57 日志契约 + 6 错误表达契约)**:下表五条是 0.3.18 – 0.3.24 窗口新增
136
138
  (0.3.28 新增的四条见上一节):
137
139
 
138
140
  | 规则 | 判据 |
@@ -238,7 +240,8 @@ tool_calls 与其结果之间"——这类问题 DeepSeek 曾容忍,但 MiMo
238
240
 
239
241
  ### 1.1 错误表达契约检查(`error-contract`)
240
242
 
241
- 对「错误是怎么抛的」做静态扫描(源码文本;不做 AST):
243
+ 对「错误是怎么抛的」做静态扫描(源码文本;不做 AST)。这是**错误表达契约 6 条**
244
+ (E1–E6;63 = 日志契约 57 + 本族 6):
242
245
  E1 一个码多成因 / E2 message 是常量 / E3 终态词用于非终态因 / E4 `cause` 未透出 /
243
246
  E5 无条件成功(候选)/ E6 声称无执行点(候选)。
244
247
 
@@ -166,6 +166,11 @@ function printViolations(violations, maxDetails = 8) {
166
166
  .filter(Boolean).join(' / ');
167
167
  const head = ` [${v.severity}] ${v.id} ${loc ? `@ ${loc}` : ''}${v.eventType ? ` (${v.eventType})` : ''}`;
168
168
  out(`${head}\n ${v.message}\n`);
169
+ // S9 诊断(本版):分类/置信度/判定式/建议;判定本身不变(仍 error、仍只报首个倒退)
170
+ if (v.id === 'S9' && v.category) {
171
+ out(` 诊断:${v.category}(置信度 ${v.confidence})|判定式:${v.basis ?? '-'}\n`);
172
+ out(` ${v.hint ?? ''}\n`);
173
+ }
169
174
  if (Array.isArray(v.missingSeqs) && v.missingSeqs.length > maxDetails) {
170
175
  out(` …另有 ${v.missingSeqs.length - maxDetails} 个缺失 seq 未列出\n`);
171
176
  }
package/docs/CONTRACTS.md CHANGED
@@ -144,7 +144,7 @@
144
144
 
145
145
  - **层级**: persistence | **严重度**: error
146
146
  - **出处**: 2026-08-28 实锤(某真实会话):文件物理序出现回退(大→小→更大);单进程 appendCore 断言 seq==cursor+i 且按 id 串行化不可能写出
147
- - **契约**: 按文件物理行序要求展开后事件 seq 严格单调递增。E2 在排序后检查(loadSessionLog 会 sort),物理序倒退被掩盖;S9 在排序前按行序检查,非单调 = 多写入者/旧光标回放交织的直接现场证据,加载会被拒。
147
+ - **契约**: 按文件物理行序要求展开后事件 seq 严格单调递增。E2 在排序后检查(loadSessionLog 会 sort),物理序倒退被掩盖;S9 在排序前按行序检查,非单调 = 多写入者/旧光标回放交织的直接现场证据,加载会被拒。本版起**判定不变**,额外输出诊断分类(old-cursor-replay / concurrent-writer / format-mix)+ 置信度 + 判定式,并提示"疑似旧内存态或并发写者,建议 loaded=no 重载后再写";分类是提示,不改变是否判红。
148
148
 
149
149
  ### S10 — sourceEventSeqs 元素必须是(解码后的)非负整数;存储形态只允许官方区间对
150
150
 
@@ -10,7 +10,7 @@
10
10
  |---|---|
11
11
  | 字段名 | `schemaVersion` |
12
12
  | 位置 | `check --json` 报告**顶层**;同值同步进 `validateSessionLog()` 返回对象顶层 |
13
- | 当前值 | `"1"`(字符串,暂不采用 semver) |
13
+ | 当前值 | `"2"`(字符串,暂不采用 semver;见下文 v2) |
14
14
  | 覆盖范围 | 仅 `check --json` 这一份报告结构。`prewrite --json` 是**另一份结构**,暂不带本字段(当前 CLI 亦无 `plan` 子命令) |
15
15
 
16
16
  `schemaVersion` 标记的是**报告结构**(字段集合 / 字段类型 / 字段含义)的版本:
@@ -25,12 +25,34 @@
25
25
  在它出现之前的报告结构就是 v1。
26
26
  - 枚举类字段新增取值属于兼容变更;消费者对未知取值应降级归入 unknown,不得崩溃。
27
27
 
28
- ### 已新增的可选键(同 `schemaVersion: "1"`)
28
+ ### 已新增的可选键(`schemaVersion: "1"` 期间)
29
29
 
30
30
  | 键 | 引入 | 形状 | 说明 |
31
31
  |---|---|---|---|
32
32
  | `errorContract` | 0.3.x | `{ family: "error-expression", rules: [{id,severity,title,layer,target,falsePositiveRisk}], note }` | 错误表达契约(E1–E6)的**规则目录**;源码扫描结果不在此键内(用 `error-contract` 子命令的独立报告)。旧消费者忽略此键即可。 |
33
33
 
34
+ ---
35
+
36
+ ## v2(本版):S9 诊断字段(兼容递增)
37
+
38
+ `schemaVersion` 由 `"1"` → `"2"`。**这次升版是按"新增枚举/诊断结构要能被消费者识别"显式登记**,
39
+ 结构上仍是**只增不改**:顶层键集合不变,仅 `violations[]` 里 S9 违规**新增可选字段**。
40
+
41
+ | 键 | 形状 | 说明 |
42
+ |---|---|---|
43
+ | `violations[].category` | `"old-cursor-replay" \| "concurrent-writer" \| "format-mix"` | 物理序非单调的**诊断分类**;仅 S9 违规携带 |
44
+ | `violations[].confidence` | `number`(0–1) | 分类置信度(启发式,非概率保证) |
45
+ | `violations[].hint` | `string` | 处置提示(含"建议 loaded=no 重载后再写") |
46
+ | `violations[].basis` | `string` | 判定式(回卷步数/方向反转/内容重复/格式代/声明版本/连续回放步数) |
47
+ | `violations[].diagnosis` | `{ category, confidence, basis, hint }` | 与上述四键同值的对象(便于整体消费) |
48
+
49
+ 兼容性:
50
+ - **v1 消费者读 v2 报告**:顶层键与 S9 的 `id/severity/seq/lineNo/message` 语义**未变**,
51
+ 新增字段按"未知键忽略"处理即可;S9 **判定不变**(仍为 error,仍只报首个物理序倒退)。
52
+ - **v2 消费者读 v1 报告**:S9 违规可能缺 `category/confidence/basis/diagnosis` ⇒ 视为
53
+ "未分类诊断",按原 S9 文案处理。
54
+ - 分类枚举后续只增(新取值按 unknown 降级);新增取值**不**再单独升版。
55
+
34
56
  ## 何时升版
35
57
 
36
58
  **不兼容才升**(`"1"` → `"2"`):
@@ -55,7 +77,7 @@
55
77
 
56
78
  | 报告域 | 命令 | 版本字段 | 备注 |
57
79
  |---|---|---|---|
58
- | 日志契约(session log contract) | `check --json` | 顶层 `schemaVersion`(当前 `"1"`) | 本文正文主要讲这一域 |
80
+ | 日志契约(session log contract) | `check --json` | 顶层 `schemaVersion`(当前 `"2"`) | 本文正文主要讲这一域 |
59
81
  | 错误表达契约(error-expression) | `error-contract --json` | 顶层 `schemaVersion`(当前 `"1"`)+ `family: "error-expression"` | 与日志契约**互不影响**:任一域升版不牵动另一域 |
60
82
 
61
83
  - 两个域的 id 集合可能重名(都有 `E1`…),消费者**必须按 `family` 分派**,⛔ 不要按 id 字面合并。
package/lib/checks.js CHANGED
@@ -369,6 +369,59 @@ export function normalizeReplaceOp(op, version) {
369
369
  : null;
370
370
  }
371
371
 
372
+ /**
373
+ * S9 诊断分类(本版 · 只增诊断,不改判定)。
374
+ *
375
+ * 物理序非单调(`seq < prevSeq`)的事实与判定不变;这里按现场证据分三类并给判定式/置信度:
376
+ * - `old-cursor-replay`:回卷到旧区间/旧游标(seq 回到已到达过的位置或旧区间的空洞),
377
+ * 之后继续单调整上升 —— 典型"旧内存态在尾部被重写后继续写";
378
+ * - `concurrent-writer`:同一 seq 重复且**内容不同**(两个写入者各分配同一 seq),
379
+ * 或物理序出现 ≥2 次回卷 + ≥2 次回升(两条单调流交错);
380
+ * - `format-mix`:同一物理流混有不同格式代(legacy `{start,end}`/`assistant/chunk`/`assistant/attempt`
381
+ * vs modern `startSeq/endSeq`/`system/message`/`developer/message`),尤其与 header 声明版本矛盾
382
+ * (跨版本重放)。
383
+ *
384
+ * ⛔ 分类是**提示性诊断**,不改变 S9 的 severity/是否判红;歧义时按
385
+ * `format-mix(声明版本矛盾) > concurrent-writer(内容重复/交错) > old-cursor-replay` 取先。
386
+ */
387
+ export const S9_CATEGORIES = Object.freeze({
388
+ OLD_CURSOR_REPLAY: 'old-cursor-replay',
389
+ CONCURRENT_WRITER: 'concurrent-writer',
390
+ FORMAT_MIX: 'format-mix',
391
+ });
392
+
393
+ const S9_CATEGORY_HINT = Object.freeze({
394
+ [S9_CATEGORIES.OLD_CURSOR_REPLAY]: '疑似旧内存态(旧光标)回放:旧态在尾部被重写后仍按旧 seq 继续写',
395
+ [S9_CATEGORIES.CONCURRENT_WRITER]: '疑似并发写者(≥2 进程/实例共享同一会话目录)交错写入',
396
+ [S9_CATEGORIES.FORMAT_MIX]: '疑似跨版本重放(legacy v0–v2 事件与 v3+ 事件混写在同一物理流)',
397
+ });
398
+
399
+ /** 事件所属"格式代":legacy(v0–v2 形态)/ modern(v3+ 形态)/ neutral(两代通用)。 */
400
+ export function eventGeneration(event) {
401
+ if (!event || typeof event !== 'object') return 'neutral';
402
+ const op = event.surfaceOp;
403
+ if (op && typeof op === 'object' && op.op === 'replace') {
404
+ if (Object.hasOwn(op, 'start') || Object.hasOwn(op, 'end')) return 'legacy';
405
+ if (Object.hasOwn(op, 'startSeq') || Object.hasOwn(op, 'endSeq')) return 'modern';
406
+ return 'neutral';
407
+ }
408
+ if (event.type === 'assistant/chunk' || event.type === 'assistant/attempt') return 'legacy';
409
+ if (event.type === 'system/message' || event.type === 'developer/message') return 'modern';
410
+ if (event.type === 'tool/result' && event.data?.message?.role === 'tool') return 'modern';
411
+ return 'neutral';
412
+ }
413
+
414
+ /** 两条同 seq 事件是否"内容不同"(type 或 data 不同);用于区分重复写者与同内容回放。 */
415
+ function sameEventContent(a, b) {
416
+ if (a === b) return true;
417
+ if (!a || !b || a.type !== b.type) return false;
418
+ try {
419
+ return JSON.stringify(a.data) === JSON.stringify(b.data);
420
+ } catch {
421
+ return false;
422
+ }
423
+ }
424
+
372
425
  /**
373
426
  * S9 —— 文件物理序 seq 单调(2026-08-30 事故固化;交接书 L2)。
374
427
  *
@@ -378,26 +431,112 @@ export function normalizeReplaceOp(op, version) {
378
431
  * 734056→733539→735470)。E2 只查「排序后连续」,排序会掩盖物理序倒退;
379
432
  * S9 补「物理序单调」盲区。
380
433
  *
434
+ * 本版起:判定不变(首个倒退报一条 error),额外带 `category` / `confidence` /
435
+ * `hint` / `basis` 诊断字段(`check --json` 里同名字段;`diagnosis` 为同内容对象)。
436
+ *
381
437
  * @param rows - loadSessionLog 的 rows(物理行序,每行含 decoded 数组)。
382
- * @returns S9 违规列表(error 级)。
438
+ * @param {{version?: number|null}} [opts] 被检文件声明版本(用于 format-mix 判据;不传则只看现场)。
439
+ * @returns S9 违规列表(error 级;最多 1 条)。
383
440
  */
384
- export function physicalOrderViolations(rows) {
385
- const out = [];
441
+ export function physicalOrderViolations(rows, { version = null } = {}) {
442
+ const events = [];
443
+ for (const row of rows ?? []) {
444
+ if (!Array.isArray(row.decoded)) continue;
445
+ for (const event of row.decoded) {
446
+ // E1 处理非法 seq;这里只统计可判定的事件
447
+ if (typeof event?.seq !== 'number' || !Number.isSafeInteger(event.seq) || event.seq < 0) continue;
448
+ events.push({ event, lineNo: row.lineNo });
449
+ }
450
+ }
451
+ if (events.length === 0) return [];
452
+
453
+ const generations = new Set();
454
+ const firstSeen = new Map(); // seq → event(首次出现)
386
455
  let prevSeq = -1;
387
456
  let prevLineNo = null;
388
- for (const row of rows) {
389
- if (!Array.isArray(row.decoded) || row.decoded.length === 0) continue;
390
- for (const event of row.decoded) {
391
- if (typeof event.seq !== 'number' || !Number.isSafeInteger(event.seq) || event.seq < 0) continue; // E1 处理
392
- if (event.seq < prevSeq) {
393
- out.push(violation('S9', { seq: event.seq, lineNo: row.lineNo, eventType: event.type }, `文件物理序 seq 倒退:${prevSeq}(line ${prevLineNo})→ ${event.seq}(line ${row.lineNo})——非单调 = 多写入者/旧光标回放交织(单进程 append 不可能写出),会话加载会被拒`));
394
- return out; // 首个倒退即现场特征,报一次足够(后续乱序都源自此)
457
+ let backwardSteps = 0;
458
+ let directionReversals = 0;
459
+ let contentDuplicates = 0;
460
+ let wasBackward = false;
461
+ let firstBackward = null;
462
+
463
+ for (let i = 0; i < events.length; i++) {
464
+ const { event, lineNo } = events[i];
465
+ const gen = eventGeneration(event);
466
+ if (gen !== 'neutral') generations.add(gen);
467
+ const seen = firstSeen.get(event.seq);
468
+ if (seen === undefined) firstSeen.set(event.seq, event);
469
+ else if (!sameEventContent(seen, event)) contentDuplicates += 1;
470
+ const isBackward = event.seq < prevSeq;
471
+ if (isBackward) {
472
+ backwardSteps += 1;
473
+ if (firstBackward === null) {
474
+ firstBackward = {
475
+ index: i,
476
+ seq: event.seq,
477
+ lineNo,
478
+ event,
479
+ previousSeq: prevSeq,
480
+ previousLineNo: prevLineNo,
481
+ seenBefore: seen !== undefined,
482
+ generation: gen,
483
+ previousGeneration: i > 0 ? eventGeneration(events[i - 1].event) : 'neutral',
484
+ };
395
485
  }
396
- prevSeq = event.seq;
397
- prevLineNo = row.lineNo;
398
- }
486
+ } else if (wasBackward) directionReversals += 1;
487
+ wasBackward = isBackward;
488
+ prevSeq = event.seq;
489
+ prevLineNo = lineNo;
399
490
  }
400
- return out;
491
+ if (firstBackward === null) return [];
492
+
493
+ // 回卷后连续 +1 的步数(旧块回放的强度信号)
494
+ let contiguousRun = 0;
495
+ for (let i = firstBackward.index + 1; i < events.length; i++) {
496
+ if (events[i].event.seq === events[i - 1].event.seq + 1) contiguousRun += 1;
497
+ else break;
498
+ }
499
+
500
+ const hasLegacy = generations.has('legacy');
501
+ const hasModern = generations.has('modern');
502
+ const declaredMismatch = (version !== null && Number.isSafeInteger(version))
503
+ && ((version >= 3 && hasLegacy) || (version <= 2 && hasModern));
504
+
505
+ let category;
506
+ let confidence;
507
+ let reason;
508
+ if (declaredMismatch) {
509
+ category = S9_CATEGORIES.FORMAT_MIX;
510
+ confidence = 0.85;
511
+ reason = `header 声明 version=${version},但物理流里混有 ${[hasLegacy ? 'legacy' : null, hasModern ? 'modern' : null].filter(Boolean).join('+')} 两代事件(跨版本重放)`;
512
+ } else if (contentDuplicates > 0) {
513
+ category = S9_CATEGORIES.CONCURRENT_WRITER;
514
+ confidence = 0.9;
515
+ reason = `同一 seq 重复出现且内容不同(${contentDuplicates} 处)——两个写入者各自分配了同一 seq`;
516
+ } else if (backwardSteps >= 2 && directionReversals >= 2) {
517
+ category = S9_CATEGORIES.CONCURRENT_WRITER;
518
+ confidence = 0.8;
519
+ reason = `物理序 ${backwardSteps} 次回卷、${directionReversals} 次回升 —— 两条单调流交错`;
520
+ } else if (hasLegacy && hasModern && firstBackward.generation !== 'neutral'
521
+ && firstBackward.previousGeneration !== 'neutral'
522
+ && firstBackward.generation !== firstBackward.previousGeneration) {
523
+ category = S9_CATEGORIES.FORMAT_MIX;
524
+ confidence = 0.7;
525
+ reason = `回卷点恰好跨越格式代(${firstBackward.previousGeneration} → ${firstBackward.generation})`;
526
+ } else {
527
+ category = S9_CATEGORIES.OLD_CURSOR_REPLAY;
528
+ confidence = contiguousRun >= 2 ? 0.85 : 0.6;
529
+ reason = firstBackward.seenBefore
530
+ ? 'seq 回卷到已出现过的旧区间,之后继续单调整上升'
531
+ : 'seq 回卷到旧坐标(旧区间的空洞),之后继续单调整上升';
532
+ if (contiguousRun >= 2) reason += `(回卷后连续 ${contiguousRun} 步 +1)`;
533
+ }
534
+
535
+ const basis = `backwardSteps=${backwardSteps},directionReversals=${directionReversals},contentDuplicates=${contentDuplicates},generations=${[...generations].join('+') || 'neutral'},declaredVersion=${version ?? '-'},contiguousRun=${contiguousRun}`;
536
+ const hint = `疑似旧内存态或并发写者(${category});${S9_CATEGORY_HINT[category]}——建议 loaded=no 重载后再写(不要沿用旧内存态继续追加)`;
537
+ const loc = { seq: firstBackward.seq, lineNo: firstBackward.lineNo, eventType: firstBackward.event.type };
538
+ const diagnosed = violation('S9', loc, `文件物理序 seq 倒退:${firstBackward.previousSeq}(line ${firstBackward.previousLineNo})→ ${firstBackward.seq}(line ${firstBackward.lineNo})——非单调 = 多写入者/旧光标回放交织(单进程 append 不可能写出),会话加载会被拒;诊断分类 ${category}(置信度 ${confidence}):${reason}`, { category, confidence, hint, basis, diagnosis: { category, confidence, basis, hint } });
539
+ return [diagnosed]; // 首个倒退即现场特征,报一次足够(后续乱序都源自此)
401
540
  }
402
541
 
403
542
  /**
package/lib/contracts.js CHANGED
@@ -147,7 +147,7 @@ export const CONTRACT_RULES = [
147
147
  layer: LAYER.PERSISTENCE,
148
148
  severity: SEVERITY.ERROR,
149
149
  source: '2026-08-28 实锤(某真实会话):文件物理序出现回退(大→小→更大);单进程 appendCore 断言 seq==cursor+i 且按 id 串行化不可能写出',
150
- description: '按文件物理行序要求展开后事件 seq 严格单调递增。E2 在排序后检查(loadSessionLog 会 sort),物理序倒退被掩盖;S9 在排序前按行序检查,非单调 = 多写入者/旧光标回放交织的直接现场证据,加载会被拒。',
150
+ description: '按文件物理行序要求展开后事件 seq 严格单调递增。E2 在排序后检查(loadSessionLog 会 sort),物理序倒退被掩盖;S9 在排序前按行序检查,非单调 = 多写入者/旧光标回放交织的直接现场证据,加载会被拒。本版起**判定不变**,额外输出诊断分类(old-cursor-replay / concurrent-writer / format-mix)+ 置信度 + 判定式,并提示"疑似旧内存态或并发写者,建议 loaded=no 重载后再写";分类是提示,不改变是否判红。',
151
151
  },
152
152
  {
153
153
  id: 'S10',
package/lib/index.js CHANGED
@@ -12,7 +12,7 @@ export { CONTRACT_RULES, LAYER, SEVERITY, ruleById } from './contracts.js';
12
12
  export { explainRule, examplePointers, relatedCommandsOf, EXPLAIN_KEYS, EXPLAIN_DOC } from './explain.js';
13
13
  export { HOST_MAX_FILE_VERSION, hostPackageVersion, hostCapability, isAssessableFileVersion } from './vocab.js';
14
14
  export { TESTED_BASELINE, compareVersions, detectSupport, supportOfLog } from './version-support.js';
15
- 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 { tokenMeterViolations, tokenMeterSourceViolations, stepKeyViolations, nullTurnStepViolations, turnEndReasonViolations, ignorableTypeViolations, physicalOrderViolations, S9_CATEGORIES, eventGeneration, inboxReplayViolations, sourceEventSeqElementViolations, rawSourceEventSeqViolations, isSeqRangePair, seedLengthViolations, carrierPairingViolations, carrierWriteViolations, isCarrierAuditSegment, carrierRangesMatch, surfaceReplaceRange, declarativeIgnorableViolations, isIgnorableRegistered, resolveIgnorableWhitelist, DEFAULT_IGNORABLE_WHITELIST } from './checks.js';
16
16
  export { collectArchivePointers, verifyArchivePointers, archiveVerdict, archiveBasename, readArchiveLines, readArchiveIndex, ARCHIVE_POINTER_FIELDS, EXTERNALIZED_POINTER_FIELDS } from './archive.js';
17
17
  export { auditToolCalls, extractText, extractToolOutputs, indexToolCalls, toolCommandOf } from './archaeology.js';
18
18
  export { ERROR_CONTRACT_RULES, ERROR_CONTRACT_RULE_BY_ID, ERROR_CONTRACT_FAMILY, scanSource, scanInvariantSentences, scanDeclaredKeysNoRead, validateWhitelist, checkErrorContract, normalizePath } from './error-contract.js';
package/lib/validate.js CHANGED
@@ -70,7 +70,7 @@ export function isAbsoluteLogPath(value) {
70
70
  * 新增可选字段不递增;消费方可据此做解析兼容判断。
71
71
  * ⛔ 不是包版本、不是日志格式版本(那是 header.version / package.json)。
72
72
  */
73
- export const REPORT_SCHEMA_VERSION = '1';
73
+ export const REPORT_SCHEMA_VERSION = '2';
74
74
 
75
75
  /** 宿主能力闸触发时**跳过**的规则(v3/被检版本语义相关)——报告里显式列出,避免"静默通过"。 */
76
76
  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'];
@@ -216,7 +216,7 @@ export function validateSessionLog(log, opts = {}) {
216
216
  }
217
217
 
218
218
  // ── S9 · 文件物理序 seq 单调(多写入者交织现场;E2 排序后检查看不到)──
219
- violations.push(...physicalOrderViolations(rows));
219
+ violations.push(...physicalOrderViolations(rows, { version: formatVersion }));
220
220
 
221
221
  // ── S · surface 增量重放(归因)+ 官方 foldSurface 终验 ────────────────
222
222
  const replay = replaySurface(events, formatVersion);
@@ -401,7 +401,7 @@ function unassessableResult({ header, headerLine, rows, events, frameInfo, baseS
401
401
  } else expectedSeq = event.seq + 1;
402
402
  }
403
403
  }
404
- violations.push(...physicalOrderViolations(rows));
404
+ violations.push(...physicalOrderViolations(rows, { version: formatVersion }));
405
405
  violations.push(...inboxReplayViolations(events, header));
406
406
  violations.push(...toolPairingViolations(events));
407
407
  violations.push(...toolResultStructureViolations(events));
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.35",
4
+ "version": "0.3.37",
5
5
  "packageManager": "pnpm@11.7.0",
6
6
  "type": "module",
7
7
  "main": "lib/index.js",
@@ -35,7 +35,8 @@
35
35
  "surface:check": "node scripts/check-external-surface.mjs",
36
36
  "review:check": "node scripts/check-review-record.mjs",
37
37
  "release:check": "node scripts/check-release-discipline.mjs && node scripts/check-external-surface.mjs && node scripts/check-review-record.mjs",
38
- "release": "node scripts/release.mjs"
38
+ "release": "node scripts/release.mjs",
39
+ "gate": "node internal/scripts/gate.mjs"
39
40
  },
40
41
  "keywords": [
41
42
  "dsh",