Files
QLinker/tools/probe/capability-check.mjs
T

163 lines
9.1 KiB
JavaScript
Raw Normal View History

// NapCat 能力目录回归门禁(DEC-005:不锁版本,但升级必须跑全量回归)。
//
// 两种模式:
// 1) 离线结构校验(默认,可在 CI 直接跑,不联网)
// node tools/probe/capability-check.mjs
// 校验 docs/capability-baseline.json 的枚举合法性、状态完整性、证据存在性、
// 「结论与证据强度是否匹配」——防止把未验证项写成已验证。
//
// 2) 实测漂移比对(升级 NapCat 后必跑)
// node tools/probe/capability-check.mjs --against=local/matrix-result-x.jsonl,local/history-audit-x.jsonl
// 把实测结果与基线 regressionProbe 期望逐条比对,任何状态漂移即失败。
//
// 退出码:0 = 门禁通过;1 = 门禁失败。凭据不涉及(两种模式都不发请求)。
import fs from 'node:fs';
import path from 'node:path';
const ROOT = path.resolve(import.meta.dirname, '../..');
const BASELINE = path.join(ROOT, 'docs/capability-baseline.json');
const errors = [];
const warns = [];
const fail = (m) => errors.push(m);
const warn = (m) => warns.push(m);
if (!fs.existsSync(BASELINE)) { console.error('基线文件缺失: ' + BASELINE); process.exit(1); }
const base = JSON.parse(fs.readFileSync(BASELINE, 'utf8'));
const caps = base.capabilities ?? [];
const STATUS = Object.keys(base.enums?.status ?? {});
const REAL = Object.keys(base.enums?.realEnvTest ?? {});
const ADAPTER = Object.keys(base.enums?.adapterStatus ?? {});
console.log(`能力目录基线:${caps.length} 项,采集于 ${base.meta?.collectedAt},目标 NapCat ${base.meta?.targetNapCat?.version_observed}`);
// ---------- 模式 1:离线结构校验 ----------
function validateStructure() {
if (!base.meta?.evidenceRule) fail('meta.evidenceRule 缺失:三证据规则必须显式声明');
if (!(base.meta?.governance?.length >= 1)) fail('meta.governance 缺失:治理规则必须显式声明');
if (!base.globalConstraints?.length) warn('globalConstraints 为空:跨能力的坑未被固化');
const seen = new Set();
for (const c of caps) {
const tag = c.id ?? '(缺 id)';
if (!c.id) fail('存在无 id 的能力项');
else if (seen.has(c.id)) fail(`能力 id 重复: ${c.id}`);
seen.add(c.id);
if (!c.name) fail(`${tag}: 缺 name`);
if (!c.kind) fail(`${tag}: 缺 kind`);
// 状态不得留空
for (const f of ['sendStatus', 'eventStatus', 'historyStatus', 'parseStatus']) {
if (!c[f]) { fail(`${tag}: ${f} 为空。未采到必须显式标 untested 并写 todo。`); continue; }
const allowed = f === 'parseStatus' ? ADAPTER : STATUS;
if (!allowed.includes(c[f])) fail(`${tag}: ${f}='${c[f]}' 不在枚举内(合法值:${allowed.join('/')})`);
}
if (c.realEnvTest && !REAL.includes(c.realEnvTest)) fail(`${tag}: realEnvTest='${c.realEnvTest}' 不在枚举内`);
// 结论强度纪律:verified 必须有回归探针 + 真实环境验证 + 限制或证据说明
const positive = ['sendStatus', 'eventStatus', 'historyStatus'].filter((f) => c[f] === 'verified');
if (positive.length) {
if (!c.regressionProbe) fail(`${tag}: 标了 verified(${positive.join(',')})但没有 regressionProbe,升级后无法回归`);
if (c.realEnvTest === 'not_tested' || c.realEnvTest === 'blocked')
fail(`${tag}: 状态含 verified 但 realEnvTest=${c.realEnvTest},结论强度与证据不匹配`);
}
// 未验证项不得伪装
if ((c.realEnvTest === 'not_tested' || c.realEnvTest === 'blocked') && positive.length)
fail(`${tag}: 未做真实验证却存在 verified 状态`);
if (['untested', 'blocked'].includes(c.sendStatus) && !(c.todo?.length))
fail(`${tag}: 状态为 ${c.sendStatus} 但未写 todo,缺口无人认领`);
if (['readback_gap', 'silent_drop', 'downgraded', 'no_event', 'rejected'].includes(c.sendStatus)
&& !(c.limitations?.length))
fail(`${tag}: 记录了假成功/缺口类结论但 limitations 为空,后续无法理解判定依据`);
// 证据可追溯
const hasEvidence = (c.automationTest && String(c.automationTest).trim()) || (c.limitations?.length);
if (!hasEvidence) fail(`${tag}: 既无 automationTest 也无 limitations,结论不可追溯`);
}
// 覆盖度:矩阵里出现过的用例必须都能映射到某个能力的 regressionProbe
const probes = caps.flatMap((c) => (c.regressionProbe ? [c.regressionProbe] : []));
const covered = new Set(probes.map((p) => `${p.probe}:${p.case ?? '-'}`));
console.log(`\n结构校验:${errors.length} 个错误,${warns.length} 个警告`);
console.log(`回归探针覆盖:${probes.length}/${caps.length} 项能力带探针`);
const byStatus = {};
for (const c of caps) byStatus[c.sendStatus] = (byStatus[c.sendStatus] ?? 0) + 1;
console.log('发送侧状态分布:' + Object.entries(byStatus).map(([k, v]) => `${k}=${v}`).join(' '));
console.log('带探针的能力:' + [...covered].sort().join(', '));
}
// ---------- 模式 2:实测漂移比对 ----------
function readJsonl(f) {
return fs.readFileSync(f, 'utf8').trim().split('\n')
.map((l) => { try { return JSON.parse(l); } catch { return null; } }).filter(Boolean);
}
function validateAgainst(measureFiles) {
const rows = [];
for (const f of measureFiles) {
const p = path.resolve(ROOT, f);
if (!fs.existsSync(p)) { fail(`实测结果文件不存在: ${f}`); continue; }
for (const r of readJsonl(p)) rows.push({ ...r, __src: path.basename(f) });
}
console.log(`\n载入实测记录 ${rows.length} 条,来自 ${measureFiles.map((f) => path.basename(f)).join(', ')}`);
// 建立 case -> 实测行 的索引(matrix / url-media / record / followup 都是 id 字段)
// kind=history 的行是「第三证据」专用行,只有段类型没有 retcode,
// 若混入 byCase 会把同名的发送侧行覆盖掉,造成 retcode 假漂移。
const byCase = new Map();
for (const r of rows) if (r.id && !r.__summary && r.kind !== 'history') byCase.set(String(r.id), r);
// history-audit 提供 history_segs
const audit = new Map();
for (const r of rows) if (r.history_segs) audit.set(String(r.id), r);
// probe 名为 manual/any 的项无法从实测 jsonl 自动比对,单列为人工确认项
const AUTO = new Set(['matrix', 'segments', 'record', 'recordAmr', 'recordDecoder', 'urlMedia', 'forwardFollowup', 'forwardReadback']);
let checked = 0, drifted = 0, missing = 0, manual = 0;
for (const c of caps) {
const p = c.regressionProbe;
if (!p || !p.case || p.case === '-') continue;
if (!AUTO.has(p.probe)) { manual++; console.log(` [人工] ${c.id.padEnd(20)} ${p.probe}:${p.case} 无自动实测源,需人工确认`); continue; }
const actual = byCase.get(p.case) ?? audit.get(p.case);
if (!actual) { missing++; console.log(` [缺测] ${p.case.padEnd(22)} 本轮实测未覆盖,基线状态 ${c.sendStatus} 无法确认`); continue; }
checked++;
const exp = p.expect ?? {};
const diffs = [];
const actSegs = actual.event_segs ?? actual.history_segs;
const actRet = actual.retcode;
if (exp.retcode !== undefined && Number(actRet) !== Number(exp.retcode))
diffs.push(`retcode 期望 ${exp.retcode} 实测 ${actRet}`);
if (exp.eventSegs !== undefined) {
const a = byCase.get(p.case)?.event_segs;
if (a !== undefined && a !== exp.eventSegs) diffs.push(`事件段 期望 ${exp.eventSegs} 实测 ${a}`);
}
if (exp.historySegs !== undefined) {
const h = audit.get(p.case)?.history_segs;
if (h !== undefined && h !== exp.historySegs) diffs.push(`history段 期望 ${exp.historySegs} 实测 ${h}`);
}
if (exp.messageContains && !String(actual.message ?? '').includes(exp.messageContains))
diffs.push(`错误原文未包含 "${exp.messageContains}",实测 "${String(actual.message ?? '').slice(0, 60)}"`);
if (diffs.length) {
drifted++;
console.log(` [漂移] ${c.id.padEnd(20)} ${p.case.padEnd(22)} ${diffs.join(' ; ')}`);
console.log(` 基线状态 ${c.sendStatus} -> 需人工判定是能力变化还是采集环境问题,确认后更新基线并记录版本`);
} else {
console.log(` [一致] ${c.id.padEnd(20)} ${p.case.padEnd(22)} retcode=${actRet}`);
}
}
console.log(`\n漂移比对:自动比对 ${checked} 项,漂移 ${drifted} 项,缺测 ${missing} 项,人工确认 ${manual} 项`);
if (drifted) fail(`${drifted} 项能力行为相对基线漂移,DEC-005 要求升级后全量回归必须通过或显式确认`);
if (missing) warn(`${missing} 项基线探针本轮未采到,不得据此认为已回归通过`);
}
validateStructure();
const againstArg = process.argv.slice(2).find((a) => a.startsWith('--against='));
if (againstArg) validateAgainst(againstArg.slice(10).split(',').map((s) => s.trim()).filter(Boolean));
console.log('');
for (const w of warns) console.log('警告: ' + w);
for (const e of errors) console.log('错误: ' + e);
if (!againstArg) console.log('\n提示:升级 NapCat 后须跑 --against=<实测jsonl,...> 做漂移比对。');
console.log(errors.length ? `\n门禁结果:FAIL(${errors.length} 项)` : '\n门禁结果:PASS');
process.exit(errors.length ? 1 : 0);