dsh-log-contract 0.3.41 → 0.3.43

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
@@ -123,8 +123,12 @@ outside `ok` / exit codes. It ships three assertion helpers for real run records
123
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
124
  | `R-1` | `assertFailureLatched(history)` | a failure is **latched**: after `failed: true`, no later snapshot (recover / reload / cache clear) may write `failed: false` |
125
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
+ | `R-2b` | `assertWithdrawalHasReason({ withdrawals, reasonField?, reasonSupported? })` | a withdrawal response must carry a **consumer-readable reason** field; a reason that only lives in logs/telemetry is red; implementations without such a field report `ok:null` (unverifiable) |
127
+ | `R-2b②` | `assertInitializedNotTreatedAsEmpty({ resources })` | a resource that is **initializing / unavailable** must not be judged as "none": judging from an empty value before `initialized === true` is red; no init signal ⇒ `ok:null` |
128
+ | `R-5` | `assertClosedSetExhaustive({ closedSet, covered })` / `assertOpenSetTolerant({ openSet, observations })` | our **closed** enumerations must be exhaustive (no missing/extra values); **open** sets (upstream event types, error codes, providers) must not be exhausted — unknown values need trace + default-allow + upgradeability |
129
+ | `R-6` | `assertIdempotentSideEffects({ operations, keyField? })` | side effects are grouped by a **stable key**: at most one execution per key, later attempts must be cached or explicitly "duplicate"; records without keys report `ok:null` (precondition: the key is supplied by the runtime) |
126
130
 
127
- `checkRunContract({...})` runs them together and lists the assertions you did not supply under
131
+ `checkRunContract({...})` runs them together (unverifiable results stay `null`) and lists the assertions you did not supply under
128
132
  `skipped`; when **none** ran, `ok` is `null` (unverifiable — never "pass"). Usage, positive/negative examples and the open items for R-2b
129
133
  (reason field) and R-6 (idempotency key) are in [docs/RUN-CONTRACT.md](docs/RUN-CONTRACT.md).
130
134
 
package/README.zh.md CHANGED
@@ -100,8 +100,12 @@ dsh-retrace 的「日志体检与修复」能力——与 dsh-retrace 一起构
100
100
  | `R-3` | `assertFailClosed({ required, provided, result })` | 任一必需输入(字段/文件/上下文)缺失 ⇒ 判定必须是**不兼容**且原因点名缺项;缺失永不匹配(判成兼容即红) |
101
101
  | `R-1` | `assertFailureLatched(history)` | 失败**置位**:出现 `failed: true` 后,任何后续快照(恢复/重载/清缓存)都不得写回 `failed: false` |
102
102
  | `R-2a` | `assertWriteOutcome({ write, artifact })` | 写失败或结果未知时,产物不得标 `complete`——必须撤回或标 `partial` / `unavailable` / `withdrawn` |
103
+ | `R-2b` | `assertWithdrawalHasReason({ withdrawals, reasonField?, reasonSupported? })` | 撤回类响应必须带**消费方可读的原因**字段;原因只在日志/遥测旁路 ⇒ 红;实现侧无该字段 ⇒ `ok:null`(unverifiable) |
104
+ | `R-2b②` | `assertInitializedNotTreatedAsEmpty({ resources })` | 资源**初始化中/取不到**时不得按空值推"没有":`initialized !== true` 却继续判断 ⇒ 红;无初始化信号 ⇒ `ok:null` |
105
+ | `R-5` | `assertClosedSetExhaustive({ closedSet, covered })` / `assertOpenSetTolerant({ openSet, observations })` | **闭集**(自己的枚举)必须穷尽(不漏值、不外溢);**开集**(上游事件类型/错误码/provider)不得穷尽——未知值须留痕 + 默认放行 + 可升级 |
106
+ | `R-6` | `assertIdempotentSideEffects({ operations, keyField? })` | 按**稳定幂等键**分组:同键副作用执行 ≤1 次,后续必须缓存或显式"重复";记录无键 ⇒ `ok:null`(缺前置:键由运行时提供) |
103
107
 
104
- `checkRunContract({...})` 可一起跑;未提供的断言列在 `skipped`;**一条都没跑**时 `ok: null`(unverifiable,⛔ 不冒充通过)。用法、正反例,
108
+ `checkRunContract({...})` 可一起跑(unverifiable 项保持 `null`);未提供的断言列在 `skipped`;**一条都没跑**时 `ok: null`(unverifiable,⛔ 不冒充通过)。用法、正反例,
105
109
  以及 R-2b(reason 字段)/ R-6(幂等键)的前置项清单见 [docs/RUN-CONTRACT.md](docs/RUN-CONTRACT.md)。
106
110
 
107
111
  ---
@@ -79,6 +79,118 @@ assertWriteOutcome({ write: { ok: false, error: 'EIO' }, artifact: { complete: t
79
79
  // ⇒ findings[0].id === 'R-2a'
80
80
  ```
81
81
 
82
+ ## R-2b · 撤回必须带消费方可读的原因(场景①)
83
+
84
+ **判据**:撤回类响应(`kind/type` 含 withdraw、或 `withdrawn === true`、或 `status === "withdrawn"`)
85
+ 必须携带**消费方可读**的原因字段(默认 `reason`,非空字符串)。原因只出现在 `log`、`metadata`、
86
+ `telemetry` 等**旁路** ⇒ 仍判红——消费方读不到日志里的原因,不等于撤回有原因。
87
+ 实现侧**没有**原因字段概念时,传 `reasonSupported: false` ⇒ `ok: null`(unverifiable,⛔ 不冒充通过)。
88
+
89
+ ```js
90
+ import { assertWithdrawalHasReason } from 'dsh-log-contract';
91
+
92
+ // ✅ 合规:原因在响应本身
93
+ assertWithdrawalHasReason({ withdrawals: [{ kind: 'withdrawal', target: 'x', reason: 'user asked' }] }).ok === true;
94
+
95
+ // ⛔ 违规:没有 reason(原因只在日志旁路)
96
+ assertWithdrawalHasReason({ withdrawals: [{ withdrawn: true, target: 'x', log: 'revoked by policy' }] });
97
+ // ⇒ findings[0].id === 'R-2b'(sideChannels: ['log'])
98
+
99
+ // ⚪ 不可判定:实现侧没有该字段
100
+ assertWithdrawalHasReason({ withdrawals: [{ withdrawn: true }], reasonSupported: false }).ok === null;
101
+ ```
102
+
103
+ > 场景②("初始化中"被当成空值继续判断)属另一条判据(`initialized !== true` 却继续),本包暂未实现。
104
+
105
+ ## R-2b② · 初始化中/取不到 不得按空值推"没有"
106
+
107
+ **判据**:资源(归档索引 / 读端 / 父链等)处于**初始化中或取不到**时,`initialized !== true`
108
+ 却按空值继续判断(把"还没准备好"当成"不存在 / 无父 / 无归档")⇒ 红。
109
+ 无初始化信号 ⇒ `ok: null`(unverifiable,⛔ 不冒充通过)。
110
+
111
+ ```js
112
+ import { assertInitializedNotTreatedAsEmpty } from 'dsh-log-contract';
113
+
114
+ // ✅ 合规:已就绪后才判断
115
+ assertInitializedNotTreatedAsEmpty({ resources: [{ name: 'archive-index', initialized: true, judgedFromEmpty: true }] }).ok === true;
116
+
117
+ // ⛔ 违规:父链还没加载就按"无父"继续
118
+ assertInitializedNotTreatedAsEmpty({ resources: [{ name: 'parent-chain', initialized: false, judgedFromEmpty: true }] });
119
+ // ⇒ findings[0].id === 'R-2b-2'
120
+
121
+ // ⚪ 无初始化信号 ⇒ unverifiable
122
+ assertInitializedNotTreatedAsEmpty({ resources: [{ name: 'x', judgedFromEmpty: true }] }).ok === null;
123
+ ```
124
+
125
+ 读端落地(本仓):
126
+ - `archiveVerdict(events, { archiveRoots, readLines, initialized })`——`initialized === false` ⇒
127
+ 显式 `not-initialized` 降级(`verdict: 'unverifiable'`、`notInitialized: true`,不冒充、不报缺失);
128
+ - 归档读端(`readArchiveIndex` / `readArchiveLines` 经 `verifyArchivePointers`)**暂不可读**时计入
129
+ `unavailable` / `notReady`,结论 `unverifiable`,**不再**并入"内容缺失"(`missing`/`lineMissing` 保持 0);
130
+ 内容级失败(行缺失等)仍判 `unrestorable`。
131
+ - 可忽略白名单解析(`resolveIgnorableWhitelist`):外部白名单缺失时保持**内置默认集**(安全侧),
132
+ 未知事件仍会以 warning 报出——不会把"白名单没加载"静默当成"全部不忽略"。
133
+ - 父链:本仓**没有**谱系读取实现(父链读取在外部实现),故本仓只提供断言接口与判据,不硬做父链逻辑。
134
+
135
+ ## R-5 · 闭集须穷尽;开集不得穷尽
136
+
137
+ **判据**:**枚举封闭 ≠ 契约封闭**,两个方向都会出事。
138
+
139
+ | 集类型 | 例子 | 断言 | 违规 |
140
+ |---|---|---|---|
141
+ | **闭集**(自己定义) | 已知事件类型表、规则 id/severity 集 | `assertClosedSetExhaustive({ closedSet, covered })` | 声明里有但没处理(漏值);处理分支出现声明外的值(外溢) |
142
+ | **开集**(外部会新增) | 上游事件 `type`、错误码、模型 provider | `assertOpenSetTolerant({ openSet, observations })` | 未知值被拒绝;未知值没留痕;未知值不可升级 |
143
+
144
+ ```js
145
+ import { assertClosedSetExhaustive, assertOpenSetTolerant } from 'dsh-log-contract';
146
+
147
+ // ✅ 闭集穷尽
148
+ assertClosedSetExhaustive({ closedSet: ['a', 'b'], covered: ['a', 'b'] }).ok === true;
149
+ // ⛔ 闭集漏值 / 外溢
150
+ assertClosedSetExhaustive({ closedSet: ['a', 'b'], covered: ['a'] }).missing; // ['b']
151
+ assertClosedSetExhaustive({ closedSet: ['a'], covered: ['a', 'c'] }).extra; // ['c']
152
+
153
+ // ✅ 开集:未知值留痕 + 默认放行 + 可升级
154
+ assertOpenSetTolerant({ openSet: ['user/message'], observations: [{ value: 'future/event', decision: 'allow', traced: true, upgradeable: true }] }).ok === true;
155
+ // ⛔ 开集:未知被拒(外部集合不得穷尽)
156
+ assertOpenSetTolerant({ openSet: [], observations: [{ value: 'future/event', decision: 'reject', traced: true, upgradeable: true }] });
157
+ ```
158
+
159
+ ## R-6 · 副作用必须幂等(同键只执行一次)
160
+
161
+ **核查结论(先查再判)**:运行记录里**已有天然稳定键**——`tool/call` 的 `data.callId`
162
+ 被持久化、且由 `tool/result` 的 `data.message.source.callId` 引用(本包 `P3` 配对即用它),
163
+ `turn+step`、消息 `id` 同样稳定。因此 R-6 可落为**接口级可机检**:调用方按稳定键把执行记录
164
+ 喂进来,断言「同键副作用执行次数 ≤ 1;第二次必须返回缓存或显式"重复"」。
165
+ **仍缺的前置清单**:
166
+
167
+ | 缺什么 | 谁提供 | 最小补法 |
168
+ |---|---|---|
169
+ | 重试**复用同一幂等键**的声明 | 写入/调用路径(运行时) | 调用的重试沿用首次的键(tool call id 已持久化,直接复用即可) |
170
+ | 第二次执行**返回缓存或显式"重复"**的标记 | 副作用执行器(工具/写入实现) | 记录里写 `effect: "cached" \| "duplicate"`(或 `applied: false`),让"未重复执行"可判 |
171
+
172
+ 记录不带键时无法判定 ⇒ `ok: null`(unverifiable,⛔ 不冒充通过)。
173
+
174
+ ```js
175
+ import { assertIdempotentSideEffects } from 'dsh-log-contract';
176
+
177
+ // ✅ 合规:同键首次执行 + 第二次返回缓存
178
+ assertIdempotentSideEffects({ operations: [
179
+ { key: 'call-1', effect: 'applied' },
180
+ { key: 'call-1', effect: 'cached' },
181
+ ] }).ok === true;
182
+
183
+ // ⛔ 违规:同键执行两次
184
+ assertIdempotentSideEffects({ operations: [
185
+ { key: 'call-1', applied: true },
186
+ { key: 'call-1', applied: true },
187
+ ] });
188
+ // ⇒ findings[0].id === 'R-6'
189
+
190
+ // ⚪ 不可判定:记录里没有稳定键(缺前置)
191
+ assertIdempotentSideEffects({ operations: [{ effect: 'applied' }] }).ok === null;
192
+ ```
193
+
82
194
  ## 一起跑
83
195
 
84
196
  ```js
@@ -93,8 +205,11 @@ const report = checkRunContract({ history, write, artifact, required, provided,
93
205
 
94
206
  | 候选 | 状态 | 前置项 |
95
207
  |---|---|---|
96
- | **R-2b** 撤回必须带原因 | 未实现 | 撤回事件需要**必填 `reason`** 字段(现结构只有 `originalText`,没有原因语义)⇒ 先补字段契约,再加断言 |
97
- | **R-6** 副作用必须幂等 | 未实现 | 需要先立"副作用携带稳定**幂等键**"契约(当前没有该概念);无幂等键时判定只能是"缺前置" |
208
+ | **R-2b 场景①** 撤回必须带原因 | **已落断言**(`assertWithdrawalHasReason`) | 记录里出现撤回类响应即可判;实现侧没有原因字段时标 unverifiable(`reasonSupported:false`) |
209
+ | **R-2b 场景②** 初始化中不得按空值继续 | **已落断言 + 读端降级**(`assertInitializedNotTreatedAsEmpty`;`archiveVerdict` 显式 `initialized`) | 父链读取在外部实现:本仓只出断言/判据,不硬做父链逻辑 |
210
+ | **R-6** 副作用必须幂等 | **已落接口级断言**(`assertIdempotentSideEffects`) | 天然键已有(tool call id / turn+step / 消息 id);**仍缺**:"重试复用同键 + 第二次返回缓存/重复"的声明(记录不带键 ⇒ unverifiable) |
211
+ | **R-5** 闭/开集 | **已落断言**(`assertClosedSetExhaustive` / `assertOpenSetTolerant`) | 闭集清单:已知事件类型表、规则 id/severity;开集:上游 `type` 词表/错误码/provider |
212
+ | **dsh-6** 归档列表写入 | **不做写入断言** | 本仓归档模块**没有写调用**(`lib/archive.js` 内 0 处写);写入方=外部 workspace archive op(协调项) |
98
213
 
99
214
  `check --json` 的 `runContract` 段只承载**规则目录**(`rules` + `note`);真实判定由调用方
100
215
  把运行记录喂给上面的断言函数(与 `errorContract` 段同一口径)。
@@ -10,7 +10,7 @@
10
10
  |---|---|
11
11
  | 字段名 | `schemaVersion` |
12
12
  | 位置 | `check --json` 报告**顶层**;同值同步进 `validateSessionLog()` 返回对象顶层 |
13
- | 当前值 | `"4"`(字符串,暂不采用 semver;见下文 v2 / v3 / v4) |
13
+ | 当前值 | `"6"`(字符串,暂不采用 semver;见下文 v2 / v3 / v4 / v5 / v6) |
14
14
  | 覆盖范围 | 仅 `check --json` 这一份报告结构。`prewrite --json` 是**另一份结构**,暂不带本字段(当前 CLI 亦无 `plan` 子命令) |
15
15
 
16
16
  `schemaVersion` 标记的是**报告结构**(字段集合 / 字段类型 / 字段含义)的版本:
@@ -85,16 +85,40 @@
85
85
  | 键 | 形状 | 说明 |
86
86
  |---|---|---|
87
87
  | `runContract.family` | `"run-contract"` | 报告域(与 `error-expression` / `version-identity` 并列,靠 family 分派) |
88
- | `runContract.rules` | `[{id,severity,title,layer}]` | 规则目录:`R-3` 输入缺失⇒不兼容 / `R-1` 失败置位不清零 / `R-2a` 写失败不得标完整 |
88
+ | `runContract.rules` | `[{id,severity,title,layer}]` | 规则目录(v6 起 7 条):`R-3` 输入缺失⇒不兼容 / `R-1` 失败置位不清零 / `R-2a` 写失败不得标完整 / `R-2b` 撤回必须带消费方可读原因 / `R-2b-2` 初始化中不得按空值推"没有" / `R-5` 闭集穷尽·开集不穷尽 / `R-6` 副作用幂等(同键只执行一次) |
89
89
  | `runContract.note` | `string` | 断言接口入口(`docs/RUN-CONTRACT.md`);真实判定需调用方提供运行记录 |
90
90
 
91
91
  兼容性:**v3 消费者读 v4 报告**忽略未知键 `runContract` 即可;`ok`/`violations`/退出码语义未变。
92
92
  断言接口(`assertFailClosed` / `assertFailureLatched` / `assertWriteOutcome` / `checkRunContract`)
93
93
  不改变任何既有报告字段,只是"可以调用"的诊断 API。
94
94
 
95
+ ## v5(本版):R-2b / R-6 断言(兼容递增)
96
+
97
+ `schemaVersion` 由 `"4"` → `"5"`。**只增内容**:`runContract.rules` 从 3 条扩到 5 条,新增两个断言
98
+ 接口;顶层键集合与 `ok`/退出码语义**不变**。
99
+
100
+ | 新增 | 形状 | 说明 |
101
+ |---|---|---|
102
+ | `R-2b` | `assertWithdrawalHasReason({ withdrawals, reasonField?, reasonSupported? })` | 撤回类响应必须带**消费方可读**的原因字段(非空字符串);原因只在 `log`/`metadata`/`telemetry` 旁路 ⇒ 红;实现侧无该字段 ⇒ 传 `reasonSupported:false` ⇒ `ok:null`(unverifiable) |
103
+ | `R-6` | `assertIdempotentSideEffects({ operations, keyField? })` | 按**稳定幂等键**分组:同键副作用执行次数 ≤1,后续尝试必须缓存/显式"重复";结果不可判定 ⇒ 红;记录无稳定键 ⇒ `ok:null`(缺前置) |
104
+
105
+ 兼容性:v4 消费者读 v5 报告忽略新增规则条目即可;既有断言与报告字段语义未变。
106
+
107
+ ## v6(本版):R-2b② / R-5 断言(兼容递增)
108
+
109
+ `schemaVersion` 由 `"5"` → `"6"`。**只增内容**:`runContract.rules` 扩到 7 条,新增两个断言接口;
110
+ 顶层键集合与 `ok`/退出码语义**不变**。
111
+
112
+ | 新增 | 形状 | 说明 |
113
+ |---|---|---|
114
+ | `R-2b-2` | `assertInitializedNotTreatedAsEmpty({ resources })` | 资源初始化中/取不到时不得按空值推"没有"(`initialized !== true` 却继续判断 ⇒ 红);无初始化信号 ⇒ `ok:null`。归档读端同步降级:`archiveVerdict` 支持 `initialized`,读端不可读时结论 `unverifiable`(`notReady`),不并入内容缺失 |
115
+ | `R-5` | `assertClosedSetExhaustive({ closedSet, covered })` / `assertOpenSetTolerant({ openSet, observations })` | 自己的闭集必须穷尽(漏值/外溢 ⇒ 红);外部开集不得穷尽——未知值须留痕 + 默认放行 + 可升级(否则红) |
116
+
117
+ 兼容性:v5 消费者读 v6 报告忽略新增规则条目即可;既有断言与报告字段语义未变。
118
+
95
119
  ## 何时升版
96
120
 
97
- **不兼容才升**(版本号只增,如 `"3"` → `"4"`):
121
+ **不兼容才升**(版本号只增,如 `"5"` → `"6"`):
98
122
 
99
123
  | 变更 | 升版? |
100
124
  |---|---|
@@ -116,7 +140,7 @@
116
140
 
117
141
  | 报告域 | 命令 | 版本字段 | 备注 |
118
142
  |---|---|---|---|
119
- | 日志契约(session log contract) | `check --json` | 顶层 `schemaVersion`(当前 `"4"`) | 本文正文主要讲这一域 |
143
+ | 日志契约(session log contract) | `check --json` | 顶层 `schemaVersion`(当前 `"6"`) | 本文正文主要讲这一域 |
120
144
  | 运行时契约(run-contract) | 断言接口(`docs/RUN-CONTRACT.md`) | `family: "run-contract"`(`check --json` 的 `runContract` 段只给规则目录) | 与日志契约**互不影响**:断言不改 `ok`/退出码 |
121
145
  | 错误表达契约(error-expression) | `error-contract --json` | 顶层 `schemaVersion`(当前 `"1"`)+ `family: "error-expression"` | 与日志契约**互不影响**:任一域升版不牵动另一域 |
122
146
 
package/lib/archive.js CHANGED
@@ -212,11 +212,14 @@ export function verifyArchivePointers(pointers, { archiveRoots = [], readLines }
212
212
  lineMissing: 0,
213
213
  shaMismatch: 0,
214
214
  duplicated: 0,
215
+ // R-2b②:读取路径不可用(索引未就绪/不可读)≠ 内容缺失 —— 单列计数,不并入 missing。
216
+ unavailable: 0,
217
+ notReady: false,
215
218
  restoredBytes: 0,
216
219
  restorableRate: 0,
217
220
  verdict: assessable ? 'restorable' : 'unverifiable',
218
221
  violations: [],
219
- details: { missing: [], relocated: [], unresolved: [], lineMissing: [], shaMismatch: [] },
222
+ details: { missing: [], relocated: [], unresolved: [], lineMissing: [], shaMismatch: [], unavailable: [] },
220
223
  };
221
224
  if (!assessable) {
222
225
  // 不可判定:没有归档根 ⇒ 不冒充通过、也不产生违规(独立维度)。
@@ -255,11 +258,16 @@ export function verifyArchivePointers(pointers, { archiveRoots = [], readLines }
255
258
  archiveIndex = (readLines ?? readArchiveIndex)(target, wanted);
256
259
  if (Array.isArray(archiveIndex)) archiveIndex = { count: archiveIndex.length, lineAt: (n) => archiveIndex[n - 1] ?? '' };
257
260
  } catch (err) {
261
+ // R-2b②(读端锚点 145/166/306):读不到 ≠ 没有。索引未就绪/文件暂不可读时**不得**
262
+ // 推"内容缺失"(那会把"还没准备好"报成 A1 内容缺失);单列 `unavailable` 并让结论
263
+ // 落到 `unverifiable`(可见原因、不崩),只有内容级失败才计入 missing/lineMissing/…
258
264
  const message = String(err?.message ?? err).slice(0, 120);
259
265
  for (const { pointer } of items) {
260
- result.missing++;
261
- if (result.details.missing.length < 20) result.details.missing.push({ seq: pointer.seq, field: pointer.field, ref: pointer.ref, target, reason: message });
262
- result.violations.push(violation('A1', { seq: pointer.seq, lineNo: pointer.lineNo, eventType: pointer.type }, `归档不可读:${pointer.field} → ${pointer.ref}(解析到 ${target})——在位可还原判定失败(${message})`));
266
+ result.unavailable++;
267
+ if (result.details.unavailable.length < 20) result.details.unavailable.push({ seq: pointer.seq, field: pointer.field, ref: pointer.ref, target, reason: message });
268
+ const v = violation('A1', { seq: pointer.seq, lineNo: pointer.lineNo, eventType: pointer.type }, `归档暂不可读(可能尚未就绪):${pointer.field} → ${pointer.ref}(解析到 ${target})——按"不可判定"记,不判内容缺失(${message})`);
269
+ v.severity = 'warning';
270
+ result.violations.push(v);
263
271
  }
264
272
  continue;
265
273
  }
@@ -292,9 +300,11 @@ export function verifyArchivePointers(pointers, { archiveRoots = [], readLines }
292
300
  }
293
301
  }
294
302
  result.restorableRate = result.effectivePointers > 0 ? result.restorable / result.effectivePointers : 1;
295
- result.verdict = result.missing === 0 && result.lineMissing === 0 && result.shaMismatch === 0 && result.unresolved === 0
296
- ? 'restorable'
297
- : 'unrestorable';
303
+ const contentFailures = result.missing + result.lineMissing + result.shaMismatch + result.unresolved;
304
+ result.notReady = result.unavailable > 0;
305
+ result.verdict = contentFailures > 0
306
+ ? 'unrestorable'
307
+ : (result.notReady ? 'unverifiable' : 'restorable');
298
308
  return result;
299
309
  }
300
310
 
@@ -303,7 +313,33 @@ export function verifyArchivePointers(pointers, { archiveRoots = [], readLines }
303
313
  * @param {Array<{event:object,lineNo?:number}>} events
304
314
  * @param {{archiveRoots?:string[]}} [opts]
305
315
  */
306
- export function archiveVerdict(events, { archiveRoots = [], readLines } = {}) {
316
+ export function archiveVerdict(events, { archiveRoots = [], readLines, initialized } = {}) {
317
+ // R-2b②:调用方能给"初始化态"时必须先判它——资源尚未就绪时,空事件流/空指针**不得**
318
+ // 被解释成"没有归档"(那会推出 restorable/unrestorable 的错误结论)。
319
+ if (initialized === false) {
320
+ return {
321
+ assessable: false,
322
+ initialized: false,
323
+ notInitialized: true,
324
+ reason: 'not-initialized',
325
+ pointers: 0,
326
+ effectivePointers: 0,
327
+ restorable: 0,
328
+ relocated: 0,
329
+ missing: 0,
330
+ unresolved: 0,
331
+ lineMissing: 0,
332
+ shaMismatch: 0,
333
+ duplicated: 0,
334
+ unavailable: 0,
335
+ notReady: true,
336
+ restoredBytes: 0,
337
+ restorableRate: 0,
338
+ verdict: 'unverifiable',
339
+ violations: [],
340
+ details: { missing: [], relocated: [], unresolved: [], lineMissing: [], shaMismatch: [], unavailable: [] },
341
+ };
342
+ }
307
343
  const pointers = collectArchivePointers(events);
308
344
  return verifyArchivePointers(pointers, { archiveRoots, readLines });
309
345
  }
package/lib/index.js CHANGED
@@ -17,4 +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';
20
+ export { RUN_CONTRACT_RULES, RUN_CONTRACT_RULE_BY_ID, RUN_CONTRACT_FAMILY, assertFailClosed, assertFailureLatched, assertWriteOutcome, checkRunContract, isMissingInput, reasonMentions, reasonTokensOf, isWithdrawalLike, assertWithdrawalHasReason, assertIdempotentSideEffects, sideEffectState, assertInitializedNotTreatedAsEmpty, assertClosedSetExhaustive, assertOpenSetTolerant } from './run-contract.js';
@@ -45,6 +45,42 @@ export const RUN_CONTRACT_RULES = [
45
45
  source: '不可信数据不得当完整数据交付:写失败(含结果未知)⇒ 撤回或标记不可用',
46
46
  description: '写入未成功(`write.ok !== true`,含 `ok` 缺省/未知)时,产物不得被标记为完整(`artifact.complete === true` 或 `artifact.status === "complete"`);必须撤回或标 `partial` / `unavailable` / `withdrawn`。接口断言,不绑定具体写入实现。',
47
47
  },
48
+ {
49
+ id: 'R-2b',
50
+ family: RUN_CONTRACT_FAMILY,
51
+ layer: 'run',
52
+ severity: 'error',
53
+ title: '撤回必须带消费方可读的原因',
54
+ source: '撤回类响应必须含 reason 字段(不是日志/旁路):原因写进日志或遥测,消费方读不到即等于没有原因',
55
+ description: '撤回类响应(`kind/type` 含 withdraw、或 `withdrawn === true`、或 `status === "withdrawn"`)必须携带**消费方可读**的原因字段(默认 `reason`,非空字符串);原因只出现在 `log` / `metadata` / `telemetry` 等旁路 ⇒ 仍判红。实现侧**没有**原因字段概念时,调用方传 `reasonSupported: false` ⇒ 结果 `ok: null`(unverifiable,⛔ 不冒充通过)。',
56
+ },
57
+ {
58
+ id: 'R-2b-2',
59
+ family: RUN_CONTRACT_FAMILY,
60
+ layer: 'run',
61
+ severity: 'error',
62
+ title: '初始化中/取不到 不得按空值推"没有"',
63
+ source: '资源未就绪(索引/读端/父链未加载)时,空结果只表示"现在还读不到",不表示"没有"',
64
+ description: '资源(归档索引/读端/父链等)处于**初始化中或取不到**时,若 `initialized !== true` 却按空值继续判断(把"还没准备好"当成"不存在/无父/无归档")⇒ 判红。调用方无初始化信号时结果 `ok: null`(unverifiable,⛔ 不冒充通过)。属性口径:看"是否在有就绪信号前就下了空值结论",不绑定具体读端实现。',
65
+ },
66
+ {
67
+ id: 'R-5',
68
+ family: RUN_CONTRACT_FAMILY,
69
+ layer: 'run',
70
+ severity: 'error',
71
+ title: '闭集须穷尽;开集不得穷尽(留痕 + 默认放行 + 可升级)',
72
+ source: '枚举封闭 ≠ 契约封闭:自己的闭集应穷尽(漏值没人发现),外部会新增的集合不得穷尽(上游加值即崩)',
73
+ description: '**闭集**(自己定义的枚举:已知事件类型表、规则 id/severity 集)必须**穷尽**——声明里有的值都要被处理(未处理 ⇒ 红),处理到的值都必须在声明内(外溢 ⇒ 红)。**开集**(外部会新增:上游事件 type、错误码、provider 名)**不得穷尽**——未知值必须**留痕 + 默认放行 + 可升级**;未知值被判拒绝、或没有留痕、或不可升级 ⇒ 红。',
74
+ },
75
+ {
76
+ id: 'R-6',
77
+ family: RUN_CONTRACT_FAMILY,
78
+ layer: 'run',
79
+ severity: 'error',
80
+ title: '副作用必须幂等(同键只执行一次)',
81
+ source: '同一稳定幂等键的副作用被重复执行 ⇒ 重复写入/重复发送等不可逆后果;第二次必须返回缓存或显式"重复"',
82
+ description: '运行记录按**稳定幂等键**(默认 `key`;运行时可提供 tool call id / turn+step / 消息 id 这类天然键)分组:同一键的副作用**执行次数必须 ≤ 1**;后续尝试必须返回缓存/显式"重复"(`effect/outcome ∈ deduped/cached/duplicate/replayed/skipped/noop`)——执行结果不可判定同样判红。⛔ 记录里没有稳定键 ⇒ `ok: null`(unverifiable,缺前置:键由运行时/调用方提供)。',
83
+ },
48
84
  ];
49
85
 
50
86
  export const RUN_CONTRACT_RULE_BY_ID = Object.freeze(Object.fromEntries(RUN_CONTRACT_RULES.map((r) => [r.id, r])));
@@ -141,7 +177,168 @@ export function assertWriteOutcome({ write = {}, artifact = {} } = {}) {
141
177
  }
142
178
 
143
179
  /**
144
- * 三条断言一起跑(调用方按需提供输入;未提供的断言跳过并在 `skipped` 里可见,⛔ 不冒充通过)。
180
+ * 撤回类响应识别(属性口径:看语义标记,不绑定具体实现)。
181
+ * @param {object} item
182
+ * @returns {boolean}
183
+ */
184
+ export function isWithdrawalLike(item) {
185
+ if (!item || typeof item !== 'object') return false;
186
+ if (item.kind === 'withdrawal' || item.type === 'withdrawal') return true;
187
+ if (item.withdrawal === true || item.withdrawn === true) return true;
188
+ if (item.status === 'withdrawn' || item.status === 'withdrawal') return true;
189
+ if (typeof item.type === 'string' && item.type.includes('withdraw')) return true;
190
+ if (typeof item.kind === 'string' && item.kind.includes('withdraw')) return true;
191
+ return false;
192
+ }
193
+
194
+ /**
195
+ * R-2b · 撤回类响应必须带**消费方可读**的原因(不是日志/旁路)。
196
+ *
197
+ * @param {{withdrawals?: object|object[], reasonField?: string, reasonSupported?: boolean}} input
198
+ * `withdrawals` 缺省 ⇒ `ok: null`(无输入,不冒充通过);
199
+ * `reasonSupported === false` ⇒ `ok: null`(实现侧无原因字段概念,按缺前置登记)。
200
+ * @returns {{id:'R-2b', ok:boolean|null, checked:number, findings:Array}}
201
+ */
202
+ export function assertWithdrawalHasReason({ withdrawals, reasonField = 'reason', reasonSupported } = {}) {
203
+ if (withdrawals === undefined) return { id: 'R-2b', ok: null, checked: 0, skipped: 'no-withdrawals-input', findings: [] };
204
+ if (reasonSupported === false) return { id: 'R-2b', ok: null, checked: 0, skipped: 'implementation-provides-no-reason-field', findings: [] };
205
+ const list = (Array.isArray(withdrawals) ? withdrawals : [withdrawals]).filter(isWithdrawalLike);
206
+ if (list.length === 0) return { id: 'R-2b', ok: null, checked: 0, skipped: 'no-withdrawal-items', findings: [] };
207
+ const findings = [];
208
+ for (const item of list) {
209
+ const reason = item?.[reasonField];
210
+ const readable = typeof reason === 'string' && reason.trim() !== '';
211
+ if (readable) continue;
212
+ const sideChannels = ['log', 'logs', 'metadata', 'telemetry'].filter((k) => item && item[k] !== undefined);
213
+ findings.push(finding('R-2b', `撤回类响应缺消费方可读的 ${reasonField} 字段(原因必须是响应本身的字段,不是日志/旁路)${sideChannels.length > 0 ? `——原因若只在 ${sideChannels.join('/')} 里,消费方读不到` : ''}`, { reasonField, sideChannels }));
214
+ }
215
+ return { id: 'R-2b', ok: findings.length === 0, checked: list.length, findings };
216
+ }
217
+
218
+ const APPLIED_TAGS = new Set(['applied', 'executed', 'side-effect', 'write', 'committed']);
219
+ const DEDUPED_TAGS = new Set(['deduped', 'cached', 'duplicate', 'replayed', 'skipped', 'noop', 'not-applied', 'ignored']);
220
+
221
+ /** 单次副作用的执行状态:applied / deduped / unknown。 */
222
+ export function sideEffectState(op) {
223
+ if (op?.applied === true) return 'applied';
224
+ if (op?.applied === false) return 'deduped';
225
+ const tag = op?.effect ?? op?.outcome ?? op?.status;
226
+ if (APPLIED_TAGS.has(tag)) return 'applied';
227
+ if (DEDUPED_TAGS.has(tag)) return 'deduped';
228
+ return 'unknown';
229
+ }
230
+
231
+ /**
232
+ * R-6 · 副作用幂等:同键执行次数 ≤1;后续尝试必须缓存/显式"重复"。
233
+ *
234
+ * @param {{operations?: object|object[], keyField?: string}} input
235
+ * `operations` 缺省或**没有任何稳定键** ⇒ `ok: null`(unverifiable,缺前置)。
236
+ * @returns {{id:'R-6', ok:boolean|null, keys:number, findings:Array}}
237
+ */
238
+ export function assertIdempotentSideEffects({ operations, keyField = 'key' } = {}) {
239
+ if (operations === undefined) return { id: 'R-6', ok: null, keys: 0, skipped: 'no-operations-input', findings: [] };
240
+ const list = (Array.isArray(operations) ? operations : [operations])
241
+ .filter((op) => op && typeof op[keyField] === 'string' && op[keyField].trim() !== '');
242
+ if (list.length === 0) return { id: 'R-6', ok: null, keys: 0, skipped: 'no-stable-keys', findings: [] };
243
+ const byKey = new Map();
244
+ for (const op of list) {
245
+ const k = op[keyField];
246
+ if (!byKey.has(k)) byKey.set(k, []);
247
+ byKey.get(k).push(op);
248
+ }
249
+ const findings = [];
250
+ for (const [key, ops] of byKey) {
251
+ const applied = ops.filter((op) => sideEffectState(op) === 'applied');
252
+ if (applied.length > 1) {
253
+ findings.push(finding('R-6', `同一幂等键 "${key}" 的副作用被执行了 ${applied.length} 次(应 ≤1)——重复执行不可逆,第二次必须返回缓存或显式"重复"`, { key, applied: applied.length }));
254
+ }
255
+ for (const op of ops) {
256
+ const state = sideEffectState(op);
257
+ if (state === 'unknown') {
258
+ findings.push(finding('R-6', `同一幂等键 "${key}" 的一次执行结果不可判定(effect/outcome=${String(op?.effect ?? op?.outcome ?? op?.status)})——必须显式标 applied 或缓存/重复`, { key }));
259
+ }
260
+ }
261
+ }
262
+ return { id: 'R-6', ok: findings.length === 0, keys: byKey.size, findings };
263
+ }
264
+
265
+ /**
266
+ * R-2b-2 · 有初始化信号时,不得在未就绪状态下按空值继续判断。
267
+ *
268
+ * @param {{resources?: object|object[], initializedField?: string, judgedField?: string}} input
269
+ * `resources` 每项:`{ name?, initialized?: boolean, judgedFromEmpty?: boolean }`;
270
+ * 没有任何 `initialized` 信号 ⇒ `ok: null`(unverifiable)。
271
+ * @returns {{id:'R-2b-2', ok:boolean|null, checked:number, findings:Array}}
272
+ */
273
+ export function assertInitializedNotTreatedAsEmpty({ resources, initializedField = 'initialized', judgedField = 'judgedFromEmpty' } = {}) {
274
+ if (resources === undefined) return { id: 'R-2b-2', ok: null, checked: 0, skipped: 'no-resources-input', findings: [] };
275
+ const list = (Array.isArray(resources) ? resources : [resources]).filter((r) => r && typeof r === 'object');
276
+ const signaled = list.filter((r) => r[initializedField] === true || r[initializedField] === false);
277
+ if (signaled.length === 0) return { id: 'R-2b-2', ok: null, checked: 0, skipped: 'no-initialization-signal', findings: [] };
278
+ const findings = [];
279
+ for (const r of signaled) {
280
+ const name = r.name ?? r.id ?? null;
281
+ if (r[initializedField] !== true && r[judgedField] === true) {
282
+ findings.push(finding('R-2b-2', `资源「${String(name ?? '?')}」未就绪(${initializedField}=${String(r[initializedField])})却按空值继续判断(${judgedField}=true)——初始化中/取不到不得推"没有"`, { resource: name, initialized: r[initializedField] }));
283
+ }
284
+ }
285
+ return { id: 'R-2b-2', ok: findings.length === 0, checked: signaled.length, findings };
286
+ }
287
+
288
+ /**
289
+ * R-5(闭集)· 自己定义的枚举必须穷尽,且不得外溢。
290
+ *
291
+ * @param {{closedSet?: string[], covered?: string[]}} input
292
+ * `closedSet` 声明的枚举;`covered` 实际处理到的值。
293
+ * @returns {{id:'R-5', kind:'closed-set', ok:boolean|null, missing:string[], extra:string[], findings:Array}}
294
+ */
295
+ export function assertClosedSetExhaustive({ closedSet, covered } = {}) {
296
+ if (closedSet === undefined || covered === undefined) {
297
+ return { id: 'R-5', kind: 'closed-set', ok: null, missing: [], extra: [], skipped: 'no-closed-set-input', findings: [] };
298
+ }
299
+ const declared = new Set(closedSet);
300
+ const handled = new Set(covered);
301
+ const missing = [...declared].filter((v) => !handled.has(v));
302
+ const extra = [...handled].filter((v) => !declared.has(v));
303
+ const findings = [];
304
+ for (const v of missing) findings.push(finding('R-5', `闭集成员「${String(v)}」在声明里但没有任何处理分支——闭集未穷尽(漏值不会被发现)`, { kind: 'closed-set', value: v }));
305
+ for (const v of extra) findings.push(finding('R-5', `处理分支出现闭集之外的值「${String(v)}」——闭集外溢(应把它加进声明,否则契约不封闭)`, { kind: 'closed-set', value: v }));
306
+ return { id: 'R-5', kind: 'closed-set', ok: findings.length === 0, missing, extra, findings };
307
+ }
308
+
309
+ /**
310
+ * R-5(开集)· 外部会新增的集合不得穷尽:未知值必须留痕 + 默认放行 + 可升级。
311
+ *
312
+ * @param {{openSet?: string[], observations?: Array<{value:string, decision?:'allow'|'reject', traced?:boolean, upgradeable?:boolean}>}} input
313
+ * @returns {{id:'R-5', kind:'open-set', ok:boolean|null, unknown:string[], findings:Array}}
314
+ */
315
+ export function assertOpenSetTolerant({ openSet = [], observations } = {}) {
316
+ if (observations === undefined) {
317
+ return { id: 'R-5', kind: 'open-set', ok: null, unknown: [], skipped: 'no-observations-input', findings: [] };
318
+ }
319
+ const known = new Set(openSet);
320
+ const list = Array.isArray(observations) ? observations : [observations];
321
+ const unknown = [];
322
+ const findings = [];
323
+ for (const obs of list) {
324
+ const value = obs?.value;
325
+ if (typeof value !== 'string' || known.has(value)) continue;
326
+ unknown.push(value);
327
+ if (obs.decision !== 'allow') {
328
+ findings.push(finding('R-5', `外部集合的未知值「${value}」被拒绝(decision=${String(obs.decision)})——外部集合会新增,不得穷尽/不得因未知而拒`, { kind: 'open-set', value }));
329
+ }
330
+ if (obs.traced !== true) {
331
+ findings.push(finding('R-5', `外部集合的未知值「${value}」没有留痕(traced!==true)——未知必须可观察`, { kind: 'open-set', value }));
332
+ }
333
+ if (obs.upgradeable !== true) {
334
+ findings.push(finding('R-5', `外部集合的未知值「${value}」未标可升级(upgradeable!==true)——必须留出升级路径`, { kind: 'open-set', value }));
335
+ }
336
+ }
337
+ return { id: 'R-5', kind: 'open-set', ok: findings.length === 0, unknown, findings };
338
+ }
339
+
340
+ /**
341
+ * 断言一起跑(调用方按需提供输入;未提供的断言跳过并在 `skipped` 里可见,⛔ 不冒充通过)。
145
342
  *
146
343
  * @param {{required?, provided?, result?, history?, write?, artifact?}} input
147
344
  * @returns {{family:string, rules:Array, checks:Array, skipped:string[], ok:boolean|null, findings:Array}}
@@ -166,7 +363,32 @@ export function checkRunContract(input = {}) {
166
363
  checks.push(r);
167
364
  findings.push(...r.findings);
168
365
  } else skipped.push('R-3');
169
- const ran = checks.length > 0;
366
+ if (input.withdrawals !== undefined) {
367
+ const r = assertWithdrawalHasReason({ withdrawals: input.withdrawals, reasonField: input.reasonField, reasonSupported: input.reasonSupported });
368
+ checks.push(r);
369
+ findings.push(...r.findings);
370
+ } else skipped.push('R-2b');
371
+ if (input.initializations !== undefined) {
372
+ const r = assertInitializedNotTreatedAsEmpty({ resources: input.initializations });
373
+ checks.push(r);
374
+ findings.push(...r.findings);
375
+ } else skipped.push('R-2b-2');
376
+ if (input.closedSet !== undefined) {
377
+ const r = assertClosedSetExhaustive(input.closedSet);
378
+ checks.push(r);
379
+ findings.push(...r.findings);
380
+ } else skipped.push('R-5-closed');
381
+ if (input.openSet !== undefined) {
382
+ const r = assertOpenSetTolerant(input.openSet);
383
+ checks.push(r);
384
+ findings.push(...r.findings);
385
+ } else skipped.push('R-5-open');
386
+ if (input.operations !== undefined) {
387
+ const r = assertIdempotentSideEffects({ operations: input.operations, keyField: input.keyField });
388
+ checks.push(r);
389
+ findings.push(...r.findings);
390
+ } else skipped.push('R-6');
391
+ const ran = checks.filter((c) => c.ok !== null).length > 0;
170
392
  return {
171
393
  family: RUN_CONTRACT_FAMILY,
172
394
  rules: RUN_CONTRACT_RULES.map(({ id, severity, title, layer }) => ({ id, severity, title, layer })),
package/lib/validate.js CHANGED
@@ -66,12 +66,12 @@ export function isAbsoluteLogPath(value) {
66
66
 
67
67
  /**
68
68
  * 报告结构版本(`schemaVersion`):`check --json` / `validateSessionLog()` 返回对象的
69
- * **结构**版本(字符串,如 `"4"`)。语义:只在报告结构发生不兼容增删/改名时递增,
69
+ * **结构**版本(字符串,如 `"6"`)。语义:只在报告结构发生不兼容增删/改名时递增,
70
70
  * 新增可选字段不递增;消费方可据此做解析兼容判断。
71
71
  * ⛔ 不是包版本、不是日志格式版本(那是 header.version / package.json)。
72
- * 历史:`"1"` 初始 → `"2"` 加 S9 诊断字段(additive)→ `"3"` 加 `identity` 段(additive)→ `"4"` 加 `runContract` 段(additive)。
72
+ * 历史:`"1"` 初始 → `"2"` 加 S9 诊断字段 → `"3"` 加 `identity` 段 → `"4"` 加 `runContract` 段 → `"5"` 加 R-2b / R-6 → `"6"` 加 R-2b② / R-5(additive)。
73
73
  */
74
- export const REPORT_SCHEMA_VERSION = '4';
74
+ export const REPORT_SCHEMA_VERSION = '6';
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.41",
4
+ "version": "0.3.43",
5
5
  "packageManager": "pnpm@11.7.0",
6
6
  "type": "module",
7
7
  "main": "lib/index.js",