feat: spec list/show и manifest validate (BHL-022)

- bhl spec list [--domain|--capability], spec show <req-id> (NOT_FOUND)
- bhl manifest validate: схема + висячие профили/параметры/требования,
  неутверждённое исключение отклоняется
- e2e-тесты на examples/synthetic-spec; пакет 29/29
This commit is contained in:
Suslov-MD
2026-11-29 00:37:52 +03:00
parent f04c4b6481
commit 224ea16ae5
6 changed files with 766 additions and 10 deletions
+158 -2
View File
@@ -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 <version|validate|spec|profile|report|audit> [args]; ' +
'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>]; ' +
'profile resolve <spec-root> [--profile <id>] [--preset <id>]; ' +
'report validate <report.json> [--spec-root <path>]; ' +
'manifest validate <manifest.yaml> [--spec-root <path>]; ' +
'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<string, unknown>,
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;
}
+361
View File
@@ -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<string, unknown> | 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<string, unknown> {
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<string, Record<string, unknown>> {
const docs: Record<string, Record<string, unknown>> = {};
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<string, unknown>): 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<string, unknown>,
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<string> {
const ids = new Set<string>();
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<string>): 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<string>): 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<string> {
const ids = new Set<string>();
collectRegistryParams(root, diagnostics, ids);
collectInlineParams(root, diagnostics, ids);
return ids;
}
function asItems(manifest: Record<string, unknown>, key: string): readonly unknown[] {
const value = manifest[key];
return Array.isArray(value) ? value : [];
}
function checkSelectedProfiles(
manifest: Record<string, unknown>,
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<string, unknown>,
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<string, unknown>,
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<string, unknown>,
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<string, unknown> | 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 };
}