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
@@ -1,9 +1,10 @@
---
id: BHL-023
title: Реализовать валидацию отчёта аудита
status: To Do
status: Done
assignee: []
created_date: '2026-11-28T14:25:50Z'
updated_date: '2026-11-28T21:14:05Z'
labels: []
milestone: m-2
dependencies:
@@ -24,13 +25,25 @@ ordinal: 23000
## Acceptance Criteria
<!-- AC:BEGIN -->
- [ ] #1 Отчёт, не соответствующий схеме, отклоняется с понятной диагностикой
- [x] #1 Отчёт, не соответствующий схеме, отклоняется с понятной диагностикой
<!-- AC:END -->
## Definition of Done
<!-- DOD:BEGIN -->
- [ ] #1 npm run check пройден (для изменений материалов и документации)
- [ ] #2 Местный quality gate затронутого модуля пройден (для кода и конфигурации)
- [ ] #3 В записи нет секретов, персональных путей и непубликуемых идентификаторов
- [ ] #4 Состояние задачи в Backlog.md актуально: прогресс, блокеры, следующий шаг
- [x] #1 npm run check пройден (для изменений материалов и документации)
- [x] #2 Местный quality gate затронутого модуля пройден (для кода и конфигурации)
- [x] #3 В записи нет секретов, персональных путей и непубликуемых идентификаторов
- [x] #4 Состояние задачи в Backlog.md актуально: прогресс, блокеры, следующий шаг
<!-- DOD:END -->
## Comments
<!-- COMMENTS:BEGIN -->
created: 2026-11-28T21:14:05Z
---
bhl report validate <report.json> [--spec-root]: JSON-отчёт по схеме audit-report + семантика: цели findings должны существовать в spec-root/requirements, сводка обязана совпадать с фактическими статусами (summary-mismatch), EXEMPT требует exemption_ref (схема). Битый JSON/недоступный файл — parse-error/read-error. Пакет 24/24.
---
<!-- COMMENTS:END -->
+64 -1
View File
@@ -1,11 +1,13 @@
import { readFileSync } from 'node:fs';
import { emit, ExitCode, failEnvelope, okEnvelope } from './envelope.ts';
import { resolveProfiles } from './resolve.ts';
import { validateReport } from './report.ts';
import { validateSpec } from './validate.ts';
const USAGE_MESSAGE =
'Usage: bhl <version|validate|spec|profile|report|audit> [args]; ' +
'profile resolve <spec-root> [--profile <id>] [--preset <id>]; ' +
'report validate <report.json> [--spec-root <path>]; ' +
'JSON envelope on stdout; exit codes: 0 ok, 1 validation failed, 2 usage, ' +
'3 not implemented, 4 internal.';
@@ -138,6 +140,64 @@ function runProfile(command: string, rest: readonly string[]): number {
return ExitCode.ValidationFailed;
}
function parseReportArgs(
args: readonly string[],
): { file: string; specRoot: string } | { error: string } {
let specRoot = 'spec';
const positional: string[] = [];
let cursor = 0;
while (cursor < args.length) {
const arg = args[cursor] ?? '';
if (arg === '--spec-root') {
const value = args[cursor + 1];
if (value === undefined) {
return { error: 'missing value for --spec-root' };
}
specRoot = value;
cursor += 2;
continue;
}
if (arg.startsWith('--')) {
return { error: `unknown flag ${arg}` };
}
positional.push(arg);
cursor += 1;
}
if (positional.length !== 1) {
return { error: 'report validate requires exactly one report file' };
}
return { file: positional[0] ?? '', specRoot };
}
function runReport(command: string, rest: readonly string[]): number {
const [sub, ...args] = rest;
if (sub !== 'validate') {
emit(failEnvelope(command, 'USAGE', 'report requires the subcommand validate'));
return ExitCode.Usage;
}
const parsed = parseReportArgs(args);
if ('error' in parsed) {
emit(failEnvelope(command, 'USAGE', parsed.error));
return ExitCode.Usage;
}
const result = validateReport(parsed.file, parsed.specRoot);
const data = { file: parsed.file, spec_root: parsed.specRoot, errors: result.diagnostics };
if (result.ok) {
emit(okEnvelope(command, data));
return ExitCode.Ok;
}
emit({
ok: false,
command,
data,
error: {
code: 'VALIDATION_FAILED',
message: `${String(result.diagnostics.length)} diagnostic(s)`,
},
});
return ExitCode.ValidationFailed;
}
function runValidate(command: string, rest: readonly string[]): number {
const [root] = rest;
if (root === undefined || root.startsWith('--')) {
@@ -179,7 +239,10 @@ export function run(argv: readonly string[]): number {
if (command === 'validate') {
return runValidate(command, rest);
}
if (command === 'spec' || command === 'report' || command === 'audit') {
if (command === 'report') {
return runReport(command, rest);
}
if (command === 'spec' || command === 'audit') {
emit(failEnvelope(command, 'NOT_IMPLEMENTED', `${command} is not implemented yet`));
return ExitCode.NotImplemented;
}
+225
View File
@@ -0,0 +1,225 @@
import { existsSync, readFileSync, readdirSync } from 'node:fs';
import path from 'node:path';
import { Ajv2020 } from 'ajv/dist/2020.js';
import type { Schema } from 'ajv';
import { parseDocument } from 'yaml';
import type { Diagnostic } from './validate.ts';
export interface ReportValidationResult {
ok: boolean;
diagnostics: Diagnostic[];
}
const SCHEMA_BASE = 'https://baseline-harness.dev/spec/schemas/';
const FINDING_STATUSES: readonly string[] = [
'PASS',
'FAIL',
'PARTIAL',
'EXEMPT',
'NOT_APPLICABLE',
'UNKNOWN',
'BLOCKED',
];
function isRecord(value: unknown): value is Record<string, unknown> {
return typeof value === 'object' && value !== null && !Array.isArray(value);
}
function isSchema(value: unknown): value is Schema {
return (typeof value === 'object' && value !== null) || typeof value === 'boolean';
}
function isString(value: unknown): value is string {
return typeof value === 'string';
}
function schemaFiles(schemasDir: string): string[] {
return readdirSync(schemasDir, { withFileTypes: true })
.filter((entry) => entry.isFile() && entry.name.endsWith('.schema.json'))
.map((entry) => path.join(schemasDir, entry.name))
.sort((a, b) => a.localeCompare(b));
}
function loadAjv(schemasDir: string, diagnostics: Diagnostic[]): Ajv2020 | undefined {
if (!existsSync(schemasDir)) {
diagnostics.push({
file: schemasDir,
code: 'missing-directory',
message: 'schemas/ is required',
});
return undefined;
}
const ajv = new Ajv2020({ strict: true, strictTypes: false, allErrors: true });
for (const file of schemaFiles(schemasDir)) {
let parsed: unknown;
try {
parsed = JSON.parse(readFileSync(file, 'utf8'));
} catch {
diagnostics.push({ file, code: 'parse-error', message: 'schema file is not valid JSON' });
continue;
}
if (isSchema(parsed)) {
ajv.addSchema(parsed);
}
}
return ajv;
}
function readReport(file: string, diagnostics: Diagnostic[]): unknown {
let text: string;
try {
text = readFileSync(file, 'utf8');
} catch {
diagnostics.push({ file, code: 'read-error', message: 'report file is not readable' });
return undefined;
}
try {
return JSON.parse(text);
} catch {
diagnostics.push({ file, code: 'parse-error', message: 'report is not valid JSON' });
return undefined;
}
}
function requirementIds(specRoot: string, diagnostics: Diagnostic[]): Set<string> {
const ids = new Set<string>();
const dir = path.join(specRoot, 'requirements');
if (!existsSync(dir)) {
diagnostics.push({
file: dir,
code: 'missing-directory',
message: 'requirements/ is required',
});
return ids;
}
for (const name of readdirSync(dir)) {
if (!name.endsWith('.yaml')) {
continue;
}
const file = path.join(dir, name);
try {
const doc: unknown = parseDocument(readFileSync(file, 'utf8'), { logLevel: 'silent' }).toJS({
maxAliasCount: 5,
});
if (isRecord(doc) && isString(doc['id'])) {
ids.add(doc['id']);
}
} catch {
diagnostics.push({ file, code: 'parse-error', message: 'requirement file is not parseable' });
}
}
return ids;
}
function checkSchema(ajv: Ajv2020, report: unknown, file: string, diagnostics: Diagnostic[]): void {
const validateFn = ajv.getSchema(`${SCHEMA_BASE}audit-report.schema.json`);
if (validateFn === undefined) {
diagnostics.push({
file,
code: 'missing-schema',
message: 'audit-report schema is not loaded',
});
return;
}
if (validateFn(report) === true) {
return;
}
for (const err of validateFn.errors ?? []) {
const where = err.instancePath === '' ? '/' : err.instancePath;
diagnostics.push({
file,
pointer: err.instancePath,
code: 'schema-error',
message: `${where}: ${err.message ?? 'invalid'}`,
});
}
}
function checkFindingReferences(
report: Record<string, unknown>,
file: string,
requirements: Set<string>,
diagnostics: Diagnostic[],
): void {
const findings = Array.isArray(report['findings']) ? report['findings'] : [];
const items: readonly unknown[] = findings;
for (const finding of items) {
if (!isRecord(finding) || !isString(finding['requirement'])) {
continue;
}
if (!requirements.has(finding['requirement'])) {
diagnostics.push({
file,
code: 'unknown-requirement',
message: `finding references undefined requirement ${finding['requirement']}`,
});
}
}
}
function statusCounts(report: Record<string, unknown>): Map<string, number> {
const counts = new Map<string, number>();
const findings = Array.isArray(report['findings']) ? report['findings'] : [];
const items: readonly unknown[] = findings;
for (const finding of items) {
if (isRecord(finding) && isString(finding['status'])) {
counts.set(finding['status'], (counts.get(finding['status']) ?? 0) + 1);
}
}
return counts;
}
function checkSummary(
report: Record<string, unknown>,
file: string,
diagnostics: Diagnostic[],
): void {
const summary = report['summary'];
if (!isRecord(summary)) {
return;
}
const counts = statusCounts(report);
for (const status of FINDING_STATUSES) {
const declared = summary[status];
const actual = counts.get(status) ?? 0;
if (typeof declared === 'number' && declared !== actual) {
diagnostics.push({
file,
code: 'summary-mismatch',
message: `summary ${status}=${String(declared)} but findings contain ${String(actual)}`,
});
}
}
const extra = Object.keys(summary).filter((key) => !FINDING_STATUSES.includes(key));
for (const key of extra) {
diagnostics.push({
file,
code: 'summary-mismatch',
message: `summary has unknown status ${key}`,
});
}
}
export function validateReport(reportFile: string, specRoot: string): ReportValidationResult {
const diagnostics: Diagnostic[] = [];
const report = readReport(reportFile, diagnostics);
if (report === undefined) {
return { ok: false, diagnostics };
}
const ajv = loadAjv(path.join(specRoot, 'schemas'), diagnostics);
if (ajv === undefined) {
return { ok: false, diagnostics };
}
checkSchema(ajv, report, reportFile, diagnostics);
if (isRecord(report)) {
checkFindingReferences(report, reportFile, requirementIds(specRoot, diagnostics), diagnostics);
checkSummary(report, reportFile, diagnostics);
}
diagnostics.sort((a, b) =>
`${a.file} ${a.code} ${a.pointer ?? ''}`.localeCompare(
`${b.file} ${b.code} ${b.pointer ?? ''}`,
),
);
return { ok: diagnostics.length === 0, diagnostics };
}
+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);
});