dsh-log-contract 0.3.29 → 0.3.34
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 +42 -13
- package/README.zh.md +32 -15
- package/bin/dsh-log-contract.mjs +220 -8
- package/docs/CONTRACTS.md +23 -9
- package/docs/ERROR-CONTRACT.md +120 -0
- package/docs/interface-versioning.md +68 -0
- package/lib/archive.js +2 -2
- package/lib/checks.js +96 -7
- package/lib/contracts.js +27 -10
- package/lib/error-contract.js +501 -0
- package/lib/explain.js +129 -0
- package/lib/index.js +2 -0
- package/lib/log-reader.js +45 -11
- package/lib/repair.js +2 -2
- package/lib/validate.js +19 -1
- package/lib/version-support.js +2 -2
- package/package.json +2 -2
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** ·
|
|
39
|
+
**Capabilities at a glance**: session formats **v0–v4** · 57 contract rules ·
|
|
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,7 +76,7 @@ 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
|
-
>
|
|
79
|
+
> 57 rules across the layers below (`contracts` lists them all, each with its
|
|
80
80
|
> official source reference).
|
|
81
81
|
|
|
82
82
|
| Layer | Rules | What it guards |
|
|
@@ -101,7 +101,7 @@ line-by-line verification against the official Host source (each rule carries it
|
|
|
101
101
|
|---|---|---|
|
|
102
102
|
| Host package | `@deepseek-ai/dsh-session@0.2.0-rc.2` | the version this rule set is developed and CI-tested against (CI runs `pnpm check` + `pnpm test`; the four `prepublishOnly` steps are green locally on it) |
|
|
103
103
|
| Session format | **v4** (`SESSION_FORMAT_VERSION = 4`) | v4 uses the runtime vocabulary + official `foldSurface` final check |
|
|
104
|
-
| Declared range | `peerDependencies: ^0.1.0-rc.7 || ^0.1.5-rc.1 || ^0.2.0-rc.1` | installable — a declared range is **not** a per-version verification |
|
|
104
|
+
| Declared range | `peerDependencies: ^0.1.0-rc.7 || ^0.1.5-rc.1 || ^0.1.7-rc.2 || ^0.2.0-rc.1` | installable — a declared range is **not** a per-version verification |
|
|
105
105
|
| Known formats | 0 / 1 / 2 / 3 / 4 | 0–2 are supported by this package's **vendored** vocabulary + local equivalent fold (`legacyFoldSurface`), independent of the host |
|
|
106
106
|
|
|
107
107
|
**What happens on unverified versions (detected and reported at runtime — never silently judged by stale rules)**:
|
|
@@ -160,7 +160,7 @@ rather than by relaxing the format gate:
|
|
|
160
160
|
- validation for v3 and earlier is **unchanged** (identical verdicts on 408 real v3 sessions before/after)
|
|
161
161
|
- the format gate still rejects **unknown** future versions (`readOnly`); v5+ remains unassessable by design
|
|
162
162
|
|
|
163
|
-
**Rules (55
|
|
163
|
+
**Rules (55 as of 0.3.28, 57 as of 0.3.32):** the five rules below were added in the
|
|
164
164
|
0.3.18 – 0.3.24 window (see above for the 0.3.28 additions):
|
|
165
165
|
|
|
166
166
|
| Rule | Checks |
|
|
@@ -171,12 +171,12 @@ rather than by relaxing the format gate:
|
|
|
171
171
|
| `P5` | two-segment carrier pairing: 2nd segment's first seq == 1st segment seq (read side accepts the legacy order) |
|
|
172
172
|
| `A1` | "in-place restorable" is judged from structured fields only (`archiveRef` / `archive` / `externalized.*`) — never from free text |
|
|
173
173
|
|
|
174
|
-
**Large sessions:** reading is line-wise (no whole-file stringification ⇒ no `ERR_STRING_TOO_LONG` above ~
|
|
174
|
+
**Large sessions:** reading is line-wise (no whole-file stringification ⇒ no `ERR_STRING_TOO_LONG` above ~536 MB),
|
|
175
175
|
and repair rebuilds `.jsonl.zstd` with streaming frames (header frame + chunked body frames, per-frame checksum + round-trip).
|
|
176
176
|
|
|
177
177
|
**Windows:** the `header.cwd` absolute-path check in `H2` is platform-aware (`win32` and `posix` both accepted).
|
|
178
178
|
|
|
179
|
-
**Compatibility:** Node ≥ 22; `@deepseek-ai/dsh-session` `^0.1.0-rc.7 || ^0.1.5-rc.1 || ^0.2.0-rc.1`; session formats v0–v4.
|
|
179
|
+
**Compatibility:** Node ≥ 22; `@deepseek-ai/dsh-session` `^0.1.0-rc.7 || ^0.1.5-rc.1 || ^0.1.7-rc.2 || ^0.2.0-rc.1`; session formats v0–v4.
|
|
180
180
|
|
|
181
181
|
## Case log — why "production-grade" is not a slogan
|
|
182
182
|
Each entry below is a **real log-corruption shape** from production sessions — the cases that
|
|
@@ -195,7 +195,7 @@ omitted.
|
|
|
195
195
|
| 8 | 2026-08-31 | A log whose **last zstd frame was torn** mid-write could not be loaded at all, with no diagnosis ⇒ **Z1** + explicit "torn tail / in-flight write" reporting | |
|
|
196
196
|
| 9 | 2026-09-09 | On **session format v4**, `tool/result` uses `role: 'tool'` and `system/message` carries a `system-prompt` source → v3-shaped checks produced **thousands of false errors on healthy v4 logs** ⇒ version dispatch + **E6/E9** v4 semantics | |
|
|
197
197
|
| 10 | 2026-09-17 | On **Windows**, `header.cwd` was judged with POSIX-only rules → **every** session flagged by **H2** ⇒ platform-aware absolute-path check | |
|
|
198
|
-
| 11 | 2026-10-20 | A **>
|
|
198
|
+
| 11 | 2026-10-20 | A **> 500 MB session** crashed the reader (`ERR_STRING_TOO_LONG`) and repair built the whole text in memory ⇒ line-wise decode + streaming frame rebuild | |
|
|
199
199
|
| 12 | 2026-10-20 | Two-segment carrier references were written with the audit segment first while an earlier convention started at the range start → readers reported hundreds of **false orphan carriers** ⇒ **P5** write-side pairing + tolerant read-side | |
|
|
200
200
|
| 13 | 2026-10-20 | `seedLength` was read as a **byte size** by some consumers (it is the number of inherited events), and `parentSession` with missing/0 was treated as corruption ⇒ **I2** semantics pinned | |
|
|
201
201
|
| 14 | 2026-10-20 | An **unknown but explicitly ignorable** event type blocked an entire migration ⇒ **G4** declarative skip + allow-list | |
|
|
@@ -233,8 +233,8 @@ with the Harness read path).
|
|
|
233
233
|
### 1. Offline health check
|
|
234
234
|
|
|
235
235
|
```bash
|
|
236
|
-
dsh-log-contract check
|
|
237
|
-
dsh-log-contract check
|
|
236
|
+
dsh-log-contract check ~/.dsh/sessions/<id>.jsonl.zstd
|
|
237
|
+
dsh-log-contract check ~/.dsh/sessions/<id>.jsonl.zstd --json # machine-readable
|
|
238
238
|
```
|
|
239
239
|
|
|
240
240
|
Sample output (the CLI reports in Chinese — it is the tool's UI language):
|
|
@@ -268,21 +268,48 @@ when the host cannot judge the file.
|
|
|
268
268
|
**Tail-completeness boundary**: `ok=true` only certifies that *the events actually
|
|
269
269
|
read* are self-consistent — see the `tailStatus` note in the 0.3.28 section above.
|
|
270
270
|
|
|
271
|
+
**Report structure versioning (`schemaVersion`)**: every `check --json` report
|
|
272
|
+
carries a top-level `schemaVersion` (currently `"1"`) that versions the **report
|
|
273
|
+
structure** itself — field set / types / meanings — not the tool version and not
|
|
274
|
+
the log format version. Within one version, reports are additive only (existing
|
|
275
|
+
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:
|
|
277
|
+
[docs/interface-versioning.md](./docs/interface-versioning.md).
|
|
278
|
+
|
|
271
279
|
`check` adds **W1/W2 wire-level checks** since 0.2.0: expand the model request
|
|
272
280
|
stream in surface order and catch "dangling tool messages" (a tool result with no
|
|
273
281
|
preceding assistant tool_calls) and "user text between tool_calls and their
|
|
274
282
|
results" — tolerated by some endpoints, `INVALID_REQUEST` on strict ones
|
|
275
283
|
(MiMo, verified 2026-08-27).
|
|
276
284
|
|
|
285
|
+
### 1.1 Error-expression contract scan (`error-contract`)
|
|
286
|
+
|
|
287
|
+
Static scan of *how errors are raised* (source text; no AST):
|
|
288
|
+
E1 one code with many causes · E2 constant message · E3 terminal word on a non-terminal
|
|
289
|
+
cause · E4 `cause` not surfaced · E5 unconditional success (candidate) · E6 claims with no
|
|
290
|
+
enforcement point (candidate).
|
|
291
|
+
|
|
292
|
+
```bash
|
|
293
|
+
dsh-log-contract error-contract lib/ bin/ --json # T1 (our code): hits ⇒ exit 1
|
|
294
|
+
dsh-log-contract error-contract <pkg>/lib/index.js --target T2 # T2 (third-party): report only, exit 0
|
|
295
|
+
dsh-log-contract error-contract lib/ --keys thresholdRatio,headroom # E6① declared-key reads
|
|
296
|
+
dsh-log-contract error-contract lib/ --config cordis.patch.yml # E6① from YAML config keys
|
|
297
|
+
```
|
|
298
|
+
|
|
299
|
+
⚠️ **Output is a suspicion list, not a verdict**: the rules are heuristics and necessarily
|
|
300
|
+
carry false positives — every finding ships raw `evidence` for human review; whitelist
|
|
301
|
+
entries must carry an `expires` date (missing/invalid/expired ⇒ exit 2, fail-closed).
|
|
302
|
+
Full criteria, false-positive risks and whitelist format: [docs/ERROR-CONTRACT.md](docs/ERROR-CONTRACT.md).
|
|
303
|
+
|
|
277
304
|
### 2. Repair (`fix`)
|
|
278
305
|
|
|
279
306
|
```bash
|
|
280
307
|
# Dry run (report only): strict seq scan + full contract check + removable-marker count
|
|
281
|
-
dsh-log-contract fix
|
|
308
|
+
dsh-log-contract fix ~/.dsh/sessions/<id>.jsonl.zstd --remove-markers
|
|
282
309
|
|
|
283
310
|
# Apply: backup first, then write (.zstd rebuilt in official frame format: frame1=header,
|
|
284
311
|
# frame2=rest, checksum, single trailing newline)
|
|
285
|
-
dsh-log-contract fix
|
|
312
|
+
dsh-log-contract fix ~/.dsh/sessions/<id>.jsonl.zstd --remove-markers --apply
|
|
286
313
|
```
|
|
287
314
|
|
|
288
315
|
- `--remove-markers`: remove retrace/message-editor markers and renumber everything
|
|
@@ -313,7 +340,7 @@ dsh-log-contract fix [path]<id>.jsonl.zstd --remove-markers --apply
|
|
|
313
340
|
```
|
|
314
341
|
|
|
315
342
|
```bash
|
|
316
|
-
dsh-log-contract prewrite marker-write.json --log
|
|
343
|
+
dsh-log-contract prewrite marker-write.json --log ~/.dsh/sessions/<id>.jsonl.zstd
|
|
317
344
|
```
|
|
318
345
|
|
|
319
346
|
- A baseline with error-level violations is rejected outright (safety protocol
|
|
@@ -394,6 +421,8 @@ pnpm check && pnpm test # syntax check + contract-doc drift gate + all unit t
|
|
|
394
421
|
without a control, and a control cannot reference a rule that was never
|
|
395
422
|
registered.
|
|
396
423
|
|
|
424
|
+
> The dev gate `scripts/check-tag-surface.mjs --json` also reports `clean` (the compliant tag list, mutually exclusive with `violations`), so "green" on the tag surface is an explicit list — not merely an empty `violations` array.
|
|
425
|
+
|
|
397
426
|
> **Scope of the published package**: it contains the runtime code and documentation only.
|
|
398
427
|
> Local maintainer tooling is not part of the public repository, so `pnpm check` and `pnpm test`
|
|
399
428
|
> work from a clean clone.
|
|
@@ -448,7 +477,7 @@ Rule count: 51 → 55.
|
|
|
448
477
|
Session format **v4** (host `dsh-session` 0.2.x) is supported by version dispatch (`tool/result` role,
|
|
449
478
|
`system/message` source); five rules were added (`G4` unknown-but-ignorable events, `S10` reference element
|
|
450
479
|
types, `I2` `seedLength` semantics, `P5` carrier pairing, `A1` structured-only in-place restorability);
|
|
451
|
-
large sessions (>
|
|
480
|
+
large sessions (> 500 MB) are read line-wise and repaired with streaming frames; the Windows absolute-path
|
|
452
481
|
check for `H2` is platform-aware. still **partial** — see the changelog's known-gap list). Verdicts, exit codes and `--json` fields are unchanged.
|
|
453
482
|
|
|
454
483
|
> **0.3.17 changes no behaviour.** It only adjusts the wording of comments, test titles, a few
|
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** · 契约规则 **
|
|
31
|
+
**能力一览**:会话格式 **v0–v4** · 契约规则 **57 条** · 退出码契约 `0/1/3/4` · 三档结论 ·
|
|
32
32
|
写前校验 · 每条规则都有负对照用例 + 规则自检 · 读取容错(单文件损坏降级为结构化结果并计数,不抛出)。
|
|
33
33
|
|
|
34
34
|
---
|
|
@@ -58,7 +58,7 @@ dsh-retrace 的「日志体检与修复」能力——与 dsh-retrace 一起构
|
|
|
58
58
|
---
|
|
59
59
|
|
|
60
60
|
## 三层契约(判定模型)
|
|
61
|
-
>
|
|
61
|
+
> 57 条规则,覆盖以下各层(`contracts` 列出全部,每条附官方源码出处)。
|
|
62
62
|
|
|
63
63
|
| 层 | 规则 | 守护什么 |
|
|
64
64
|
|---|---|---|
|
|
@@ -80,7 +80,7 @@ dsh-retrace 的「日志体检与修复」能力——与 dsh-retrace 一起构
|
|
|
80
80
|
|---|---|---|
|
|
81
81
|
| 宿主包 | `@deepseek-ai/dsh-session@0.2.0-rc.2` | 本规则集开发与 CI 验证所用的版本(CI 跑 `pnpm check` + `pnpm test`;`prepublishOnly` 四步在本机该版本上全绿) |
|
|
82
82
|
| 会话格式 | **v4**(`SESSION_FORMAT_VERSION = 4`) | v4 走运行时词表 + 官方 `foldSurface` 终验 |
|
|
83
|
-
| 声明范围 | `peerDependencies: ^0.1.0-rc.7 || ^0.1.5-rc.1 || ^0.2.0-rc.1` | 允许安装;**范围内不等于逐个验证过** |
|
|
83
|
+
| 声明范围 | `peerDependencies: ^0.1.0-rc.7 || ^0.1.5-rc.1 || ^0.1.7-rc.2 || ^0.2.0-rc.1` | 允许安装;**范围内不等于逐个验证过** |
|
|
84
84
|
| 已知格式 | 0 / 1 / 2 / 3 / 4 | 0–2 由本包**自带** vendored 词表 + 本地等价折叠(`legacyFoldSurface`)支持,与宿主版本无关 |
|
|
85
85
|
|
|
86
86
|
**未验证的版本会发生什么(运行时检测并报告,不闷着按旧规则判)**:
|
|
@@ -98,7 +98,7 @@ dsh-retrace 的「日志体检与修复」能力——与 dsh-retrace 一起构
|
|
|
98
98
|
|
|
99
99
|
```
|
|
100
100
|
版本支持:宿主 @deepseek-ai/dsh-session@0.2.0-rc.2(基线 0.2.0-rc.2,baseline) | 文件格式 v4(header,baseline)
|
|
101
|
-
测试基线:@deepseek-ai/dsh-session@0.2.0-rc.2 | 会话格式 v4(已知 0/1/2/3/4;peer ^0.1.0-rc.7 || ^0.1.5-rc.1 || ^0.2.0-rc.1)
|
|
101
|
+
测试基线:@deepseek-ai/dsh-session@0.2.0-rc.2 | 会话格式 v4(已知 0/1/2/3/4;peer ^0.1.0-rc.7 || ^0.1.5-rc.1 || ^0.1.7-rc.2 || ^0.2.0-rc.1)
|
|
102
102
|
```
|
|
103
103
|
|
|
104
104
|
## 🆕 0.3.28 · 读取容错 / 尾部完整性 / seq 来源
|
|
@@ -129,10 +129,10 @@ dsh-retrace 的「日志体检与修复」能力——与 dsh-retrace 一起构
|
|
|
129
129
|
|
|
130
130
|
- `tool/result` 按 v4 形状校验(`role: 'tool'`、无 `tool-result` 包裹块)
|
|
131
131
|
- `system/message` 接受 v4 的 `source.kind: 'system-prompt'`
|
|
132
|
-
- **v3
|
|
132
|
+
- **v3 及更早的判据零改动**(多份真实语料 v3 会话前后判定完全一致)
|
|
133
133
|
- 格式闸门仍**拒绝未知的未来版本**(`readOnly`);v5+ 按设计保持"不可评估"
|
|
134
134
|
|
|
135
|
-
**规则(0.3.28
|
|
135
|
+
**规则(0.3.28 起 55 条;0.3.32 起 57 条)**:下表五条是 0.3.18 – 0.3.24 窗口新增
|
|
136
136
|
(0.3.28 新增的四条见上一节):
|
|
137
137
|
|
|
138
138
|
| 规则 | 判据 |
|
|
@@ -143,12 +143,12 @@ dsh-retrace 的「日志体检与修复」能力——与 dsh-retrace 一起构
|
|
|
143
143
|
| `P5` | 两段 carrier 配对:第 2 段首元素 = 第 1 段 seq(读侧兼容早期写法) |
|
|
144
144
|
| `A1` | 「在位可还原」**只认结构化字段**(`archiveRef`/`archive`/`externalized.*`),不从自由文本推断 |
|
|
145
145
|
|
|
146
|
-
|
|
146
|
+
**大会话**:读取改为**按行解码**(不再整文件字符串化 ⇒ 约 536MB 以上不再抛 `ERR_STRING_TOO_LONG`);
|
|
147
147
|
修复采用**流式帧重建** `.jsonl.zstd`(header 帧 + 正文分块多帧,逐帧 checksum + roundtrip 校验)。
|
|
148
148
|
|
|
149
149
|
**Windows**:`H2` 的 `header.cwd` 绝对路径判断改为**平台感知**(`win32` 与 `posix` 都认)。
|
|
150
150
|
|
|
151
|
-
**兼容性**:Node ≥ 22;`@deepseek-ai/dsh-session` `^0.1.0-rc.7 || ^0.1.5-rc.1 || ^0.2.0-rc.1`;会话格式 v0–v4。
|
|
151
|
+
**兼容性**:Node ≥ 22;`@deepseek-ai/dsh-session` `^0.1.0-rc.7 || ^0.1.5-rc.1 || ^0.1.7-rc.2 || ^0.2.0-rc.1`;会话格式 v0–v4。
|
|
152
152
|
|
|
153
153
|
## 案例记录 ——「生产级保证」不是口号
|
|
154
154
|
下面每一条都来自**生产会话中实际出现的日志损坏形态**——正是这些案例促成了本工具。日期与形态真实,会话 id 与文件名省略。
|
|
@@ -165,7 +165,7 @@ dsh-retrace 的「日志体检与修复」能力——与 dsh-retrace 一起构
|
|
|
165
165
|
| 8 | 2026-08-31 | **尾帧在写入中被撕裂**的日志完全无法加载、且没有诊断 ⇒ **Z1** + 明确报「尾帧撕裂 / 写入中」 | |
|
|
166
166
|
| 9 | 2026-09-09 | **会话格式 v4** 下 `tool/result` 改用 `role:'tool'`、`system/message` 带 `system-prompt` 来源 → v3 语义的检查在**健康 v4 日志**上产出**数千条误报** ⇒ 版本分派 + **E6/E9** v4 语义 | |
|
|
167
167
|
| 10 | 2026-09-17 | **Windows** 上 `header.cwd` 用 POSIX 规则判定 → **所有**会话被 **H2** 误报 ⇒ 平台感知的绝对路径判定 | |
|
|
168
|
-
| 11 | 2026-10-20 | **超过
|
|
168
|
+
| 11 | 2026-10-20 | **超过 500MB 的会话**让读取器崩溃(`ERR_STRING_TOO_LONG`),修复时又把全文拼进内存 ⇒ 按行解码 + 流式帧重建 | |
|
|
169
169
|
| 12 | 2026-10-20 | 两段式载体引用有的把「审计段」写在前面、早期约定从区间起点开始 → 读取侧报出**数百个假孤儿载体** ⇒ **P5** 写侧成对 + 读侧容错 | |
|
|
170
170
|
| 13 | 2026-10-20 | `seedLength` 被部分消费方当作**字节数**(其语义是「继承事件条数」),且 `parentSession` 配缺失/0 被当成损坏 ⇒ **I2** 语义钉死 | |
|
|
171
171
|
| 14 | 2026-10-20 | 一种**未知但显式可忽略**的事件类型让整条迁移卡死 ⇒ **G4** 声明式跳过 + 白名单 | |
|
|
@@ -199,8 +199,8 @@ pnpm dlx dsh-log-contract --help
|
|
|
199
199
|
### 1. 离线体检
|
|
200
200
|
|
|
201
201
|
```bash
|
|
202
|
-
dsh-log-contract check
|
|
203
|
-
dsh-log-contract check
|
|
202
|
+
dsh-log-contract check ~/.dsh/sessions/<id>.jsonl.zstd
|
|
203
|
+
dsh-log-contract check ~/.dsh/sessions/<id>.jsonl.zstd --json # 机器可读
|
|
204
204
|
```
|
|
205
205
|
|
|
206
206
|
输出示例:
|
|
@@ -236,14 +236,31 @@ dsh-log-contract check [path]<id>.jsonl.zstd --json # 机器可读
|
|
|
236
236
|
tool_calls 与其结果之间"——这类问题 DeepSeek 曾容忍,但 MiMo 等严格端点会直接
|
|
237
237
|
`INVALID_REQUEST`(2026-08-27 实锤)。
|
|
238
238
|
|
|
239
|
+
### 1.1 错误表达契约检查(`error-contract`)
|
|
240
|
+
|
|
241
|
+
对「错误是怎么抛的」做静态扫描(源码文本;不做 AST):
|
|
242
|
+
E1 一个码多成因 / E2 message 是常量 / E3 终态词用于非终态因 / E4 `cause` 未透出 /
|
|
243
|
+
E5 无条件成功(候选)/ E6 声称无执行点(候选)。
|
|
244
|
+
|
|
245
|
+
```bash
|
|
246
|
+
dsh-log-contract error-contract lib/ bin/ --json # T1(我方代码):命中 ⇒ exit 1
|
|
247
|
+
dsh-log-contract error-contract <pkg>/lib/index.js --target T2 # T2(第三方):只登记,exit 0
|
|
248
|
+
dsh-log-contract error-contract lib/ --keys thresholdRatio,headroom # E6① 声明 key 的读取点
|
|
249
|
+
dsh-log-contract error-contract lib/ --config cordis.patch.yml # E6① 从 YAML config 段派生
|
|
250
|
+
```
|
|
251
|
+
|
|
252
|
+
⚠️ **输出是可疑清单,不是缺陷认定**:规则是启发式的、必然有假阳性——每条命中带原始
|
|
253
|
+
`evidence` 供人工复核;白名单条目必须带 `expires` 到期日(缺失/非法/过期 ⇒ exit 2,fail-closed)。
|
|
254
|
+
完整判据、假阳性风险与白名单格式:[docs/ERROR-CONTRACT.md](docs/ERROR-CONTRACT.md)。
|
|
255
|
+
|
|
239
256
|
### 2. 修复(`fix`)
|
|
240
257
|
|
|
241
258
|
```bash
|
|
242
259
|
# 干跑(只报告):严格 seq 连续扫描 + 全契约体检(含 W1/W2)+ 可移除 marker 数
|
|
243
|
-
dsh-log-contract fix
|
|
260
|
+
dsh-log-contract fix ~/.dsh/sessions/<id>.jsonl.zstd --remove-markers
|
|
244
261
|
|
|
245
262
|
# 应用:备份后落盘(.zstd 走官方帧格式重建:帧1=header、帧2=其余、checksum、单个结尾换行)
|
|
246
|
-
dsh-log-contract fix
|
|
263
|
+
dsh-log-contract fix ~/.dsh/sessions/<id>.jsonl.zstd --remove-markers --apply
|
|
247
264
|
```
|
|
248
265
|
|
|
249
266
|
- `--remove-markers`:移除 retrace/message-editor marker 并全量重编号
|
|
@@ -269,7 +286,7 @@ dsh-log-contract fix [path]<id>.jsonl.zstd --remove-markers --apply
|
|
|
269
286
|
```
|
|
270
287
|
|
|
271
288
|
```bash
|
|
272
|
-
dsh-log-contract prewrite marker-write.json --log
|
|
289
|
+
dsh-log-contract prewrite marker-write.json --log ~/.dsh/sessions/<id>.jsonl.zstd
|
|
273
290
|
```
|
|
274
291
|
|
|
275
292
|
- 基线本身有 error 级违规时直接拒绝校验(安全修复协议第 2 步:**改前基线必须绿**)。
|
|
@@ -385,7 +402,7 @@ git config --get core.hooksPath # 验证:应输出 .githooks
|
|
|
385
402
|
|
|
386
403
|
**会话格式 v4**(宿主 `dsh-session` 0.2.x)改为按版本分派判定(`tool/result` 的 role、`system/message` 的来源);
|
|
387
404
|
新增五条规则(`G4` 未知但可忽略事件、`S10` 引用元素类型、`I2` `seedLength` 语义、`P5` 载体配对、`A1` 只认结构化字段的在位可还原);
|
|
388
|
-
|
|
405
|
+
大会话(>500MB)按行读取 + 流式帧重建;Windows 的 `header.cwd` 判定改为平台感知。
|
|
389
406
|
> **0.3.17 不含行为变更。** 它只调整了注释、测试标题、少量诊断文案与 README 的措辞。
|
|
390
407
|
> 所有判定结果、退出码与 `--json` 字段与 0.3.15 完全一致,
|
|
391
408
|
> 因此从 0.3.12 升到 0.3.17 时,下面各条与原来完全一致。
|
package/bin/dsh-log-contract.mjs
CHANGED
|
@@ -13,13 +13,13 @@
|
|
|
13
13
|
* contracts 列出内置契约规则目录
|
|
14
14
|
*/
|
|
15
15
|
import fs from 'node:fs';
|
|
16
|
-
import { delimiter as pathDelimiter } from 'node:path';
|
|
17
|
-
import { loadSessionLog, validateSessionLog, resumeVerdict, migrationVerdict, assessmentScope, createPreWriter, repairSession, readSessionHeader, CONTRACT_RULES, ruleById, extractToolOutputs, auditToolCalls, hostCapability, HOST_MAX_FILE_VERSION, detectSupport } from '../lib/index.js';
|
|
16
|
+
import { delimiter as pathDelimiter, join as pathJoin } from 'node:path';
|
|
17
|
+
import { loadSessionLog, validateSessionLog, resumeVerdict, migrationVerdict, assessmentScope, createPreWriter, repairSession, readSessionHeader, CONTRACT_RULES, ruleById, explainRule, extractToolOutputs, auditToolCalls, hostCapability, HOST_MAX_FILE_VERSION, detectSupport, ERROR_CONTRACT_RULES, checkErrorContract, normalizePath } from '../lib/index.js';
|
|
18
18
|
|
|
19
19
|
/**
|
|
20
20
|
* 同步写 fd——`process.stdout.write` 在**管道**下是异步的,紧跟着的
|
|
21
21
|
* `process.exit()` 不会等待 flush:>~64KiB 的输出会丢尾,`--json` 因此变成非法 JSON
|
|
22
|
-
* (实测在 3000 事件夹具与真实
|
|
22
|
+
* (实测在 3000 事件夹具与真实 14.5MB v3 会话上复现,stdout 56648B 处 "Unterminated string")。
|
|
23
23
|
* 这里直接同步写 fd 1/2(非阻塞管道 EAGAIN 时自旋重试),做到"先写完再 exit"。
|
|
24
24
|
*/
|
|
25
25
|
function writeAllSync(fd, text) {
|
|
@@ -122,6 +122,32 @@ const USAGE = `dsh-log-contract —— 日志契约守护(DSH session log cont
|
|
|
122
122
|
dsh-log-contract contracts
|
|
123
123
|
列出内置契约规则目录(含官方源码出处)。
|
|
124
124
|
|
|
125
|
+
dsh-log-contract explain <ruleId> [--json]
|
|
126
|
+
规则解读:标题 / 判据(原文引自规则注册表,⛔ 不另立文本)/ 正反例指针
|
|
127
|
+
(指向 test/ 里的对照用例与夹具)/ 相关命令。
|
|
128
|
+
未知 id ⇒ 明确提示 + 非零退出;--json 输出稳定键集(id/found/title/severity/
|
|
129
|
+
layer/source/criteria/examples/relatedCommands/doc)。
|
|
130
|
+
|
|
131
|
+
dsh-log-contract error-contract <path...> [--json] [--target T1|T2] [--whitelist <file>]
|
|
132
|
+
[--keys <json|a,b,c>] [--config <cordis.patch.yml>]
|
|
133
|
+
[--exclude <path[,path]>] [--strict]
|
|
134
|
+
错误表达契约静态检查(E1–E6 · 可疑清单,⛔ 不是"某包违规"的认定)。
|
|
135
|
+
E1 一个码多成因 / E2 message 是常量 / E3 终态词用于非终态因 / E4 cause 未透出 /
|
|
136
|
+
E5 无条件成功(候选)/ E6 声称无执行点(候选)。
|
|
137
|
+
path 可为文件或目录(目录递归 *.js/*.mjs/*.cjs + README*.md);--target T1 我方代码
|
|
138
|
+
(命中 ⇒ exit 1)/ T2 官方产物(只登记 ⇒ 默认 exit 0,--strict 才非 0)。
|
|
139
|
+
--whitelist <file> 逐条例外 JSON:{entries:[{rule,file,line?,reason,expires}]}
|
|
140
|
+
expires 必填 YYYY-MM-DD;缺失/非法/过期 ⇒ exit 2(fail-closed)。
|
|
141
|
+
--keys / --config E6① 的配置声明来源:--keys 给 JSON 数组/逗号列表,--config 从
|
|
142
|
+
YAML 的 config: 段派生 key,再查代码里有无读取点。
|
|
143
|
+
--exclude <path> 显式排除(可重复/逗号分隔;目录前缀匹配)。默认已跳过
|
|
144
|
+
node_modules/.git/reports;扫仓库根时用 --exclude test,contract
|
|
145
|
+
把测试与未接线骨架排除在发布面之外。
|
|
146
|
+
--json 输出稳定键集(schemaVersion/family/target/rules/findings/summary);
|
|
147
|
+
每条 finding 带 id/rule/severity/evidence。
|
|
148
|
+
退出码:0 绿 | 1 T1 命中(T2 默认不阻断,--strict 才 1)| 2 无法判定
|
|
149
|
+
(target 非法/路径不存在/无参/白名单不合规)。
|
|
150
|
+
|
|
125
151
|
dsh-log-contract --version / --help
|
|
126
152
|
`;
|
|
127
153
|
|
|
@@ -146,7 +172,7 @@ function printViolations(violations, maxDetails = 8) {
|
|
|
146
172
|
}
|
|
147
173
|
}
|
|
148
174
|
|
|
149
|
-
/** 漂移抬头(2026-09-14):漂移清单 +
|
|
175
|
+
/** 漂移抬头(2026-09-14):漂移清单 + 未复核清单 + "勿据此跑 fix --apply"。 */
|
|
150
176
|
function driftLines(drift, probes) {
|
|
151
177
|
if (!drift) return '';
|
|
152
178
|
const host = probes ? `${probes.hostPackage}(SESSION_FORMAT_VERSION=${probes.sessionFormatVersion},词表 ${probes.knownTypes} 类)` : '未知';
|
|
@@ -158,10 +184,10 @@ function driftLines(drift, probes) {
|
|
|
158
184
|
if (drift.unverifiedRules.length > 0) {
|
|
159
185
|
out += ` ⛔ **UNVERIFIED**(探针与规则假设不一致,结论不可采信):${drift.unverifiedRules.join('、')}\n`;
|
|
160
186
|
}
|
|
161
|
-
out += `
|
|
187
|
+
out += ` 出处未复核(已知债,仅告警):${drift.driftedSources.join('、')}\n`;
|
|
162
188
|
out += ` 判定前提存疑(仅告警):${drift.premiseStale.join('、')}${drift.undecidable.length ? `;无法判定:${drift.undecidable.join('、')}` : ''}\n`;
|
|
163
189
|
if (drift.fixApplyBlocked) {
|
|
164
|
-
out += ' ⛔ **禁止据此跑 `fix --apply`**(存在未验证规则:写入类动作不可逆)——先按 report
|
|
190
|
+
out += ' ⛔ **禁止据此跑 `fix --apply`**(存在未验证规则:写入类动作不可逆)——先按 report 复核这些规则或显式确认。\n';
|
|
165
191
|
}
|
|
166
192
|
return out;
|
|
167
193
|
}
|
|
@@ -304,7 +330,10 @@ function cmdCheck(args) {
|
|
|
304
330
|
const exitCode = notAssessable ? 3 : (!ok ? 1 : (migGate ? 4 : 0));
|
|
305
331
|
|
|
306
332
|
if (json) {
|
|
307
|
-
const payload = { file, ok, assessable: !notAssessable, assessmentScope: scope, host: hostCapability(), support: result.support ?? null, probes: result.probes ?? null, drift: result.drift ?? null, migration, summary, violations, archive: result.archive ?? null, ignorableDrops: result.ignorableDrops ?? null };
|
|
333
|
+
const payload = { schemaVersion: result.schemaVersion ?? '1', file, ok, assessable: !notAssessable, assessmentScope: scope, host: hostCapability(), support: result.support ?? null, probes: result.probes ?? null, drift: result.drift ?? null, migration, summary, violations, archive: result.archive ?? null, ignorableDrops: result.ignorableDrops ?? null };
|
|
334
|
+
// 新增键(additive,同 schemaVersion 下既有键不删/不改义):错误表达契约规则目录。
|
|
335
|
+
// findings 需要源码输入,故只在 `error-contract` 子命令产出;此处只给规则清单。
|
|
336
|
+
payload.errorContract = { family: 'error-expression', rules: ERROR_CONTRACT_RULES.map((r) => ({ id: r.id, severity: r.severity, title: r.title, layer: r.layer, target: r.target, falsePositiveRisk: r.falsePositiveRisk })), note: '静态规则目录;源码扫描用 error-contract 子命令' };
|
|
308
337
|
if (notAssessable) payload.notAssessable = result.notAssessable;
|
|
309
338
|
if (resume) payload.resume = resumeVerdict(result);
|
|
310
339
|
out(JSON.stringify(payload, null, 2) + '\n');
|
|
@@ -446,18 +475,199 @@ function cmdPrewrite(args) {
|
|
|
446
475
|
process.exit(1);
|
|
447
476
|
}
|
|
448
477
|
|
|
478
|
+
/**
|
|
479
|
+
* `error-contract <path...>` —— 错误表达契约静态检查(E1–E6 · 可疑清单,⛔ 非缺陷认定)。
|
|
480
|
+
* 输入:源码文件或目录(递归 *.js|*.mjs|*.cjs;*.md 仅做 E6 不变式句候选扫描)。
|
|
481
|
+
* --target T1(我方代码,命中 error/warning ⇒ exit 1)|T2(官方产物,只登记 ⇒ 默认 exit 0,--strict 才非 0)
|
|
482
|
+
* --whitelist <file>:{entries:[{rule,file,line?,reason,expires}]};expires 必填(缺失/非法/过期 ⇒ exit 2 fail-closed)。
|
|
483
|
+
*/
|
|
484
|
+
function cmdErrorContract(args) {
|
|
485
|
+
const json = args.includes('--json');
|
|
486
|
+
const strict = args.includes('--strict');
|
|
487
|
+
const valOf = (flag) => {
|
|
488
|
+
const i = args.indexOf(flag);
|
|
489
|
+
return i >= 0 && i + 1 < args.length ? args[i + 1] : null;
|
|
490
|
+
};
|
|
491
|
+
// N2:无法判定/用法错误一律 exit 2(与「红=1 / 绿=0」区分)
|
|
492
|
+
const target = String(valOf('--target') || 'T1').toUpperCase();
|
|
493
|
+
if (target !== 'T1' && target !== 'T2') {
|
|
494
|
+
errOut(`error-contract: --target 只允许 T1/T2(实际 ${target})—— 无法判定 ⇒ exit 2\n`);
|
|
495
|
+
process.exit(2);
|
|
496
|
+
}
|
|
497
|
+
const whitelistPath = valOf('--whitelist');
|
|
498
|
+
const configPath = valOf('--config');
|
|
499
|
+
const keysArg = valOf('--keys');
|
|
500
|
+
const VALUE_FLAGS = new Set(['--target', '--whitelist', '--config', '--keys', '--exclude']);
|
|
501
|
+
// N8:显式排除(可重复 / 逗号分隔;目录前缀匹配,归一化后比较)
|
|
502
|
+
const excludes = [];
|
|
503
|
+
args.forEach((a, i) => {
|
|
504
|
+
if (a === '--exclude' && args[i + 1]) {
|
|
505
|
+
for (const x of String(args[i + 1]).split(',').map((v) => v.trim()).filter(Boolean)) excludes.push(normalizePath(x));
|
|
506
|
+
}
|
|
507
|
+
});
|
|
508
|
+
// 语义:含 '/' ⇒ 前缀匹配(相对/绝对路径);不含 '/' ⇒ 按任意路径段(目录名)匹配
|
|
509
|
+
const isExcluded = (p) => excludes.some((x) => (x.includes('/')
|
|
510
|
+
? (p === x || p.startsWith(`${x}/`))
|
|
511
|
+
: (p === x || p.startsWith(`${x}/`) || p.endsWith(`/${x}`) || p.includes(`/${x}/`))));
|
|
512
|
+
const paths = args.filter((a, i) => {
|
|
513
|
+
if (a.startsWith('-')) return false;
|
|
514
|
+
return !VALUE_FLAGS.has(args[i - 1]);
|
|
515
|
+
});
|
|
516
|
+
if (paths.length === 0) {
|
|
517
|
+
errOut(`error-contract: 至少给一个路径(文件或目录)—— 无法判定 ⇒ exit 2\n\n`);
|
|
518
|
+
errOut(USAGE);
|
|
519
|
+
process.exit(2);
|
|
520
|
+
}
|
|
521
|
+
|
|
522
|
+
// N1:输入路径归一(去尾斜杠/折叠 //),保证 findings.file 与白名单比较同一口径
|
|
523
|
+
const files = [];
|
|
524
|
+
const walk = (p) => {
|
|
525
|
+
const np = normalizePath(p);
|
|
526
|
+
if (isExcluded(np)) return;
|
|
527
|
+
const st = fs.statSync(np);
|
|
528
|
+
if (st.isDirectory()) {
|
|
529
|
+
for (const name of fs.readdirSync(np)) {
|
|
530
|
+
if (name === 'node_modules' || name === '.git' || name === 'reports') continue;
|
|
531
|
+
walk(pathJoin(np, name));
|
|
532
|
+
}
|
|
533
|
+
return;
|
|
534
|
+
}
|
|
535
|
+
if (!/\.(mjs|cjs|js)$/i.test(np) && !/\.md$/i.test(np)) return;
|
|
536
|
+
files.push({ file: normalizePath(np), text: fs.readFileSync(np, 'utf8') });
|
|
537
|
+
};
|
|
538
|
+
for (const p of paths) {
|
|
539
|
+
if (!fs.existsSync(normalizePath(p))) {
|
|
540
|
+
errOut(`error-contract: 路径不存在: ${p} —— 无法判定 ⇒ exit 2\n`);
|
|
541
|
+
process.exit(2);
|
|
542
|
+
}
|
|
543
|
+
walk(p);
|
|
544
|
+
}
|
|
545
|
+
|
|
546
|
+
let whitelist = [];
|
|
547
|
+
if (whitelistPath) {
|
|
548
|
+
try {
|
|
549
|
+
whitelist = JSON.parse(fs.readFileSync(whitelistPath, 'utf8')).entries ?? [];
|
|
550
|
+
} catch (e) {
|
|
551
|
+
errOut(`error-contract: 白名单读取/解析失败(无法判定 ⇒ exit 2): ${e.message}\n`);
|
|
552
|
+
process.exit(2);
|
|
553
|
+
}
|
|
554
|
+
}
|
|
555
|
+
|
|
556
|
+
// N3:E6① 配置声明 key 的读取点检查(--keys 直接给,或 --config 从 YAML 派生)
|
|
557
|
+
const declaredKeys = [];
|
|
558
|
+
if (keysArg) {
|
|
559
|
+
try {
|
|
560
|
+
if (/\.json$/i.test(keysArg)) {
|
|
561
|
+
const j = JSON.parse(fs.readFileSync(keysArg, 'utf8'));
|
|
562
|
+
for (const k of (Array.isArray(j) ? j : (j.keys ?? []))) declaredKeys.push(typeof k === 'string' ? { name: k } : k);
|
|
563
|
+
} else {
|
|
564
|
+
for (const k of keysArg.split(',').map((x) => x.trim()).filter(Boolean)) declaredKeys.push({ name: k });
|
|
565
|
+
}
|
|
566
|
+
} catch (e) {
|
|
567
|
+
errOut(`error-contract: --keys 读取/解析失败(无法判定 ⇒ exit 2): ${e.message}\n`);
|
|
568
|
+
process.exit(2);
|
|
569
|
+
}
|
|
570
|
+
}
|
|
571
|
+
if (configPath) {
|
|
572
|
+
let text = '';
|
|
573
|
+
try { text = fs.readFileSync(configPath, 'utf8'); }
|
|
574
|
+
catch (e) { errOut(`error-contract: --config 读取失败(无法判定 ⇒ exit 2): ${e.message}\n`); process.exit(2); }
|
|
575
|
+
let inConfig = false;
|
|
576
|
+
text.split('\n').forEach((line, i) => {
|
|
577
|
+
const noComment = line.replace(/#.*$/, '');
|
|
578
|
+
if (/^config\s*:/.test(noComment)) { inConfig = true; return; }
|
|
579
|
+
if (inConfig && /^\S/.test(noComment) && noComment.trim()) { inConfig = false; return; }
|
|
580
|
+
if (!inConfig) return;
|
|
581
|
+
const m = noComment.match(/^\s+([A-Za-z_][\w-]*)\s*:/);
|
|
582
|
+
if (m) declaredKeys.push({ name: m[1], line: i + 1, file: normalizePath(configPath) });
|
|
583
|
+
});
|
|
584
|
+
}
|
|
585
|
+
|
|
586
|
+
const report = checkErrorContract({ files, target, whitelist, declaredKeys });
|
|
587
|
+
if (report.summary.whitelistProblems.length) {
|
|
588
|
+
errOut(`error-contract: ⛔ 白名单不合规(fail-closed ⇒ exit 2):\n${report.summary.whitelistProblems.map((x) => ` - ${x}`).join('\n')}\n`);
|
|
589
|
+
process.exit(2);
|
|
590
|
+
}
|
|
591
|
+
const hits = report.findings.filter((f) => f.severity === 'error' || f.severity === 'warning');
|
|
592
|
+
const candidates = report.findings.filter((f) => f.severity === 'info');
|
|
593
|
+
const exitCode = target === 'T2' ? (strict && report.findings.length ? 1 : 0) : (hits.length ? 1 : 0);
|
|
594
|
+
|
|
595
|
+
if (json) {
|
|
596
|
+
out(JSON.stringify(report, null, 2) + '\n');
|
|
597
|
+
process.exit(exitCode);
|
|
598
|
+
}
|
|
599
|
+
|
|
600
|
+
out(`\n🔎 dsh-log-contract error-contract —— target=${target} | 扫 ${files.length} 个文件 | 可疑 ${report.findings.length}(白名单抑制 ${report.summary.suppressed})\n`);
|
|
601
|
+
out(' ⚠️ 启发式检查:输出的是**可疑清单**,不是"某包违规"的认定;每条请开 --json 看 evidence 后人工复核。\n');
|
|
602
|
+
out(` E1 多成因 ${report.summary.byRule.E1 || 0} | E2 常量 message ${report.summary.byRule.E2 || 0} | E3 终态词 ${report.summary.byRule.E3 || 0} | E4 cause 未透出 ${report.summary.byRule.E4 || 0} | E5 无条件成功 ${report.summary.byRule.E5 || 0} | E6 无执行点 ${report.summary.byRule.E6 || 0}\n`);
|
|
603
|
+
for (const f of report.findings) {
|
|
604
|
+
const loc = f.line ? `:${f.line}` : '';
|
|
605
|
+
out(` [${f.severity}] ${f.id} ${f.file}${loc} — ${f.message}\n`);
|
|
606
|
+
}
|
|
607
|
+
if (!report.findings.length) out(' ✔ 未发现可疑点(注意:规则集只覆盖 E1–E6,未覆盖 ≠ 无问题)\n');
|
|
608
|
+
out(`\n 目标口径:T1=我方代码(要修)|T2=官方产物(只登记/报上游)—— 两类不混报。\n`);
|
|
609
|
+
if (candidates.length) out(` ℹ️ 其中 ${candidates.length} 条为候选(E5/E6),默认不阻断,需人工确认。\n`);
|
|
610
|
+
out('\n');
|
|
611
|
+
process.exit(exitCode);
|
|
612
|
+
}
|
|
613
|
+
|
|
449
614
|
function cmdContracts() {
|
|
450
615
|
out('dsh-log-contract 契约规则目录(spec:官方源码逐行核对 + 实测事故固化)\n\n');
|
|
451
616
|
for (const r of CONTRACT_RULES) {
|
|
452
617
|
const flags = [
|
|
453
618
|
r.candidate ? '候选规则' : null,
|
|
454
|
-
r.sourceVerified === false ? '
|
|
619
|
+
r.sourceVerified === false ? '出处未复核' : null,
|
|
455
620
|
r.premiseStale ? '判定前提存疑' : null,
|
|
456
621
|
].filter(Boolean).join(' / ');
|
|
457
622
|
out(` ${r.id} [${r.severity}/${r.layer}] ${r.title}${flags ? ` ⟪${flags}⟫` : ''}\n ${r.description}\n 出处: ${r.source}\n\n`);
|
|
458
623
|
}
|
|
459
624
|
}
|
|
460
625
|
|
|
626
|
+
/**
|
|
627
|
+
* `explain <ruleId>` —— 规则解读(标题 / 判据 / 正反例指针 / 相关命令)。
|
|
628
|
+
* 数据源 = `lib/contracts.js` 规则注册表(单一权威,判据原文引用);
|
|
629
|
+
* 未知 id ⇒ 明确提示 + 非零退出(--json 时输出同键稳定结构 + found:false)。
|
|
630
|
+
*/
|
|
631
|
+
function cmdExplain(args) {
|
|
632
|
+
const json = args.includes('--json');
|
|
633
|
+
const id = args.find((a) => !a.startsWith('-'));
|
|
634
|
+
if (!id) fail(USAGE);
|
|
635
|
+
const info = explainRule(id);
|
|
636
|
+
if (!info.found) {
|
|
637
|
+
if (json) {
|
|
638
|
+
out(JSON.stringify(info, null, 2) + '\n');
|
|
639
|
+
} else {
|
|
640
|
+
errOut(`❌ ${info.hint}\n`);
|
|
641
|
+
}
|
|
642
|
+
process.exit(1);
|
|
643
|
+
}
|
|
644
|
+
if (json) {
|
|
645
|
+
out(JSON.stringify(info, null, 2) + '\n');
|
|
646
|
+
process.exit(0);
|
|
647
|
+
}
|
|
648
|
+
out(`\n📘 dsh-log-contract explain —— ${info.id}\n\n`);
|
|
649
|
+
out(` id ${info.id} | 严重度 ${info.severity} | 层级 ${info.layer}\n`);
|
|
650
|
+
out(` 标题 ${info.title}\n`);
|
|
651
|
+
out(` 出处 ${info.source}\n\n`);
|
|
652
|
+
out(' 判据 / 触发条件(原文引自规则注册表 lib/contracts.js;⛔ 不另立第二权威):\n');
|
|
653
|
+
out(` ${info.criteria}\n\n`);
|
|
654
|
+
out(' 正/反例指针(测试 / 夹具):\n');
|
|
655
|
+
const rows = [
|
|
656
|
+
...info.examples.negative.map((p) => ['反例', p]),
|
|
657
|
+
...info.examples.positive.map((p) => ['正例', p]),
|
|
658
|
+
...info.examples.unclassified.map((p) => ['对照', p]),
|
|
659
|
+
];
|
|
660
|
+
if (rows.length === 0) {
|
|
661
|
+
out(` ${info.examples.note ?? '(未找到该 id 的对照引用——以规则注册表判据为准)'}\n`);
|
|
662
|
+
} else {
|
|
663
|
+
for (const [kind, p] of rows.slice(0, 12)) out(` [${kind}] ${p}\n`);
|
|
664
|
+
}
|
|
665
|
+
out('\n 相关命令:\n');
|
|
666
|
+
for (const c of info.relatedCommands) out(` - ${c}\n`);
|
|
667
|
+
out(`\n 完整目录:${info.doc}(由规则注册表生成)\n\n`);
|
|
668
|
+
process.exit(0);
|
|
669
|
+
}
|
|
670
|
+
|
|
461
671
|
function cmdFix(args) {
|
|
462
672
|
const json = args.includes('--json');
|
|
463
673
|
const removeMarkers = args.includes('--remove-markers');
|
|
@@ -603,4 +813,6 @@ else if (cmd === 'audit-report') cmdAuditReport(args.slice(1));
|
|
|
603
813
|
else if (cmd === 'prewrite') cmdPrewrite(args.slice(1));
|
|
604
814
|
else if (cmd === 'fix') cmdFix(args.slice(1));
|
|
605
815
|
else if (cmd === 'contracts') cmdContracts();
|
|
816
|
+
else if (cmd === 'error-contract') cmdErrorContract(args.slice(1));
|
|
817
|
+
else if (cmd === 'explain') cmdExplain(args.slice(1));
|
|
606
818
|
else fail(`未知子命令 "${cmd}"\n\n${USAGE}`);
|