diff --git a/backlog/tasks/bhl-025 - Реализовать-рендер-человекочитаемого-отчёта.md b/backlog/tasks/bhl-025 - Реализовать-рендер-человекочитаемого-отчёта.md index ee15f4a..44aa8b0 100644 --- a/backlog/tasks/bhl-025 - Реализовать-рендер-человекочитаемого-отчёта.md +++ b/backlog/tasks/bhl-025 - Реализовать-рендер-человекочитаемого-отчёта.md @@ -1,9 +1,10 @@ --- id: BHL-025 title: Реализовать рендер человекочитаемого отчёта -status: To Do +status: Done assignee: [] created_date: '2026-11-28T14:31:21Z' +updated_date: '2026-11-28T22:55:48Z' labels: [] milestone: m-2 dependencies: @@ -23,14 +24,26 @@ ordinal: 25000 ## Acceptance Criteria -- [ ] #1 Один и тот же отчёт рендерится идентично повторно -- [ ] #2 Все статусы PASS/FAIL/PARTIAL/EXEMPT/N-A/UNKNOWN отображаются корректно +- [x] #1 Один и тот же отчёт рендерится идентично повторно +- [x] #2 Все статусы PASS/FAIL/PARTIAL/EXEMPT/N-A/UNKNOWN отображаются корректно ## Definition of Done -- [ ] #1 npm run check пройден (для изменений материалов и документации) -- [ ] #2 Местный quality gate затронутого модуля пройден (для кода и конфигурации) -- [ ] #3 В записи нет секретов, персональных путей и непубликуемых идентификаторов +- [x] #1 npm run check пройден (для изменений материалов и документации) +- [x] #2 Местный quality gate затронутого модуля пройден (для кода и конфигурации) +- [x] #3 В записи нет секретов, персональных путей и непубликуемых идентификаторов - [ ] #4 Состояние задачи в Backlog.md актуально: прогресс, блокеры, следующий шаг + +## Comments + + +created: 2026-11-28T22:55:48Z + +--- + +bhl report render --out : детерминированный Markdown (тест: повторный рендер идентичен). Сводка — таблица по всем 7 статусам (PASS/FAIL/PARTIAL/EXEMPT/NOT_APPLICABLE/UNKNOWN/BLOCKED), секции находок в фиксированном порядке с методом, уверенностью semantic, ссылкой на исключение и доказательствами (locator+fingerprint). Процентного рейтинга нет (D-019). Пакет 38/38. + +--- + diff --git a/packages/bhl/src/cli.ts b/packages/bhl/src/cli.ts index 4d53a7c..f796e6b 100644 --- a/packages/bhl/src/cli.ts +++ b/packages/bhl/src/cli.ts @@ -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 --out ; ' + 'profile resolve [--profile ] [--preset ]; ' + 'report validate [--spec-root ]; ' + + 'report render --out ; ' + 'manifest validate [--spec-root ]; ' + 'fetch --version --cache ; ' + 'verify --version --cache ; ' + @@ -150,21 +151,47 @@ function runProfile(command: string, rest: readonly string[]): number { return ExitCode.ValidationFailed; } +const REPORT_FLAGS: Readonly> = { + '--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 ')); + 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) { diff --git a/packages/bhl/src/render.ts b/packages/bhl/src/render.ts index 785faff..c03e325 100644 --- a/packages/bhl/src/render.ts +++ b/packages/bhl/src/render.ts @@ -17,6 +17,19 @@ export interface RenderResult { const GENERATED_HEADER = '\n'; +const REPORT_HEADER = + '\n'; + +const REPORT_STATUSES: readonly string[] = [ + 'PASS', + 'FAIL', + 'PARTIAL', + 'EXEMPT', + 'NOT_APPLICABLE', + 'UNKNOWN', + 'BLOCKED', +]; + function isRecord(value: unknown): value is Record { 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[] { + 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[] { + 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[] { + 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 { + 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'); +} diff --git a/packages/bhl/tests/report.test.mjs b/packages/bhl/tests/report.test.mjs index c77a0f8..d86d045 100644 --- a/packages/bhl/tests/report.test.mjs +++ b/packages/bhl/tests/report.test.mjs @@ -1,7 +1,7 @@ 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 { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'; import os from 'node:os'; import path from 'node:path'; @@ -176,3 +176,100 @@ test('использование команды report', () => { const noFile = spawnSync(process.execPath, [cli, 'report', 'validate'], { encoding: 'utf8' }); 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); +});