dsh-log-contract 0.3.33 → 0.3.34

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -282,6 +282,25 @@ preceding assistant tool_calls) and "user text between tool_calls and their
282
282
  results" — tolerated by some endpoints, `INVALID_REQUEST` on strict ones
283
283
  (MiMo, verified 2026-08-27).
284
284
 
285
+ ### 1.1 Error-expression contract scan (`error-contract`)
286
+
287
+ Static scan of *how errors are raised* (source text; no AST):
288
+ E1 one code with many causes · E2 constant message · E3 terminal word on a non-terminal
289
+ cause · E4 `cause` not surfaced · E5 unconditional success (candidate) · E6 claims with no
290
+ enforcement point (candidate).
291
+
292
+ ```bash
293
+ dsh-log-contract error-contract lib/ bin/ --json # T1 (our code): hits ⇒ exit 1
294
+ dsh-log-contract error-contract <pkg>/lib/index.js --target T2 # T2 (third-party): report only, exit 0
295
+ dsh-log-contract error-contract lib/ --keys thresholdRatio,headroom # E6① declared-key reads
296
+ dsh-log-contract error-contract lib/ --config cordis.patch.yml # E6① from YAML config keys
297
+ ```
298
+
299
+ ⚠️ **Output is a suspicion list, not a verdict**: the rules are heuristics and necessarily
300
+ carry false positives — every finding ships raw `evidence` for human review; whitelist
301
+ entries must carry an `expires` date (missing/invalid/expired ⇒ exit 2, fail-closed).
302
+ Full criteria, false-positive risks and whitelist format: [docs/ERROR-CONTRACT.md](docs/ERROR-CONTRACT.md).
303
+
285
304
  ### 2. Repair (`fix`)
286
305
 
287
306
  ```bash
package/README.zh.md CHANGED
@@ -236,6 +236,23 @@ dsh-log-contract check ~/.dsh/sessions/<id>.jsonl.zstd --json # 机器可读
236
236
  tool_calls 与其结果之间"——这类问题 DeepSeek 曾容忍,但 MiMo 等严格端点会直接
237
237
  `INVALID_REQUEST`(2026-08-27 实锤)。
238
238
 
239
+ ### 1.1 错误表达契约检查(`error-contract`)
240
+
241
+ 对「错误是怎么抛的」做静态扫描(源码文本;不做 AST):
242
+ E1 一个码多成因 / E2 message 是常量 / E3 终态词用于非终态因 / E4 `cause` 未透出 /
243
+ E5 无条件成功(候选)/ E6 声称无执行点(候选)。
244
+
245
+ ```bash
246
+ dsh-log-contract error-contract lib/ bin/ --json # T1(我方代码):命中 ⇒ exit 1
247
+ dsh-log-contract error-contract <pkg>/lib/index.js --target T2 # T2(第三方):只登记,exit 0
248
+ dsh-log-contract error-contract lib/ --keys thresholdRatio,headroom # E6① 声明 key 的读取点
249
+ dsh-log-contract error-contract lib/ --config cordis.patch.yml # E6① 从 YAML config 段派生
250
+ ```
251
+
252
+ ⚠️ **输出是可疑清单,不是缺陷认定**:规则是启发式的、必然有假阳性——每条命中带原始
253
+ `evidence` 供人工复核;白名单条目必须带 `expires` 到期日(缺失/非法/过期 ⇒ exit 2,fail-closed)。
254
+ 完整判据、假阳性风险与白名单格式:[docs/ERROR-CONTRACT.md](docs/ERROR-CONTRACT.md)。
255
+
239
256
  ### 2. 修复(`fix`)
240
257
 
241
258
  ```bash
@@ -13,8 +13,8 @@
13
13
  * contracts 列出内置契约规则目录
14
14
  */
15
15
  import fs from 'node:fs';
16
- import { delimiter as pathDelimiter } from 'node:path';
17
- import { loadSessionLog, validateSessionLog, resumeVerdict, migrationVerdict, assessmentScope, createPreWriter, repairSession, readSessionHeader, CONTRACT_RULES, ruleById, explainRule, extractToolOutputs, auditToolCalls, hostCapability, HOST_MAX_FILE_VERSION, detectSupport } from '../lib/index.js';
16
+ import { delimiter as pathDelimiter, join as pathJoin } from 'node:path';
17
+ import { loadSessionLog, validateSessionLog, resumeVerdict, migrationVerdict, assessmentScope, createPreWriter, repairSession, readSessionHeader, CONTRACT_RULES, ruleById, explainRule, extractToolOutputs, auditToolCalls, hostCapability, HOST_MAX_FILE_VERSION, detectSupport, ERROR_CONTRACT_RULES, checkErrorContract, normalizePath } from '../lib/index.js';
18
18
 
19
19
  /**
20
20
  * 同步写 fd——`process.stdout.write` 在**管道**下是异步的,紧跟着的
@@ -128,6 +128,26 @@ const USAGE = `dsh-log-contract —— 日志契约守护(DSH session log cont
128
128
  未知 id ⇒ 明确提示 + 非零退出;--json 输出稳定键集(id/found/title/severity/
129
129
  layer/source/criteria/examples/relatedCommands/doc)。
130
130
 
131
+ dsh-log-contract error-contract <path...> [--json] [--target T1|T2] [--whitelist <file>]
132
+ [--keys <json|a,b,c>] [--config <cordis.patch.yml>]
133
+ [--exclude <path[,path]>] [--strict]
134
+ 错误表达契约静态检查(E1–E6 · 可疑清单,⛔ 不是"某包违规"的认定)。
135
+ E1 一个码多成因 / E2 message 是常量 / E3 终态词用于非终态因 / E4 cause 未透出 /
136
+ E5 无条件成功(候选)/ E6 声称无执行点(候选)。
137
+ path 可为文件或目录(目录递归 *.js/*.mjs/*.cjs + README*.md);--target T1 我方代码
138
+ (命中 ⇒ exit 1)/ T2 官方产物(只登记 ⇒ 默认 exit 0,--strict 才非 0)。
139
+ --whitelist <file> 逐条例外 JSON:{entries:[{rule,file,line?,reason,expires}]}
140
+ expires 必填 YYYY-MM-DD;缺失/非法/过期 ⇒ exit 2(fail-closed)。
141
+ --keys / --config E6① 的配置声明来源:--keys 给 JSON 数组/逗号列表,--config 从
142
+ YAML 的 config: 段派生 key,再查代码里有无读取点。
143
+ --exclude <path> 显式排除(可重复/逗号分隔;目录前缀匹配)。默认已跳过
144
+ node_modules/.git/reports;扫仓库根时用 --exclude test,contract
145
+ 把测试与未接线骨架排除在发布面之外。
146
+ --json 输出稳定键集(schemaVersion/family/target/rules/findings/summary);
147
+ 每条 finding 带 id/rule/severity/evidence。
148
+ 退出码:0 绿 | 1 T1 命中(T2 默认不阻断,--strict 才 1)| 2 无法判定
149
+ (target 非法/路径不存在/无参/白名单不合规)。
150
+
131
151
  dsh-log-contract --version / --help
132
152
  `;
133
153
 
@@ -311,6 +331,9 @@ function cmdCheck(args) {
311
331
 
312
332
  if (json) {
313
333
  const payload = { schemaVersion: result.schemaVersion ?? '1', file, ok, assessable: !notAssessable, assessmentScope: scope, host: hostCapability(), support: result.support ?? null, probes: result.probes ?? null, drift: result.drift ?? null, migration, summary, violations, archive: result.archive ?? null, ignorableDrops: result.ignorableDrops ?? null };
334
+ // 新增键(additive,同 schemaVersion 下既有键不删/不改义):错误表达契约规则目录。
335
+ // findings 需要源码输入,故只在 `error-contract` 子命令产出;此处只给规则清单。
336
+ payload.errorContract = { family: 'error-expression', rules: ERROR_CONTRACT_RULES.map((r) => ({ id: r.id, severity: r.severity, title: r.title, layer: r.layer, target: r.target, falsePositiveRisk: r.falsePositiveRisk })), note: '静态规则目录;源码扫描用 error-contract 子命令' };
314
337
  if (notAssessable) payload.notAssessable = result.notAssessable;
315
338
  if (resume) payload.resume = resumeVerdict(result);
316
339
  out(JSON.stringify(payload, null, 2) + '\n');
@@ -452,6 +475,142 @@ function cmdPrewrite(args) {
452
475
  process.exit(1);
453
476
  }
454
477
 
478
+ /**
479
+ * `error-contract <path...>` —— 错误表达契约静态检查(E1–E6 · 可疑清单,⛔ 非缺陷认定)。
480
+ * 输入:源码文件或目录(递归 *.js|*.mjs|*.cjs;*.md 仅做 E6 不变式句候选扫描)。
481
+ * --target T1(我方代码,命中 error/warning ⇒ exit 1)|T2(官方产物,只登记 ⇒ 默认 exit 0,--strict 才非 0)
482
+ * --whitelist <file>:{entries:[{rule,file,line?,reason,expires}]};expires 必填(缺失/非法/过期 ⇒ exit 2 fail-closed)。
483
+ */
484
+ function cmdErrorContract(args) {
485
+ const json = args.includes('--json');
486
+ const strict = args.includes('--strict');
487
+ const valOf = (flag) => {
488
+ const i = args.indexOf(flag);
489
+ return i >= 0 && i + 1 < args.length ? args[i + 1] : null;
490
+ };
491
+ // N2:无法判定/用法错误一律 exit 2(与「红=1 / 绿=0」区分)
492
+ const target = String(valOf('--target') || 'T1').toUpperCase();
493
+ if (target !== 'T1' && target !== 'T2') {
494
+ errOut(`error-contract: --target 只允许 T1/T2(实际 ${target})—— 无法判定 ⇒ exit 2\n`);
495
+ process.exit(2);
496
+ }
497
+ const whitelistPath = valOf('--whitelist');
498
+ const configPath = valOf('--config');
499
+ const keysArg = valOf('--keys');
500
+ const VALUE_FLAGS = new Set(['--target', '--whitelist', '--config', '--keys', '--exclude']);
501
+ // N8:显式排除(可重复 / 逗号分隔;目录前缀匹配,归一化后比较)
502
+ const excludes = [];
503
+ args.forEach((a, i) => {
504
+ if (a === '--exclude' && args[i + 1]) {
505
+ for (const x of String(args[i + 1]).split(',').map((v) => v.trim()).filter(Boolean)) excludes.push(normalizePath(x));
506
+ }
507
+ });
508
+ // 语义:含 '/' ⇒ 前缀匹配(相对/绝对路径);不含 '/' ⇒ 按任意路径段(目录名)匹配
509
+ const isExcluded = (p) => excludes.some((x) => (x.includes('/')
510
+ ? (p === x || p.startsWith(`${x}/`))
511
+ : (p === x || p.startsWith(`${x}/`) || p.endsWith(`/${x}`) || p.includes(`/${x}/`))));
512
+ const paths = args.filter((a, i) => {
513
+ if (a.startsWith('-')) return false;
514
+ return !VALUE_FLAGS.has(args[i - 1]);
515
+ });
516
+ if (paths.length === 0) {
517
+ errOut(`error-contract: 至少给一个路径(文件或目录)—— 无法判定 ⇒ exit 2\n\n`);
518
+ errOut(USAGE);
519
+ process.exit(2);
520
+ }
521
+
522
+ // N1:输入路径归一(去尾斜杠/折叠 //),保证 findings.file 与白名单比较同一口径
523
+ const files = [];
524
+ const walk = (p) => {
525
+ const np = normalizePath(p);
526
+ if (isExcluded(np)) return;
527
+ const st = fs.statSync(np);
528
+ if (st.isDirectory()) {
529
+ for (const name of fs.readdirSync(np)) {
530
+ if (name === 'node_modules' || name === '.git' || name === 'reports') continue;
531
+ walk(pathJoin(np, name));
532
+ }
533
+ return;
534
+ }
535
+ if (!/\.(mjs|cjs|js)$/i.test(np) && !/\.md$/i.test(np)) return;
536
+ files.push({ file: normalizePath(np), text: fs.readFileSync(np, 'utf8') });
537
+ };
538
+ for (const p of paths) {
539
+ if (!fs.existsSync(normalizePath(p))) {
540
+ errOut(`error-contract: 路径不存在: ${p} —— 无法判定 ⇒ exit 2\n`);
541
+ process.exit(2);
542
+ }
543
+ walk(p);
544
+ }
545
+
546
+ let whitelist = [];
547
+ if (whitelistPath) {
548
+ try {
549
+ whitelist = JSON.parse(fs.readFileSync(whitelistPath, 'utf8')).entries ?? [];
550
+ } catch (e) {
551
+ errOut(`error-contract: 白名单读取/解析失败(无法判定 ⇒ exit 2): ${e.message}\n`);
552
+ process.exit(2);
553
+ }
554
+ }
555
+
556
+ // N3:E6① 配置声明 key 的读取点检查(--keys 直接给,或 --config 从 YAML 派生)
557
+ const declaredKeys = [];
558
+ if (keysArg) {
559
+ try {
560
+ if (/\.json$/i.test(keysArg)) {
561
+ const j = JSON.parse(fs.readFileSync(keysArg, 'utf8'));
562
+ for (const k of (Array.isArray(j) ? j : (j.keys ?? []))) declaredKeys.push(typeof k === 'string' ? { name: k } : k);
563
+ } else {
564
+ for (const k of keysArg.split(',').map((x) => x.trim()).filter(Boolean)) declaredKeys.push({ name: k });
565
+ }
566
+ } catch (e) {
567
+ errOut(`error-contract: --keys 读取/解析失败(无法判定 ⇒ exit 2): ${e.message}\n`);
568
+ process.exit(2);
569
+ }
570
+ }
571
+ if (configPath) {
572
+ let text = '';
573
+ try { text = fs.readFileSync(configPath, 'utf8'); }
574
+ catch (e) { errOut(`error-contract: --config 读取失败(无法判定 ⇒ exit 2): ${e.message}\n`); process.exit(2); }
575
+ let inConfig = false;
576
+ text.split('\n').forEach((line, i) => {
577
+ const noComment = line.replace(/#.*$/, '');
578
+ if (/^config\s*:/.test(noComment)) { inConfig = true; return; }
579
+ if (inConfig && /^\S/.test(noComment) && noComment.trim()) { inConfig = false; return; }
580
+ if (!inConfig) return;
581
+ const m = noComment.match(/^\s+([A-Za-z_][\w-]*)\s*:/);
582
+ if (m) declaredKeys.push({ name: m[1], line: i + 1, file: normalizePath(configPath) });
583
+ });
584
+ }
585
+
586
+ const report = checkErrorContract({ files, target, whitelist, declaredKeys });
587
+ if (report.summary.whitelistProblems.length) {
588
+ errOut(`error-contract: ⛔ 白名单不合规(fail-closed ⇒ exit 2):\n${report.summary.whitelistProblems.map((x) => ` - ${x}`).join('\n')}\n`);
589
+ process.exit(2);
590
+ }
591
+ const hits = report.findings.filter((f) => f.severity === 'error' || f.severity === 'warning');
592
+ const candidates = report.findings.filter((f) => f.severity === 'info');
593
+ const exitCode = target === 'T2' ? (strict && report.findings.length ? 1 : 0) : (hits.length ? 1 : 0);
594
+
595
+ if (json) {
596
+ out(JSON.stringify(report, null, 2) + '\n');
597
+ process.exit(exitCode);
598
+ }
599
+
600
+ out(`\n🔎 dsh-log-contract error-contract —— target=${target} | 扫 ${files.length} 个文件 | 可疑 ${report.findings.length}(白名单抑制 ${report.summary.suppressed})\n`);
601
+ out(' ⚠️ 启发式检查:输出的是**可疑清单**,不是"某包违规"的认定;每条请开 --json 看 evidence 后人工复核。\n');
602
+ out(` E1 多成因 ${report.summary.byRule.E1 || 0} | E2 常量 message ${report.summary.byRule.E2 || 0} | E3 终态词 ${report.summary.byRule.E3 || 0} | E4 cause 未透出 ${report.summary.byRule.E4 || 0} | E5 无条件成功 ${report.summary.byRule.E5 || 0} | E6 无执行点 ${report.summary.byRule.E6 || 0}\n`);
603
+ for (const f of report.findings) {
604
+ const loc = f.line ? `:${f.line}` : '';
605
+ out(` [${f.severity}] ${f.id} ${f.file}${loc} — ${f.message}\n`);
606
+ }
607
+ if (!report.findings.length) out(' ✔ 未发现可疑点(注意:规则集只覆盖 E1–E6,未覆盖 ≠ 无问题)\n');
608
+ out(`\n 目标口径:T1=我方代码(要修)|T2=官方产物(只登记/报上游)—— 两类不混报。\n`);
609
+ if (candidates.length) out(` ℹ️ 其中 ${candidates.length} 条为候选(E5/E6),默认不阻断,需人工确认。\n`);
610
+ out('\n');
611
+ process.exit(exitCode);
612
+ }
613
+
455
614
  function cmdContracts() {
456
615
  out('dsh-log-contract 契约规则目录(spec:官方源码逐行核对 + 实测事故固化)\n\n');
457
616
  for (const r of CONTRACT_RULES) {
@@ -654,5 +813,6 @@ else if (cmd === 'audit-report') cmdAuditReport(args.slice(1));
654
813
  else if (cmd === 'prewrite') cmdPrewrite(args.slice(1));
655
814
  else if (cmd === 'fix') cmdFix(args.slice(1));
656
815
  else if (cmd === 'contracts') cmdContracts();
816
+ else if (cmd === 'error-contract') cmdErrorContract(args.slice(1));
657
817
  else if (cmd === 'explain') cmdExplain(args.slice(1));
658
818
  else fail(`未知子命令 "${cmd}"\n\n${USAGE}`);
@@ -0,0 +1,120 @@
1
+ # 错误表达契约检查(E1–E6)
2
+
3
+ > ⚠️ **这是可疑清单,不是缺陷认定。** 规则是启发式的,必然有假阳性:
4
+ > 每条命中都带原始片段(`evidence`)供人工复核;白名单见下文。
5
+ > 检测器输出的是「值得看一眼的地方」,不是「某包违规」。
6
+
7
+ ## 核心判据(一句话)
8
+
9
+ > **调用方必须靠匹配错误字符串才能分辨「该重试还是该放弃」—— 那就说明缺的是契约,不是文案。**
10
+
11
+ 反过来说:凡是需要「读 message 才知道怎么办」的地方,都是这条契约被违反的地方。
12
+
13
+ ## 规则
14
+
15
+ | # | 规则 | 判据(可直接写成检测逻辑) | 假阳性风险 |
16
+ |---|---|---|---|
17
+ | **E1** | 一个码多成因 | 按 error code 聚合 `new XxxError(msg, "CODE", …)`:同一 CODE 出现在 **≥2 个 throw site**,且(message 不同 **或** 上下文不同:一处 `catch` 内、一处在正常路径)⇒ 报 | 低 |
18
+ | **E2** | message 是常量 | 同一模板(插值只含**标识**:id/路径/序号)被 **≥2 个 throw site 共用**,且不含判据词 ⇒ 报(message 无法区分分支) | 低 |
19
+ | **E3** | 终态词用于非终态因 | code 名匹配 `NOT_[A-Z]+`/`UNAVAILABLE`/`FATAL`/`CORRUPT`,且该 throw 位于 `catch (e) { throw new X(…, CODE, { cause: e }) }` 形态内(把任意 error 收编成终态码)⇒ 报 | 中(需白名单) |
20
+ | **E4** | `cause` 未透出 | throw 带 `{ cause }` 但 message 不含 cause 的摘要(`error.code`/`error.name`/`error.message`)⇒ 报 | 中 |
21
+ | **E5** | 无条件成功 | `async` 函数所有正常返回都是 `true`/`void` 且无 `throw` ⇒ 只报**候选**(需看调用方如何消费返回值) | 低 |
22
+ | **E6** | 声称无执行点 | ① 配置声明的 key 在代码里**无读取点**;② README 的 `never`/`always`/`guaranteed`/`must not` 不变式句,在写入路径**无对应断言** ⇒ 只报**候选** | 高(只输出候选,需人工过) |
23
+
24
+ 分层(决定能否直接进 CI):
25
+
26
+ | 层 | 规则 | 说明 |
27
+ |---|---|---|
28
+ | L1 纯静态 | E1/E2/E3/E4/E5 | 单文件即可判定,可进 CI |
29
+ | L2 跨文件 | E6 | 要跨「声明(schema/YAML/README)↔ 执行(代码)」两处比对,半自动 |
30
+
31
+ ## 范围:T1 / T2 必须分开
32
+
33
+ | target | 扫什么 | 用途 | 命中后 |
34
+ |---|---|---|---|
35
+ | **T1** | 我方代码 | 修 | `error/warning` 命中 ⇒ 退出码 1 |
36
+ | **T2** | 第三方/官方打包产物 | 只登记、报上游、做选题 | 默认退出码 0(`--strict` 才非 0) |
37
+
38
+ 两类**不得混在同一份报告**里:T1 是自查,T2 是观察;混在一起会让「我们自己的违规」
39
+ 看起来像「别人的违规」。
40
+
41
+ ## 用法
42
+
43
+ ```bash
44
+ # T1:扫我方源码(文件或目录;目录递归 *.js/*.mjs/*.cjs,*.md 仅做 E6 候选句扫描)
45
+ dsh-log-contract error-contract lib/ bin/ --json
46
+
47
+ # T2:只登记官方产物(默认 exit 0)
48
+ dsh-log-contract error-contract node_modules/@deepseek-ai/dsh-session/lib/index.js --target T2 --json
49
+
50
+ # 带白名单(逐条、带到期日)
51
+ dsh-log-contract error-contract lib/ --whitelist whitelist.json
52
+
53
+ # 扫仓库根时排除测试与未接线骨架(默认已跳过 node_modules/.git/reports)
54
+ dsh-log-contract error-contract . --exclude test,contract
55
+
56
+ # E6①:配置声明 key 的读取点(--keys 直接给;--config 从 YAML 的 config: 段派生)
57
+ dsh-log-contract error-contract lib/ --keys thresholdRatio,headroom --json
58
+ dsh-log-contract error-contract lib/ --config cordis.patch.yml --json
59
+ ```
60
+
61
+ `--json` 输出稳定键集:`schemaVersion` / `family` / `target` / `rules` / `findings` / `summary`;
62
+ 每条 finding 带 `id` / `rule` / `severity` / `file` / `line` / `message` / `evidence`。
63
+ 外层 `schemaVersion` 遵循 `docs/interface-versioning.md`(只增不改)。
64
+
65
+ 退出码:
66
+
67
+ | 码 | 含义 |
68
+ |---|---|
69
+ | 0 | 无可疑点(或 T2 只登记) |
70
+ | 1 | T1 命中 error/warning |
71
+ | 2 | 无法判定(白名单不合规/读不了路径等)—— fail-closed |
72
+
73
+ ## 白名单(逐条例外,到期复审)
74
+
75
+ ```json
76
+ { "entries": [
77
+ { "rule": "E3", "file": "lib/foo.js", "line": 12,
78
+ "reason": "该处 transition 有专门测试覆盖,判定为设计意图", "expires": "2026-12-31" }
79
+ ] }
80
+ ```
81
+
82
+ - `rule` 必须是 E1–E6;`file` 必填;`line` 可选(精确到行)。
83
+ - **`expires` 必填**(`YYYY-MM-DD`):缺失、非法或已过期 ⇒ 退出码 2(fail-closed),
84
+ ⛔ 不得静默放行。与仓库内其他登记制例外同口径。
85
+
86
+ ## 与日志契约规则的关系
87
+
88
+ 本工具的日志契约规则集里也有 `E1`–`E11`(seq/词汇表等,见 `CONTRACTS.md`)。
89
+ 两者是**不同家族**:错误表达规则带 `family: "error-expression"` 字段,报告里独立成块
90
+ (`check --json` 的 `errorContract` 只给规则目录;源码扫描结果在 `error-contract` 子命令)。
91
+ 消费者按 `family` 区分,⛔ 不要按 id 字面合并。
92
+
93
+ ## 已知边界
94
+
95
+ - 只扫**源码文本**(不做完整 AST/类型分析):动态构造的 code/message、跨文件聚合、
96
+ 包装函数不在覆盖内。
97
+ - E2 的「同一模板」判定 = 模板文本(插值**归一为 `$`**):同一句只换插值变量名
98
+ (`thing ${z} failed` vs `thing ${w} failed`)仍算同一模板 ⇒ **计 E2**(贴 spec 语义)。
99
+ 但插值末段是判据/摘要字段(`code`/`name`/`message`/`reason`/`status`)时视为携带判据
100
+ ⇒ **不算常量**(不报 E2)。变量名 vs 判据字段的边界是启发式的,见本条即边界。
101
+ - E5 只看函数体,**不看调用方**:幂等操作返回 `true` 本身不是错。
102
+ - E6 默认只输出候选:不变式句与校验点的对应关系需要人判。
103
+ - 「名字是否准确」(码名与 throw 条件是否相符)机器判不了 ⇒ 只能输出可疑清单给人过。
104
+
105
+ ## 仓库布局与发布面(纳入/排除)
106
+
107
+ | 路径 | 内容 | 是否随 npm 包发布 |
108
+ |---|---|---|
109
+ | `lib/error-contract.js` | 本检查器的运行时(规则 + 检测器 + 报告) | ✅ 是(`files` 白名单含 `lib/**`) |
110
+ | `bin/dsh-log-contract.mjs` | CLI(`error-contract` 子命令) | ✅ 是 |
111
+ | `docs/ERROR-CONTRACT.md` | 本文 | ✅ 是(白名单含 `docs/**`) |
112
+ | `test/error-contract*.test.mjs` | 单元测试 / CLI 测试 | ❌ 否(不发布;`vitest run` 收集) |
113
+ | `contract/` | 抽象契约 Phase1 骨架(未接线,供后续迁移) | ❌ 否(白名单不含 `contract/`) |
114
+
115
+ 扫描口径:`error-contract <path>` 会**递归扫入**传入目录下所有 `*.js/*.mjs/*.cjs` 与 `*.md`
116
+ (含未跟踪文件)。因此扫仓库根时会连 `test/`、`contract/` 一起扫到;要只看发布面请显式
117
+ 传 `lib/ bin/` 或用 `--exclude test,contract`(默认已跳过 `node_modules/`、`.git/`、`reports/`)。
118
+
119
+ 判据:npm `files` 白名单 = `lib/**`、`bin/**`、`docs/**`、README、LICENSE;
120
+ 白名单之外的目录不随包发布,也不构成运行时契约的一部分。
@@ -25,6 +25,12 @@
25
25
  在它出现之前的报告结构就是 v1。
26
26
  - 枚举类字段新增取值属于兼容变更;消费者对未知取值应降级归入 unknown,不得崩溃。
27
27
 
28
+ ### 已新增的可选键(同 `schemaVersion: "1"`)
29
+
30
+ | 键 | 引入 | 形状 | 说明 |
31
+ |---|---|---|---|
32
+ | `errorContract` | 0.3.x | `{ family: "error-expression", rules: [{id,severity,title,layer,target,falsePositiveRisk}], note }` | 错误表达契约(E1–E6)的**规则目录**;源码扫描结果不在此键内(用 `error-contract` 子命令的独立报告)。旧消费者忽略此键即可。 |
33
+
28
34
  ## 何时升版
29
35
 
30
36
  **不兼容才升**(`"1"` → `"2"`):
@@ -43,4 +49,20 @@
43
49
 
44
50
  ---
45
51
 
52
+ ## 报告域(`family`)与版本独立性
53
+
54
+ `schemaVersion` 是**按报告域**计数,不是全局单号:
55
+
56
+ | 报告域 | 命令 | 版本字段 | 备注 |
57
+ |---|---|---|---|
58
+ | 日志契约(session log contract) | `check --json` | 顶层 `schemaVersion`(当前 `"1"`) | 本文正文主要讲这一域 |
59
+ | 错误表达契约(error-expression) | `error-contract --json` | 顶层 `schemaVersion`(当前 `"1"`)+ `family: "error-expression"` | 与日志契约**互不影响**:任一域升版不牵动另一域 |
60
+
61
+ - 两个域的 id 集合可能重名(都有 `E1`…),消费者**必须按 `family` 分派**,⛔ 不要按 id 字面合并。
62
+ - 「只增不改」承诺按域生效:某域新增键/取值 → 该域不升版;字段类型/含义变更 → 只升该域的版本。
63
+ - `check --json` 里的 `errorContract` 键只承载**规则目录**(无 findings);`error-contract` 的完整
64
+ 报告(findings/`evidence`)在它自己的输出里。
65
+
66
+ ---
67
+
46
68
  本文与实现同口径;报告语义如有修订,随实现一并更新本文。
@@ -0,0 +1,501 @@
1
+ /**
2
+ * lib/error-contract.js —— 错误表达契约静态检查(E1–E6 · 可疑清单,非缺陷认定)
3
+ *
4
+ * 依据:错误表达契约的核心判据 + E4–E6 的可执行判据与 T1/T2 范围约定(内部讨论结论)。
5
+ *
6
+ * 核心判据:调用方必须靠匹配错误字符串才能分辨「该重试还是该放弃」⇒ 缺的是契约,不是文案。
7
+ *
8
+ * ⚠️ 本模块输出的是**可疑清单**,不是"某包违规"的判定:规则是启发式的,必然有假阳性,
9
+ * 每条 finding 都带 `evidence`(原始片段)供人复核;白名单见 `whitelist` 参数。
10
+ *
11
+ * 规则(E1–E6,target 分 T1 我方 / T2 官方):
12
+ * E1 一个码多成因:同一 CODE ≥2 个 throw site,且 message 或前置条件(是否在 catch 内)不同
13
+ * E2 message 是常量:同一 CODE 的 ≥2 个 site 共用**同一 message 模板**(插值只含标识)⇒ 无法区分分支
14
+ * E3 终态词用于非终态因:码名含 NOT_*/UNAVAILABLE/FATAL/CORRUPT,却在 catch 内把任意 error 收编(带 cause)
15
+ * E4 cause 未透出:throw 带 { cause },但 message 不含 cause 的摘要(error.code/error.name/error.message)
16
+ * E5 无条件成功:async 函数所有正常返回都是 true/void,且无 throw(需看调用方,默认只报候选)
17
+ * E6 声称无执行点:① 配置声明 key 无读取点;② README 不变式句(never/always/guaranteed/must not)无对应断言
18
+ * ⇒ 默认只输出候选(info),不阻断
19
+ *
20
+ * 范围:`target: 'T1'` = 我方代码(要修);`'T2'` = 官方产物(只登记/报上游)。
21
+ * 两类**不得混在同一份报告**里(summary 分列 + CLI `--target` 显式选择)。
22
+ */
23
+
24
+ export const ERROR_CONTRACT_FAMILY = 'error-expression';
25
+
26
+ /** 规则目录(id 为 E1–E6;注意:与日志契约的 E1–E11 是**不同家族**,靠 family 区分)。 */
27
+ export const ERROR_CONTRACT_RULES = [
28
+ {
29
+ id: 'E1',
30
+ title: '一个码多成因',
31
+ family: ERROR_CONTRACT_FAMILY,
32
+ severity: 'error',
33
+ layer: 'L1',
34
+ target: 'T1',
35
+ detection: '按 code 聚合 new XxxError(msg, "CODE", …):同一 CODE ≥2 个 throw site 且(message 模板不同 或 是否在 catch 内不同)⇒ 报',
36
+ falsePositiveRisk: 'low',
37
+ },
38
+ {
39
+ id: 'E2',
40
+ title: 'message 是常量',
41
+ family: ERROR_CONTRACT_FAMILY,
42
+ severity: 'error',
43
+ layer: 'L1',
44
+ target: 'T1',
45
+ detection: '同一 CODE 的 ≥2 个 site 共用同一 message 模板(插值只含标识,不含判据)⇒ 报',
46
+ falsePositiveRisk: 'low',
47
+ },
48
+ {
49
+ id: 'E3',
50
+ title: '终态词用于非终态因',
51
+ family: ERROR_CONTRACT_FAMILY,
52
+ severity: 'warning',
53
+ layer: 'L1',
54
+ target: 'T1',
55
+ detection: 'code 名匹配 NOT_[A-Z]+/UNAVAILABLE/FATAL/CORRUPT,且该 throw 位于 catch 内并把任意 error 以 cause 收编 ⇒ 报',
56
+ falsePositiveRisk: 'medium',
57
+ },
58
+ {
59
+ id: 'E4',
60
+ title: 'cause 未透出',
61
+ family: ERROR_CONTRACT_FAMILY,
62
+ severity: 'warning',
63
+ layer: 'L1',
64
+ target: 'T1',
65
+ detection: 'throw 带 { cause } 但 message 不含 cause.code/cause.name/cause.message 等摘要 ⇒ 报',
66
+ falsePositiveRisk: 'medium',
67
+ },
68
+ {
69
+ id: 'E5',
70
+ title: '无条件成功',
71
+ family: ERROR_CONTRACT_FAMILY,
72
+ severity: 'info',
73
+ layer: 'L1',
74
+ target: 'T1',
75
+ detection: 'async 函数所有正常返回都是 true/void 且无 throw(需看调用方是否把返回值当"已成功"消费)⇒ 只报候选',
76
+ falsePositiveRisk: 'low',
77
+ },
78
+ {
79
+ id: 'E6',
80
+ title: '声称无执行点',
81
+ family: ERROR_CONTRACT_FAMILY,
82
+ severity: 'info',
83
+ layer: 'L2',
84
+ target: 'T1',
85
+ detection: '① 配置声明的 key 在代码里无读取点;② README 的 never/always/guaranteed/must not 不变式句在写入路径无对应断言 ⇒ 只输出候选',
86
+ falsePositiveRisk: 'high',
87
+ },
88
+ ];
89
+
90
+ export const ERROR_CONTRACT_RULE_BY_ID = new Map(ERROR_CONTRACT_RULES.map((r) => [r.id, r]));
91
+
92
+ // ── 词表 ────────────────────────────────────────────────────────────────��───
93
+ /** 码名里的终态词(E3)。 */
94
+ const TERMINAL_CODE_RE = /(^|_)(NOT_[A-Z0-9_]+|UNAVAILABLE|FATAL|CORRUPT)($|_)/;
95
+ /** 判据词(E2 反面):message 里出现这些词说明它带"为什么",不算常量。 */
96
+ const JUDGEMENT_WORDS = /\b(because|due to|reason|when|while|if|since|unsupported|invalid|missing|mismatch|conflict|exceed|exceeded|denied|refused|blocked)\b/i;
97
+ /** 标识类插值字段(E2:只插标识 ⇒ 无法区分分支)。 */
98
+ const IDENT_FIELDS = new Set(['id', 'childid', 'taskid', 'parentid', 'callid', 'path', 'file', 'filename', 'name', 'seq', 'index', 'line', 'lineno', 'count', 'size', 'key', 'type', 'code']);
99
+
100
+ // ── 词法:掩码注释/字符串 + 收集字符串字面量 ─────────────────────────────
101
+ /**
102
+ * @param {string} text
103
+ * @returns {{masked:string, strings:Array<{start:number,end:number,kind:'string'|'template',value:string,interpolations:Array<{start:number,end:number,expr:string}>}>}}
104
+ */
105
+ function lexMask(text) {
106
+ const chars = text.split('');
107
+ const strings = [];
108
+ let i = 0;
109
+ while (i < text.length) {
110
+ const c = text[i];
111
+ if (c === '/' && text[i + 1] === '/') {
112
+ let j = i;
113
+ while (j < text.length && text[j] !== '\n') j++;
114
+ for (let k = i; k < j; k++) chars[k] = ' ';
115
+ i = j;
116
+ continue;
117
+ }
118
+ if (c === '/' && text[i + 1] === '*') {
119
+ let j = text.indexOf('*/', i + 2);
120
+ j = j < 0 ? text.length : j + 2;
121
+ for (let k = i; k < j; k++) chars[k] = ' ';
122
+ i = j;
123
+ continue;
124
+ }
125
+ if (c === '"' || c === "'" || c === '`') {
126
+ const start = i;
127
+ const quote = c;
128
+ i++;
129
+ let value = '';
130
+ const interpolations = [];
131
+ while (i < text.length) {
132
+ if (text[i] === '\\') {
133
+ value += text.slice(i, i + 2);
134
+ i += 2;
135
+ continue;
136
+ }
137
+ if (quote === '`' && text[i] === '$' && text[i + 1] === '{') {
138
+ let depth = 1;
139
+ let j = i + 2;
140
+ const exprStart = j;
141
+ while (j < text.length && depth > 0) {
142
+ if (text[j] === '{') depth++;
143
+ else if (text[j] === '}') depth--;
144
+ if (depth === 0) break;
145
+ j++;
146
+ }
147
+ interpolations.push({ start: exprStart, end: j, expr: text.slice(exprStart, j) });
148
+ value += '${}';
149
+ i = j + 1;
150
+ continue;
151
+ }
152
+ if (text[i] === quote) {
153
+ i++;
154
+ break;
155
+ }
156
+ if (text[i] === '\n' && quote !== '`') break;
157
+ value += text[i];
158
+ i++;
159
+ }
160
+ const end = i;
161
+ strings.push({ start, end, kind: quote === '`' ? 'template' : 'string', value, interpolations });
162
+ for (let k = start; k < end; k++) chars[k] = ' ';
163
+ continue;
164
+ }
165
+ i++;
166
+ }
167
+ return { masked: chars.join(''), strings };
168
+ }
169
+
170
+ const lineOf = (text, index) => text.slice(0, index).split('\n').length;
171
+
172
+ /** 在掩码文本上从 `(` 起步解析参数区间(括号/方/花括号联合计深)。 */
173
+ function parseArgs(masked, openIdx) {
174
+ const args = [];
175
+ let depth = 0;
176
+ let cur = openIdx + 1;
177
+ for (let i = openIdx; i < masked.length; i++) {
178
+ const c = masked[i];
179
+ if (c === '(' || c === '[' || c === '{') depth++;
180
+ else if (c === ')' || c === ']' || c === '}') {
181
+ depth--;
182
+ if (depth === 0) {
183
+ if (i > cur) args.push({ start: cur, end: i });
184
+ return args;
185
+ }
186
+ } else if (c === ',' && depth === 1) {
187
+ args.push({ start: cur, end: i });
188
+ cur = i + 1;
189
+ }
190
+ }
191
+ return args;
192
+ }
193
+
194
+ /** catch 区域(掩码文本上的 `catch (e) { … }`)。 */
195
+ function catchRegions(masked) {
196
+ const regions = [];
197
+ const re = /\bcatch\s*(?:\(([^)]*)\))?\s*\{/g;
198
+ let m;
199
+ while ((m = re.exec(masked)) !== null) {
200
+ const open = m.index + m[0].length - 1;
201
+ let depth = 0;
202
+ let end = masked.length;
203
+ for (let i = open; i < masked.length; i++) {
204
+ if (masked[i] === '{') depth++;
205
+ else if (masked[i] === '}') {
206
+ depth--;
207
+ if (depth === 0) { end = i; break; }
208
+ }
209
+ }
210
+ regions.push({ start: open, end, param: (m[1] || '').trim() });
211
+ }
212
+ return regions;
213
+ }
214
+
215
+ /** 从字符串字面量取 message 模板信息。 */
216
+ function messageInfo(text, str) {
217
+ return {
218
+ kind: str.kind,
219
+ raw: text.slice(str.start, str.end),
220
+ value: str.value,
221
+ interpolations: str.interpolations.map((it) => it.expr.trim()),
222
+ };
223
+ }
224
+
225
+ /** message 模板签名(E1/E2 判"是否同一模板")。
226
+ * N6:插值**归一为 `$`**(`${z}` 与 `${w}` 视为同一模板)——贴「message 是常量」的语义;
227
+ * 变量名差异不再被当成"不同 message"。 */
228
+ function templateSig(msg) {
229
+ return msg.value;
230
+ }
231
+
232
+ /** 判据/摘要类末段:这些字段本身就在表达"为什么",不算纯标识。 */
233
+ const JUDGEMENT_MEMBERS = new Set(['code', 'name', 'message', 'reason', 'status', 'kind', 'error']);
234
+
235
+ /** E2 判据:插值只含标识(简单变量/属性路径;不含调用/运算/比较;末段不是判据字段)。 */
236
+ function onlyIdentifiers(msg) {
237
+ if (msg.interpolations.length === 0) return true;
238
+ return msg.interpolations.every((expr) => {
239
+ if (!/^[A-Za-z_$][\w$]*(\.[A-Za-z_$][\w$]*)*$/.test(expr)) return false; // 含调用/运算/比较 ⇒ 可能带判据
240
+ const last = expr.split('.').pop().toLowerCase();
241
+ if (JUDGEMENT_MEMBERS.has(last)) return false;
242
+ return IDENT_FIELDS.has(last) || /^[a-z]$/.test(last) || /id$|path$|seq$|count$|size$|name$/.test(last);
243
+ });
244
+ }
245
+
246
+ /** 扫一个文件的 throw 点。 */
247
+ function scanThrows(text, masked, strings, catches) {
248
+ const sites = [];
249
+ const re = /\bnew\s+([A-Za-z_$][\w$]*)\s*\(/g;
250
+ let m;
251
+ while ((m = re.exec(masked)) !== null) {
252
+ const ctor = m[1];
253
+ const openIdx = m.index + m[0].length - 1;
254
+ const argRanges = parseArgs(masked, openIdx);
255
+ const site = { index: m.index, line: lineOf(text, m.index), ctor, code: null, msg: null, hasCause: false, causeExpr: null, inCatch: false, catchParam: null };
256
+ const argInfo = argRanges.map((a, idx) => {
257
+ const raw = text.slice(a.start, a.end);
258
+ const trimmed = raw.trim();
259
+ const strLit = strings.find((s) => s.start >= a.start && s.end <= a.end);
260
+ return {
261
+ idx,
262
+ raw,
263
+ trimmed,
264
+ str: strLit && strLit.kind === 'template' ? strLit : (strLit && /^["']/.test(trimmed) ? strLit : null),
265
+ cause: (trimmed.match(/\bcause\s*:\s*([^,}]+)/) || [])[1],
266
+ };
267
+ });
268
+ const firstString = argInfo.find((x) => x.str && x.idx === 0);
269
+ const codeArg = argInfo.find((x) => x.str && x.idx >= 1 && /^[A-Z][A-Z0-9_]*$/.test(x.str.value));
270
+ const msgArg = firstString || argInfo.find((x) => x.str);
271
+ if (msgArg) site.msg = messageInfo(text, msgArg.str);
272
+ if (codeArg) site.code = codeArg.str.value;
273
+ for (const x of argInfo) {
274
+ if (x.cause) { site.hasCause = true; site.causeExpr = x.cause.trim(); }
275
+ }
276
+ const region = catches.find((r) => site.index > r.start && site.index < r.end);
277
+ if (region) { site.inCatch = true; site.catchParam = region.param; }
278
+ if (site.msg || site.code) sites.push(site);
279
+ }
280
+ return sites;
281
+ }
282
+
283
+ /** 扫 E5 候选:async 函数体里正常返回恒 true/void 且无 throw。 */
284
+ function scanE5(text, masked) {
285
+ const out = [];
286
+ const re = /\basync\s+function\s+([A-Za-z_$][\w$]*)\s*\([^)]*\)\s*\{/g;
287
+ let m;
288
+ while ((m = re.exec(masked)) !== null) {
289
+ const open = m.index + m[0].length - 1;
290
+ let depth = 0;
291
+ let end = masked.length;
292
+ for (let i = open; i < masked.length; i++) {
293
+ if (masked[i] === '{') depth++;
294
+ else if (masked[i] === '}') { depth--; if (depth === 0) { end = i; break; } }
295
+ }
296
+ const body = masked.slice(open, end + 1);
297
+ if (/\bthrow\b/.test(body)) continue; // 有失败路径可不报
298
+ const returns = [...body.matchAll(/\breturn\b([^;\n}]*)/g)].map((x) => x[1].trim());
299
+ if (returns.length === 0) continue;
300
+ const allTrue = returns.every((r) => r === '' || r === 'true');
301
+ if (allTrue) {
302
+ out.push({ name: m[1], line: lineOf(text, m.index), returns });
303
+ }
304
+ }
305
+ return out;
306
+ }
307
+
308
+ /**
309
+ * 扫单个源码文本。
310
+ * @param {{file:string, text:string}} input
311
+ * @returns {Array<object>} findings(未做白名单过滤)
312
+ */
313
+ export function scanSource({ file, text }) {
314
+ const { masked, strings } = lexMask(text);
315
+ const catches = catchRegions(masked);
316
+ const sites = scanThrows(text, masked, strings, catches);
317
+ const findings = [];
318
+
319
+ // E1 / E2 / E3 / E4(按 code 聚合与逐点判定)
320
+ const byCode = new Map();
321
+ for (const s of sites) {
322
+ if (!s.code) continue;
323
+ if (!byCode.has(s.code)) byCode.set(s.code, []);
324
+ byCode.get(s.code).push(s);
325
+ }
326
+
327
+ for (const [code, group] of byCode) {
328
+ const msgs = group.filter((s) => s.msg);
329
+ const sigs = new Set(msgs.map((s) => templateSig(s.msg)));
330
+ const catchMix = new Set(group.map((s) => (s.inCatch ? 'catch' : 'top')));
331
+ if (group.length >= 2 && (sigs.size >= 2 || catchMix.size >= 2)) {
332
+ findings.push({
333
+ id: 'E1', rule: 'E1', family: ERROR_CONTRACT_FAMILY, severity: 'error', file, ruleMeta: 'E1',
334
+ line: group[0].line,
335
+ message: `一个码多成因:CODE=${code} 有 ${group.length} 个 throw site(message 模板 ${sigs.size} 种 / 上下文 ${[...catchMix].join('+')})`,
336
+ evidence: { code, sites: group.map((s) => ({ line: s.line, ctor: s.ctor, inCatch: s.inCatch, msg: s.msg ? s.msg.raw : null })) },
337
+ });
338
+ }
339
+ // E2:同一模板被 ≥2 个 throw site 共用(插值只含标识、无判据词)⇒ message 是常量,无法区分分支
340
+ const byTemplate = new Map();
341
+ for (const s of msgs) {
342
+ const sig = templateSig(s.msg);
343
+ if (!byTemplate.has(sig)) byTemplate.set(sig, []);
344
+ byTemplate.get(sig).push(s);
345
+ }
346
+ for (const [, same] of byTemplate) {
347
+ if (same.length < 2) continue;
348
+ if (!onlyIdentifiers(same[0].msg) || JUDGEMENT_WORDS.test(same[0].msg.value)) continue;
349
+ findings.push({
350
+ id: 'E2', rule: 'E2', family: ERROR_CONTRACT_FAMILY, severity: 'error', file, ruleMeta: 'E2',
351
+ line: same[0].line,
352
+ message: `message 是常量:CODE=${code} 的 ${same.length} 个 site 共用同一模板(插值只含标识,未带判据)`,
353
+ evidence: { code, template: same[0].msg.raw, sites: same.map((s) => s.line) },
354
+ });
355
+ break;
356
+ }
357
+ for (const s of group) {
358
+ if (!s.msg) continue;
359
+ if (TERMINAL_CODE_RE.test(code) && s.inCatch && s.hasCause) {
360
+ findings.push({
361
+ id: 'E3', rule: 'E3', family: ERROR_CONTRACT_FAMILY, severity: 'warning', file, ruleMeta: 'E3',
362
+ line: s.line,
363
+ message: `终态词用于非终态因:CODE=${code} 在 catch 内把任意 error 收编为终态码`,
364
+ evidence: { code, ctor: s.ctor, cause: s.causeExpr, msg: s.msg.raw },
365
+ });
366
+ }
367
+ if (s.hasCause && !/(\.code|\.name|\.message)\b/.test(s.msg.value) && !s.msg.interpolations.some((e) => /\.(code|name|message)\b/.test(e))) {
368
+ findings.push({
369
+ id: 'E4', rule: 'E4', family: ERROR_CONTRACT_FAMILY, severity: 'warning', file, ruleMeta: 'E4',
370
+ line: s.line,
371
+ message: `cause 未透出:CODE=${code} 带 { cause } 但 message 不含 cause 摘要`,
372
+ evidence: { code, cause: s.causeExpr, msg: s.msg.raw },
373
+ });
374
+ }
375
+ }
376
+ }
377
+
378
+ // E5(候选)
379
+ for (const fn of scanE5(text, masked)) {
380
+ findings.push({
381
+ id: 'E5', rule: 'E5', family: ERROR_CONTRACT_FAMILY, severity: 'info', file, ruleMeta: 'E5',
382
+ line: fn.line,
383
+ message: `无条件成功(候选):async ${fn.name}() 所有正常返回恒 true/void 且无 throw —— 需看调用方`,
384
+ evidence: { fn: fn.name, returns: fn.returns },
385
+ });
386
+ }
387
+
388
+ return findings;
389
+ }
390
+
391
+ /** E6①:声明 key 无读取点(跨文件,候选)。 */
392
+ export function scanDeclaredKeysNoRead({ keys = [], sources = [], file = '(config)' } = {}) {
393
+ const findings = [];
394
+ const esc = (x) => String(x).replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
395
+ for (const k of keys) {
396
+ const name = typeof k === 'string' ? k : k && k.name;
397
+ if (!name) continue;
398
+ const readRe = new RegExp(`(?:config\\.|config\\[|\\b)${esc(name)}\\b`);
399
+ const hit = sources.some((src) => readRe.test(src.text));
400
+ if (!hit) {
401
+ findings.push({
402
+ id: 'E6', rule: 'E6', family: ERROR_CONTRACT_FAMILY, severity: 'info', file: (k && k.file) || file, ruleMeta: 'E6',
403
+ line: (k && k.line) ?? null,
404
+ message: `声称无执行点(候选):配置声明 key "${name}" 在已扫代码里无读取点`,
405
+ evidence: { key: name, searched: sources.map((src) => src.file) },
406
+ });
407
+ }
408
+ }
409
+ return findings;
410
+ }
411
+
412
+ /** E6②:README 不变式句(候选,需人工确认写入路径有无对应校验)。 */
413
+ export function scanInvariantSentences({ file, text }) {
414
+ const findings = [];
415
+ const re = /(never|always|guaranteed|must\s+not)/i;
416
+ text.split('\n').forEach((line, i) => {
417
+ if (!re.test(line)) return;
418
+ if (line.trim().length < 20) return; // 太短的多半是标题/表格残片
419
+ findings.push({
420
+ id: 'E6', rule: 'E6', family: ERROR_CONTRACT_FAMILY, severity: 'info', file, ruleMeta: 'E6',
421
+ line: i + 1,
422
+ message: '声称无执行点(候选):不变式句需人工确认写入路径有对应校验',
423
+ evidence: { sentence: line.trim().slice(0, 160) },
424
+ });
425
+ });
426
+ return findings;
427
+ }
428
+
429
+ /**
430
+ * 白名单(fail-closed):entries[{rule, file, line?, reason, expires}]
431
+ * expires 必填且 YYYY-MM-DD;缺失/非法/过期 ⇒ 抛错(由调用方 exit 2),⛔ 不得静默放行。
432
+ */
433
+ export function validateWhitelist(entries, today = new Date().toISOString().slice(0, 10)) {
434
+ const list = Array.isArray(entries) ? entries : [];
435
+ const problems = [];
436
+ const active = [];
437
+ for (let i = 0; i < list.length; i++) {
438
+ const e = list[i] || {};
439
+ if (!e.rule || !ERROR_CONTRACT_RULE_BY_ID.has(String(e.rule))) problems.push(`whitelist[${i}].rule 非法(须为 E1–E6):${e.rule}`);
440
+ if (typeof e.file !== 'string' || e.file.length === 0) problems.push(`whitelist[${i}].file 必填`);
441
+ if (typeof e.reason !== 'string' || e.reason.trim().length === 0) problems.push(`whitelist[${i}].reason 必填`);
442
+ if (typeof e.expires !== 'string' || !/^\d{4}-\d{2}-\d{2}$/.test(e.expires)) problems.push(`whitelist[${i}].expires 必填且须 YYYY-MM-DD`);
443
+ else if (e.expires < today) problems.push(`whitelist[${i}] 已过期(expires=${e.expires})`);
444
+ else active.push(e);
445
+ }
446
+ return { ok: problems.length === 0, problems, active };
447
+ }
448
+
449
+ /** 路径归一(N1):折叠重复斜杠、去尾斜杠;白名单比较与 CLI walk 共用同一口径。 */
450
+ export function normalizePath(p) {
451
+ if (typeof p !== 'string') return p;
452
+ let x = p.replace(/\\/g, '/').replace(/\/{2,}/g, '/');
453
+ if (x.length > 1) x = x.replace(/\/+$/, '');
454
+ return x;
455
+ }
456
+
457
+ const isWhitelisted = (finding, active) =>
458
+ active.some((w) => w.rule === finding.id
459
+ && (w.file === '*' || normalizePath(finding.file) === normalizePath(w.file))
460
+ && (w.line === undefined || w.line === finding.line));
461
+
462
+ /**
463
+ * 汇总报告(CLI 与测试共用;同一 schemaVersion 纪律,新增键不破坏旧消费者)。
464
+ * @param {{files:Array<{file:string,text:string}>, target?:'T1'|'T2', whitelist?:Array<object>}} input
465
+ */
466
+ export function checkErrorContract({ files = [], target = 'T1', whitelist = [], declaredKeys = [] }) {
467
+ const { ok: wlOk, problems: wlProblems, active } = validateWhitelist(whitelist);
468
+ const rawFindings = [];
469
+ const sources = files.filter((f) => /\.(mjs|cjs|js)$/i.test(f.file));
470
+ for (const f of files) {
471
+ rawFindings.push(...scanSource({ file: f.file, text: f.text }));
472
+ if (/\.md$/i.test(f.file)) rawFindings.push(...scanInvariantSentences({ file: f.file, text: f.text }));
473
+ }
474
+ // E6①:配置声明 key 的读取点检查(N3:CLI --keys/--config 可达)
475
+ if (declaredKeys.length) rawFindings.push(...scanDeclaredKeysNoRead({ keys: declaredKeys, sources }));
476
+ const suppressed = rawFindings.filter((x) => isWhitelisted(x, active));
477
+ const findings = rawFindings.filter((x) => !isWhitelisted(x, active));
478
+ const byRule = {};
479
+ const bySeverity = { error: 0, warning: 0, info: 0 };
480
+ for (const f of findings) {
481
+ byRule[f.id] = (byRule[f.id] || 0) + 1;
482
+ bySeverity[f.severity] = (bySeverity[f.severity] || 0) + 1;
483
+ }
484
+ return {
485
+ schemaVersion: '1',
486
+ family: ERROR_CONTRACT_FAMILY,
487
+ target,
488
+ rules: ERROR_CONTRACT_RULES.map((r) => ({ id: r.id, severity: r.severity, title: r.title, layer: r.layer, target: r.target, falsePositiveRisk: r.falsePositiveRisk })),
489
+ findings,
490
+ suppressed: suppressed.map(({ evidence, ...rest }) => rest),
491
+ summary: {
492
+ files: files.length,
493
+ findings: findings.length,
494
+ suppressed: suppressed.length,
495
+ byRule,
496
+ bySeverity,
497
+ whitelistOk: wlOk,
498
+ whitelistProblems: wlProblems,
499
+ },
500
+ };
501
+ }
package/lib/index.js CHANGED
@@ -15,3 +15,4 @@ export { TESTED_BASELINE, compareVersions, detectSupport, supportOfLog } from '.
15
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';
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
+ export { ERROR_CONTRACT_RULES, ERROR_CONTRACT_RULE_BY_ID, ERROR_CONTRACT_FAMILY, scanSource, scanInvariantSentences, scanDeclaredKeysNoRead, validateWhitelist, checkErrorContract, normalizePath } from './error-contract.js';
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.33",
4
+ "version": "0.3.34",
5
5
  "packageManager": "pnpm@11.7.0",
6
6
  "type": "module",
7
7
  "main": "lib/index.js",