dsh-log-contract 0.3.36 → 0.3.38
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 +28 -7
- package/README.zh.md +23 -4
- package/bin/dsh-log-contract.mjs +10 -1
- package/docs/CONTRACTS.md +1 -1
- package/docs/interface-versioning.md +50 -4
- package/lib/checks.js +153 -14
- package/lib/contracts.js +1 -1
- package/lib/identity.js +248 -0
- package/lib/index.js +2 -1
- package/lib/validate.js +5 -4
- package/package.json +3 -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** · **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
|
-
>
|
|
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
|
|---|---|---|
|
|
@@ -94,6 +96,24 @@ line-by-line verification against the official Host source (each rule carries it
|
|
|
94
96
|
|
|
95
97
|
---
|
|
96
98
|
|
|
99
|
+
## Identity contract (ID1 / ID2) — "is what runs what you think it is?"
|
|
100
|
+
A **separate report family** (`version-identity`): not counted in the 57 log-contract rules,
|
|
101
|
+
and **not part of `ok` / exit codes** — it answers whether the artifact you run is the one
|
|
102
|
+
the declared version promises.
|
|
103
|
+
|
|
104
|
+
| Rule | What it guards |
|
|
105
|
+
|---|---|
|
|
106
|
+
| `ID1` | **One version, one digest**: the registry (`docs/identity-registry.json`) must not map one version to two different content digests ⇒ red with `file:line` evidence (duplicate entries sharing the same digest do not fire). |
|
|
107
|
+
| `ID2` | **The number is verifiable**: the digest is computed **from the artifact** — runtime identity = `lib/**/*.js` + `bin/**/*.mjs`, per-file sha256 → sorted → sha256 — and bound to `package.json.version`. Unregistered version, mismatched or **forged** digest, or *same version after a code change* ⇒ red. **Doc-only changes keep the digest unchanged ⇒ green** (no noise). |
|
|
108
|
+
|
|
109
|
+
`check --json` exposes it as the `identity` section (`family`, `rules`, `ok`, `version`,
|
|
110
|
+
`digest`, `runtime`, `registry`, `findings[]` with `file:line`, `summary`); `identity.ok` is
|
|
111
|
+
`null` (**unverifiable**, never "pass") when the registry is absent — npm tarballs ship
|
|
112
|
+
`docs/**/*.md` only. After a version bump or a runtime-code change, re-register:
|
|
113
|
+
`pnpm identity:register` (or `node scripts/identity-register.mjs [version]`).
|
|
114
|
+
|
|
115
|
+
---
|
|
116
|
+
|
|
97
117
|
## Version support (host / session format)
|
|
98
118
|
**Tested baseline (the versions this rule set was verified against)**:
|
|
99
119
|
|
|
@@ -160,7 +180,7 @@ rather than by relaxing the format gate:
|
|
|
160
180
|
- validation for v3 and earlier is **unchanged** (identical verdicts on 408 real v3 sessions before/after)
|
|
161
181
|
- the format gate still rejects **unknown** future versions (`readOnly`); v5+ remains unassessable by design
|
|
162
182
|
|
|
163
|
-
**Rules (55 as of 0.3.28, 57 as of 0.3.32):** the five rules below were added in the
|
|
183
|
+
**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
184
|
0.3.18 – 0.3.24 window (see above for the 0.3.28 additions):
|
|
165
185
|
|
|
166
186
|
| Rule | Checks |
|
|
@@ -269,11 +289,11 @@ when the host cannot judge the file.
|
|
|
269
289
|
read* are self-consistent — see the `tailStatus` note in the 0.3.28 section above.
|
|
270
290
|
|
|
271
291
|
**Report structure versioning (`schemaVersion`)**: every `check --json` report
|
|
272
|
-
carries a top-level `schemaVersion` (currently `"
|
|
292
|
+
carries a top-level `schemaVersion` (currently `"2"`) that versions the **report
|
|
273
293
|
structure** itself — field set / types / meanings — not the tool version and not
|
|
274
294
|
the log format version. Within one version, reports are additive only (existing
|
|
275
295
|
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:
|
|
296
|
+
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
297
|
[docs/interface-versioning.md](./docs/interface-versioning.md).
|
|
278
298
|
|
|
279
299
|
`check` adds **W1/W2 wire-level checks** since 0.2.0: expand the model request
|
|
@@ -284,7 +304,8 @@ results" — tolerated by some endpoints, `INVALID_REQUEST` on strict ones
|
|
|
284
304
|
|
|
285
305
|
### 1.1 Error-expression contract scan (`error-contract`)
|
|
286
306
|
|
|
287
|
-
Static scan of *how errors are raised* (source text; no AST)
|
|
307
|
+
Static scan of *how errors are raised* (source text; no AST). This is the **6-rule
|
|
308
|
+
error-expression family** (E1–E6; 63 = 57 log-contract + 6 here):
|
|
288
309
|
E1 one code with many causes · E2 constant message · E3 terminal word on a non-terminal
|
|
289
310
|
cause · E4 `cause` not surfaced · E5 unconditional success (candidate) · E6 claims with no
|
|
290
311
|
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
|
|
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
|
|
61
|
+
> **63 条规则分两族**:以下各层的**日志契约 57 条**(每条附官方源码出处)+ **错误表达契约 6 条**
|
|
62
|
+
> (E1–E6,见 §1.1)。`contracts` 列出日志契约 57 条;错误表达规则目录由 `check --json` 的
|
|
63
|
+
> `errorContract` 返回,`error-contract` 子命令对源码做第二族扫描。
|
|
62
64
|
|
|
63
65
|
| 层 | 规则 | 守护什么 |
|
|
64
66
|
|---|---|---|
|
|
@@ -73,6 +75,22 @@ dsh-retrace 的「日志体检与修复」能力——与 dsh-retrace 一起构
|
|
|
73
75
|
|
|
74
76
|
---
|
|
75
77
|
|
|
78
|
+
## 身份契约(ID1 / ID2)——「跑的东西是不是你以为的那个」
|
|
79
|
+
**独立报告域**(`family: version-identity`):**不并入** 57 条日志契约计数,也**不进** `ok`/退出码——
|
|
80
|
+
它回答"你跑的产物是不是声明版本承诺的那一份"。
|
|
81
|
+
|
|
82
|
+
| 规则 | 守护什么 |
|
|
83
|
+
|---|---|
|
|
84
|
+
| `ID1` | **一物一号**:登记表(`docs/identity-registry.json`)里同一版本不得对应两个不同内容摘要 ⇒ 判红(带 `file:line` 证据;重复登记但摘要相同不报,防噪音)。 |
|
|
85
|
+
| `ID2` | **号可验**:摘要必须由**产物**实算——运行身份 = `lib/**/*.js` + `bin/**/*.mjs` 逐文件 sha256 → 按路径排序后再 sha256——并与 `package.json.version` 绑定。未登记版本、摘要不符或**伪造**、"同号改了代码" ⇒ 判红;**只改文档/测试/机制件 ⇒ 摘要不变 ⇒ 绿**(防噪音)。 |
|
|
86
|
+
|
|
87
|
+
`check --json` 以 `identity` 段输出(`family` / `rules` / `ok` / `version` / `digest` / `runtime` /
|
|
88
|
+
`registry` / `findings[]`(含 `file:line`)/ `summary`);登记表缺失时 `identity.ok = null`
|
|
89
|
+
(**unverifiable**,不冒充通过——npm 包只含 `docs/**/*.md`)。换版本或改运行时代码后重登记:
|
|
90
|
+
`pnpm identity:register`(或 `node scripts/identity-register.mjs [version]`)。
|
|
91
|
+
|
|
92
|
+
---
|
|
93
|
+
|
|
76
94
|
## 版本支持(宿主 / 会话格式)
|
|
77
95
|
**测试基线(本规则集验证过的版本)**:
|
|
78
96
|
|
|
@@ -132,7 +150,7 @@ dsh-retrace 的「日志体检与修复」能力——与 dsh-retrace 一起构
|
|
|
132
150
|
- **v3 及更早的判据零改动**(多份真实语料 v3 会话前后判定完全一致)
|
|
133
151
|
- 格式闸门仍**拒绝未知的未来版本**(`readOnly`);v5+ 按设计保持"不可评估"
|
|
134
152
|
|
|
135
|
-
**规则(0.3.28 起 55 条;0.3.32 起 57
|
|
153
|
+
**规则(0.3.28 起 55 条;0.3.32 起 57 条;0.3.36 起共 63 条 = 57 日志契约 + 6 错误表达契约)**:下表五条是 0.3.18 – 0.3.24 窗口新增
|
|
136
154
|
(0.3.28 新增的四条见上一节):
|
|
137
155
|
|
|
138
156
|
| 规则 | 判据 |
|
|
@@ -238,7 +256,8 @@ tool_calls 与其结果之间"——这类问题 DeepSeek 曾容忍,但 MiMo
|
|
|
238
256
|
|
|
239
257
|
### 1.1 错误表达契约检查(`error-contract`)
|
|
240
258
|
|
|
241
|
-
对「错误是怎么抛的」做静态扫描(源码文本;不做 AST
|
|
259
|
+
对「错误是怎么抛的」做静态扫描(源码文本;不做 AST)。这是**错误表达契约 6 条**
|
|
260
|
+
(E1–E6;63 = 日志契约 57 + 本族 6):
|
|
242
261
|
E1 一个码多成因 / E2 message 是常量 / E3 终态词用于非终态因 / E4 `cause` 未透出 /
|
|
243
262
|
E5 无条件成功(候选)/ E6 声称无执行点(候选)。
|
|
244
263
|
|
package/bin/dsh-log-contract.mjs
CHANGED
|
@@ -14,7 +14,7 @@
|
|
|
14
14
|
*/
|
|
15
15
|
import fs from 'node:fs';
|
|
16
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';
|
|
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, checkIdentity, IDENTITY_RULES, packageRoot } from '../lib/index.js';
|
|
18
18
|
|
|
19
19
|
/**
|
|
20
20
|
* 同步写 fd——`process.stdout.write` 在**管道**下是异步的,紧跟着的
|
|
@@ -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
|
}
|
|
@@ -334,6 +339,10 @@ function cmdCheck(args) {
|
|
|
334
339
|
// 新增键(additive,同 schemaVersion 下既有键不删/不改义):错误表达契约规则目录。
|
|
335
340
|
// findings 需要源码输入,故只在 `error-contract` 子命令产出;此处只给规则清单。
|
|
336
341
|
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 子命令' };
|
|
342
|
+
// IDENTITY 段(schemaVersion 3 · additive):版本同一性(判据 −1:跑的东西是不是你以为的那个)。
|
|
343
|
+
// ⛔ 只给诊断,不进 ok/退出码;登记表缺失(npm 安装包不含 internal/)⇒ ok:null(unverifiable)。
|
|
344
|
+
const identity = checkIdentity({ root: packageRoot() });
|
|
345
|
+
payload.identity = { ...identity, rules: IDENTITY_RULES.map((r) => ({ id: r.id, severity: r.severity, title: r.title, layer: r.layer })) };
|
|
337
346
|
if (notAssessable) payload.notAssessable = result.notAssessable;
|
|
338
347
|
if (resume) payload.resume = resumeVerdict(result);
|
|
339
348
|
out(JSON.stringify(payload, null, 2) + '\n');
|
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
|
-
| 当前值 | `"
|
|
13
|
+
| 当前值 | `"3"`(字符串,暂不采用 semver;见下文 v2 / v3) |
|
|
14
14
|
| 覆盖范围 | 仅 `check --json` 这一份报告结构。`prewrite --json` 是**另一份结构**,暂不带本字段(当前 CLI 亦无 `plan` 子命令) |
|
|
15
15
|
|
|
16
16
|
`schemaVersion` 标记的是**报告结构**(字段集合 / 字段类型 / 字段含义)的版本:
|
|
@@ -25,15 +25,61 @@
|
|
|
25
25
|
在它出现之前的报告结构就是 v1。
|
|
26
26
|
- 枚举类字段新增取值属于兼容变更;消费者对未知取值应降级归入 unknown,不得崩溃。
|
|
27
27
|
|
|
28
|
-
###
|
|
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
|
+
|
|
56
|
+
## v3(本版):IDENTITY 段(版本同一性诊断 · 兼容递增)
|
|
57
|
+
|
|
58
|
+
`schemaVersion` 由 `"2"` → `"3"`。**只增顶层键**:新增 `identity` 段(判据 −1"跑的东西是不是你以为的那个"),
|
|
59
|
+
既有键与 `ok`/退出码**语义不变**(identity 是**独立诊断维度**,不进 `ok`)。
|
|
60
|
+
|
|
61
|
+
| 键 | 形状 | 说明 |
|
|
62
|
+
|---|---|---|
|
|
63
|
+
| `identity.family` | `"version-identity"` | 报告域(与 `error-expression` 并列,靠 family 分派) |
|
|
64
|
+
| `identity.rules` | `[{id,severity,title,layer}]` | IDENTITY 规则目录(ID1 一物一号 / ID2 号可验) |
|
|
65
|
+
| `identity.ok` | `true \| false \| null` | `null` = unverifiable(登记表缺失/不可读:npm 安装包不含该文件)——**不冒充通过** |
|
|
66
|
+
| `identity.version` | `string \| null` | `package.json` 声明版本(或调用方注入) |
|
|
67
|
+
| `identity.digest` | `sha256:…` | 由**产物**实算的运行身份摘要(`lib/**/*.js` + `bin/**/*.mjs` 逐文件 sha256 → 排序后再 sha256) |
|
|
68
|
+
| `identity.runtime.files` | `number` | 计入摘要的运行时代码文件数 |
|
|
69
|
+
| `identity.registry` | `{file, present, entries}` | 登记表位置与条目数 |
|
|
70
|
+
| `identity.findings[]` | `[{id,severity,title,file,line,message}]` | 判红项:`ID1`(同一版本两个摘要)/`ID2`(声明↔登记↔实算不一致、未登记、摘要伪造);**带 file:line 证据** |
|
|
71
|
+
| `identity.summary.byRule` | `object` | 按规则计数 |
|
|
72
|
+
|
|
73
|
+
兼容性与边界:
|
|
74
|
+
- **v2 消费者读 v3 报告**:忽略未知键 `identity` 即可;`ok`/`violations`/退出码语义未变。
|
|
75
|
+
- **防噪音**:只改文档/测试/机制件(不改运行时代码)⇒ `identity.digest` 不变 ⇒ 绿;
|
|
76
|
+
只改代码不动版本 ⇒ `ID2` 红("同号改代码"必须换号并重新登记摘要)。
|
|
77
|
+
- 登记表 `docs/identity-registry.json` **不随 npm 包发布**(npm 只打包 `docs/**/*.md`) ⇒ 安装包内 `identity.ok = null`(unverifiable)。
|
|
78
|
+
- 换版本或改运行时代码后**重登记摘要**:`pnpm identity:register`(或 `node scripts/identity-register.mjs [version]`)。登记旧摘要/伪造摘要 ⇒ `ID2` 红(发布前闸,不是可选项)。
|
|
79
|
+
|
|
34
80
|
## 何时升版
|
|
35
81
|
|
|
36
|
-
|
|
82
|
+
**不兼容才升**(版本号只增,如 `"2"` → `"3"`):
|
|
37
83
|
|
|
38
84
|
| 变更 | 升版? |
|
|
39
85
|
|---|---|
|
|
@@ -55,7 +101,7 @@
|
|
|
55
101
|
|
|
56
102
|
| 报告域 | 命令 | 版本字段 | 备注 |
|
|
57
103
|
|---|---|---|---|
|
|
58
|
-
| 日志契约(session log contract) | `check --json` | 顶层 `schemaVersion`(当前 `"
|
|
104
|
+
| 日志契约(session log contract) | `check --json` | 顶层 `schemaVersion`(当前 `"3"`) | 本文正文主要讲这一域 |
|
|
59
105
|
| 错误表达契约(error-expression) | `error-contract --json` | 顶层 `schemaVersion`(当前 `"1"`)+ `family: "error-expression"` | 与日志契约**互不影响**:任一域升版不牵动另一域 |
|
|
60
106
|
|
|
61
107
|
- 两个域的 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
|
-
* @
|
|
438
|
+
* @param {{version?: number|null}} [opts] 被检文件声明版本(用于 format-mix 判据;不传则只看现场)。
|
|
439
|
+
* @returns S9 违规列表(error 级;最多 1 条)。
|
|
383
440
|
*/
|
|
384
|
-
export function physicalOrderViolations(rows) {
|
|
385
|
-
const
|
|
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
|
-
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
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
|
-
|
|
397
|
-
|
|
398
|
-
|
|
486
|
+
} else if (wasBackward) directionReversals += 1;
|
|
487
|
+
wasBackward = isBackward;
|
|
488
|
+
prevSeq = event.seq;
|
|
489
|
+
prevLineNo = lineNo;
|
|
399
490
|
}
|
|
400
|
-
return
|
|
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/identity.js
ADDED
|
@@ -0,0 +1,248 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* lib/identity.js —— IDENTITY(版本同一性)契约:判据 −1「跑的东西是不是你以为的那个」
|
|
3
|
+
*
|
|
4
|
+
* 背景:`0.2.3-alpha.1` 全平台启动即死的真实故障 —— vendored 依赖源码更新了,但**版本号没换**
|
|
5
|
+
* (npm 又不许重发同一版本)⇒ 消费方拿到的仍是旧构建,ESM 链接崩。官方只报
|
|
6
|
+
* `released v2 row … has seq gap` 这类下游症状,指不出"病因在版本同一性"。
|
|
7
|
+
*
|
|
8
|
+
* 两条规则(家族 `version-identity`,与日志契约家族靠 `family` 区分):
|
|
9
|
+
* ID1 一物一号:登记表里每个 `版本 → 内容摘要` 必须唯一;同一版本登记两个不同摘要 ⇒ 红。
|
|
10
|
+
* ID2 号可验:发布前摘要必须**从产物计算**并与声明版本绑定(声明↔登记不一致 ⇒ 红);
|
|
11
|
+
* **防噪音**:只改文档/不改运行时代码/不动号 ⇒ 摘要不变 ⇒ 绿(不误报)。
|
|
12
|
+
* **硬反例**:同号改代码但登记摘要未更新/伪造 ⇒ 红。
|
|
13
|
+
*
|
|
14
|
+
* "产物"口径(明确定义,避免歧义):**运行身份 = 运行时代码清单**(`lib/**\/*.js` + `bin/**\/*.mjs`),
|
|
15
|
+
* 每个文件取 sha256,按相对路径排序后整体再 sha256。文档/测试/机制件**不承载运行身份**,
|
|
16
|
+
* 改它们不改变摘要 —— 这就是"只改文档必须绿"的判据边界。
|
|
17
|
+
*
|
|
18
|
+
* ⛔ 本模块只产出**诊断**(identity 段),不参与 `check` 的 ok/退出码(不改既有判定);
|
|
19
|
+
* 登记表缺失(如 npm 安装包不含该文件)⇒ `ok: null`(unverifiable),不冒充通过、不误报红。
|
|
20
|
+
*/
|
|
21
|
+
import fs from 'node:fs';
|
|
22
|
+
import path from 'node:path';
|
|
23
|
+
import crypto from 'node:crypto';
|
|
24
|
+
import { fileURLToPath } from 'node:url';
|
|
25
|
+
|
|
26
|
+
export const IDENTITY_FAMILY = 'version-identity';
|
|
27
|
+
|
|
28
|
+
/** 登记表(版本 → 内容摘要)。位于 `docs/`(随仓入库;npm 只打包 `docs/**\/*.md` ⇒ 安装包不含本文件,故为 unverifiable)。 */
|
|
29
|
+
export const IDENTITY_REGISTRY = 'docs/identity-registry.json';
|
|
30
|
+
|
|
31
|
+
/** 运行身份口径:只含运行时代码(文档/测试/机制件不计入)。 */
|
|
32
|
+
export const RUNTIME_SOURCES = Object.freeze({ dirs: ['lib', 'bin'], extensions: ['.js', '.mjs'] });
|
|
33
|
+
|
|
34
|
+
export const IDENTITY_RULES = [
|
|
35
|
+
{
|
|
36
|
+
id: 'ID1',
|
|
37
|
+
title: '一物一号:同一版本只能对应一个内容摘要',
|
|
38
|
+
family: IDENTITY_FAMILY,
|
|
39
|
+
layer: 'identity',
|
|
40
|
+
severity: 'error',
|
|
41
|
+
source: '0.2.3-alpha.1 全平台启动即死:vendored 源码更新但版本未换(npm 不许重发)⇒ 消费方拿到旧构建',
|
|
42
|
+
description: '登记表(`docs/identity-registry.json`)里同一个版本出现**两个不同内容摘要** ⇒ 判红(证据带 file:line)。同一版本重复登记但摘要相同不算违规(不产生噪音)。',
|
|
43
|
+
},
|
|
44
|
+
{
|
|
45
|
+
id: 'ID2',
|
|
46
|
+
title: '号可验:摘要必须由产物计算并与声明版本绑定',
|
|
47
|
+
family: IDENTITY_FAMILY,
|
|
48
|
+
layer: 'identity',
|
|
49
|
+
severity: 'error',
|
|
50
|
+
source: '同上;判据:package.json 声明版本 ↔ 登记表登记的产物摘要 ↔ 由运行时代码实算的摘要,三者必须一致',
|
|
51
|
+
description: '发布前从**产物**计算摘要(运行时代码清单 `lib/**/*.js` + `bin/**/*.mjs` 逐文件 sha256 → 排序后再 sha256)并与声明版本绑定:`package.json.version` 在登记表无条目、或登记摘要 ≠ 实算摘要 ⇒ 判红(证据带 file:line);摘要**伪造**同样被实算拦下。**防噪音反例**:只改文档/测试/机制件(不改运行时代码)⇒ 摘要不变 ⇒ 绿;**硬反例**:同号改代码但登记未更新 ⇒ 红。',
|
|
52
|
+
},
|
|
53
|
+
];
|
|
54
|
+
|
|
55
|
+
export const IDENTITY_RULE_BY_ID = Object.freeze(Object.fromEntries(IDENTITY_RULES.map((r) => [r.id, r])));
|
|
56
|
+
|
|
57
|
+
const sha256 = (buf) => crypto.createHash('sha256').update(buf).digest('hex');
|
|
58
|
+
const toRel = (root, file) => path.relative(root, file).split(path.sep).join('/');
|
|
59
|
+
|
|
60
|
+
/** 包根(本模块位于 `<root>/lib/identity.js`)。 */
|
|
61
|
+
export function packageRoot() {
|
|
62
|
+
return path.dirname(path.dirname(fileURLToPath(import.meta.url)));
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
function walkRuntime(root) {
|
|
66
|
+
const out = [];
|
|
67
|
+
for (const dir of RUNTIME_SOURCES.dirs) {
|
|
68
|
+
const abs = path.join(root, dir);
|
|
69
|
+
if (!fs.existsSync(abs)) continue;
|
|
70
|
+
const stack = [abs];
|
|
71
|
+
while (stack.length > 0) {
|
|
72
|
+
const cur = stack.pop();
|
|
73
|
+
for (const name of fs.readdirSync(cur)) {
|
|
74
|
+
const full = path.join(cur, name);
|
|
75
|
+
const st = fs.statSync(full);
|
|
76
|
+
if (st.isDirectory()) stack.push(full);
|
|
77
|
+
else if (RUNTIME_SOURCES.extensions.includes(path.extname(name))) out.push(toRel(root, full));
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
return out.sort();
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/**
|
|
85
|
+
* 计算运行身份摘要(确定性:与目录遍历顺序无关,只依赖"路径 + 文件内容")。
|
|
86
|
+
*
|
|
87
|
+
* @param {{root?: string}} [opts] `root` 缺省 = 本包根(测试可传临时夹具根)
|
|
88
|
+
* @returns {{digest: string, algorithm: string, files: Array<{path: string, sha256: string}>}}
|
|
89
|
+
*/
|
|
90
|
+
export function computeRuntimeDigest({ root } = {}) {
|
|
91
|
+
const base = root ?? packageRoot();
|
|
92
|
+
const files = walkRuntime(base).map((rel) => ({ path: rel, sha256: sha256(fs.readFileSync(path.join(base, rel))) }));
|
|
93
|
+
const manifest = files.map((f) => `${f.path}\u0000${f.sha256}`).join('\n');
|
|
94
|
+
return { digest: `sha256:${sha256(Buffer.from(manifest, 'utf8'))}`, algorithm: 'sha256( sorted(path+sha256(file)) over lib/**/*.js + bin/**/*.mjs )', files };
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/** 文件里第一次出现 `needle` 的行号(1-based;找不到 ⇒ null)。用于 file:line 证据。 */
|
|
98
|
+
export function lineOfOccurrence(file, needle) {
|
|
99
|
+
try {
|
|
100
|
+
const lines = fs.readFileSync(file, 'utf8').split('\n');
|
|
101
|
+
const idx = lines.findIndex((l) => l.includes(needle));
|
|
102
|
+
return idx >= 0 ? idx + 1 : null;
|
|
103
|
+
} catch {
|
|
104
|
+
return null;
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
/**
|
|
109
|
+
* 读登记表(缺文件/坏 JSON 不抛:分别记为 present:false / parseError)。
|
|
110
|
+
* @param {{root?: string, registryPath?: string}} [opts]
|
|
111
|
+
*/
|
|
112
|
+
export function readIdentityRegistry({ root, registryPath } = {}) {
|
|
113
|
+
const base = root ?? packageRoot();
|
|
114
|
+
const rel = registryPath ?? IDENTITY_REGISTRY;
|
|
115
|
+
const file = path.join(base, rel);
|
|
116
|
+
if (!fs.existsSync(file)) return { present: false, file: rel, entries: [], parseError: null };
|
|
117
|
+
const text = fs.readFileSync(file, 'utf8');
|
|
118
|
+
let data;
|
|
119
|
+
try {
|
|
120
|
+
data = JSON.parse(text);
|
|
121
|
+
} catch (err) {
|
|
122
|
+
return { present: true, file: rel, entries: [], parseError: String(err?.message ?? err) };
|
|
123
|
+
}
|
|
124
|
+
const lines = text.split('\n');
|
|
125
|
+
let cursor = 0;
|
|
126
|
+
const entries = (Array.isArray(data.entries) ? data.entries : []).map((e) => {
|
|
127
|
+
const marker = `"${String(e.version)}"`;
|
|
128
|
+
let line = null;
|
|
129
|
+
for (let i = cursor; i < lines.length; i++) {
|
|
130
|
+
if (lines[i].includes(marker)) { line = i + 1; cursor = i + 1; break; }
|
|
131
|
+
}
|
|
132
|
+
return { version: e.version, digest: e.digest, line };
|
|
133
|
+
});
|
|
134
|
+
return { present: true, file: rel, entries, parseError: null };
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
const finding = (ruleId, { file, line = null, message, extra = {} }) => {
|
|
138
|
+
const rule = IDENTITY_RULE_BY_ID[ruleId];
|
|
139
|
+
const findingObj = { id: ruleId, rule: ruleId, family: IDENTITY_FAMILY, severity: rule?.severity ?? 'error', title: rule?.title ?? null, file, line, message };
|
|
140
|
+
return Object.keys(extra).length > 0 ? { ...findingObj, extra } : findingObj;
|
|
141
|
+
};
|
|
142
|
+
|
|
143
|
+
/**
|
|
144
|
+
* 版本同一性检查(IDENTITY 家族报告;⛔ 不进 check 的 ok/退出码)。
|
|
145
|
+
*
|
|
146
|
+
* @param {{root?: string, version?: string, registryPath?: string}} [opts]
|
|
147
|
+
* @returns {{
|
|
148
|
+
* ok: boolean|null, // null = unverifiable(登记表缺失/损坏,不冒充通过)
|
|
149
|
+
* family: string, version: string|null,
|
|
150
|
+
* digest: string|null, algorithm: string,
|
|
151
|
+
* runtime: {files: number},
|
|
152
|
+
* registry: {file: string, present: boolean, entries: number},
|
|
153
|
+
* findings: Array<object>,
|
|
154
|
+
* summary: {byRule: object},
|
|
155
|
+
* note?: string,
|
|
156
|
+
* }}
|
|
157
|
+
*/
|
|
158
|
+
export function checkIdentity({ root, version, registryPath } = {}) {
|
|
159
|
+
const base = root ?? packageRoot();
|
|
160
|
+
const pkgFile = path.join(base, 'package.json');
|
|
161
|
+
const pkgText = fs.existsSync(pkgFile) ? fs.readFileSync(pkgFile, 'utf8') : null;
|
|
162
|
+
let declared = version ?? null;
|
|
163
|
+
if (declared === null && pkgText !== null) {
|
|
164
|
+
try {
|
|
165
|
+
declared = JSON.parse(pkgText).version ?? null;
|
|
166
|
+
} catch {
|
|
167
|
+
declared = null;
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
const pkgVersionLine = pkgText !== null ? lineOfOccurrence(pkgFile, '"version"') : null;
|
|
171
|
+
const pkgRel = 'package.json';
|
|
172
|
+
const runtime = computeRuntimeDigest({ root: base });
|
|
173
|
+
const registry = readIdentityRegistry({ root: base, registryPath });
|
|
174
|
+
const baseReport = {
|
|
175
|
+
ok: null,
|
|
176
|
+
family: IDENTITY_FAMILY,
|
|
177
|
+
version: declared,
|
|
178
|
+
digest: runtime.digest,
|
|
179
|
+
algorithm: runtime.algorithm,
|
|
180
|
+
runtime: { files: runtime.files.length },
|
|
181
|
+
registry: { file: registry.file, present: registry.present, entries: registry.entries.length },
|
|
182
|
+
findings: [],
|
|
183
|
+
summary: { byRule: {} },
|
|
184
|
+
};
|
|
185
|
+
|
|
186
|
+
if (!registry.present) {
|
|
187
|
+
return { ...baseReport, note: `登记表缺失(${registry.file}):本安装不含登记表(发布包只含运行时代码与 *.md 文档)——身份校验需在源码仓/发布流水线内运行(unverifiable,不冒充通过)` };
|
|
188
|
+
}
|
|
189
|
+
if (registry.parseError) {
|
|
190
|
+
return {
|
|
191
|
+
...baseReport,
|
|
192
|
+
findings: [finding('ID2', { file: registry.file, message: `登记表不是合法 JSON:${registry.parseError}` })],
|
|
193
|
+
ok: false,
|
|
194
|
+
summary: { byRule: { ID2: 1 } },
|
|
195
|
+
};
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
const findings = [];
|
|
199
|
+
// ── ID1 · 一物一号:同一版本出现两个不同摘要 ──────────────────────────
|
|
200
|
+
const byVersion = new Map();
|
|
201
|
+
for (const entry of registry.entries) {
|
|
202
|
+
if (!byVersion.has(entry.version)) byVersion.set(entry.version, []);
|
|
203
|
+
byVersion.get(entry.version).push(entry);
|
|
204
|
+
}
|
|
205
|
+
for (const [v, entries] of byVersion) {
|
|
206
|
+
const digests = [...new Set(entries.map((e) => e.digest))];
|
|
207
|
+
if (digests.length <= 1) continue; // 重复但摘要相同:不产生噪音
|
|
208
|
+
const first = entries[0];
|
|
209
|
+
for (const entry of entries.slice(1)) {
|
|
210
|
+
if (entry.digest === first.digest) continue;
|
|
211
|
+
findings.push(finding('ID1', {
|
|
212
|
+
file: registry.file,
|
|
213
|
+
line: entry.line,
|
|
214
|
+
message: `同一版本 ${v} 登记了两个不同内容摘要:${first.digest}(line ${first.line ?? '?'})与 ${entry.digest}(line ${entry.line ?? '?'})——一物多号/一物多内容(判红)`,
|
|
215
|
+
extra: { version: v, digests },
|
|
216
|
+
}));
|
|
217
|
+
}
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
// ── ID2 · 号可验:声明版本 ↔ 登记摘要 ↔ 产物实算摘要 必须一致 ─────────────
|
|
221
|
+
if (declared === null) {
|
|
222
|
+
findings.push(finding('ID2', { file: pkgRel, line: pkgVersionLine, message: 'package.json 无法解析出版本号,无法与登记表绑定(声明↔登记不可验)' }));
|
|
223
|
+
} else {
|
|
224
|
+
const entries = registry.entries.filter((e) => e.version === declared);
|
|
225
|
+
if (entries.length === 0) {
|
|
226
|
+
findings.push(finding('ID2', {
|
|
227
|
+
file: pkgRel,
|
|
228
|
+
line: pkgVersionLine,
|
|
229
|
+
message: `声明版本 ${declared} 在登记表中没有摘要条目——发布前须把由产物实算的摘要登记进去(实算 ${runtime.digest})`,
|
|
230
|
+
extra: { version: declared, computedDigest: runtime.digest },
|
|
231
|
+
}));
|
|
232
|
+
} else {
|
|
233
|
+
const mismatched = entries.filter((e) => e.digest !== runtime.digest);
|
|
234
|
+
if (mismatched.length > 0) {
|
|
235
|
+
findings.push(finding('ID2', {
|
|
236
|
+
file: registry.file,
|
|
237
|
+
line: mismatched[0].line,
|
|
238
|
+
message: `声明版本 ${declared} 的登记摘要 ≠ 产物实算摘要(同号改代码未换号/未更新登记/摘要伪造均命中):登记 ${mismatched[0].digest},实算 ${runtime.digest}(package.json:${pkgVersionLine ?? '?'})`,
|
|
239
|
+
extra: { version: declared, registeredDigest: mismatched[0].digest, computedDigest: runtime.digest },
|
|
240
|
+
}));
|
|
241
|
+
}
|
|
242
|
+
}
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
const byRule = {};
|
|
246
|
+
for (const f of findings) byRule[f.id] = (byRule[f.id] ?? 0) + 1;
|
|
247
|
+
return { ...baseReport, ok: findings.length === 0, findings, summary: { byRule } };
|
|
248
|
+
}
|
package/lib/index.js
CHANGED
|
@@ -12,7 +12,8 @@ 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';
|
|
19
|
+
export { IDENTITY_RULES, IDENTITY_RULE_BY_ID, IDENTITY_FAMILY, IDENTITY_REGISTRY, RUNTIME_SOURCES, checkIdentity, computeRuntimeDigest, readIdentityRegistry, lineOfOccurrence, packageRoot } from './identity.js';
|
package/lib/validate.js
CHANGED
|
@@ -66,11 +66,12 @@ export function isAbsoluteLogPath(value) {
|
|
|
66
66
|
|
|
67
67
|
/**
|
|
68
68
|
* 报告结构版本(`schemaVersion`):`check --json` / `validateSessionLog()` 返回对象的
|
|
69
|
-
* **结构**版本(字符串,如 `"
|
|
69
|
+
* **结构**版本(字符串,如 `"3"`)。语义:只在报告结构发生不兼容增删/改名时递增,
|
|
70
70
|
* 新增可选字段不递增;消费方可据此做解析兼容判断。
|
|
71
71
|
* ⛔ 不是包版本、不是日志格式版本(那是 header.version / package.json)。
|
|
72
|
+
* 历史:`"1"` 初始 → `"2"` 加 S9 诊断字段(additive)→ `"3"` 加 `identity` 段(additive)。
|
|
72
73
|
*/
|
|
73
|
-
export const REPORT_SCHEMA_VERSION = '
|
|
74
|
+
export const REPORT_SCHEMA_VERSION = '3';
|
|
74
75
|
|
|
75
76
|
/** 宿主能力闸触发时**跳过**的规则(v3/被检版本语义相关)——报告里显式列出,避免"静默通过"。 */
|
|
76
77
|
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 +217,7 @@ export function validateSessionLog(log, opts = {}) {
|
|
|
216
217
|
}
|
|
217
218
|
|
|
218
219
|
// ── S9 · 文件物理序 seq 单调(多写入者交织现场;E2 排序后检查看不到)──
|
|
219
|
-
violations.push(...physicalOrderViolations(rows));
|
|
220
|
+
violations.push(...physicalOrderViolations(rows, { version: formatVersion }));
|
|
220
221
|
|
|
221
222
|
// ── S · surface 增量重放(归因)+ 官方 foldSurface 终验 ────────────────
|
|
222
223
|
const replay = replaySurface(events, formatVersion);
|
|
@@ -401,7 +402,7 @@ function unassessableResult({ header, headerLine, rows, events, frameInfo, baseS
|
|
|
401
402
|
} else expectedSeq = event.seq + 1;
|
|
402
403
|
}
|
|
403
404
|
}
|
|
404
|
-
violations.push(...physicalOrderViolations(rows));
|
|
405
|
+
violations.push(...physicalOrderViolations(rows, { version: formatVersion }));
|
|
405
406
|
violations.push(...inboxReplayViolations(events, header));
|
|
406
407
|
violations.push(...toolPairingViolations(events));
|
|
407
408
|
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.
|
|
4
|
+
"version": "0.3.38",
|
|
5
5
|
"packageManager": "pnpm@11.7.0",
|
|
6
6
|
"type": "module",
|
|
7
7
|
"main": "lib/index.js",
|
|
@@ -36,7 +36,8 @@
|
|
|
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
38
|
"release": "node scripts/release.mjs",
|
|
39
|
-
"gate": "node internal/scripts/gate.mjs"
|
|
39
|
+
"gate": "node internal/scripts/gate.mjs",
|
|
40
|
+
"identity:register": "node scripts/identity-register.mjs"
|
|
40
41
|
},
|
|
41
42
|
"keywords": [
|
|
42
43
|
"dsh",
|