feat: bhl report render — детерминированный Markdown отчёта (BHL-025)

- сводка по всем статусам, секции находок в фиксированном порядке
- метод+уверенность semantic, exemption_ref, доказательства с fingerprint
- без процентного рейтинга (D-019); повторный рендер идентичен (тест)
- пакет: 38/38 тестов
This commit is contained in:
Suslov-MD
2026-11-29 01:55:48 +03:00
parent 64f6f3ccb3
commit 53b167268f
4 changed files with 295 additions and 20 deletions
@@ -1,9 +1,10 @@
--- ---
id: BHL-025 id: BHL-025
title: Реализовать рендер человекочитаемого отчёта title: Реализовать рендер человекочитаемого отчёта
status: To Do status: Done
assignee: [] assignee: []
created_date: '2026-11-28T14:31:21Z' created_date: '2026-11-28T14:31:21Z'
updated_date: '2026-11-28T22:55:48Z'
labels: [] labels: []
milestone: m-2 milestone: m-2
dependencies: dependencies:
@@ -23,14 +24,26 @@ ordinal: 25000
## Acceptance Criteria ## Acceptance Criteria
<!-- AC:BEGIN --> <!-- AC:BEGIN -->
- [ ] #1 Один и тот же отчёт рендерится идентично повторно - [x] #1 Один и тот же отчёт рендерится идентично повторно
- [ ] #2 Все статусы PASS/FAIL/PARTIAL/EXEMPT/N-A/UNKNOWN отображаются корректно - [x] #2 Все статусы PASS/FAIL/PARTIAL/EXEMPT/N-A/UNKNOWN отображаются корректно
<!-- AC:END --> <!-- AC:END -->
## Definition of Done ## Definition of Done
<!-- DOD:BEGIN --> <!-- DOD:BEGIN -->
- [ ] #1 npm run check пройден (для изменений материалов и документации) - [x] #1 npm run check пройден (для изменений материалов и документации)
- [ ] #2 Местный quality gate затронутого модуля пройден (для кода и конфигурации) - [x] #2 Местный quality gate затронутого модуля пройден (для кода и конфигурации)
- [ ] #3 В записи нет секретов, персональных путей и непубликуемых идентификаторов - [x] #3 В записи нет секретов, персональных путей и непубликуемых идентификаторов
- [ ] #4 Состояние задачи в Backlog.md актуально: прогресс, блокеры, следующий шаг - [ ] #4 Состояние задачи в Backlog.md актуально: прогресс, блокеры, следующий шаг
<!-- DOD:END --> <!-- DOD:END -->
## Comments
<!-- COMMENTS:BEGIN -->
created: 2026-11-28T22:55:48Z
---
bhl report render <report.json> --out <file.md>: детерминированный Markdown (тест: повторный рендер идентичен). Сводка — таблица по всем 7 статусам (PASS/FAIL/PARTIAL/EXEMPT/NOT_APPLICABLE/UNKNOWN/BLOCKED), секции находок в фиксированном порядке с методом, уверенностью semantic, ссылкой на исключение и доказательствами (locator+fingerprint). Процентного рейтинга нет (D-019). Пакет 38/38.
---
<!-- COMMENTS:END -->
+66 -13
View File
@@ -2,7 +2,7 @@ import { mkdirSync, readFileSync, writeFileSync } from 'node:fs';
import path from 'node:path'; import path from 'node:path';
import { emit, ExitCode, failEnvelope, okEnvelope } from './envelope.ts'; import { emit, ExitCode, failEnvelope, okEnvelope } from './envelope.ts';
import { fetchSpec, verifyCache } from './fetch.ts'; import { fetchSpec, verifyCache } from './fetch.ts';
import { renderSpec } from './render.ts'; import { renderReport, renderSpec } from './render.ts';
import { resolveProfiles } from './resolve.ts'; import { resolveProfiles } from './resolve.ts';
import { specList, specShow, validateManifest } from './spec.ts'; import { specList, specShow, validateManifest } from './spec.ts';
import { validateReport } from './report.ts'; import { validateReport } from './report.ts';
@@ -15,6 +15,7 @@ const USAGE_MESSAGE =
'spec render --spec-root <path> --out <dir>; ' + 'spec render --spec-root <path> --out <dir>; ' +
'profile resolve <spec-root> [--profile <id>] [--preset <id>]; ' + 'profile resolve <spec-root> [--profile <id>] [--preset <id>]; ' +
'report validate <report.json> [--spec-root <path>]; ' + 'report validate <report.json> [--spec-root <path>]; ' +
'report render <report.json> --out <file.md>; ' +
'manifest validate <manifest.yaml> [--spec-root <path>]; ' + 'manifest validate <manifest.yaml> [--spec-root <path>]; ' +
'fetch <release-dir> --version <semver> --cache <dir>; ' + 'fetch <release-dir> --version <semver> --cache <dir>; ' +
'verify --version <semver> --cache <dir>; ' + 'verify --version <semver> --cache <dir>; ' +
@@ -150,21 +151,47 @@ function runProfile(command: string, rest: readonly string[]): number {
return ExitCode.ValidationFailed; 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( function parseReportArgs(
args: readonly string[], args: readonly string[],
): { file: string; specRoot: string } | { error: string } { ): { file: string; specRoot: string; out: string | undefined } | { error: string } {
let specRoot = 'spec'; const target: { specRoot: string; out: string | undefined } = {
specRoot: 'spec',
out: undefined,
};
const positional: string[] = []; const positional: string[] = [];
let cursor = 0; let cursor = 0;
while (cursor < args.length) { while (cursor < args.length) {
const arg = args[cursor] ?? ''; const arg = args[cursor] ?? '';
if (arg === '--spec-root') { if (REPORT_FLAGS[arg] !== undefined) {
const value = args[cursor + 1]; const taken = takeReportFlag(args, cursor, target, arg);
if (value === undefined) { if ('error' in taken) {
return { error: 'missing value for --spec-root' }; return taken;
} }
specRoot = value; cursor = taken.next;
cursor += 2;
continue; continue;
} }
if (arg.startsWith('--')) { if (arg.startsWith('--')) {
@@ -174,9 +201,9 @@ function parseReportArgs(
cursor += 1; cursor += 1;
} }
if (positional.length !== 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 { interface SpecFlags {
@@ -468,10 +495,33 @@ function runManifest(command: string, rest: readonly string[]): number {
return ExitCode.ValidationFailed; 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 { function runReport(command: string, rest: readonly string[]): number {
const [sub, ...args] = rest; const [sub, ...args] = rest;
if (sub !== 'validate') { if (sub !== 'validate' && sub !== 'render') {
emit(failEnvelope(command, 'USAGE', 'report requires the subcommand validate')); emit(failEnvelope(command, 'USAGE', 'report requires the subcommand validate or render'));
return ExitCode.Usage; return ExitCode.Usage;
} }
const parsed = parseReportArgs(args); const parsed = parseReportArgs(args);
@@ -479,6 +529,9 @@ function runReport(command: string, rest: readonly string[]): number {
emit(failEnvelope(command, 'USAGE', parsed.error)); emit(failEnvelope(command, 'USAGE', parsed.error));
return ExitCode.Usage; return ExitCode.Usage;
} }
if (sub === 'render') {
return runReportRender(parsed);
}
const result = validateReport(parsed.file, parsed.specRoot); const result = validateReport(parsed.file, parsed.specRoot);
const data = { file: parsed.file, spec_root: parsed.specRoot, errors: result.diagnostics }; const data = { file: parsed.file, spec_root: parsed.specRoot, errors: result.diagnostics };
if (result.ok) { if (result.ok) {
+112
View File
@@ -17,6 +17,19 @@ export interface RenderResult {
const GENERATED_HEADER = const GENERATED_HEADER =
'<!-- Сгенерировано bhl spec render из машиночитаемой спецификации. Не редактировать вручную. -->\n'; '<!-- Сгенерировано 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> { function isRecord(value: unknown): value is Record<string, unknown> {
return typeof value === 'object' && value !== null && !Array.isArray(value); 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 }; 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');
}
+98 -1
View File
@@ -1,7 +1,7 @@
import test from 'node:test'; import test from 'node:test';
import assert from 'node:assert/strict'; import assert from 'node:assert/strict';
import { spawnSync } from 'node:child_process'; import { spawnSync } from 'node:child_process';
import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'; import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
import os from 'node:os'; import os from 'node:os';
import path from 'node:path'; import path from 'node:path';
@@ -176,3 +176,100 @@ test('использование команды report', () => {
const noFile = spawnSync(process.execPath, [cli, 'report', 'validate'], { encoding: 'utf8' }); const noFile = spawnSync(process.execPath, [cli, 'report', 'validate'], { encoding: 'utf8' });
assert.equal(noFile.status, 2); assert.equal(noFile.status, 2);
}); });
function runRender(t, report) {
const root = fixture(t, { 'report.json': JSON.stringify(report) });
const out = path.join(root, 'out', 'report.md');
const proc = spawnSync(
process.execPath,
[cli, 'report', 'render', path.join(root, 'report.json'), '--out', out],
{
encoding: 'utf8',
},
);
return { code: proc.status, out, stdout: JSON.parse(proc.stdout) };
}
test('report render: повторный рендер идентичен и показывает все статусы', (t) => {
const findings = [
{ ...PASS_FINDING, requirement: 'req-alpha' },
{
...PASS_FINDING,
requirement: 'req-alpha',
status: 'FAIL',
rationale: 'Найден провал проверки фикстуры.',
},
{
...PASS_FINDING,
requirement: 'req-alpha',
status: 'PARTIAL',
rationale: 'Проверка выполнена частично.',
},
{
...PASS_FINDING,
requirement: 'req-alpha',
status: 'EXEMPT',
exemption_ref: 'ex-fixture',
rationale: 'Снято обоснованным исключением.',
},
{
...PASS_FINDING,
requirement: 'req-alpha',
status: 'NOT_APPLICABLE',
rationale: 'Требование неприменимо к фикстуре.',
},
{
...PASS_FINDING,
requirement: 'req-alpha',
status: 'UNKNOWN',
method: 'semantic',
confidence: 'medium',
rationale: 'Наблюдение неполно.',
},
{
...PASS_FINDING,
requirement: 'req-alpha',
status: 'BLOCKED',
rationale: 'Инструмент недоступен.',
},
];
const report = reportDoc(findings, undefined);
const first = runRender(t, report);
assert.equal(first.code, 0);
const markdown = readFileSync(first.out, 'utf8');
for (const status of [
'PASS',
'FAIL',
'PARTIAL',
'EXEMPT',
'NOT_APPLICABLE',
'UNKNOWN',
'BLOCKED',
]) {
assert.ok(markdown.includes(`### ${status}`), `секция ${status}`);
}
assert.ok(markdown.includes('ex-fixture'), 'ссылка на исключение');
assert.ok(markdown.includes('уверенность medium'), 'уверенность semantic');
assert.ok(!/%\s*оцен|процент/i.test(markdown), 'процентного рейтинга нет');
const second = runRender(t, report);
assert.equal(readFileSync(second.out, 'utf8'), markdown, 'повторный рендер идентичен');
});
test('report render: битый JSON и отсутствие --out дают понятные ошибки', (t) => {
const root = fixture(t, { 'report.json': '{ not json' });
const proc = spawnSync(
process.execPath,
[cli, 'report', 'render', path.join(root, 'report.json'), '--out', path.join(root, 'o.md')],
{
encoding: 'utf8',
},
);
assert.equal(proc.status, 1);
assert.equal(JSON.parse(proc.stdout).error.code, 'READ_ERROR');
const noOut = spawnSync(
process.execPath,
[cli, 'report', 'render', path.join(root, 'report.json')],
{ encoding: 'utf8' },
);
assert.equal(noOut.status, 2);
});