feat: генерация человекочитаемой документации из спецификации (BHL-017)
- bhl spec render: index + страницы требований и антипаттернов, детерминированный вывод - docs/spec/ закоммичен; SSOT остаётся spec/; метка 'не редактировать вручную' - тесты: идемпотентность, детект устаревания, синхронность с Git - AGENTS.md и README: правила сгенерированных страниц
This commit is contained in:
+39
-5
@@ -1,5 +1,7 @@
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { mkdirSync, readFileSync, writeFileSync } from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { emit, ExitCode, failEnvelope, okEnvelope } from './envelope.ts';
|
||||
import { renderSpec } from './render.ts';
|
||||
import { resolveProfiles } from './resolve.ts';
|
||||
import { specList, specShow, validateManifest } from './spec.ts';
|
||||
import { validateReport } from './report.ts';
|
||||
@@ -9,6 +11,7 @@ const USAGE_MESSAGE =
|
||||
'Usage: bhl <version|validate|spec|profile|report|manifest|audit> [args]; ' +
|
||||
'spec list [--spec-root <path>] [--domain <id>] [--capability <id>]; ' +
|
||||
'spec show <req-id> [--spec-root <path>]; ' +
|
||||
'spec render --spec-root <path> --out <dir>; ' +
|
||||
'profile resolve <spec-root> [--profile <id>] [--preset <id>]; ' +
|
||||
'report validate <report.json> [--spec-root <path>]; ' +
|
||||
'manifest validate <manifest.yaml> [--spec-root <path>]; ' +
|
||||
@@ -177,6 +180,7 @@ interface SpecFlags {
|
||||
root: string;
|
||||
domain?: string;
|
||||
capability?: string;
|
||||
out?: string;
|
||||
positional: string[];
|
||||
}
|
||||
|
||||
@@ -194,8 +198,10 @@ function takeNamedFlag(
|
||||
target.root = value;
|
||||
} else if (arg === '--domain') {
|
||||
target.domain = value;
|
||||
} else {
|
||||
} else if (arg === '--capability') {
|
||||
target.capability = value;
|
||||
} else {
|
||||
target.out = value;
|
||||
}
|
||||
return { next: cursor + 2 };
|
||||
}
|
||||
@@ -205,7 +211,7 @@ function parseSpecArgs(args: readonly string[]): SpecFlags | { error: string } {
|
||||
let cursor = 0;
|
||||
while (cursor < args.length) {
|
||||
const arg = args[cursor] ?? '';
|
||||
if (arg === '--spec-root' || arg === '--domain' || arg === '--capability') {
|
||||
if (arg === '--spec-root' || arg === '--domain' || arg === '--capability' || arg === '--out') {
|
||||
const taken = takeNamedFlag(args, cursor, target, arg);
|
||||
if ('error' in taken) {
|
||||
return taken;
|
||||
@@ -268,10 +274,35 @@ function emitSpecShow(parsed: SpecFlags): number {
|
||||
return ExitCode.Ok;
|
||||
}
|
||||
|
||||
function emitSpecRender(parsed: SpecFlags): number {
|
||||
const out = parsed.out;
|
||||
if (out === undefined) {
|
||||
emit(failEnvelope('spec', 'USAGE', 'spec render requires --out <dir>'));
|
||||
return ExitCode.Usage;
|
||||
}
|
||||
const result = renderSpec(parsed.root);
|
||||
if (!result.ok) {
|
||||
return emitValidationFailure(
|
||||
'spec',
|
||||
{ root: parsed.root, errors: result.diagnostics },
|
||||
result.diagnostics.length,
|
||||
);
|
||||
}
|
||||
for (const file of result.files) {
|
||||
const target = path.join(out, file.path);
|
||||
mkdirSync(path.dirname(target), { recursive: true });
|
||||
writeFileSync(target, file.content, 'utf8');
|
||||
}
|
||||
emit(
|
||||
okEnvelope('spec', { root: parsed.root, out, files: result.files.map((file) => file.path) }),
|
||||
);
|
||||
return ExitCode.Ok;
|
||||
}
|
||||
|
||||
function runSpec(command: string, rest: readonly string[]): number {
|
||||
const [sub, ...args] = rest;
|
||||
if (sub !== 'list' && sub !== 'show') {
|
||||
emit(failEnvelope(command, 'USAGE', 'spec requires the subcommand list or show'));
|
||||
if (sub !== 'list' && sub !== 'show' && sub !== 'render') {
|
||||
emit(failEnvelope(command, 'USAGE', 'spec requires the subcommand list, show or render'));
|
||||
return ExitCode.Usage;
|
||||
}
|
||||
const parsed = parseSpecArgs(args);
|
||||
@@ -282,6 +313,9 @@ function runSpec(command: string, rest: readonly string[]): number {
|
||||
if (sub === 'list') {
|
||||
return emitSpecList(parsed);
|
||||
}
|
||||
if (sub === 'render') {
|
||||
return emitSpecRender(parsed);
|
||||
}
|
||||
return emitSpecShow(parsed);
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,301 @@
|
||||
import { existsSync, readFileSync, readdirSync } from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { parseDocument } from 'yaml';
|
||||
import type { Diagnostic } from './validate.ts';
|
||||
|
||||
export interface RenderedFile {
|
||||
path: string;
|
||||
content: string;
|
||||
}
|
||||
|
||||
export interface RenderResult {
|
||||
ok: boolean;
|
||||
files: RenderedFile[];
|
||||
diagnostics: Diagnostic[];
|
||||
}
|
||||
|
||||
const GENERATED_HEADER =
|
||||
'<!-- Сгенерировано bhl spec render из машиночитаемой спецификации. Не редактировать вручную. -->\n';
|
||||
|
||||
function isRecord(value: unknown): value is Record<string, unknown> {
|
||||
return typeof value === 'object' && value !== null && !Array.isArray(value);
|
||||
}
|
||||
|
||||
function isString(value: unknown): value is string {
|
||||
return typeof value === 'string';
|
||||
}
|
||||
|
||||
function text(value: unknown, fallback = ''): string {
|
||||
return isString(value) ? value : fallback;
|
||||
}
|
||||
|
||||
function readYaml(file: string, diagnostics: Diagnostic[]): unknown {
|
||||
try {
|
||||
const doc = parseDocument(readFileSync(file, 'utf8'), { logLevel: 'silent' });
|
||||
if (doc.errors.length > 0) {
|
||||
diagnostics.push({
|
||||
file,
|
||||
code: 'parse-error',
|
||||
message: doc.errors[0]?.message ?? 'invalid YAML',
|
||||
});
|
||||
return undefined;
|
||||
}
|
||||
return doc.toJS({ maxAliasCount: 5 });
|
||||
} catch {
|
||||
diagnostics.push({ file, code: 'parse-error', message: 'YAML is not parseable' });
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
function loadDocs(
|
||||
root: string,
|
||||
dir: string,
|
||||
diagnostics: Diagnostic[],
|
||||
): Record<string, Record<string, unknown>> {
|
||||
const docs: Record<string, Record<string, unknown>> = {};
|
||||
const full = path.join(root, dir);
|
||||
if (!existsSync(full)) {
|
||||
return docs;
|
||||
}
|
||||
const files = readdirSync(full, { withFileTypes: true })
|
||||
.filter((entry) => entry.isFile() && entry.name.endsWith('.yaml'))
|
||||
.map((entry) => path.join(full, entry.name))
|
||||
.sort((a, b) => a.localeCompare(b));
|
||||
for (const file of files) {
|
||||
const value = readYaml(file, diagnostics);
|
||||
if (isRecord(value) && isString(value['id'])) {
|
||||
docs[value['id']] = value;
|
||||
}
|
||||
}
|
||||
return docs;
|
||||
}
|
||||
|
||||
function sortedIds(docs: Record<string, Record<string, unknown>>): string[] {
|
||||
return Object.keys(docs).sort((a, b) => a.localeCompare(b));
|
||||
}
|
||||
|
||||
function renderDomainSection(
|
||||
domainId: string,
|
||||
domain: Record<string, unknown>,
|
||||
capabilities: Record<string, Record<string, unknown>>,
|
||||
requirements: Record<string, Record<string, unknown>>,
|
||||
): string[] {
|
||||
const lines: string[] = [
|
||||
`## ${domainId} — ${text(domain['title'])}`,
|
||||
'',
|
||||
text(domain['description']),
|
||||
'',
|
||||
];
|
||||
const caps = sortedIds(capabilities).filter((id) => capabilities[id]?.['domain'] === domainId);
|
||||
for (const capId of caps) {
|
||||
lines.push(
|
||||
`### ${capId} — ${text(capabilities[capId]?.['title'])}`,
|
||||
'',
|
||||
text(capabilities[capId]?.['description']),
|
||||
'',
|
||||
);
|
||||
}
|
||||
const reqs = sortedIds(requirements).filter((id) => requirements[id]?.['domain'] === domainId);
|
||||
if (reqs.length > 0) {
|
||||
lines.push('| Требование | Уровень | Жизненный цикл | Название |', '|---|---|---|---|');
|
||||
for (const reqId of reqs) {
|
||||
const req = requirements[reqId];
|
||||
const lifecycle = isRecord(req?.['lifecycle']) ? text(req['lifecycle']['status']) : '';
|
||||
lines.push(
|
||||
`| [${reqId}](requirements/${reqId}.md) | ${text(req?.['level'])} | ${lifecycle} | ${text(req?.['title'])} |`,
|
||||
);
|
||||
}
|
||||
lines.push('');
|
||||
}
|
||||
return lines;
|
||||
}
|
||||
|
||||
function renderIndex(
|
||||
domains: Record<string, Record<string, unknown>>,
|
||||
capabilities: Record<string, Record<string, unknown>>,
|
||||
requirements: Record<string, Record<string, unknown>>,
|
||||
): string {
|
||||
const lines: string[] = [
|
||||
GENERATED_HEADER,
|
||||
'# Спецификация — обзор',
|
||||
'',
|
||||
'Машиночитаемая спецификация остаётся нормативным источником истины.',
|
||||
'',
|
||||
];
|
||||
for (const domainId of sortedIds(domains)) {
|
||||
const domain = domains[domainId];
|
||||
if (domain !== undefined) {
|
||||
lines.push(...renderDomainSection(domainId, domain, capabilities, requirements));
|
||||
}
|
||||
}
|
||||
return lines.join('\n');
|
||||
}
|
||||
|
||||
function renderList(
|
||||
items: readonly unknown[],
|
||||
format: (item: Record<string, unknown>) => string,
|
||||
): string[] {
|
||||
const lines: string[] = [];
|
||||
for (const item of items) {
|
||||
if (isRecord(item)) {
|
||||
lines.push(`- ${format(item)}`);
|
||||
}
|
||||
}
|
||||
return lines;
|
||||
}
|
||||
|
||||
function renderParameters(requirement: Record<string, unknown>): string[] {
|
||||
const items = Array.isArray(requirement['parameters']) ? requirement['parameters'] : [];
|
||||
const known: readonly unknown[] = items;
|
||||
if (known.length === 0) {
|
||||
return [];
|
||||
}
|
||||
const lines = [
|
||||
'',
|
||||
'## Параметры',
|
||||
'',
|
||||
'| ID | Тип | Default | Ограничения |',
|
||||
'|---|---|---|---|',
|
||||
];
|
||||
for (const item of known) {
|
||||
if (!isRecord(item)) {
|
||||
continue;
|
||||
}
|
||||
const constraints = isRecord(item['constraints']) ? JSON.stringify(item['constraints']) : '';
|
||||
const def = item['default'] === undefined ? '' : JSON.stringify(item['default']);
|
||||
lines.push(`| ${text(item['id'])} | ${text(item['type'])} | ${def} | ${constraints} |`);
|
||||
}
|
||||
return lines;
|
||||
}
|
||||
|
||||
function applicabilityLine(item: Record<string, unknown>): string {
|
||||
const unless = text(item['unless']);
|
||||
return unless === ''
|
||||
? `when: ${text(item['when'])}`
|
||||
: `when: ${text(item['when'])}; unless: ${unless}`;
|
||||
}
|
||||
|
||||
function sourceLine(item: Record<string, unknown>): string {
|
||||
const note = text(item['note']);
|
||||
return note === '' ? text(item['material']) : `${text(item['material'])} — ${note}`;
|
||||
}
|
||||
|
||||
function renderRequirementCore(req: Record<string, unknown>): string[] {
|
||||
const lines: string[] = [GENERATED_HEADER, `# ${text(req['id'])} — ${text(req['title'])}`, ''];
|
||||
lines.push(`- Уровень: **${text(req['level'])}**`);
|
||||
const lifecycle = isRecord(req['lifecycle']) ? text(req['lifecycle']['status']) : '';
|
||||
lines.push(`- Жизненный цикл: ${lifecycle}`);
|
||||
lines.push(`- Домен: ${text(req['domain'])}; возможность: ${text(req['capability'])}`, '');
|
||||
lines.push('## Формулировка', '', text(req['statement']), '');
|
||||
lines.push('## Обоснование', '', text(req['rationale']), '');
|
||||
const applicability = Array.isArray(req['applicability']) ? req['applicability'] : [];
|
||||
lines.push('## Применимость', '');
|
||||
lines.push(...renderList(applicability, applicabilityLine), '');
|
||||
lines.push(...renderParameters(req), '');
|
||||
return lines;
|
||||
}
|
||||
|
||||
function renderRequirementChecks(req: Record<string, unknown>): string[] {
|
||||
const lines: string[] = [];
|
||||
const criteria = Array.isArray(req['acceptance_criteria']) ? req['acceptance_criteria'] : [];
|
||||
lines.push('## Критерии приёмки', '');
|
||||
lines.push(...renderList(criteria, (item) => text(item['criterion'])), '');
|
||||
const verification = isRecord(req['verification']) ? req['verification'] : {};
|
||||
lines.push(
|
||||
'## Проверка',
|
||||
'',
|
||||
`Вид: ${text(verification['kind'])}`,
|
||||
'',
|
||||
text(verification['procedure']),
|
||||
'',
|
||||
);
|
||||
const evidence = Array.isArray(req['expected_evidence']) ? req['expected_evidence'] : [];
|
||||
lines.push('## Ожидаемые доказательства', '');
|
||||
lines.push(
|
||||
...renderList(evidence, (item) => `${text(item['kind'])}: ${text(item['description'])}`),
|
||||
'',
|
||||
);
|
||||
return lines;
|
||||
}
|
||||
|
||||
function renderRequirementLinks(req: Record<string, unknown>): string[] {
|
||||
const lines: string[] = [];
|
||||
const relations = Array.isArray(req['relations']) ? req['relations'] : [];
|
||||
if (relations.length > 0) {
|
||||
lines.push('## Связи', '');
|
||||
lines.push(
|
||||
...renderList(relations, (item) => `${text(item['kind'])}: ${text(item['target'])}`),
|
||||
'',
|
||||
);
|
||||
}
|
||||
const antipatterns = Array.isArray(req['antipatterns']) ? req['antipatterns'] : [];
|
||||
if (antipatterns.length > 0) {
|
||||
lines.push('## Антипаттерны', '');
|
||||
for (const item of antipatterns) {
|
||||
if (isString(item)) {
|
||||
lines.push(`- [${item}](../antipatterns/${item}.md)`);
|
||||
}
|
||||
}
|
||||
lines.push('');
|
||||
}
|
||||
return lines;
|
||||
}
|
||||
|
||||
function renderRequirement(req: Record<string, unknown>): string {
|
||||
return [
|
||||
...renderRequirementCore(req),
|
||||
...renderRequirementChecks(req),
|
||||
...renderRequirementLinks(req),
|
||||
].join('\n');
|
||||
}
|
||||
|
||||
function renderAntipattern(antipattern: Record<string, unknown>): string {
|
||||
const lines: string[] = [
|
||||
GENERATED_HEADER,
|
||||
`# ${text(antipattern['id'])} — ${text(antipattern['title'])}`,
|
||||
'',
|
||||
];
|
||||
lines.push(`- Уровень: **${text(antipattern['level'])}**`);
|
||||
const lifecycle = isRecord(antipattern['lifecycle'])
|
||||
? text(antipattern['lifecycle']['status'])
|
||||
: '';
|
||||
lines.push(`- Жизненный цикл: ${lifecycle}`, '');
|
||||
lines.push(text(antipattern['description']), '');
|
||||
const relations = Array.isArray(antipattern['relations']) ? antipattern['relations'] : [];
|
||||
lines.push('## Противоречит требованиям', '');
|
||||
lines.push(
|
||||
...renderList(
|
||||
relations,
|
||||
(item) => `[${text(item['target'])}](../requirements/${text(item['target'])}.md)`,
|
||||
),
|
||||
'',
|
||||
);
|
||||
const sources = Array.isArray(antipattern['sources']) ? antipattern['sources'] : [];
|
||||
lines.push('## Происхождение', '');
|
||||
lines.push(...renderList(sources, sourceLine), '');
|
||||
return lines.join('\n');
|
||||
}
|
||||
|
||||
export function renderSpec(root: string): RenderResult {
|
||||
const diagnostics: Diagnostic[] = [];
|
||||
const domains = loadDocs(root, 'domains', diagnostics);
|
||||
const capabilities = loadDocs(root, 'capabilities', diagnostics);
|
||||
const requirements = loadDocs(root, 'requirements', diagnostics);
|
||||
const antipatterns = loadDocs(root, 'antipatterns', diagnostics);
|
||||
const files: RenderedFile[] = [
|
||||
{ path: 'index.md', content: renderIndex(domains, capabilities, requirements) },
|
||||
];
|
||||
for (const id of sortedIds(requirements)) {
|
||||
const doc = requirements[id];
|
||||
if (doc !== undefined) {
|
||||
files.push({ path: `requirements/${id}.md`, content: renderRequirement(doc) });
|
||||
}
|
||||
}
|
||||
for (const id of sortedIds(antipatterns)) {
|
||||
const doc = antipatterns[id];
|
||||
if (doc !== undefined) {
|
||||
files.push({ path: `antipatterns/${id}.md`, content: renderAntipattern(doc) });
|
||||
}
|
||||
}
|
||||
return { ok: diagnostics.length === 0, files, diagnostics };
|
||||
}
|
||||
Reference in New Issue
Block a user