feat: каркас bhl и валидатор спецификации (BHL-020, BHL-011)
packages/bhl: @baseline-harness/bhl 0.0.1 — детерминированный CLI без LLM/оркестрации/сервера/БД; JSON-конверт и коды выхода 0/1/2/3/4 задокументированы и закреплены тестами. validate: Ajv 2020-12 по схемам <root>/schemas, семантическая сверка ID, ссылок, RFC-2119 слов и циклов depends-on. Местный строгий gate (prettier, eslint --max-warnings 0, tsc strict) зелёный: 10 тестов.
This commit is contained in:
@@ -0,0 +1,503 @@
|
||||
import { existsSync, readdirSync, readFileSync } from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { Ajv2020 } from 'ajv/dist/2020.js';
|
||||
import type { Schema } from 'ajv';
|
||||
import { parseDocument } from 'yaml';
|
||||
|
||||
export interface Diagnostic {
|
||||
file: string;
|
||||
pointer?: string;
|
||||
code: string;
|
||||
message: string;
|
||||
}
|
||||
|
||||
export interface ValidateResult {
|
||||
ok: boolean;
|
||||
files: number;
|
||||
diagnostics: Diagnostic[];
|
||||
}
|
||||
|
||||
interface Doc {
|
||||
kind: string;
|
||||
file: string;
|
||||
value: Record<string, unknown>;
|
||||
}
|
||||
|
||||
interface Changelog {
|
||||
entries: Doc[];
|
||||
}
|
||||
|
||||
const ENTITY_DIRS: readonly { dir: string; schema: string }[] = [
|
||||
{ dir: 'domains', schema: 'domain' },
|
||||
{ dir: 'capabilities', schema: 'capability' },
|
||||
{ dir: 'requirements', schema: 'requirement' },
|
||||
{ dir: 'parameters', schema: 'parameter' },
|
||||
];
|
||||
|
||||
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 readYamlDoc(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) {
|
||||
const first = doc.errors[0];
|
||||
diagnostics.push({
|
||||
file,
|
||||
code: 'parse-error',
|
||||
message: `YAML error at line ${String(first?.linePos?.[0]?.line ?? 1)}: ${first?.message ?? 'invalid'}`,
|
||||
});
|
||||
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[] {
|
||||
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 keywordOk(statement: string, level: string): boolean {
|
||||
if (level === 'MUST') {
|
||||
return /\bMUST\b(?! NOT)/.test(statement);
|
||||
}
|
||||
if (level === 'MUST NOT') {
|
||||
return /\bMUST NOT\b/.test(statement);
|
||||
}
|
||||
if (level === 'SHOULD') {
|
||||
return /\bSHOULD\b(?! NOT)/.test(statement);
|
||||
}
|
||||
if (level === 'SHOULD NOT') {
|
||||
return /\bSHOULD NOT\b/.test(statement);
|
||||
}
|
||||
if (level === 'MAY') {
|
||||
return /\bMAY\b/.test(statement);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
class Validator {
|
||||
private readonly ajv = new Ajv2020({ strict: true, strictTypes: false, allErrors: true });
|
||||
private readonly diagnostics: Diagnostic[] = [];
|
||||
private readonly idsSeen = new Map<string, string>();
|
||||
private files = 0;
|
||||
private readonly root: string;
|
||||
|
||||
constructor(root: string) {
|
||||
this.root = root;
|
||||
}
|
||||
|
||||
run(): ValidateResult {
|
||||
if (this.addSchemas()) {
|
||||
const docs = this.loadEntityDocs();
|
||||
const changelog = this.loadChangelog();
|
||||
this.checkUniqueIds([...docs, ...(changelog?.entries ?? [])]);
|
||||
this.checkReferences(docs, changelog);
|
||||
this.checkKeywords(docs);
|
||||
this.checkCycles(docs);
|
||||
}
|
||||
return {
|
||||
ok: this.diagnostics.length === 0,
|
||||
files: this.files,
|
||||
diagnostics: this.diagnostics,
|
||||
};
|
||||
}
|
||||
|
||||
private push(file: string, code: string, message: string, pointer?: string): void {
|
||||
const item: Diagnostic =
|
||||
pointer === undefined ? { file, code, message } : { file, pointer, code, message };
|
||||
this.diagnostics.push(item);
|
||||
}
|
||||
|
||||
private addSchemas(): boolean {
|
||||
const schemasDir = path.join(this.root, 'schemas');
|
||||
if (!existsSync(schemasDir)) {
|
||||
this.push(
|
||||
'schemas/',
|
||||
'missing-directory',
|
||||
'spec root must contain schemas/ with *.schema.json',
|
||||
);
|
||||
return false;
|
||||
}
|
||||
const names = readdirSync(schemasDir)
|
||||
.filter((n) => n.endsWith('.schema.json'))
|
||||
.sort((a, b) => a.localeCompare(b));
|
||||
if (names.length === 0) {
|
||||
this.push('schemas/', 'missing-schema', 'no *.schema.json found');
|
||||
return false;
|
||||
}
|
||||
for (const name of names) {
|
||||
const file = `schemas/${name}`;
|
||||
let text: string;
|
||||
try {
|
||||
text = readFileSync(path.join(schemasDir, name), 'utf8');
|
||||
} catch {
|
||||
this.push(file, 'read-error', 'schema file is not readable');
|
||||
continue;
|
||||
}
|
||||
const parsed: unknown = JSON.parse(text);
|
||||
if (isSchema(parsed)) {
|
||||
this.ajv.addSchema(parsed);
|
||||
} else {
|
||||
this.push(file, 'parse-error', 'schema must be an object or boolean');
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
private schemaValidate(doc: Doc): void {
|
||||
const validateFn = this.ajv.getSchema(`${SCHEMA_BASE}${doc.kind}.schema.json`);
|
||||
if (validateFn === undefined) {
|
||||
this.push(doc.file, 'missing-schema', `schema ${doc.kind} is not loaded`);
|
||||
return;
|
||||
}
|
||||
if (validateFn(doc.value) === true) {
|
||||
return;
|
||||
}
|
||||
for (const err of validateFn.errors ?? []) {
|
||||
const where = err.instancePath === '' ? '/' : err.instancePath;
|
||||
this.push(
|
||||
doc.file,
|
||||
'schema-error',
|
||||
`${where}: ${err.message ?? 'invalid'}`,
|
||||
err.instancePath,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
private loadEntityDocs(): Doc[] {
|
||||
const docs: Doc[] = [];
|
||||
for (const spec of ENTITY_DIRS) {
|
||||
const dir = path.join(this.root, spec.dir);
|
||||
if (!existsSync(dir)) {
|
||||
this.push(`${spec.dir}/`, 'missing-directory', `directory ${spec.dir}/ is required`);
|
||||
continue;
|
||||
}
|
||||
for (const file of yamlFiles(dir)) {
|
||||
this.files += 1;
|
||||
const value = readYamlDoc(file, this.diagnostics);
|
||||
if (isRecord(value)) {
|
||||
const doc: Doc = { kind: spec.schema, file, value };
|
||||
this.schemaValidate(doc);
|
||||
this.collectInlineParameters(doc, spec.schema);
|
||||
docs.push(doc);
|
||||
} else if (value !== undefined) {
|
||||
this.push(file, 'parse-error', 'top level must be a mapping');
|
||||
}
|
||||
}
|
||||
}
|
||||
return docs;
|
||||
}
|
||||
|
||||
private collectInlineParameters(doc: Doc, kind: string): void {
|
||||
if (kind !== 'requirement') {
|
||||
return;
|
||||
}
|
||||
const parameters = doc.value['parameters'];
|
||||
if (!Array.isArray(parameters)) {
|
||||
return;
|
||||
}
|
||||
const items: readonly unknown[] = parameters;
|
||||
for (const [index, item] of items.entries()) {
|
||||
if (isRecord(item)) {
|
||||
this.schemaValidate({
|
||||
kind: 'parameter',
|
||||
file: `${doc.file}#parameters[${String(index)}]`,
|
||||
value: item,
|
||||
});
|
||||
} else {
|
||||
this.push(
|
||||
`${doc.file}#parameters[${String(index)}]`,
|
||||
'schema-error',
|
||||
'parameter must be a mapping',
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private loadChangelog(): Changelog | undefined {
|
||||
const file = path.join(this.root, 'CHANGELOG.yaml');
|
||||
if (!existsSync(file)) {
|
||||
this.push('CHANGELOG.yaml', 'missing-file', 'canonical normative change log is required');
|
||||
return undefined;
|
||||
}
|
||||
this.files += 1;
|
||||
const value = readYamlDoc(file, this.diagnostics);
|
||||
if (!isRecord(value)) {
|
||||
if (!this.diagnostics.some((item) => item.file === file)) {
|
||||
this.push(file, 'parse-error', 'top level must be a mapping');
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
const changes = value['changes'];
|
||||
if (!Array.isArray(changes)) {
|
||||
this.push(file, 'schema-error', 'changes must be an array');
|
||||
return undefined;
|
||||
}
|
||||
const items: readonly unknown[] = changes;
|
||||
const entries: Doc[] = [];
|
||||
for (const [index, item] of items.entries()) {
|
||||
const where = `${file}#changes[${String(index)}]`;
|
||||
if (isRecord(item)) {
|
||||
const doc: Doc = { kind: 'normative-change', file: where, value: item };
|
||||
this.schemaValidate(doc);
|
||||
entries.push(doc);
|
||||
} else {
|
||||
this.push(where, 'schema-error', 'each change must be a mapping');
|
||||
}
|
||||
}
|
||||
return { entries };
|
||||
}
|
||||
|
||||
private checkUniqueIds(all: Doc[]): void {
|
||||
for (const doc of all) {
|
||||
const id = doc.value['id'];
|
||||
if (typeof id !== 'string') {
|
||||
continue;
|
||||
}
|
||||
const previous = this.idsSeen.get(id);
|
||||
if (previous !== undefined) {
|
||||
this.push(doc.file, 'duplicate-id', `id ${id} already defined in ${previous}`);
|
||||
} else {
|
||||
this.idsSeen.set(id, doc.file);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private buildIndexes(docs: Doc[]): {
|
||||
domains: Set<string>;
|
||||
capabilities: Map<string, string>;
|
||||
requirements: Set<string>;
|
||||
} {
|
||||
const domains = new Set<string>();
|
||||
const capabilities = new Map<string, string>();
|
||||
const requirements = new Set<string>();
|
||||
for (const doc of docs) {
|
||||
const id = doc.value['id'];
|
||||
if (typeof id !== 'string') {
|
||||
continue;
|
||||
}
|
||||
if (doc.kind === 'domain') {
|
||||
domains.add(id);
|
||||
}
|
||||
if (doc.kind === 'requirement') {
|
||||
requirements.add(id);
|
||||
}
|
||||
if (doc.kind === 'capability' && typeof doc.value['domain'] === 'string') {
|
||||
capabilities.set(id, doc.value['domain']);
|
||||
}
|
||||
}
|
||||
return { domains, capabilities, requirements };
|
||||
}
|
||||
|
||||
private checkReferences(docs: Doc[], changelog: Changelog | undefined): void {
|
||||
const { domains, capabilities, requirements } = this.buildIndexes(docs);
|
||||
for (const doc of docs) {
|
||||
if (doc.kind === 'capability') {
|
||||
this.checkCapability(doc, domains);
|
||||
}
|
||||
if (doc.kind === 'requirement') {
|
||||
this.checkRequirement(doc, domains, capabilities, requirements);
|
||||
}
|
||||
}
|
||||
if (changelog !== undefined) {
|
||||
this.checkChangelogReferences(changelog, requirements);
|
||||
}
|
||||
}
|
||||
|
||||
private checkChangelogReferences(changelog: Changelog, requirements: Set<string>): void {
|
||||
for (const entry of changelog.entries) {
|
||||
const targets = entry.value['requirements'];
|
||||
if (!Array.isArray(targets)) {
|
||||
continue;
|
||||
}
|
||||
const items: readonly unknown[] = targets;
|
||||
for (const target of items) {
|
||||
if (typeof target === 'string' && !requirements.has(target)) {
|
||||
this.push(
|
||||
entry.file,
|
||||
'unknown-requirement',
|
||||
`change references undefined requirement ${target}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private checkCapability(doc: Doc, domains: Set<string>): void {
|
||||
const domain = doc.value['domain'];
|
||||
if (typeof domain === 'string' && !domains.has(domain)) {
|
||||
this.push(doc.file, 'missing-domain', `domain ${domain} is not defined`);
|
||||
}
|
||||
}
|
||||
|
||||
private checkRequirement(
|
||||
doc: Doc,
|
||||
domains: Set<string>,
|
||||
capabilities: Map<string, string>,
|
||||
requirements: Set<string>,
|
||||
): void {
|
||||
this.checkRequirementTargets(doc, domains, capabilities);
|
||||
this.checkRequirementRelations(doc, requirements);
|
||||
}
|
||||
|
||||
private checkRequirementTargets(
|
||||
doc: Doc,
|
||||
domains: Set<string>,
|
||||
capabilities: Map<string, string>,
|
||||
): void {
|
||||
const domain = doc.value['domain'];
|
||||
const capability = doc.value['capability'];
|
||||
if (typeof domain === 'string' && !domains.has(domain)) {
|
||||
this.push(doc.file, 'missing-domain', `domain ${domain} is not defined`);
|
||||
}
|
||||
if (typeof capability !== 'string') {
|
||||
return;
|
||||
}
|
||||
const capabilityDomain = capabilities.get(capability);
|
||||
if (capabilityDomain === undefined) {
|
||||
this.push(doc.file, 'missing-capability', `capability ${capability} is not defined`);
|
||||
} else if (typeof domain === 'string' && capabilityDomain !== domain) {
|
||||
this.push(
|
||||
doc.file,
|
||||
'domain-mismatch',
|
||||
`capability ${capability} belongs to ${capabilityDomain}, not ${domain}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
private checkRequirementRelations(doc: Doc, requirements: Set<string>): void {
|
||||
const relations = doc.value['relations'];
|
||||
if (!Array.isArray(relations)) {
|
||||
return;
|
||||
}
|
||||
const items: readonly unknown[] = relations;
|
||||
for (const relation of items) {
|
||||
if (!isRecord(relation)) {
|
||||
continue;
|
||||
}
|
||||
const target = relation['target'];
|
||||
if (typeof target === 'string' && !requirements.has(target)) {
|
||||
this.push(
|
||||
doc.file,
|
||||
'unknown-requirement',
|
||||
`relation targets undefined requirement ${target}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private checkKeywords(docs: Doc[]): void {
|
||||
for (const doc of docs) {
|
||||
if (doc.kind !== 'requirement') {
|
||||
continue;
|
||||
}
|
||||
const statement = doc.value['statement'];
|
||||
const level = doc.value['level'];
|
||||
if (typeof statement !== 'string' || typeof level !== 'string') {
|
||||
continue;
|
||||
}
|
||||
if (!keywordOk(statement, level)) {
|
||||
this.push(
|
||||
doc.file,
|
||||
'keyword-mismatch',
|
||||
`statement does not contain the ${level} keyword it declares`,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private checkCycles(docs: Doc[]): void {
|
||||
const { edges, files } = this.buildDependsEdges(docs);
|
||||
const state = new Map<string, number>();
|
||||
const stack: string[] = [];
|
||||
const visit = (id: string): void => {
|
||||
const mark = state.get(id) ?? 0;
|
||||
if (mark === 1) {
|
||||
const start = stack.indexOf(id);
|
||||
const cycle = stack.slice(start).concat(id);
|
||||
this.push(
|
||||
files.get(id) ?? 'spec',
|
||||
'dependency-cycle',
|
||||
`depends-on cycle: ${cycle.join(' -> ')}`,
|
||||
);
|
||||
return;
|
||||
}
|
||||
if (mark === 2) {
|
||||
return;
|
||||
}
|
||||
state.set(id, 1);
|
||||
stack.push(id);
|
||||
for (const next of edges.get(id) ?? []) {
|
||||
visit(next);
|
||||
}
|
||||
stack.pop();
|
||||
state.set(id, 2);
|
||||
};
|
||||
for (const id of edges.keys()) {
|
||||
visit(id);
|
||||
}
|
||||
}
|
||||
|
||||
private buildDependsEdges(docs: Doc[]): {
|
||||
edges: Map<string, string[]>;
|
||||
files: Map<string, string>;
|
||||
} {
|
||||
const edges = new Map<string, string[]>();
|
||||
const files = new Map<string, string>();
|
||||
for (const doc of docs) {
|
||||
if (doc.kind !== 'requirement') {
|
||||
continue;
|
||||
}
|
||||
const id = doc.value['id'];
|
||||
if (typeof id !== 'string') {
|
||||
continue;
|
||||
}
|
||||
files.set(id, doc.file);
|
||||
edges.set(id, this.dependsTargets(doc));
|
||||
}
|
||||
return { edges, files };
|
||||
}
|
||||
|
||||
private dependsTargets(doc: Doc): string[] {
|
||||
const relations = doc.value['relations'];
|
||||
if (!Array.isArray(relations)) {
|
||||
return [];
|
||||
}
|
||||
const items: readonly unknown[] = relations;
|
||||
const list: string[] = [];
|
||||
for (const relation of items) {
|
||||
if (!isRecord(relation) || relation['kind'] !== 'depends-on') {
|
||||
continue;
|
||||
}
|
||||
if (typeof relation['target'] === 'string') {
|
||||
list.push(relation['target']);
|
||||
}
|
||||
}
|
||||
return list;
|
||||
}
|
||||
}
|
||||
|
||||
export function validateSpec(root: string): ValidateResult {
|
||||
return new Validator(root).run();
|
||||
}
|
||||
Reference in New Issue
Block a user