dsh-log-contract 0.3.29 → 0.3.34
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +42 -13
- package/README.zh.md +32 -15
- package/bin/dsh-log-contract.mjs +220 -8
- package/docs/CONTRACTS.md +23 -9
- package/docs/ERROR-CONTRACT.md +120 -0
- package/docs/interface-versioning.md +68 -0
- package/lib/archive.js +2 -2
- package/lib/checks.js +96 -7
- package/lib/contracts.js +27 -10
- package/lib/error-contract.js +501 -0
- package/lib/explain.js +129 -0
- package/lib/index.js +2 -0
- package/lib/log-reader.js +45 -11
- package/lib/repair.js +2 -2
- package/lib/validate.js +19 -1
- package/lib/version-support.js +2 -2
- package/package.json +2 -2
|
@@ -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/explain.js
ADDED
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* dsh-log-contract · lib/explain.js
|
|
3
|
+
*
|
|
4
|
+
* `explain <ruleId>` 的数据层:把一条契约规则"解读"成结构化对象。
|
|
5
|
+
*
|
|
6
|
+
* **单一权威**:标题 / 判据(触发条件)/ 严重度 / 层级 / 出处 **原样引自
|
|
7
|
+
* `lib/contracts.js` 的 `CONTRACT_RULES`**——本模块 ⛔ 不复制、不改写判据文本,
|
|
8
|
+
* 也不维护第二份规则清单(改规则只改注册表一处)。
|
|
9
|
+
*
|
|
10
|
+
* 本模块只补充两类**指针**(不是判据):
|
|
11
|
+
* - 正/反例指针:扫描 `test/` 里以该规则 id 做断言的用例(文件 + 标题);
|
|
12
|
+
* 发布包不含 `test/` 时如实为空(不冒充有对照)。
|
|
13
|
+
* - 相关命令:用法指针(check / prewrite / contracts,按层级补专项开关)。
|
|
14
|
+
*/
|
|
15
|
+
import fs from 'node:fs';
|
|
16
|
+
import path from 'node:path';
|
|
17
|
+
import { fileURLToPath } from 'node:url';
|
|
18
|
+
import { CONTRACT_RULES, ruleById } from './contracts.js';
|
|
19
|
+
|
|
20
|
+
/** 契约目录文档(判据全文的可读版;与注册表由生成器同步)。 */
|
|
21
|
+
export const EXPLAIN_DOC = 'docs/CONTRACTS.md';
|
|
22
|
+
|
|
23
|
+
/** `--json` 输出的**稳定键集**(未知 id 时同键、值为 null/空)。 */
|
|
24
|
+
export const EXPLAIN_KEYS = Object.freeze([
|
|
25
|
+
'id', 'found', 'title', 'severity', 'layer', 'source', 'criteria',
|
|
26
|
+
'examples', 'relatedCommands', 'doc',
|
|
27
|
+
]);
|
|
28
|
+
|
|
29
|
+
const NEGATIVE_HINTS = ['负对照', '反例', '违规', '判红', '拒绝', '拒', '撕裂', '缺口', '损坏', '截断', '坏', 'poison', 'corrupt', 'bad', 'gap', 'torn', 'missing', 'fail', '未知 id', 'unknown'];
|
|
30
|
+
const POSITIVE_HINTS = ['正对照', '正例', '合规', '判绿', '通过', '健康', 'good', 'green', 'complete', '绿'];
|
|
31
|
+
|
|
32
|
+
function classify(text) {
|
|
33
|
+
const t = String(text);
|
|
34
|
+
const neg = NEGATIVE_HINTS.some((k) => t.includes(k));
|
|
35
|
+
const pos = POSITIVE_HINTS.some((k) => t.includes(k));
|
|
36
|
+
if (neg && !pos) return 'negative';
|
|
37
|
+
if (pos && !neg) return 'positive';
|
|
38
|
+
return 'unclassified';
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/**
|
|
42
|
+
* 扫描 `test/` 找该规则 id 的对照用例指针(文件 + 最近的用例标题)。
|
|
43
|
+
* 发布包/无 test 目录 ⇒ 空列表 + note(⛔ 不冒充"有对照")。
|
|
44
|
+
*/
|
|
45
|
+
export function examplePointers(ruleId, { testDir } = {}) {
|
|
46
|
+
const root = path.dirname(path.dirname(fileURLToPath(import.meta.url)));
|
|
47
|
+
const dir = testDir ?? path.join(root, 'test');
|
|
48
|
+
const out = { negative: [], positive: [], unclassified: [], note: null };
|
|
49
|
+
if (!fs.existsSync(dir)) {
|
|
50
|
+
out.note = '本安装不含 test/ 目录(发布包只含运行时代码与文档)——判据以规则注册表为准';
|
|
51
|
+
return out;
|
|
52
|
+
}
|
|
53
|
+
const quoted = [`'${ruleId}'`, `"${ruleId}"`, `\`${ruleId}\``];
|
|
54
|
+
for (const name of fs.readdirSync(dir).filter((f) => f.endsWith('.js')).sort()) {
|
|
55
|
+
const file = path.join(dir, name);
|
|
56
|
+
let text;
|
|
57
|
+
try {
|
|
58
|
+
text = fs.readFileSync(file, 'utf8');
|
|
59
|
+
} catch {
|
|
60
|
+
continue;
|
|
61
|
+
}
|
|
62
|
+
const lines = text.split('\n');
|
|
63
|
+
for (let i = 0; i < lines.length; i++) {
|
|
64
|
+
if (!quoted.some((q) => lines[i].includes(q))) continue;
|
|
65
|
+
// 最近的 it/test/describe 标题(往上找,至多 60 行)——指针指向"哪条用例"。
|
|
66
|
+
let title = '';
|
|
67
|
+
for (let j = i; j >= 0 && j >= i - 60; j--) {
|
|
68
|
+
const m = /(?:^|[^\w.])(?:it|test|describe)(?:\.\w+)*\(\s*[`'"]([^`'"]{4,120})/.exec(lines[j]);
|
|
69
|
+
if (m) { title = m[1]; break; }
|
|
70
|
+
}
|
|
71
|
+
const bucket = classify(`${title} ${lines[i]}`);
|
|
72
|
+
const pointer = `test/${name}${title ? ` › ${title}` : ''}`;
|
|
73
|
+
if (!out[bucket].includes(pointer)) out[bucket].push(pointer);
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
return out;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/** 相关命令(用法指针,按层级补专项开关)。 */
|
|
80
|
+
export function relatedCommandsOf(rule) {
|
|
81
|
+
const cmds = [
|
|
82
|
+
'dsh-log-contract check <session-log> # 离线体检:逐条判定本规则',
|
|
83
|
+
'dsh-log-contract prewrite <edit-file> --log <session-log> # 写前校验(落盘前拦截)',
|
|
84
|
+
`dsh-log-contract contracts # 全部规则目录(${CONTRACT_RULES.length} 条,含出处)`,
|
|
85
|
+
];
|
|
86
|
+
if (rule?.layer === 'archive') {
|
|
87
|
+
cmds.push('dsh-log-contract check <session-log> --archive-root DIR # A1 维度需归档根才可判');
|
|
88
|
+
}
|
|
89
|
+
if (rule?.layer === 'migration') {
|
|
90
|
+
cmds.push('dsh-log-contract check <session-log> --json # migration 维度(G 段独立于 ok/verdict)');
|
|
91
|
+
}
|
|
92
|
+
return cmds;
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/**
|
|
96
|
+
* 解读一条规则。**数据只来自 `CONTRACT_RULES`**(单一权威)。
|
|
97
|
+
*
|
|
98
|
+
* @param {string} ruleId 规则 id(如 `E5`;大小写不敏感)。
|
|
99
|
+
* @param {{testDir?: string}} [opts]
|
|
100
|
+
* @returns {object} 与 `EXPLAIN_KEYS` 同键的稳定结构;未知 id ⇒ `found:false`
|
|
101
|
+
* 且其余字段为 null/空数组(键集不变,便于机器判读)。
|
|
102
|
+
*/
|
|
103
|
+
export function explainRule(ruleId, opts = {}) {
|
|
104
|
+
const raw = String(ruleId ?? '').trim();
|
|
105
|
+
const rule = ruleById(raw) ?? CONTRACT_RULES.find((r) => r.id.toLowerCase() === raw.toLowerCase());
|
|
106
|
+
const base = {
|
|
107
|
+
id: rule?.id ?? raw,
|
|
108
|
+
found: Boolean(rule),
|
|
109
|
+
title: rule?.title ?? null,
|
|
110
|
+
severity: rule?.severity ?? null,
|
|
111
|
+
layer: rule?.layer ?? null,
|
|
112
|
+
source: rule?.source ?? null,
|
|
113
|
+
criteria: rule?.description ?? null,
|
|
114
|
+
examples: { negative: [], positive: [], unclassified: [] },
|
|
115
|
+
relatedCommands: [],
|
|
116
|
+
doc: EXPLAIN_DOC,
|
|
117
|
+
};
|
|
118
|
+
if (!rule) {
|
|
119
|
+
return {
|
|
120
|
+
...base,
|
|
121
|
+
error: 'unknown-rule',
|
|
122
|
+
knownCount: CONTRACT_RULES.length,
|
|
123
|
+
hint: `未知规则 id "${raw}"——用 \`dsh-log-contract contracts\` 查看全部 ${CONTRACT_RULES.length} 条(或见 ${EXPLAIN_DOC})`,
|
|
124
|
+
};
|
|
125
|
+
}
|
|
126
|
+
base.examples = examplePointers(rule.id, opts);
|
|
127
|
+
base.relatedCommands = relatedCommandsOf(rule);
|
|
128
|
+
return base;
|
|
129
|
+
}
|
package/lib/index.js
CHANGED
|
@@ -9,8 +9,10 @@ export { validateSessionLog, resumeVerdict, migrationVerdict, assessmentScope }
|
|
|
9
9
|
export { createPreWriter, preWriterFromLog } from './prewrite.js';
|
|
10
10
|
export { repairSession, strictScanText, removeMarkersText, neutralizeMarkersText, clipCrossStepSourcesText, dropFailedTurnsText, trimLastMessagesText, trimLastMessagesByBudget, estimateTokensText, compactLastMessagesText, rebuildZstdText, tailRenumberText, neutralizeOrphanText, extractTurnText, keepRangesText } from './repair.js';
|
|
11
11
|
export { CONTRACT_RULES, LAYER, SEVERITY, ruleById } from './contracts.js';
|
|
12
|
+
export { explainRule, examplePointers, relatedCommandsOf, EXPLAIN_KEYS, EXPLAIN_DOC } from './explain.js';
|
|
12
13
|
export { HOST_MAX_FILE_VERSION, hostPackageVersion, hostCapability, isAssessableFileVersion } from './vocab.js';
|
|
13
14
|
export { TESTED_BASELINE, compareVersions, detectSupport, supportOfLog } from './version-support.js';
|
|
14
15
|
export { tokenMeterViolations, tokenMeterSourceViolations, stepKeyViolations, nullTurnStepViolations, turnEndReasonViolations, ignorableTypeViolations, physicalOrderViolations, inboxReplayViolations, sourceEventSeqElementViolations, rawSourceEventSeqViolations, isSeqRangePair, seedLengthViolations, carrierPairingViolations, carrierWriteViolations, isCarrierAuditSegment, carrierRangesMatch, surfaceReplaceRange, declarativeIgnorableViolations, isIgnorableRegistered, resolveIgnorableWhitelist, DEFAULT_IGNORABLE_WHITELIST } from './checks.js';
|
|
15
16
|
export { collectArchivePointers, verifyArchivePointers, archiveVerdict, archiveBasename, readArchiveLines, readArchiveIndex, ARCHIVE_POINTER_FIELDS, EXTERNALIZED_POINTER_FIELDS } from './archive.js';
|
|
16
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';
|