- bhl fetch/verify: lock.json (sha256 байтов, без LF-нормализации), несовпадение суммы прерывает использование артефакта - missing-file/unexpected-file/missing-cache — явные диагностики - офлайн validate зафиксированной версии после загрузки (тест) - validate.ts: Ajv strict-отказ и битый JSON — диагностики вместо crash - пакет: 36/36 тестов
595 lines
17 KiB
TypeScript
595 lines
17 KiB
TypeScript
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 Indexes {
|
|
domains: Set<string>;
|
|
capabilities: Map<string, string>;
|
|
requirements: Set<string>;
|
|
antipatterns: Set<string>;
|
|
}
|
|
|
|
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' },
|
|
{ dir: 'antipatterns', schema: 'antipattern' },
|
|
];
|
|
|
|
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 addSchemaFile(schemasDir: string, name: string): void {
|
|
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');
|
|
return;
|
|
}
|
|
let parsed: unknown;
|
|
try {
|
|
parsed = JSON.parse(text);
|
|
} catch {
|
|
this.push(file, 'parse-error', 'schema file is not valid JSON');
|
|
return;
|
|
}
|
|
if (!isSchema(parsed)) {
|
|
this.push(file, 'parse-error', 'schema must be an object or boolean');
|
|
return;
|
|
}
|
|
try {
|
|
this.ajv.addSchema(parsed);
|
|
} catch {
|
|
this.push(file, 'schema-error', 'schema is rejected by Ajv strict mode');
|
|
}
|
|
}
|
|
|
|
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) {
|
|
this.addSchemaFile(schemasDir, name);
|
|
}
|
|
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[]): Indexes {
|
|
const indexes: Indexes = {
|
|
domains: new Set<string>(),
|
|
capabilities: new Map<string, string>(),
|
|
requirements: new Set<string>(),
|
|
antipatterns: new Set<string>(),
|
|
};
|
|
for (const doc of docs) {
|
|
this.indexDoc(doc, indexes);
|
|
}
|
|
return indexes;
|
|
}
|
|
|
|
private indexDoc(doc: Doc, indexes: Indexes): void {
|
|
const id = doc.value['id'];
|
|
if (typeof id !== 'string') {
|
|
return;
|
|
}
|
|
switch (doc.kind) {
|
|
case 'domain': {
|
|
indexes.domains.add(id);
|
|
break;
|
|
}
|
|
case 'requirement': {
|
|
indexes.requirements.add(id);
|
|
break;
|
|
}
|
|
case 'antipattern': {
|
|
indexes.antipatterns.add(id);
|
|
break;
|
|
}
|
|
case 'capability': {
|
|
const domain = doc.value['domain'];
|
|
if (typeof domain === 'string') {
|
|
indexes.capabilities.set(id, domain);
|
|
}
|
|
break;
|
|
}
|
|
default: {
|
|
break;
|
|
}
|
|
}
|
|
}
|
|
|
|
private checkReferences(docs: Doc[], changelog: Changelog | undefined): void {
|
|
const indexes = this.buildIndexes(docs);
|
|
for (const doc of docs) {
|
|
this.checkDocReferences(doc, indexes);
|
|
}
|
|
if (changelog !== undefined) {
|
|
this.checkChangelogReferences(changelog, indexes.requirements);
|
|
}
|
|
}
|
|
|
|
private checkDocReferences(doc: Doc, indexes: Indexes): void {
|
|
if (doc.kind === 'capability') {
|
|
this.checkCapability(doc, indexes.domains);
|
|
return;
|
|
}
|
|
if (doc.kind === 'requirement') {
|
|
this.checkRequirement(
|
|
doc,
|
|
indexes.domains,
|
|
indexes.capabilities,
|
|
indexes.requirements,
|
|
indexes.antipatterns,
|
|
);
|
|
return;
|
|
}
|
|
if (doc.kind === 'antipattern') {
|
|
this.checkAntipattern(doc, indexes.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>,
|
|
antipatterns: Set<string>,
|
|
): void {
|
|
this.checkRequirementTargets(doc, domains, capabilities);
|
|
this.checkRequirementRelations(doc, requirements);
|
|
this.checkRequirementAntipatterns(doc, antipatterns);
|
|
}
|
|
|
|
private checkRequirementAntipatterns(doc: Doc, antipatterns: Set<string>): void {
|
|
const items = doc.value['antipatterns'];
|
|
if (!Array.isArray(items)) {
|
|
return;
|
|
}
|
|
const known: readonly unknown[] = items;
|
|
for (const item of known) {
|
|
if (typeof item === 'string' && !antipatterns.has(item)) {
|
|
this.push(doc.file, 'unknown-antipattern', `antipattern ${item} is not defined`);
|
|
}
|
|
}
|
|
}
|
|
|
|
private checkAntipattern(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',
|
|
`antipattern contradicts undefined requirement ${target}`,
|
|
);
|
|
}
|
|
}
|
|
}
|
|
|
|
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();
|
|
}
|