feat: bhl report render — детерминированный Markdown отчёта (BHL-025)
- сводка по всем статусам, секции находок в фиксированном порядке - метод+уверенность semantic, exemption_ref, доказательства с fingerprint - без процентного рейтинга (D-019); повторный рендер идентичен (тест) - пакет: 38/38 тестов
This commit is contained in:
+66
-13
@@ -2,7 +2,7 @@ import { mkdirSync, readFileSync, writeFileSync } from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { emit, ExitCode, failEnvelope, okEnvelope } from './envelope.ts';
|
||||
import { fetchSpec, verifyCache } from './fetch.ts';
|
||||
import { renderSpec } from './render.ts';
|
||||
import { renderReport, renderSpec } from './render.ts';
|
||||
import { resolveProfiles } from './resolve.ts';
|
||||
import { specList, specShow, validateManifest } from './spec.ts';
|
||||
import { validateReport } from './report.ts';
|
||||
@@ -15,6 +15,7 @@ const USAGE_MESSAGE =
|
||||
'spec render --spec-root <path> --out <dir>; ' +
|
||||
'profile resolve <spec-root> [--profile <id>] [--preset <id>]; ' +
|
||||
'report validate <report.json> [--spec-root <path>]; ' +
|
||||
'report render <report.json> --out <file.md>; ' +
|
||||
'manifest validate <manifest.yaml> [--spec-root <path>]; ' +
|
||||
'fetch <release-dir> --version <semver> --cache <dir>; ' +
|
||||
'verify --version <semver> --cache <dir>; ' +
|
||||
@@ -150,21 +151,47 @@ function runProfile(command: string, rest: readonly string[]): number {
|
||||
return ExitCode.ValidationFailed;
|
||||
}
|
||||
|
||||
const REPORT_FLAGS: Readonly<Record<string, 'spec-root' | 'out'>> = {
|
||||
'--spec-root': 'spec-root',
|
||||
'--out': 'out',
|
||||
};
|
||||
|
||||
function takeReportFlag(
|
||||
args: readonly string[],
|
||||
cursor: number,
|
||||
target: { specRoot: string; out: string | undefined },
|
||||
arg: string,
|
||||
): { next: number } | { error: string } {
|
||||
const flag = REPORT_FLAGS[arg];
|
||||
const value = args[cursor + 1];
|
||||
if (flag === undefined || value === undefined) {
|
||||
return { error: `missing value for ${arg}` };
|
||||
}
|
||||
if (flag === 'spec-root') {
|
||||
target.specRoot = value;
|
||||
} else {
|
||||
target.out = value;
|
||||
}
|
||||
return { next: cursor + 2 };
|
||||
}
|
||||
|
||||
function parseReportArgs(
|
||||
args: readonly string[],
|
||||
): { file: string; specRoot: string } | { error: string } {
|
||||
let specRoot = 'spec';
|
||||
): { file: string; specRoot: string; out: string | undefined } | { error: string } {
|
||||
const target: { specRoot: string; out: string | undefined } = {
|
||||
specRoot: 'spec',
|
||||
out: undefined,
|
||||
};
|
||||
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' };
|
||||
if (REPORT_FLAGS[arg] !== undefined) {
|
||||
const taken = takeReportFlag(args, cursor, target, arg);
|
||||
if ('error' in taken) {
|
||||
return taken;
|
||||
}
|
||||
specRoot = value;
|
||||
cursor += 2;
|
||||
cursor = taken.next;
|
||||
continue;
|
||||
}
|
||||
if (arg.startsWith('--')) {
|
||||
@@ -174,9 +201,9 @@ function parseReportArgs(
|
||||
cursor += 1;
|
||||
}
|
||||
if (positional.length !== 1) {
|
||||
return { error: 'report validate requires exactly one report file' };
|
||||
return { error: 'report requires exactly one report file' };
|
||||
}
|
||||
return { file: positional[0] ?? '', specRoot };
|
||||
return { file: positional[0] ?? '', specRoot: target.specRoot, out: target.out };
|
||||
}
|
||||
|
||||
interface SpecFlags {
|
||||
@@ -468,10 +495,33 @@ function runManifest(command: string, rest: readonly string[]): number {
|
||||
return ExitCode.ValidationFailed;
|
||||
}
|
||||
|
||||
function runReportRender(parsed: { file: string; out: string | undefined }): number {
|
||||
const out = parsed.out;
|
||||
if (out === undefined) {
|
||||
emit(failEnvelope('report', 'USAGE', 'report render requires --out <file.md>'));
|
||||
return ExitCode.Usage;
|
||||
}
|
||||
let report: unknown;
|
||||
try {
|
||||
report = JSON.parse(readFileSync(parsed.file, 'utf8'));
|
||||
} catch {
|
||||
emit(failEnvelope('report', 'READ_ERROR', `report file ${parsed.file} is not readable JSON`));
|
||||
return ExitCode.ValidationFailed;
|
||||
}
|
||||
if (!isRecord(report)) {
|
||||
emit(failEnvelope('report', 'READ_ERROR', 'report must be a JSON object'));
|
||||
return ExitCode.ValidationFailed;
|
||||
}
|
||||
mkdirSync(path.dirname(out), { recursive: true });
|
||||
writeFileSync(out, renderReport(report), 'utf8');
|
||||
emit(okEnvelope('report', { file: parsed.file, out }));
|
||||
return ExitCode.Ok;
|
||||
}
|
||||
|
||||
function runReport(command: string, rest: readonly string[]): number {
|
||||
const [sub, ...args] = rest;
|
||||
if (sub !== 'validate') {
|
||||
emit(failEnvelope(command, 'USAGE', 'report requires the subcommand validate'));
|
||||
if (sub !== 'validate' && sub !== 'render') {
|
||||
emit(failEnvelope(command, 'USAGE', 'report requires the subcommand validate or render'));
|
||||
return ExitCode.Usage;
|
||||
}
|
||||
const parsed = parseReportArgs(args);
|
||||
@@ -479,6 +529,9 @@ function runReport(command: string, rest: readonly string[]): number {
|
||||
emit(failEnvelope(command, 'USAGE', parsed.error));
|
||||
return ExitCode.Usage;
|
||||
}
|
||||
if (sub === 'render') {
|
||||
return runReportRender(parsed);
|
||||
}
|
||||
const result = validateReport(parsed.file, parsed.specRoot);
|
||||
const data = { file: parsed.file, spec_root: parsed.specRoot, errors: result.diagnostics };
|
||||
if (result.ok) {
|
||||
|
||||
@@ -17,6 +17,19 @@ export interface RenderResult {
|
||||
const GENERATED_HEADER =
|
||||
'<!-- Сгенерировано bhl spec render из машиночитаемой спецификации. Не редактировать вручную. -->\n';
|
||||
|
||||
const REPORT_HEADER =
|
||||
'<!-- Сгенерировано bhl report render из машиночитаемого отчёта аудита. Не редактировать вручную. -->\n';
|
||||
|
||||
const REPORT_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);
|
||||
}
|
||||
@@ -299,3 +312,102 @@ export function renderSpec(root: string): RenderResult {
|
||||
}
|
||||
return { ok: diagnostics.length === 0, files, diagnostics };
|
||||
}
|
||||
|
||||
function renderReportMeta(report: Record<string, unknown>): string[] {
|
||||
const tool = isRecord(report['tool']) ? report['tool'] : {};
|
||||
const agent = isRecord(report['agent']) ? report['agent'] : {};
|
||||
const subject = isRecord(report['subject']) ? report['subject'] : {};
|
||||
const revision =
|
||||
subject['revision'] === undefined ? '' : `, ревизия ${text(subject['revision'])}`;
|
||||
const dirtyValue = subject['dirty'];
|
||||
const dirty = typeof dirtyValue === 'boolean' ? `, dirty=${String(dirtyValue)}` : '';
|
||||
const lines: string[] = [REPORT_HEADER, `# Отчёт аудита ${text(report['id'])}`, ''];
|
||||
lines.push(`- Сгенерирован: ${text(report['generated_at'])}`);
|
||||
lines.push(`- Инструмент: ${text(tool['name'])} ${text(tool['version'])}`);
|
||||
if (agent['name'] !== undefined) {
|
||||
lines.push(`- Агент: ${text(agent['name'])} ${text(agent['version'])}`);
|
||||
}
|
||||
lines.push(
|
||||
`- Объект: ${text(subject['kind'])}, отпечаток ${text(subject['fingerprint'])}${revision}${dirty}`,
|
||||
);
|
||||
lines.push(`- Версия спецификации: ${text(report['spec_version'])}`);
|
||||
const profiles = Array.isArray(report['profiles']) ? report['profiles'] : [];
|
||||
lines.push(`- Профили: ${profiles.filter(isString).join(', ') || '—'}`, '');
|
||||
return lines;
|
||||
}
|
||||
|
||||
function renderReportSummary(report: Record<string, unknown>): string[] {
|
||||
const findings = Array.isArray(report['findings']) ? report['findings'] : [];
|
||||
const items: readonly unknown[] = findings;
|
||||
const lines: string[] = ['## Сводка', '', '| Статус | Находок |', '|---|---|'];
|
||||
for (const status of REPORT_STATUSES) {
|
||||
const count = items.filter((item) => isRecord(item) && item['status'] === status).length;
|
||||
lines.push(`| ${status} | ${String(count)} |`);
|
||||
}
|
||||
lines.push('');
|
||||
return lines;
|
||||
}
|
||||
|
||||
function renderEvidence(evidence: readonly unknown[]): string[] {
|
||||
const lines: string[] = [];
|
||||
for (const item of evidence) {
|
||||
if (!isRecord(item)) {
|
||||
continue;
|
||||
}
|
||||
const locator = text(item['locator']);
|
||||
const fingerprint = text(item['fingerprint']);
|
||||
const parts = [`${text(item['kind'])}: ${text(item['description'])}`];
|
||||
if (locator !== '') {
|
||||
parts.push(`\`${locator}\``);
|
||||
}
|
||||
if (fingerprint !== '') {
|
||||
parts.push(fingerprint);
|
||||
}
|
||||
lines.push(` - ${parts.join(' — ')}`);
|
||||
}
|
||||
return lines;
|
||||
}
|
||||
|
||||
function renderFinding(finding: Record<string, unknown>): string[] {
|
||||
const lines: string[] = [`- Требование: ${text(finding['requirement'])}`];
|
||||
const confidence =
|
||||
finding['confidence'] === undefined ? '' : `, уверенность ${text(finding['confidence'])}`;
|
||||
lines.push(`- Метод: ${text(finding['method'])}${confidence}`);
|
||||
if (finding['exemption_ref'] !== undefined) {
|
||||
lines.push(`- Ссылка на исключение: ${text(finding['exemption_ref'])}`);
|
||||
}
|
||||
lines.push(`- Основание: ${text(finding['rationale'])}`);
|
||||
const evidence = Array.isArray(finding['evidence']) ? finding['evidence'] : [];
|
||||
lines.push('- Доказательства:');
|
||||
lines.push(...renderEvidence(evidence));
|
||||
return lines;
|
||||
}
|
||||
|
||||
function renderReportStatusSection(status: string, findings: readonly unknown[]): string[] {
|
||||
const matched = findings.filter((item) => isRecord(item) && item['status'] === status);
|
||||
if (matched.length === 0) {
|
||||
return [];
|
||||
}
|
||||
const lines: string[] = [`### ${status}`, ''];
|
||||
for (const item of matched) {
|
||||
if (isRecord(item)) {
|
||||
lines.push(...renderFinding(item), '');
|
||||
}
|
||||
}
|
||||
return lines;
|
||||
}
|
||||
|
||||
export function renderReport(report: Record<string, unknown>): string {
|
||||
const findings = Array.isArray(report['findings']) ? report['findings'] : [];
|
||||
const items: readonly unknown[] = findings;
|
||||
const lines: string[] = [
|
||||
...renderReportMeta(report),
|
||||
...renderReportSummary(report),
|
||||
'## Находки',
|
||||
'',
|
||||
];
|
||||
for (const status of REPORT_STATUSES) {
|
||||
lines.push(...renderReportStatusSection(status, items));
|
||||
}
|
||||
return lines.join('\n');
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user