feat: bhl report validate по схемам отчёта аудита (BHL-023)

- packages/bhl/src/report.ts: схема audit-report + ссылки на требования + сверка сводки
- EXEMPT без exemption_ref и отчёт вне схемы отклоняются с диагностикой
- пакет: 24/24 тестов
This commit is contained in:
Suslov-MD
2026-11-29 00:14:05 +03:00
parent c50092f7e4
commit f04c4b6481
5 changed files with 488 additions and 9 deletions
+2 -2
View File
@@ -32,8 +32,8 @@ test('использование: пустой запуск, --help и неиз
assert.equal(unknown.envelope.error.code, 'USAGE');
});
test('известные команды Wave C/D пока возвращают NOT_IMPLEMENTED и код 3', () => {
for (const command of ['spec', 'report', 'audit']) {
test('известные команды Wave D/E пока возвращают NOT_IMPLEMENTED и код 3', () => {
for (const command of ['spec', 'audit']) {
const result = run(command);
assert.equal(result.code, 3, command);
assert.equal(result.envelope.ok, false, command);
+178
View File
@@ -0,0 +1,178 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { spawnSync } from 'node:child_process';
import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
import os from 'node:os';
import path from 'node:path';
const cli = path.join(import.meta.dirname, '..', 'src', 'cli.ts');
const REPORT_SCHEMA = {
$schema: 'https://json-schema.org/draft/2020-12/schema',
$id: 'https://baseline-harness.dev/spec/schemas/audit-report.schema.json',
type: 'object',
required: ['id', 'generated_at', 'tool', 'subject', 'spec_version', 'findings'],
properties: {
id: { type: 'string', pattern: '^rep-[a-z0-9-]+$' },
generated_at: { type: 'string' },
tool: { type: 'object' },
subject: { type: 'object' },
spec_version: { type: 'string' },
profiles: { type: 'array' },
findings: {
type: 'array',
items: {
type: 'object',
required: ['requirement', 'status', 'method', 'evidence', 'rationale'],
properties: {
requirement: { type: 'string' },
status: {
enum: ['PASS', 'FAIL', 'PARTIAL', 'EXEMPT', 'NOT_APPLICABLE', 'UNKNOWN', 'BLOCKED'],
},
method: { enum: ['deterministic', 'semantic', 'hybrid'] },
confidence: { enum: ['high', 'medium', 'low'] },
exemption_ref: { type: 'string' },
evidence: { type: 'array', minItems: 1 },
rationale: { type: 'string' },
},
allOf: [
{
if: { properties: { status: { const: 'EXEMPT' } }, required: ['status'] },
then: { required: ['exemption_ref'], properties: { exemption_ref: true } },
},
{
if: { properties: { method: { const: 'semantic' } }, required: ['method'] },
then: { required: ['confidence'], properties: { confidence: true } },
},
],
},
},
summary: { type: 'object' },
},
};
const PASS_FINDING = {
requirement: 'req-alpha',
status: 'PASS',
method: 'deterministic',
evidence: [{ kind: 'test-run', locator: 'npm test', description: 'Прогон проверки фикстуры.' }],
rationale: 'Проверка выполнена и зафиксирована.',
};
const BASE_SPEC = {
'schemas/audit-report.schema.json': JSON.stringify(REPORT_SCHEMA),
'requirements/req-alpha.yaml': 'id: req-alpha\nlevel: MUST\n',
};
function fixture(t, extra = {}) {
const root = mkdtempSync(path.join(os.tmpdir(), 'bhl-report-'));
const files = { ...BASE_SPEC, ...extra };
for (const [name, contents] of Object.entries(files)) {
const target = path.join(root, name);
mkdirSync(path.dirname(target), { recursive: true });
writeFileSync(
target,
typeof contents === 'string' ? contents : JSON.stringify(contents),
'utf8',
);
}
t.after(() => rmSync(root, { recursive: true, force: true }));
return root;
}
function reportDoc(findings, summary) {
return {
id: 'rep-fixture-2026-11-28',
generated_at: '2026-11-28',
tool: { name: 'bhl', version: '0.0.1' },
subject: { kind: 'repository', fingerprint: `sha256:${'a'.repeat(64)}` },
spec_version: '0.1.0',
findings,
summary,
};
}
function runReportValidate(t, report, extraSpec = {}) {
const root = fixture(t, { 'report.json': JSON.stringify(report), ...extraSpec });
const proc = spawnSync(
process.execPath,
[cli, 'report', 'validate', path.join(root, 'report.json'), '--spec-root', root],
{
encoding: 'utf8',
},
);
return { code: proc.status, envelope: JSON.parse(proc.stdout) };
}
function codes(result) {
return result.envelope.data.errors.map((item) => item.code);
}
test('валидный отчёт проходит report validate с кодом 0', (t) => {
const report = reportDoc([PASS_FINDING], {
PASS: 1,
FAIL: 0,
PARTIAL: 0,
EXEMPT: 0,
NOT_APPLICABLE: 0,
UNKNOWN: 0,
BLOCKED: 0,
});
const result = runReportValidate(t, report);
assert.equal(result.code, 0);
assert.deepEqual(result.envelope.data.errors, []);
});
test('отчёт вне схемы отклоняется с понятной диагностикой', (t) => {
const report = reportDoc([{ ...PASS_FINDING, status: 'MUST' }], undefined);
const result = runReportValidate(t, report);
assert.equal(result.code, 1);
assert.ok(codes(result).includes('schema-error'));
const message = result.envelope.data.errors.find((item) => item.code === 'schema-error').message;
assert.ok(message.includes('status'), 'диагностика указывает на status');
});
test('ссылка на несуществующее требование и расхождение сводки ловятся', (t) => {
const ghost = reportDoc([{ ...PASS_FINDING, requirement: 'req-ghost' }], undefined);
assert.ok(codes(runReportValidate(t, ghost)).includes('unknown-requirement'));
const wrongSummary = reportDoc([PASS_FINDING], { PASS: 2, FAIL: 0 });
const result = runReportValidate(t, wrongSummary);
assert.ok(codes(result).includes('summary-mismatch'));
});
test('EXEMPT без exemption_ref отклоняется', (t) => {
const report = reportDoc([{ ...PASS_FINDING, status: 'EXEMPT' }], undefined);
const result = runReportValidate(t, report);
assert.equal(result.code, 1);
assert.ok(codes(result).includes('schema-error'));
});
test('битый JSON и недоступный файл дают диагностики чтения', (t) => {
const root = fixture(t, { 'report.json': '{ not json' });
const proc = spawnSync(
process.execPath,
[cli, 'report', 'validate', path.join(root, 'report.json'), '--spec-root', root],
{
encoding: 'utf8',
},
);
assert.equal(proc.status, 1);
assert.ok(JSON.parse(proc.stdout).data.errors.some((item) => item.code === 'parse-error'));
const missing = spawnSync(
process.execPath,
[cli, 'report', 'validate', '/nonexistent/report.json', '--spec-root', root],
{
encoding: 'utf8',
},
);
assert.equal(missing.status, 1);
assert.ok(JSON.parse(missing.stdout).data.errors.some((item) => item.code === 'read-error'));
});
test('использование команды report', () => {
const noSub = spawnSync(process.execPath, [cli, 'report'], { encoding: 'utf8' });
assert.equal(noSub.status, 2);
assert.equal(JSON.parse(noSub.stdout).error.code, 'USAGE');
const noFile = spawnSync(process.execPath, [cli, 'report', 'validate'], { encoding: 'utf8' });
assert.equal(noFile.status, 2);
});