dsh-log-contract 0.3.40 → 0.3.41

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
@@ -114,6 +114,22 @@ the declared version promises.
114
114
 
115
115
  ---
116
116
 
117
+ ## Runtime contract (R-3 / R-1 / R-2a) — "will it silently change while running?"
118
+ A **separate report family** (`run-contract`, exposed as `check --json` → `runContract`), again
119
+ outside `ok` / exit codes. It ships three assertion helpers for real run records:
120
+
121
+ | Rule | Assertion | What it guards |
122
+ |---|---|---|
123
+ | `R-3` | `assertFailClosed({ required, provided, result })` | any missing required input (field / file / context) ⇒ the verdict must be **incompatible**, with a visible reason naming the missing input — a missing input never matches (`fail-open` is red) |
124
+ | `R-1` | `assertFailureLatched(history)` | a failure is **latched**: after `failed: true`, no later snapshot (recover / reload / cache clear) may write `failed: false` |
125
+ | `R-2a` | `assertWriteOutcome({ write, artifact })` | a failed or unknown write must never leave the artifact marked `complete` — withdraw it or mark it `partial` / `unavailable` / `withdrawn` |
126
+
127
+ `checkRunContract({...})` runs them together and lists the assertions you did not supply under
128
+ `skipped`; when **none** ran, `ok` is `null` (unverifiable — never "pass"). Usage, positive/negative examples and the open items for R-2b
129
+ (reason field) and R-6 (idempotency key) are in [docs/RUN-CONTRACT.md](docs/RUN-CONTRACT.md).
130
+
131
+ ---
132
+
117
133
  ## Version support (host / session format)
118
134
  **Tested baseline (the versions this rule set was verified against)**:
119
135
 
package/README.zh.md CHANGED
@@ -91,6 +91,21 @@ dsh-retrace 的「日志体检与修复」能力——与 dsh-retrace 一起构
91
91
 
92
92
  ---
93
93
 
94
+ ## 运行时契约(R-3 / R-1 / R-2a)——「跑起来会不会静默变样」
95
+ **独立报告域**(`family: run-contract`,`check --json` 的 `runContract` 段),同样**不进** `ok`/退出码。
96
+ 提供三个断言函数(调用方喂真实运行记录):
97
+
98
+ | 规则 | 断言 | 守护什么 |
99
+ |---|---|---|
100
+ | `R-3` | `assertFailClosed({ required, provided, result })` | 任一必需输入(字段/文件/上下文)缺失 ⇒ 判定必须是**不兼容**且原因点名缺项;缺失永不匹配(判成兼容即红) |
101
+ | `R-1` | `assertFailureLatched(history)` | 失败**置位**:出现 `failed: true` 后,任何后续快照(恢复/重载/清缓存)都不得写回 `failed: false` |
102
+ | `R-2a` | `assertWriteOutcome({ write, artifact })` | 写失败或结果未知时,产物不得标 `complete`——必须撤回或标 `partial` / `unavailable` / `withdrawn` |
103
+
104
+ `checkRunContract({...})` 可一起跑;未提供的断言列在 `skipped`;**一条都没跑**时 `ok: null`(unverifiable,⛔ 不冒充通过)。用法、正反例,
105
+ 以及 R-2b(reason 字段)/ R-6(幂等键)的前置项清单见 [docs/RUN-CONTRACT.md](docs/RUN-CONTRACT.md)。
106
+
107
+ ---
108
+
94
109
  ## 版本支持(宿主 / 会话格式)
95
110
  **测试基线(本规则集验证过的版本)**:
96
111
 
@@ -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, checkIdentity, IDENTITY_RULES, packageRoot } 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, RUN_CONTRACT_RULES } from '../lib/index.js';
18
18
 
19
19
  /**
20
20
  * 同步写 fd——`process.stdout.write` 在**管道**下是异步的,紧跟着的
@@ -343,6 +343,10 @@ function cmdCheck(args) {
343
343
  // ⛔ 只给诊断,不进 ok/退出码;登记表缺失(npm 安装包不含该 JSON)⇒ ok:null(unverifiable)。
344
344
  const identity = checkIdentity({ root: packageRoot() });
345
345
  payload.identity = { ...identity, rules: IDENTITY_RULES.map((r) => ({ id: r.id, severity: r.severity, title: r.title, layer: r.layer })) };
346
+ // RUN CONTRACT 段(schemaVersion 4 · additive):运行时契约规则目录(R-3 / R-1 / R-2a)。
347
+ // 断言接口见 lib/run-contract.js(assertFailClosed / assertFailureLatched / assertWriteOutcome);
348
+ // 本段只给规则清单(真实判定需调用方喂运行记录),⛔ 不进 ok/退出码。
349
+ payload.runContract = { family: 'run-contract', rules: RUN_CONTRACT_RULES.map((r) => ({ id: r.id, severity: r.severity, title: r.title, layer: r.layer })), note: '运行时契约规则目录;断言接口见 docs/RUN-CONTRACT.md(真实判定需调用方提供运行记录)' };
346
350
  if (notAssessable) payload.notAssessable = result.notAssessable;
347
351
  if (resume) payload.resume = resumeVerdict(result);
348
352
  out(JSON.stringify(payload, null, 2) + '\n');
@@ -0,0 +1,100 @@
1
+ # 运行时契约(RUN CONTRACT)· R-3 / R-1 / R-2a
2
+
3
+ > 报告域 `family: "run-contract"`:与日志契约(`check --json` 主报告)、错误表达契约
4
+ > (`error-expression`)、版本同一性契约(`version-identity`)并列,按 `family` 分派。
5
+ > 这三条规则只做**断言**(判定函数),不改 `check` 的 `ok` / 退出码语义。
6
+
7
+ 一句话:日志契约问"这份日志合法吗",版本同一性问"跑的是不是你以为的那份",
8
+ 运行时契约问"**跑起来会不会静默变样**"。
9
+
10
+ ## R-3 · 任一输入缺失 ⇒ 判不兼容(fail-closed)
11
+
12
+ **判据**:必需输入(字段 / 文件 / 必需上下文)缺失时,判定必须是**不兼容**(拒绝),
13
+ 且拒绝原因**可见**(点出缺了哪一项)。原因可见性按**完整 token** 判定(按非字母数字切词后
14
+ 相等),⛔ 不是子串包含:`required:['file']` + `reasons:['profile missing']` **不算**点名。
15
+ 缺失永不匹配:声明值、解析值、期望值三者必须完全相等才算匹配;任一缺失 ⇒ 不匹配。
16
+
17
+ ```js
18
+ import { assertFailClosed } from 'dsh-log-contract';
19
+
20
+ // ✅ 合规:缺 fileB ⇒ 拒绝,且原因点名 fileB
21
+ assertFailClosed({
22
+ required: ['fieldA', 'fileB'],
23
+ provided: { fieldA: 1 },
24
+ result: { compatible: false, reasons: ['fileB missing'] },
25
+ }).ok === true;
26
+
27
+ // ⛔ 违规:缺 fileB 却判兼容(fail-open)
28
+ assertFailClosed({ required: ['fieldA', 'fileB'], provided: { fieldA: 1 }, result: { compatible: true } });
29
+ // ⇒ findings[0].id === 'R-3'
30
+
31
+ // ⛔ 违规:拒绝原因不可见(reasons 未点名缺项)
32
+ assertFailClosed({ required: ['fileB'], provided: {}, result: { compatible: false, reasons: ['bad input'] } });
33
+ ```
34
+
35
+ `isMissingInput(v)` 的口径:缺键 / `undefined` / `null` / 空白字符串 / `NaN` 都算缺失。
36
+
37
+ ## R-1 · 失败一次即置位,恢复不清零
38
+
39
+ **判据**:状态历史一旦出现 `failed: true`,其后任何快照都不得再出现 `failed: false`——
40
+ 恢复、重载、清缓存同样禁止清零;状态只能「未失败 → 失败」单向。缺省(未声明)视为
41
+ 未清零,只有**显式** `false` 才算违规。
42
+
43
+ ```js
44
+ import { assertFailureLatched } from 'dsh-log-contract';
45
+
46
+ // ✅ 合规:失败后恢复,但置位保持 true
47
+ assertFailureLatched([
48
+ { phase: 'run', failed: false },
49
+ { phase: 'run', failed: true },
50
+ { phase: 'recover', failed: true },
51
+ { phase: 'reload', failed: true },
52
+ ]).ok === true;
53
+
54
+ // ⛔ 违规:恢复路径把置位清零
55
+ assertFailureLatched([
56
+ { phase: 'run', failed: true },
57
+ { phase: 'reload', failed: false },
58
+ ]);
59
+ // ⇒ findings[0].id === 'R-1'(带 index/phase 证据)
60
+ ```
61
+
62
+ ## R-2a · 写失败不得把产物标为完整
63
+
64
+ **判据**:写入未成功(`write.ok !== true`,含 `ok` 缺省/结果未知)时,产物不得被标记为
65
+ 完整(`artifact.complete === true` 或 `artifact.status === "complete"`);必须撤回或标
66
+ `partial` / `unavailable` / `withdrawn`。接口断言,不绑定具体写入实现。
67
+
68
+ ```js
69
+ import { assertWriteOutcome } from 'dsh-log-contract';
70
+
71
+ // ✅ 合规:写成功 ⇒ 产物可标完整
72
+ assertWriteOutcome({ write: { ok: true }, artifact: { complete: true } }).ok === true;
73
+
74
+ // ✅ 合规:写失败 ⇒ 产物标 partial/unavailable
75
+ assertWriteOutcome({ write: { ok: false, error: 'EIO' }, artifact: { complete: false, status: 'partial' } }).ok === true;
76
+
77
+ // ⛔ 违规:写失败却把产物标完整
78
+ assertWriteOutcome({ write: { ok: false, error: 'EIO' }, artifact: { complete: true } });
79
+ // ⇒ findings[0].id === 'R-2a'
80
+ ```
81
+
82
+ ## 一起跑
83
+
84
+ ```js
85
+ import { checkRunContract } from 'dsh-log-contract';
86
+ const report = checkRunContract({ history, write, artifact, required, provided, result });
87
+ // { family: 'run-contract', rules, checks, skipped, ok, findings }
88
+ ```
89
+
90
+ 未提供输入的断言会列在 `skipped` 里;**一条断言都没跑**时 `ok: null`(unverifiable,⛔ 不冒充通过)。
91
+
92
+ ## 前置项(未实现,列出边界)
93
+
94
+ | 候选 | 状态 | 前置项 |
95
+ |---|---|---|
96
+ | **R-2b** 撤回必须带原因 | 未实现 | 撤回事件需要**必填 `reason`** 字段(现结构只有 `originalText`,没有原因语义)⇒ 先补字段契约,再加断言 |
97
+ | **R-6** 副作用必须幂等 | 未实现 | 需要先立"副作用携带稳定**幂等键**"契约(当前没有该概念);无幂等键时判定只能是"缺前置" |
98
+
99
+ `check --json` 的 `runContract` 段只承载**规则目录**(`rules` + `note`);真实判定由调用方
100
+ 把运行记录喂给上面的断言函数(与 `errorContract` 段同一口径)。
@@ -10,7 +10,7 @@
10
10
  |---|---|
11
11
  | 字段名 | `schemaVersion` |
12
12
  | 位置 | `check --json` 报告**顶层**;同值同步进 `validateSessionLog()` 返回对象顶层 |
13
- | 当前值 | `"3"`(字符串,暂不采用 semver;见下文 v2 / v3) |
13
+ | 当前值 | `"4"`(字符串,暂不采用 semver;见下文 v2 / v3 / v4) |
14
14
  | 覆盖范围 | 仅 `check --json` 这一份报告结构。`prewrite --json` 是**另一份结构**,暂不带本字段(当前 CLI 亦无 `plan` 子命令) |
15
15
 
16
16
  `schemaVersion` 标记的是**报告结构**(字段集合 / 字段类型 / 字段含义)的版本:
@@ -75,11 +75,26 @@
75
75
  - **防噪音**:只改文档/测试/机制件(不改运行时代码)⇒ `identity.digest` 不变 ⇒ 绿;
76
76
  只改代码不动版本 ⇒ `ID2` 红("同号改代码"必须换号并重新登记摘要)。
77
77
  - 登记表 `docs/identity-registry.json` **不随 npm 包发布**(npm 只打包 `docs/**/*.md`) ⇒ 安装包内 `identity.ok = null`(unverifiable)。
78
- - 换版本或改运行时代码后**重登记摘要**:`pnpm identity:register`(仅源码仓;npm 包不含 `scripts/` 目录)。登记旧摘要/伪造摘要 ⇒ `ID2` 红(发布前闸,不是可选项)。
78
+ - 换版本或改运行时代码后**重登记摘要**:`pnpm identity:register`(仅源码仓;npm 包不含 `scripts/` 目录)。登记旧摘要/伪造摘要 ⇒ `ID2` 红(发布前检查,不是可选项)。
79
+
80
+ ## v4(本版):RUN CONTRACT 段(运行时契约 · 兼容递增)
81
+
82
+ `schemaVersion` 由 `"3"` → `"4"`。**只增顶层键**:新增 `runContract` 段(三条断言的规则目录),
83
+ 既有键与 `ok`/退出码**语义不变**(真实判定由调用方把运行记录喂给断言函数)。
84
+
85
+ | 键 | 形状 | 说明 |
86
+ |---|---|---|
87
+ | `runContract.family` | `"run-contract"` | 报告域(与 `error-expression` / `version-identity` 并列,靠 family 分派) |
88
+ | `runContract.rules` | `[{id,severity,title,layer}]` | 规则目录:`R-3` 输入缺失⇒不兼容 / `R-1` 失败置位不清零 / `R-2a` 写失败不得标完整 |
89
+ | `runContract.note` | `string` | 断言接口入口(`docs/RUN-CONTRACT.md`);真实判定需调用方提供运行记录 |
90
+
91
+ 兼容性:**v3 消费者读 v4 报告**忽略未知键 `runContract` 即可;`ok`/`violations`/退出码语义未变。
92
+ 断言接口(`assertFailClosed` / `assertFailureLatched` / `assertWriteOutcome` / `checkRunContract`)
93
+ 不改变任何既有报告字段,只是"可以调用"的诊断 API。
79
94
 
80
95
  ## 何时升版
81
96
 
82
- **不兼容才升**(版本号只增,如 `"2"` → `"3"`):
97
+ **不兼容才升**(版本号只增,如 `"3"` → `"4"`):
83
98
 
84
99
  | 变更 | 升版? |
85
100
  |---|---|
@@ -101,7 +116,8 @@
101
116
 
102
117
  | 报告域 | 命令 | 版本字段 | 备注 |
103
118
  |---|---|---|---|
104
- | 日志契约(session log contract) | `check --json` | 顶层 `schemaVersion`(当前 `"3"`) | 本文正文主要讲这一域 |
119
+ | 日志契约(session log contract) | `check --json` | 顶层 `schemaVersion`(当前 `"4"`) | 本文正文主要讲这一域 |
120
+ | 运行时契约(run-contract) | 断言接口(`docs/RUN-CONTRACT.md`) | `family: "run-contract"`(`check --json` 的 `runContract` 段只给规则目录) | 与日志契约**互不影响**:断言不改 `ok`/退出码 |
105
121
  | 错误表达契约(error-expression) | `error-contract --json` | 顶层 `schemaVersion`(当前 `"1"`)+ `family: "error-expression"` | 与日志契约**互不影响**:任一域升版不牵动另一域 |
106
122
 
107
123
  - 两个域的 id 集合可能重名(都有 `E1`…),消费者**必须按 `family` 分派**,⛔ 不要按 id 字面合并。
package/lib/index.js CHANGED
@@ -17,3 +17,4 @@ export { collectArchivePointers, verifyArchivePointers, archiveVerdict, archiveB
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
19
  export { IDENTITY_RULES, IDENTITY_RULE_BY_ID, IDENTITY_FAMILY, IDENTITY_REGISTRY, RUNTIME_SOURCES, checkIdentity, computeRuntimeDigest, readIdentityRegistry, lineOfOccurrence, packageRoot } from './identity.js';
20
+ export { RUN_CONTRACT_RULES, RUN_CONTRACT_RULE_BY_ID, RUN_CONTRACT_FAMILY, assertFailClosed, assertFailureLatched, assertWriteOutcome, checkRunContract, isMissingInput, reasonMentions, reasonTokensOf } from './run-contract.js';
@@ -0,0 +1,179 @@
1
+ /**
2
+ * lib/run-contract.js —— 运行时契约(family `run-contract`):判据「跑的时候会不会静默变样」
3
+ *
4
+ * 三条可机检规则(断言接口,不绑定具体实现):
5
+ * R-3 任一输入缺失 ⇒ 判不兼容(fail-closed):缺字段/缺文件/缺必需上下文 ⇒ 必须拒绝且原因可见;
6
+ * ⛔ 不得落到"兼容/通过"或静默默认值 —— 「缺失永不匹配」:声明值、解析值、期望值三者必须完全相等。
7
+ * R-1 失败一次即置位(latched),恢复不清零:状态历史只能「未失败 → 失败」单向;任何
8
+ * 恢复/重载/清缓存路径都不得把置位写回 false。
9
+ * R-2a 写失败(含写入结果未知)⇒ 产物不得标记为「完整」:必须撤回或标记不可用。
10
+ *
11
+ * 用法(调用方以**真实运行记录**喂进来;本模块只做判定,不读外部状态):
12
+ * assertFailClosed({ required, provided, result }) → { ok, missing, findings }
13
+ * assertFailureLatched(history) → { ok, latchedAt, findings }
14
+ * assertWriteOutcome({ write, artifact }) → { ok, findings }
15
+ *
16
+ * 全部断言:合规样本 ⇒ `ok: true`;违规样本 ⇒ `ok: false` + 带证据的 finding(逐条可定位)。
17
+ */
18
+ export const RUN_CONTRACT_FAMILY = 'run-contract';
19
+
20
+ export const RUN_CONTRACT_RULES = [
21
+ {
22
+ id: 'R-3',
23
+ family: RUN_CONTRACT_FAMILY,
24
+ layer: 'run',
25
+ severity: 'error',
26
+ title: '任一输入缺失 ⇒ 判不兼容(fail-closed)',
27
+ source: '与「三重全等、缺失永不匹配」同口径:声明值/解析值/期望值必须完全相等,任一缺失即不匹配',
28
+ description: '必需输入(字段 / 文件 / 上下文)缺失时,判定必须是**不兼容**(拒绝),且拒绝原因必须**可见**(点出缺了哪一项)。⛔ 缺输入却落到"兼容/通过"、或静默取默认值,都判红——缺失永不匹配。',
29
+ },
30
+ {
31
+ id: 'R-1',
32
+ family: RUN_CONTRACT_FAMILY,
33
+ layer: 'run',
34
+ severity: 'error',
35
+ title: '失败一次即置位,恢复不清零',
36
+ source: '失败一旦发生即 latched;状态历史单向:未失败 → 失败,不得回退',
37
+ description: '状态历史里一旦出现 `failed: true`,其后任何快照都不得再出现 `failed: false`(恢复/重载/清缓存同样禁止清零)。缺省(未声明)视为"未清零",只有显式 `false` 才算违规。',
38
+ },
39
+ {
40
+ id: 'R-2a',
41
+ family: RUN_CONTRACT_FAMILY,
42
+ layer: 'run',
43
+ severity: 'error',
44
+ title: '写失败不得把产物标为完整',
45
+ source: '不可信数据不得当完整数据交付:写失败(含结果未知)⇒ 撤回或标记不可用',
46
+ description: '写入未成功(`write.ok !== true`,含 `ok` 缺省/未知)时,产物不得被标记为完整(`artifact.complete === true` 或 `artifact.status === "complete"`);必须撤回或标 `partial` / `unavailable` / `withdrawn`。接口断言,不绑定具体写入实现。',
47
+ },
48
+ ];
49
+
50
+ export const RUN_CONTRACT_RULE_BY_ID = Object.freeze(Object.fromEntries(RUN_CONTRACT_RULES.map((r) => [r.id, r])));
51
+
52
+ /** 输入是否"缺失":缺键 / undefined / null / 空白字符串 / NaN。 */
53
+ export function isMissingInput(value) {
54
+ if (value === undefined || value === null) return true;
55
+ if (typeof value === 'string' && value.trim() === '') return true;
56
+ if (typeof value === 'number' && Number.isNaN(value)) return true;
57
+ return false;
58
+ }
59
+
60
+ const finding = (id, message, extra = {}) => {
61
+ const rule = RUN_CONTRACT_RULE_BY_ID[id];
62
+ return { id, rule: id, family: RUN_CONTRACT_FAMILY, severity: rule?.severity ?? 'error', title: rule?.title ?? null, message, ...extra };
63
+ };
64
+
65
+ /**
66
+ * R-3 · 输入缺失必须 fail-closed 且原因可见。
67
+ *
68
+ * @param {{required?: string[], provided?: object, result?: {compatible?: boolean, reasons?: string[]}}} input
69
+ * `required` 必需输入名;`provided` 实际提供值;`result.compatible` 判定结论(true=兼容);
70
+ * `result.reasons` 拒绝原因(必须点名缺失项)。
71
+ * @returns {{id:'R-3', ok:boolean, missing:string[], findings:Array}}
72
+ */
73
+ /** 按非字母数字切词(`file.b` → ['file','b'];用于完整 token 匹配,避免子串假通过)。 */
74
+ export function reasonTokensOf(text) {
75
+ return String(text ?? '').split(/[^A-Za-z0-9_]+/).filter(Boolean);
76
+ }
77
+
78
+ /**
79
+ * 拒绝原因是否**点名**了某输入:完整 token 相等(非子串)。
80
+ * 反例:`required:['file']` + `reasons:['profile missing']` ⇒ 不点名('file' 不是 'profile' 的一部分)。
81
+ */
82
+ export function reasonMentions(reason, name) {
83
+ const nameTokens = reasonTokensOf(name);
84
+ if (nameTokens.length === 0) return false;
85
+ const reasonTokens = reasonTokensOf(reason);
86
+ return nameTokens.every((t) => reasonTokens.includes(t));
87
+ }
88
+
89
+ export function assertFailClosed({ required = [], provided = {}, result = {} } = {}) {
90
+ const findings = [];
91
+ const missing = required.filter((name) => !Object.hasOwn(provided ?? {}, name) || isMissingInput(provided[name]));
92
+ const compatible = result?.compatible;
93
+ const reasons = Array.isArray(result?.reasons) ? result.reasons : [];
94
+ for (const name of missing) {
95
+ if (compatible !== false) {
96
+ findings.push(finding('R-3', `必需输入 "${name}" 缺失,但判定未拒绝(compatible=${String(compatible)})——缺失必须判不兼容(fail-closed),不得落到兼容/通过或静默默认值`, { input: name, compatible: compatible ?? null }));
97
+ } else if (!reasons.some((r) => typeof r === 'string' && reasonMentions(r, name))) {
98
+ findings.push(finding('R-3', `必需输入 "${name}" 缺失且已拒绝,但拒绝原因不可见(reasons 未以完整 token 点名该输入)——原因必须能定位到缺项`, { input: name }));
99
+ }
100
+ }
101
+ return { id: 'R-3', ok: findings.length === 0, missing, findings };
102
+ }
103
+
104
+ /**
105
+ * R-1 · 失败置位后不得被清零(恢复/重载/清缓存同样禁止)。
106
+ *
107
+ * @param {Array<{phase?: string, failed?: boolean}>} history 时间序状态快照
108
+ * @returns {{id:'R-1', ok:boolean, latchedAt: {index:number, phase:string|null}|null, findings:Array}}
109
+ */
110
+ export function assertFailureLatched(history = []) {
111
+ const findings = [];
112
+ let latchedAt = null;
113
+ (Array.isArray(history) ? history : []).forEach((snap, index) => {
114
+ const failed = snap?.failed;
115
+ if (failed === true && latchedAt === null) {
116
+ latchedAt = { index, phase: snap?.phase ?? null };
117
+ return;
118
+ }
119
+ if (latchedAt !== null && failed === false) {
120
+ findings.push(finding('R-1', `失败在 ${latchedAt.phase ?? `#${latchedAt.index}`} 置位后,第 ${index} 步(phase=${snap?.phase ?? '-'})把置位清零(failed=false)——恢复/重载/清缓存不得清零`, { index, phase: snap?.phase ?? null, latchedAt }));
121
+ }
122
+ });
123
+ return { id: 'R-1', ok: findings.length === 0, latchedAt, findings };
124
+ }
125
+
126
+ /**
127
+ * R-2a · 写失败(含结果未知)⇒ 产物不得标"完整"。
128
+ *
129
+ * @param {{write?: {ok?: boolean, error?: unknown}, artifact?: {complete?: boolean, status?: string}}} input
130
+ * @returns {{id:'R-2a', ok:boolean, findings:Array}}
131
+ */
132
+ export function assertWriteOutcome({ write = {}, artifact = {} } = {}) {
133
+ const findings = [];
134
+ const writeOk = write?.ok === true;
135
+ const markedComplete = artifact?.complete === true
136
+ || artifact?.status === 'complete';
137
+ if (!writeOk && markedComplete) {
138
+ findings.push(finding('R-2a', `写入未成功(ok=${String(write?.ok)}${write?.error ? `,error=${String(write.error)}` : ''})但产物被标记为完整(${artifact?.complete === true ? 'complete=true' : `status=${String(artifact?.status)}`})——写失败必须撤回或标记不可用(partial/unavailable/withdrawn)`, { writeOk, artifact }));
139
+ }
140
+ return { id: 'R-2a', ok: findings.length === 0, findings };
141
+ }
142
+
143
+ /**
144
+ * 三条断言一起跑(调用方按需提供输入;未提供的断言跳过并在 `skipped` 里可见,⛔ 不冒充通过)。
145
+ *
146
+ * @param {{required?, provided?, result?, history?, write?, artifact?}} input
147
+ * @returns {{family:string, rules:Array, checks:Array, skipped:string[], ok:boolean|null, findings:Array}}
148
+ * `ok: null` = **unverifiable**(三条断言一条都没跑:没有任何输入)——⛔ 不冒充通过。
149
+ */
150
+ export function checkRunContract(input = {}) {
151
+ const checks = [];
152
+ const skipped = [];
153
+ const findings = [];
154
+ if (input.history !== undefined) {
155
+ const r = assertFailureLatched(input.history);
156
+ checks.push(r);
157
+ findings.push(...r.findings);
158
+ } else skipped.push('R-1');
159
+ if (input.write !== undefined || input.artifact !== undefined) {
160
+ const r = assertWriteOutcome({ write: input.write, artifact: input.artifact });
161
+ checks.push(r);
162
+ findings.push(...r.findings);
163
+ } else skipped.push('R-2a');
164
+ if (input.required !== undefined) {
165
+ const r = assertFailClosed({ required: input.required, provided: input.provided, result: input.result });
166
+ checks.push(r);
167
+ findings.push(...r.findings);
168
+ } else skipped.push('R-3');
169
+ const ran = checks.length > 0;
170
+ return {
171
+ family: RUN_CONTRACT_FAMILY,
172
+ rules: RUN_CONTRACT_RULES.map(({ id, severity, title, layer }) => ({ id, severity, title, layer })),
173
+ checks: checks.map(({ id, ok, findings: f }) => ({ id, ok, findings: f.length })),
174
+ skipped,
175
+ // 一条都没跑 ⇒ unverifiable(null),⛔ 不冒充通过;跑过 ⇒ 只看已跑断言的结论。
176
+ ok: ran ? findings.length === 0 : null,
177
+ findings,
178
+ };
179
+ }
package/lib/validate.js CHANGED
@@ -66,12 +66,12 @@ export function isAbsoluteLogPath(value) {
66
66
 
67
67
  /**
68
68
  * 报告结构版本(`schemaVersion`):`check --json` / `validateSessionLog()` 返回对象的
69
- * **结构**版本(字符串,如 `"3"`)。语义:只在报告结构发生不兼容增删/改名时递增,
69
+ * **结构**版本(字符串,如 `"4"`)。语义:只在报告结构发生不兼容增删/改名时递增,
70
70
  * 新增可选字段不递增;消费方可据此做解析兼容判断。
71
71
  * ⛔ 不是包版本、不是日志格式版本(那是 header.version / package.json)。
72
- * 历史:`"1"` 初始 → `"2"` 加 S9 诊断字段(additive)→ `"3"` 加 `identity` 段(additive)。
72
+ * 历史:`"1"` 初始 → `"2"` 加 S9 诊断字段(additive)→ `"3"` 加 `identity` 段(additive)→ `"4"` 加 `runContract` 段(additive)。
73
73
  */
74
- export const REPORT_SCHEMA_VERSION = '3';
74
+ export const REPORT_SCHEMA_VERSION = '4';
75
75
 
76
76
  /** 宿主能力闸触发时**跳过**的规则(v3/被检版本语义相关)——报告里显式列出,避免"静默通过"。 */
77
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'];
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.40",
4
+ "version": "0.3.41",
5
5
  "packageManager": "pnpm@11.7.0",
6
6
  "type": "module",
7
7
  "main": "lib/index.js",