From 224ea16ae57f5eaeb619a3320ffa8ae3e7d1f1bb Mon Sep 17 00:00:00 2001 From: Suslov-MD Date: Sun, 29 Nov 2026 00:37:52 +0300 Subject: [PATCH] =?UTF-8?q?feat:=20spec=20list/show=20=D0=B8=20manifest=20?= =?UTF-8?q?validate=20(BHL-022)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - bhl spec list [--domain|--capability], spec show (NOT_FOUND) - bhl manifest validate: схема + висячие профили/параметры/требования, неутверждённое исключение отклоняется - e2e-тесты на examples/synthetic-spec; пакет 29/29 --- ...lidate-profile-resolve-и-spec-list-show.md | 27 +- packages/bhl/src/cli.ts | 160 +++++++- packages/bhl/src/spec.ts | 361 ++++++++++++++++++ packages/bhl/tests/cli.test.mjs | 2 +- packages/bhl/tests/spec.test.mjs | 209 ++++++++++ tests/synthetic-spec.test.mjs | 17 + 6 files changed, 766 insertions(+), 10 deletions(-) create mode 100644 packages/bhl/src/spec.ts create mode 100644 packages/bhl/tests/spec.test.mjs diff --git a/backlog/tasks/bhl-022 - Реализовать-validate-profile-resolve-и-spec-list-show.md b/backlog/tasks/bhl-022 - Реализовать-validate-profile-resolve-и-spec-list-show.md index c23452c..4833ef0 100644 --- a/backlog/tasks/bhl-022 - Реализовать-validate-profile-resolve-и-spec-list-show.md +++ b/backlog/tasks/bhl-022 - Реализовать-validate-profile-resolve-и-spec-list-show.md @@ -1,9 +1,10 @@ --- id: BHL-022 title: Реализовать validate, profile resolve и spec list/show -status: To Do +status: Done assignee: [] created_date: '2026-11-28T14:25:47Z' +updated_date: '2026-11-28T21:37:52Z' labels: [] milestone: m-2 dependencies: @@ -27,14 +28,26 @@ ordinal: 22000 ## Acceptance Criteria -- [ ] #1 Команды validate/resolve/spec list|show работают на синтетической спецификации -- [ ] #2 Effective Specification объясняет происхождение каждого требования +- [x] #1 Команды validate/resolve/spec list|show работают на синтетической спецификации +- [x] #2 Effective Specification объясняет происхождение каждого требования ## Definition of Done -- [ ] #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 актуально: прогресс, блокеры, следующий шаг + +## Comments + + +created: 2026-11-28T21:37:52Z + +--- + +CLI-трио замкнуто: validate и profile resolve были готовы ранее; добавлены spec list (--domain/--capability), spec show (NOT_FOUND для отсутствующих), manifest validate (схема project-manifest + висячие профили/параметры/требования исключений + неутверждённое исключение). Все команды проходят на examples/synthetic-spec; Effective Specification несёт sources и applicability (AC#2 BHL-022 подтверждён тестом). Пакет 29/29, корень зелёный. + +--- + diff --git a/packages/bhl/src/cli.ts b/packages/bhl/src/cli.ts index fbfafa7..8e3bea7 100644 --- a/packages/bhl/src/cli.ts +++ b/packages/bhl/src/cli.ts @@ -1,13 +1,17 @@ import { readFileSync } from 'node:fs'; import { emit, ExitCode, failEnvelope, okEnvelope } from './envelope.ts'; import { resolveProfiles } from './resolve.ts'; +import { specList, specShow, validateManifest } from './spec.ts'; import { validateReport } from './report.ts'; import { validateSpec } from './validate.ts'; const USAGE_MESSAGE = - 'Usage: bhl [args]; ' + + 'Usage: bhl [args]; ' + + 'spec list [--spec-root ] [--domain ] [--capability ]; ' + + 'spec show [--spec-root ]; ' + 'profile resolve [--profile ] [--preset ]; ' + 'report validate [--spec-root ]; ' + + 'manifest validate [--spec-root ]; ' + 'JSON envelope on stdout; exit codes: 0 ok, 1 validation failed, 2 usage, ' + '3 not implemented, 4 internal.'; @@ -169,6 +173,152 @@ function parseReportArgs( return { file: positional[0] ?? '', specRoot }; } +interface SpecFlags { + root: string; + domain?: string; + capability?: string; + positional: string[]; +} + +function takeNamedFlag( + args: readonly string[], + cursor: number, + target: SpecFlags, + arg: string, +): { next: number } | { error: string } { + const value = args[cursor + 1]; + if (value === undefined) { + return { error: `missing value for ${arg}` }; + } + if (arg === '--spec-root') { + target.root = value; + } else if (arg === '--domain') { + target.domain = value; + } else { + target.capability = value; + } + return { next: cursor + 2 }; +} + +function parseSpecArgs(args: readonly string[]): SpecFlags | { error: string } { + const target: SpecFlags = { root: 'spec', positional: [] }; + let cursor = 0; + while (cursor < args.length) { + const arg = args[cursor] ?? ''; + if (arg === '--spec-root' || arg === '--domain' || arg === '--capability') { + const taken = takeNamedFlag(args, cursor, target, arg); + if ('error' in taken) { + return taken; + } + cursor = taken.next; + continue; + } + if (arg.startsWith('--')) { + return { error: `unknown flag ${arg}` }; + } + target.positional.push(arg); + cursor += 1; + } + return target; +} + +function emitValidationFailure( + command: string, + data: Record, + count: number, + code = 'VALIDATION_FAILED', +): number { + emit({ + ok: false, + command, + data, + error: { code, message: `${String(count)} diagnostic(s)` }, + }); + return ExitCode.ValidationFailed; +} + +function emitSpecList(parsed: SpecFlags): number { + const result = specList(parsed.root, parsed.domain, parsed.capability); + const data = { root: parsed.root, requirements: result.requirements, errors: result.diagnostics }; + if (!result.ok) { + return emitValidationFailure('spec', data, result.diagnostics.length); + } + emit(okEnvelope('spec', data)); + return ExitCode.Ok; +} + +function emitSpecShow(parsed: SpecFlags): number { + const id = parsed.positional[0]; + if (id === undefined || parsed.positional.length !== 1) { + emit(failEnvelope('spec', 'USAGE', 'spec show requires exactly one requirement id')); + return ExitCode.Usage; + } + const result = specShow(parsed.root, id); + if (!result.ok) { + const code = + result.diagnostics[0]?.code === 'unknown-requirement' ? 'NOT_FOUND' : 'VALIDATION_FAILED'; + return emitValidationFailure( + 'spec', + { root: parsed.root, errors: result.diagnostics }, + result.diagnostics.length, + code, + ); + } + emit(okEnvelope('spec', { root: parsed.root, requirement: result.requirement })); + 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')); + return ExitCode.Usage; + } + const parsed = parseSpecArgs(args); + if ('error' in parsed) { + emit(failEnvelope(command, 'USAGE', parsed.error)); + return ExitCode.Usage; + } + if (sub === 'list') { + return emitSpecList(parsed); + } + return emitSpecShow(parsed); +} + +function runManifest(command: string, rest: readonly string[]): number { + const [sub, ...args] = rest; + if (sub !== 'validate') { + emit(failEnvelope(command, 'USAGE', 'manifest requires the subcommand validate')); + return ExitCode.Usage; + } + const parsed = parseSpecArgs(args); + if ('error' in parsed) { + emit(failEnvelope(command, 'USAGE', parsed.error)); + return ExitCode.Usage; + } + const file = parsed.positional[0]; + if (file === undefined || parsed.positional.length !== 1) { + emit(failEnvelope(command, 'USAGE', 'manifest validate requires exactly one manifest file')); + return ExitCode.Usage; + } + const result = validateManifest(file, parsed.root); + const data = { file, spec_root: parsed.root, 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 runReport(command: string, rest: readonly string[]): number { const [sub, ...args] = rest; if (sub !== 'validate') { @@ -239,10 +389,16 @@ export function run(argv: readonly string[]): number { if (command === 'validate') { return runValidate(command, rest); } + if (command === 'spec') { + return runSpec(command, rest); + } + if (command === 'manifest') { + return runManifest(command, rest); + } if (command === 'report') { return runReport(command, rest); } - if (command === 'spec' || command === 'audit') { + if (command === 'audit') { emit(failEnvelope(command, 'NOT_IMPLEMENTED', `${command} is not implemented yet`)); return ExitCode.NotImplemented; } diff --git a/packages/bhl/src/spec.ts b/packages/bhl/src/spec.ts new file mode 100644 index 0000000..c550abb --- /dev/null +++ b/packages/bhl/src/spec.ts @@ -0,0 +1,361 @@ +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 SpecListResult { + ok: boolean; + requirements: SpecSummary[]; + diagnostics: Diagnostic[]; +} + +export interface SpecSummary { + id: string; + title: string; + level: string; + lifecycle: string; + domain: string; + capability: string; +} + +export interface SpecShowResult { + ok: boolean; + requirement?: Record | undefined; + diagnostics: Diagnostic[]; +} + +export interface ManifestResult { + ok: boolean; + diagnostics: Diagnostic[]; +} + +const SCHEMA_BASE = 'https://baseline-harness.dev/spec/schemas/'; + +function isRecord(value: unknown): value is Record { + 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 readYaml(file: string, diagnostics: Diagnostic[]): unknown { + let text: string; + try { + text = readFileSync(file, 'utf8'); + } catch { + diagnostics.push({ file, code: 'read-error', message: 'file is not readable' }); + return undefined; + } + try { + const doc = parseDocument(text, { prettyErrors: false, 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 yamlFiles(dir: string): string[] { + if (!existsSync(dir)) { + return []; + } + return readdirSync(dir, { withFileTypes: true }) + .filter((entry) => entry.isFile() && entry.name.endsWith('.yaml')) + .map((entry) => path.join(dir, entry.name)) + .sort((a, b) => a.localeCompare(b)); +} + +function loadRequirementDocs( + root: string, + diagnostics: Diagnostic[], +): Record> { + const docs: Record> = {}; + for (const file of yamlFiles(path.join(root, 'requirements'))) { + const value = readYaml(file, diagnostics); + if (!isRecord(value)) { + if (value !== undefined) { + diagnostics.push({ file, code: 'parse-error', message: 'top level must be a mapping' }); + } + continue; + } + const id = value['id']; + if (isString(id)) { + docs[id] = value; + } + } + return docs; +} + +function summaryOf(doc: Record): SpecSummary { + const lifecycle = + isRecord(doc['lifecycle']) && isString(doc['lifecycle']['status']) + ? doc['lifecycle']['status'] + : 'unknown'; + return { + id: isString(doc['id']) ? doc['id'] : '', + title: isString(doc['title']) ? doc['title'] : '', + level: isString(doc['level']) ? doc['level'] : '', + lifecycle, + domain: isString(doc['domain']) ? doc['domain'] : '', + capability: isString(doc['capability']) ? doc['capability'] : '', + }; +} + +function matchesFilter( + summary: SpecSummary, + domain: string | undefined, + capability: string | undefined, +): boolean { + if (domain !== undefined && summary.domain !== domain) { + return false; + } + return !(capability !== undefined && summary.capability !== capability); +} + +export function specList(root: string, domain?: string, capability?: string): SpecListResult { + const diagnostics: Diagnostic[] = []; + const docs = loadRequirementDocs(root, diagnostics); + const requirements = Object.values(docs) + .map(summaryOf) + .filter((summary) => matchesFilter(summary, domain, capability)) + .sort((a, b) => a.id.localeCompare(b.id)); + return { ok: diagnostics.length === 0, requirements, diagnostics }; +} + +export function specShow(root: string, id: string): SpecShowResult { + const diagnostics: Diagnostic[] = []; + const docs = loadRequirementDocs(root, diagnostics); + const requirement = docs[id]; + if (requirement === undefined && diagnostics.length === 0) { + diagnostics.push({ + file: root, + code: 'unknown-requirement', + message: `requirement ${id} is not defined`, + }); + } + return { ok: diagnostics.length === 0, requirement, diagnostics }; +} + +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 }); + const schemaFiles = 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)); + for (const file of schemaFiles) { + 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)) { + try { + ajv.addSchema(parsed); + } catch { + diagnostics.push({ + file, + code: 'schema-error', + message: 'schema is rejected by Ajv strict mode', + }); + } + } + } + return ajv; +} + +function validateAgainst( + ajv: Ajv2020, + kind: string, + value: Record, + file: string, + diagnostics: Diagnostic[], +): boolean { + const validateFn = ajv.getSchema(`${SCHEMA_BASE}${kind}.schema.json`); + if (validateFn === undefined) { + diagnostics.push({ file, code: 'missing-schema', message: `schema ${kind} is not loaded` }); + return false; + } + if (validateFn(value) === true) { + return true; + } + 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'}`, + }); + } + return false; +} + +function knownProfiles(root: string): Set { + const ids = new Set(); + for (const file of yamlFiles(path.join(root, 'profiles'))) { + const diagnostics: Diagnostic[] = []; + const value = readYaml(file, diagnostics); + if (isRecord(value) && isString(value['id'])) { + ids.add(value['id']); + } + } + return ids; +} + +function collectRegistryParams(root: string, diagnostics: Diagnostic[], ids: Set): void { + for (const file of yamlFiles(path.join(root, 'parameters'))) { + const value = readYaml(file, diagnostics); + if (isRecord(value) && isString(value['id'])) { + ids.add(value['id']); + } + } +} + +function collectInlineParams(root: string, diagnostics: Diagnostic[], ids: Set): void { + for (const doc of Object.values(loadRequirementDocs(root, diagnostics))) { + const items = Array.isArray(doc['parameters']) ? doc['parameters'] : []; + const known: readonly unknown[] = items; + for (const item of known) { + if (isRecord(item) && isString(item['id'])) { + ids.add(item['id']); + } + } + } +} + +function knownParameters(root: string, diagnostics: Diagnostic[]): Set { + const ids = new Set(); + collectRegistryParams(root, diagnostics, ids); + collectInlineParams(root, diagnostics, ids); + return ids; +} + +function asItems(manifest: Record, key: string): readonly unknown[] { + const value = manifest[key]; + return Array.isArray(value) ? value : []; +} + +function checkSelectedProfiles( + manifest: Record, + root: string, + file: string, + diagnostics: Diagnostic[], +): void { + const profiles = knownProfiles(root); + for (const item of asItems(manifest, 'profiles')) { + if (isString(item) && !profiles.has(item)) { + diagnostics.push({ + file, + code: 'unknown-profile', + message: `manifest selects undefined profile ${item}`, + }); + } + } +} + +function checkManifestOverrides( + manifest: Record, + root: string, + file: string, + diagnostics: Diagnostic[], +): void { + const parameters = knownParameters(root, diagnostics); + for (const item of asItems(manifest, 'parameter_overrides')) { + if (isRecord(item) && isString(item['parameter']) && !parameters.has(item['parameter'])) { + diagnostics.push({ + file, + code: 'unknown-parameter', + message: `override targets undefined parameter ${item['parameter']}`, + }); + } + } +} + +function checkManifestExceptions( + manifest: Record, + root: string, + file: string, + diagnostics: Diagnostic[], +): void { + const requirements = new Set(Object.keys(loadRequirementDocs(root, diagnostics))); + for (const item of asItems(manifest, 'exceptions')) { + if (isRecord(item) && isString(item['requirement']) && !requirements.has(item['requirement'])) { + diagnostics.push({ + file, + code: 'unknown-requirement', + message: `exception references undefined requirement ${item['requirement']}`, + }); + } + } +} + +function checkManifestReferences( + manifest: Record, + root: string, + file: string, + diagnostics: Diagnostic[], +): void { + checkSelectedProfiles(manifest, root, file, diagnostics); + checkManifestOverrides(manifest, root, file, diagnostics); + checkManifestExceptions(manifest, root, file, diagnostics); +} + +function readManifest( + file: string, + diagnostics: Diagnostic[], +): Record | undefined { + const value = readYaml(file, diagnostics); + if (isRecord(value)) { + return value; + } + if (value !== undefined) { + diagnostics.push({ + file, + code: 'parse-error', + message: 'manifest top level must be a mapping', + }); + } + return undefined; +} + +export function validateManifest(manifestFile: string, root: string): ManifestResult { + const diagnostics: Diagnostic[] = []; + const value = readManifest(manifestFile, diagnostics); + if (value === undefined) { + return { ok: false, diagnostics }; + } + const ajv = loadAjv(path.join(root, 'schemas'), diagnostics); + if (ajv === undefined) { + return { ok: false, diagnostics }; + } + if (validateAgainst(ajv, 'project-manifest', value, manifestFile, diagnostics)) { + checkManifestReferences(value, root, manifestFile, diagnostics); + } + diagnostics.sort((a, b) => `${a.file} ${a.code}`.localeCompare(`${b.file} ${b.code}`)); + return { ok: diagnostics.length === 0, diagnostics }; +} diff --git a/packages/bhl/tests/cli.test.mjs b/packages/bhl/tests/cli.test.mjs index b8ee414..9cb45fd 100644 --- a/packages/bhl/tests/cli.test.mjs +++ b/packages/bhl/tests/cli.test.mjs @@ -33,7 +33,7 @@ test('использование: пустой запуск, --help и неиз }); test('известные команды Wave D/E пока возвращают NOT_IMPLEMENTED и код 3', () => { - for (const command of ['spec', 'audit']) { + for (const command of ['audit']) { const result = run(command); assert.equal(result.code, 3, command); assert.equal(result.envelope.ok, false, command); diff --git a/packages/bhl/tests/spec.test.mjs b/packages/bhl/tests/spec.test.mjs new file mode 100644 index 0000000..69c206b --- /dev/null +++ b/packages/bhl/tests/spec.test.mjs @@ -0,0 +1,209 @@ +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 SCHEMAS = { + 'requirement.schema.json': { + $id: 'https://baseline-harness.dev/spec/schemas/requirement.schema.json', + type: 'object', + required: ['id', 'title', 'level', 'domain', 'capability', 'lifecycle'], + properties: { + id: { type: 'string', pattern: '^req-[a-z0-9-]+$' }, + title: { type: 'string' }, + level: { enum: ['MUST', 'MUST NOT', 'SHOULD', 'SHOULD NOT', 'MAY'] }, + domain: { type: 'string' }, + capability: { type: 'string' }, + lifecycle: { type: 'object' }, + parameters: { type: 'array' }, + }, + }, + 'parameter.schema.json': { + $id: 'https://baseline-harness.dev/spec/schemas/parameter.schema.json', + type: 'object', + required: ['id', 'type'], + properties: { id: { type: 'string', pattern: '^param-[a-z0-9-]+$' } }, + }, + 'profile.schema.json': { + $id: 'https://baseline-harness.dev/spec/schemas/profile.schema.json', + type: 'object', + required: ['id', 'requirements'], + properties: { id: { type: 'string', pattern: '^prof-[a-z0-9-]+$' } }, + }, + 'project-exception.schema.json': { + $id: 'https://baseline-harness.dev/spec/schemas/project-exception.schema.json', + type: 'object', + required: ['id', 'requirement', 'scope', 'reason', 'decision_ref', 'review_condition'], + properties: { + id: { type: 'string', pattern: '^ex-[a-z0-9-]+$' }, + requirement: { type: 'string', pattern: '^req-[a-z0-9-]+$' }, + scope: { type: 'object' }, + reason: { type: 'string' }, + decision_ref: { type: 'string', minLength: 3 }, + review_condition: { type: 'string' }, + }, + }, + 'project-manifest.schema.json': { + $id: 'https://baseline-harness.dev/spec/schemas/project-manifest.schema.json', + type: 'object', + required: ['project', 'spec_version', 'profiles'], + properties: { + project: { type: 'string' }, + spec_version: { type: 'string', pattern: '^\\d+\\.\\d+\\.\\d+(-[0-9A-Za-z.-]+)?$' }, + profiles: { type: 'array', items: { type: 'string' } }, + parameter_overrides: { type: 'array' }, + exceptions: { + type: 'array', + items: { $ref: 'https://baseline-harness.dev/spec/schemas/project-exception.schema.json' }, + }, + }, + }, +}; + +const EXCEPTION = + ' - id: ex-fixture-budget\n requirement: req-alpha\n scope:\n kind: path\n paths: [src/]\n description: Область исключения для тестов манифеста.\n reason: Параметр недоступен в тестовой фикстуре без исключения.\n decision_ref: D-099\n review_condition: Пересмотр при появлении параметра в фикстуре.\n'; + +const BASE_FILES = { + 'requirements/req-alpha.yaml': + 'id: req-alpha\ntitle: Альфа\ndomain: dom-build\ncapability: cap-verify\nlevel: MUST\nlifecycle:\n status: proposed\nparameters:\n - id: param-alpha-budget\n type: integer\n', + 'requirements/req-beta.yaml': + 'id: req-beta\ntitle: Бета\ndomain: dom-docs\ncapability: cap-write\nlevel: SHOULD\nlifecycle:\n status: proposed\n', + 'profiles/prof-fixture.yaml': 'id: prof-fixture\nrequirements:\n - requirement: req-alpha\n', + 'parameters/param-registry-mode.yaml': 'id: param-registry-mode\ntype: enum\n', + 'manifest.yaml': `project: fixture\nspec_version: 0.1.0\nprofiles: [prof-fixture]\nparameter_overrides:\n - parameter: param-registry-mode\n value: json\nexceptions:\n${EXCEPTION}`, +}; + +function fixture(t, overrides = {}) { + const root = mkdtempSync(path.join(os.tmpdir(), 'bhl-spec-')); + const files = { ...BASE_FILES, ...overrides }; + mkdirSync(path.join(root, 'schemas'), { recursive: true }); + for (const [name, schema] of Object.entries(SCHEMAS)) { + writeFileSync(path.join(root, 'schemas', name), JSON.stringify(schema), 'utf8'); + } + for (const [name, contents] of Object.entries(files)) { + const target = path.join(root, name); + mkdirSync(path.dirname(target), { recursive: true }); + writeFileSync(target, contents, 'utf8'); + } + t.after(() => rmSync(root, { recursive: true, force: true })); + return root; +} + +function runCli(...args) { + const proc = spawnSync(process.execPath, [cli, ...args], { encoding: 'utf8' }); + return { code: proc.status, envelope: JSON.parse(proc.stdout) }; +} + +function codes(result) { + return result.envelope.data.errors.map((item) => item.code); +} + +test('spec list: сортированный список и фильтр по возможности', (t) => { + const root = fixture(t); + const all = runCli('spec', 'list', '--spec-root', root); + assert.equal(all.code, 0); + assert.deepEqual( + all.envelope.data.requirements.map((item) => [ + item.id, + item.level, + item.lifecycle, + item.capability, + ]), + [ + ['req-alpha', 'MUST', 'proposed', 'cap-verify'], + ['req-beta', 'SHOULD', 'proposed', 'cap-write'], + ], + ); + const filtered = runCli('spec', 'list', '--spec-root', root, '--capability', 'cap-write'); + assert.deepEqual( + filtered.envelope.data.requirements.map((item) => item.id), + ['req-beta'], + ); +}); + +test('spec show: полный документ и NOT_FOUND для неизвестного ID', (t) => { + const root = fixture(t); + const shown = runCli('spec', 'show', 'req-alpha', '--spec-root', root); + assert.equal(shown.code, 0); + assert.equal(shown.envelope.data.requirement.title, 'Альфа'); + const ghost = runCli('spec', 'show', 'req-ghost', '--spec-root', root); + assert.equal(ghost.code, 1); + assert.equal(ghost.envelope.error.code, 'NOT_FOUND'); +}); + +test('manifest validate: валидный манифест проходит', (t) => { + const root = fixture(t); + const result = runCli( + 'manifest', + 'validate', + path.join(root, 'manifest.yaml'), + '--spec-root', + root, + ); + assert.equal(result.code, 0); + assert.deepEqual(result.envelope.data.errors, []); +}); + +test('manifest validate: висячие ссылки и неутверждённое исключение падают', (t) => { + const ghostProfile = fixture(t, { + 'manifest.yaml': BASE_FILES['manifest.yaml'].replace('prof-fixture]', 'prof-ghost]'), + }); + assert.ok( + codes( + runCli( + 'manifest', + 'validate', + path.join(ghostProfile, 'manifest.yaml'), + '--spec-root', + ghostProfile, + ), + ).includes('unknown-profile'), + ); + const ghostParam = fixture(t, { + 'manifest.yaml': BASE_FILES['manifest.yaml'].replace('param-registry-mode', 'param-ghost'), + }); + assert.ok( + codes( + runCli( + 'manifest', + 'validate', + path.join(ghostParam, 'manifest.yaml'), + '--spec-root', + ghostParam, + ), + ).includes('unknown-parameter'), + ); + const ghostReq = fixture(t, { + 'manifest.yaml': BASE_FILES['manifest.yaml'].replace('req-alpha\n', 'req-ghost\n'), + }); + assert.ok( + codes( + runCli('manifest', 'validate', path.join(ghostReq, 'manifest.yaml'), '--spec-root', ghostReq), + ).includes('unknown-requirement'), + ); + const unapproved = fixture(t, { + 'manifest.yaml': BASE_FILES['manifest.yaml'].replace('decision_ref: D-099', 'decision_ref: ""'), + }); + assert.ok( + codes( + runCli( + 'manifest', + 'validate', + path.join(unapproved, 'manifest.yaml'), + '--spec-root', + unapproved, + ), + ).includes('schema-error'), + ); +}); + +test('использование команд spec и manifest', () => { + assert.equal(runCli('spec').code, 2); + assert.equal(runCli('spec', 'show').code, 2); + assert.equal(runCli('manifest').code, 2); + assert.equal(runCli('manifest', 'validate').code, 2); +}); diff --git a/tests/synthetic-spec.test.mjs b/tests/synthetic-spec.test.mjs index 9cc4795..cd4739c 100644 --- a/tests/synthetic-spec.test.mjs +++ b/tests/synthetic-spec.test.mjs @@ -62,3 +62,20 @@ test('пример явно отмечен как инфраструктурны assert.ok(readme.includes('не является'), 'отметка о не-стандартности'); assert.ok(readme.includes('BHS 0.1.0'), 'ссылка на содержательную редакцию'); }); + +test('spec list и spec show работают на синтетической спецификации', () => { + const list = runCli('spec', 'list', '--spec-root', specRoot); + assert.equal(list.code, 0); + assert.deepEqual( + list.envelope.data.requirements.map((item) => item.id), + ['req-synth-alpha', 'req-synth-beta', 'req-synth-gamma'], + ); + const byDomain = runCli('spec', 'list', '--spec-root', specRoot, '--domain', 'dom-synth-build'); + assert.equal(byDomain.envelope.data.requirements.length, 3); + const shown = runCli('spec', 'show', 'req-synth-alpha', '--spec-root', specRoot); + assert.equal(shown.code, 0); + assert.equal(shown.envelope.data.requirement.level, 'MUST'); + const ghost = runCli('spec', 'show', 'req-ghost', '--spec-root', specRoot); + assert.equal(ghost.code, 1); + assert.equal(ghost.envelope.error.code, 'NOT_FOUND'); +});