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:
Suslov-MD
2026-11-28 20:31:24 +03:00
parent af81424fc2
commit 294bf9d68f
16 changed files with 3555 additions and 3 deletions
+1 -1
View File
@@ -1,6 +1,6 @@
# Принятые инструменты
Здесь будут находиться расширения и инструменты, которые владелец принял для использования. Сейчас таких пакетов в лаборатории ещё нет; [Pi Supervisor](../experiments/pi-supervisor/README.md) остаётся экспериментом.
Здесь будут находиться расширения и инструменты, которые владелец принял для использования. Сейчас опубликованных пакетов в лаборатории ещё нет; [Pi Supervisor](../experiments/pi-supervisor/README.md) остаётся экспериментом. В разработке: [`bhl`](bhl/README.md) — CLI стандарта BHS (`@baseline-harness/bhl`), создан в `packages/` напрямую по решению D-028; публикация — отдельное поручение (D-034).
Каждый `packages/<id>/` — самостоятельный комплект со своими зависимостями, lockfile, проверками, документацией запуска и версией. Для него должно быть понятно, что работает, какие ограничения сохраняются и каким [результатом](../results/README.md) подтверждена готовность. Принятие не означает доказанную эффективность во всех условиях.
+5
View File
@@ -0,0 +1,5 @@
{
"singleQuote": true,
"printWidth": 100,
"trailingComma": "all"
}
+7
View File
@@ -0,0 +1,7 @@
# bhl: местные инструкции
Код, зависимости, lockfile и проверки принадлежат этому каталогу; корневые команды их не запускают. Качество — `npm run quality` из этого каталога (format, lint `--max-warnings 0`, typecheck strict, тесты).
CLI детерминирован: одинаковые аргументы — идентичный stdout и код выхода; никаких неявных изменений рабочего дерева; вывод — один JSON-конверт (контракт в [README.md](README.md)). Команды, не покрытые реализацией, возвращают `NOT_IMPLEMENTED` (код 3), а не зелёную заглушку.
Схемы и журнал изменений спецификации — [spec/](../../spec/) лаборатории (SSOT); пакет их не копирует. Изменения контракта вывода и кодов выхода — только вместе с обновлением README и тестов.
+22
View File
@@ -0,0 +1,22 @@
# Профиль качества bhl
Область принятия практик: только этот пакет, его тесты и его конфиги. Основание — [work-harness](../../library/code-quality-practices/typescript/work-harness.md) через `experiments/pi-supervisor/eslint.config.mjs` (адаптация зафиксирована в комментарии конфига).
## Команды
- `npm run quality` — `format:check`, `lint` (`--max-warnings 0`), `typecheck` (strict, `noUncheckedIndexedAccess`, `exactOptionalPropertyTypes`, `erasableSyntaxOnly`), затем `node --test tests/`.
- Корневые `npm run check`/`npm test` этот пакет не проверяют; его проверки живут здесь.
## Обязательные свойства CLI
- Детерминизм: одинаковые аргументы — идентичный stdout и код выхода; проверка закреплена тестом.
- JSON-конверт и коды выхода задокументированы в [README.md](README.md) и не меняются без записи в журнале изменений пакета.
- Команда либо реализована с тестами, либо честно возвращает `NOT_IMPLEMENTED` (код 3); заглушек «зелёного» результата нет.
- CLI не вносит неявных изменений рабочего дерева; side effects только по явной команде.
- Строгие линтер и тип-check без ослаблений ради зелёного результата; исключения — только с причиной и узкой областью в конфиге.
## Что ещё не подтверждено
- Полезность CLI в рабочих аудиты не измерена (технический gate не доказывает полезность — принцип инвентаризации).
- Публичная упаковка и установка из реестра — BHL-028, до публикации контракт установки не объявляется.
- Производительность на больших спецификациях не измерялась.
+44
View File
@@ -0,0 +1,44 @@
# bhl — CLI Baseline Harness Standard
`@baseline-harness/bhl` — детерминированный CLI стандарта BHS: валидация спецификации и манифестов, разрешение профилей и параметров, структурированные отчёты аудита. Без LLM, оркестрации, сервера и обязательной базы данных (D-012). Пакет создан по D-028; статус — **в разработке** (BHL-020…BHL-028), не опубликован; публикация — отдельное поручение (D-034).
## Запуск
Требуется Node.js не ниже 22.19.0 (нативное выполнение TypeScript). Из каталога пакета:
```text
npm run bhl -- version
```
После публикации установка ожидается как `npm i -g @baseline-harness/bhl` или `npx @baseline-harness/bhl` (не проверено до публикации).
## Контракт вывода
Команды пишут один JSON-конверт в stdout и сигнализируют результат кодом выхода:
```json
{
"ok": true,
"command": "version",
"data": { "name": "@baseline-harness/bhl", "version": "0.0.1", "args": [] }
}
```
Ошибки — тот же конверт с `ok: false` и полем `error: { code, message }`. Коды выхода: `0` — успех, `1` — валидация не прошла, `2` — ошибка использования, `3` — команда ещё не реализована (запланирована бэклогом), `4` — внутренняя ошибка. Повторный прогон тех же аргументов даёт идентичный вывод; неявных изменений рабочего дерева CLI не вносит.
## Команды
| Команда | Назначение | Статус |
|---|---|---|
| `version` | имя и версия пакета | работает |
| `validate` | валидация спецификации и манифеста | работает (BHL-011); манифест проекта — BHL-014 |
| `spec` | `list` / `show` требований | BHL-022 |
| `profile` | разрешение Effective Specification | BHL-022 |
| `report` | `validate` / `render` отчёта аудита | BHL-023, BHL-025 |
| `audit` | детерминированный аудит | BHL-026 |
## Зависимости и границы
Runtime-зависимости: `ajv` (JSON Schema 2020-12) и `yaml`. LLM-клиента, сети, сервера и БД у CLI нет; офлайн-работа после загрузки версий спецификации — требование BHL-021. Схемы спецификации живут в [spec/schemas](../../spec/schemas/) лаборатории; их версионирование — D-039.
Профиль качества и границы принятия — в [QUALITY.md](QUALITY.md).
+84
View File
@@ -0,0 +1,84 @@
import js from '@eslint/js';
import { defineConfig } from 'eslint/config';
import importX from 'eslint-plugin-import-x';
import sonarjs from 'eslint-plugin-sonarjs';
import globals from 'globals';
import tseslint from 'typescript-eslint';
// Adapted from ../../library/code-quality-practices/typescript/work-harness.md
// via experiments/pi-supervisor/eslint.config.mjs.
// Only this package, its tests and this config are in the adoption scope.
const files = ['src/**/*.ts', 'tests/**/*.{ts,mjs}', 'eslint.config.mjs'];
const typedFiles = ['src/**/*.ts', 'tests/**/*.ts'];
export default defineConfig(
{
files,
extends: [js.configs.recommended],
languageOptions: { globals: globals.node },
linterOptions: {
noInlineConfig: true,
reportUnusedDisableDirectives: 'error',
reportUnusedInlineConfigs: 'error',
},
rules: {
'array-callback-return': ['error', { checkForEach: true }],
eqeqeq: ['error', 'always'],
curly: ['error', 'all'],
'no-console': 'error',
'no-eval': 'error',
'no-implicit-coercion': 'error',
'no-promise-executor-return': 'error',
'no-return-assign': ['error', 'always'],
'no-unmodified-loop-condition': 'error',
'no-unreachable-loop': 'error',
'no-unsafe-optional-chaining': 'error',
'prefer-const': 'error',
'prefer-promise-reject-errors': 'error',
},
},
{
files: typedFiles,
extends: [
tseslint.configs.strictTypeChecked,
importX.flatConfigs.recommended,
importX.flatConfigs.typescript,
sonarjs.configs.recommended,
],
languageOptions: {
parserOptions: { projectService: true, tsconfigRootDir: import.meta.dirname },
},
settings: {
'import-x/resolver': { typescript: { project: './tsconfig.json' } },
},
rules: {
'@typescript-eslint/consistent-type-imports': [
'error',
{ fixStyle: 'separate-type-imports' },
],
'@typescript-eslint/consistent-type-exports': 'error',
'@typescript-eslint/consistent-type-assertions': ['error', { assertionStyle: 'never' }],
'@typescript-eslint/no-floating-promises': [
'error',
{ ignoreVoid: false, ignoreIIFE: false },
],
'@typescript-eslint/no-misused-promises': 'error',
'@typescript-eslint/strict-boolean-expressions': 'error',
'@typescript-eslint/switch-exhaustiveness-check': 'error',
'@typescript-eslint/no-shadow': 'error',
'@typescript-eslint/return-await': ['error', 'error-handling-correctness-only'],
'max-lines-per-function': [
'error',
{ max: 80, IIFEs: true, skipBlankLines: true, skipComments: true },
],
'sonarjs/cognitive-complexity': ['error', 10],
},
},
{
files: ['tests/**/*.ts'],
rules: {
// A scenario keeps setup, action and assertions together; production stays at 80.
'max-lines-per-function': 'off',
},
},
);
+2453
View File
File diff suppressed because it is too large Load Diff
+40
View File
@@ -0,0 +1,40 @@
{
"name": "@baseline-harness/bhl",
"version": "0.0.1",
"private": true,
"type": "module",
"description": "Детерминированный CLI Baseline Harness Standard: валидация, разрешение профилей, аудит",
"license": "UNLICENSED",
"bin": {
"bhl": "./src/cli.ts"
},
"engines": {
"node": ">=22.19.0"
},
"scripts": {
"bhl": "node src/cli.ts",
"check": "npm run format:check && npm run lint && npm run typecheck",
"test": "node --test \"tests/*.test.mjs\"",
"lint": "eslint --max-warnings 0 \"src/**/*.ts\" \"tests/**/*.{ts,mjs}\" eslint.config.mjs",
"typecheck": "tsc --project tsconfig.json",
"format:check": "prettier --check \"src/**/*.ts\" \"tests/**/*.{ts,mjs}\" eslint.config.mjs tsconfig.json .prettierrc.json",
"format": "prettier --write \"src/**/*.ts\" \"tests/**/*.{ts,mjs}\" eslint.config.mjs tsconfig.json .prettierrc.json",
"quality": "npm run check && npm test"
},
"dependencies": {
"ajv": "8.20.0",
"yaml": "2.9.1"
},
"devDependencies": {
"@eslint/js": "9.39.5",
"@types/node": "22.19.19",
"eslint": "9.39.5",
"eslint-import-resolver-typescript": "4.4.5",
"eslint-plugin-import-x": "4.17.1",
"eslint-plugin-sonarjs": "4.2.0",
"globals": "16.5.0",
"prettier": "3.6.2",
"typescript": "5.9.3",
"typescript-eslint": "8.65.0"
}
}
+90
View File
@@ -0,0 +1,90 @@
import { readFileSync } from 'node:fs';
import { emit, ExitCode, failEnvelope, okEnvelope } from './envelope.ts';
import { validateSpec } from './validate.ts';
interface PackageManifest {
name: string;
version: string;
}
const USAGE_MESSAGE =
'Usage: bhl <version|validate|spec|profile|report|audit> [args]; ' +
'JSON envelope on stdout; exit codes: 0 ok, 1 validation failed, 2 usage, ' +
'3 not implemented, 4 internal.';
const KNOWN: ReadonlySet<string> = new Set([
'version',
'validate',
'spec',
'profile',
'report',
'audit',
]);
function isRecord(value: unknown): value is Record<string, unknown> {
return typeof value === 'object' && value !== null;
}
function manifest(): PackageManifest {
const parsed: unknown = JSON.parse(
readFileSync(new URL('../package.json', import.meta.url), 'utf8'),
);
if (
!isRecord(parsed) ||
typeof parsed['name'] !== 'string' ||
typeof parsed['version'] !== 'string'
) {
throw new Error('package.json must carry string name and version');
}
return { name: parsed['name'], version: parsed['version'] };
}
export function run(argv: readonly string[]): number {
const [command, ...rest] = argv;
if (command === undefined || command === '-h' || command === '--help') {
emit(failEnvelope(command ?? '', 'USAGE', USAGE_MESSAGE));
return ExitCode.Usage;
}
if (!KNOWN.has(command)) {
emit(failEnvelope(command, 'USAGE', `Unknown command "${command}". ${USAGE_MESSAGE}`));
return ExitCode.Usage;
}
if (command === 'version') {
const { name, version } = manifest();
emit(okEnvelope(command, { name, version, args: rest }));
return ExitCode.Ok;
}
if (command === 'validate') {
const [target] = rest;
if (target === undefined) {
emit(failEnvelope(command, 'USAGE', 'validate requires a spec root path'));
return ExitCode.Usage;
}
const result = validateSpec(target);
const data = { root: target, files: result.files, 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;
}
emit(
failEnvelope(
command,
'NOT_IMPLEMENTED',
`Command "${command}" is scheduled by the laboratory backlog (Wave B/C).`,
),
);
return ExitCode.NotImplemented;
}
process.exitCode = run(process.argv.slice(2));
+33
View File
@@ -0,0 +1,33 @@
export interface EnvelopeError {
code: string;
message: string;
}
export interface Envelope {
ok: boolean;
command: string;
data?: Record<string, unknown>;
error?: EnvelopeError;
}
export const ExitCode = {
Ok: 0,
ValidationFailed: 1,
Usage: 2,
NotImplemented: 3,
Internal: 4,
} as const;
export type ExitCodeValue = (typeof ExitCode)[keyof typeof ExitCode];
export function okEnvelope(command: string, data: Record<string, unknown>): Envelope {
return { ok: true, command, data };
}
export function failEnvelope(command: string, code: string, message: string): Envelope {
return { ok: false, command, error: { code, message } };
}
export function emit(envelope: Envelope): void {
process.stdout.write(`${JSON.stringify(envelope, null, 2)}\n`);
}
+503
View File
@@ -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();
}
+42
View File
@@ -0,0 +1,42 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { spawnSync } from 'node:child_process';
import { readFileSync } from 'node:fs';
import path from 'node:path';
const cli = path.join(import.meta.dirname, '..', 'src', 'cli.ts');
const pkg = JSON.parse(readFileSync(path.join(import.meta.dirname, '..', 'package.json'), 'utf8'));
function run(...args) {
const proc = spawnSync(process.execPath, [cli, ...args], { encoding: 'utf8' });
return { code: proc.status, stdout: proc.stdout, envelope: JSON.parse(proc.stdout) };
}
test('version: стабильный JSON-конверт и код 0', () => {
const first = run('version');
assert.equal(first.code, 0);
assert.equal(first.envelope.ok, true);
assert.equal(first.envelope.command, 'version');
assert.equal(first.envelope.data.version, pkg.version);
assert.equal(first.envelope.data.name, '@baseline-harness/bhl');
const again = run('version');
assert.equal(again.stdout, first.stdout, 'повторный прогон даёт идентичный JSON');
});
test('использование: пустой запуск, --help и неизвестная команда — код 2', () => {
assert.equal(run().code, 2);
assert.equal(run('--help').code, 2);
const unknown = run('nope');
assert.equal(unknown.code, 2);
assert.equal(unknown.envelope.ok, false);
assert.equal(unknown.envelope.error.code, 'USAGE');
});
test('известные команды Wave B/C пока возвращают NOT_IMPLEMENTED и код 3', () => {
for (const command of ['spec', 'profile', 'report', 'audit']) {
const result = run(command);
assert.equal(result.code, 3, command);
assert.equal(result.envelope.ok, false, command);
assert.equal(result.envelope.error.code, 'NOT_IMPLEMENTED', command);
}
});
+194
View File
@@ -0,0 +1,194 @@
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 = {
'domain.schema.json': {
$id: 'https://baseline-harness.dev/spec/schemas/domain.schema.json',
type: 'object',
additionalProperties: false,
required: ['id', 'title', 'description'],
properties: {
id: { type: 'string', pattern: '^dom-[a-z0-9-]+$' },
title: { type: 'string' },
description: { type: 'string' },
},
},
'capability.schema.json': {
$id: 'https://baseline-harness.dev/spec/schemas/capability.schema.json',
type: 'object',
additionalProperties: false,
required: ['id', 'domain', 'title', 'description'],
properties: {
id: { type: 'string', pattern: '^cap-[a-z0-9-]+$' },
domain: { type: 'string', pattern: '^dom-[a-z0-9-]+$' },
title: { type: 'string' },
description: { type: 'string' },
},
},
'requirement.schema.json': {
$id: 'https://baseline-harness.dev/spec/schemas/requirement.schema.json',
type: 'object',
required: ['id', 'domain', 'capability', 'statement', 'level'],
properties: {
id: { type: 'string', pattern: '^req-[a-z0-9-]+$' },
domain: { type: 'string', pattern: '^dom-[a-z0-9-]+$' },
capability: { type: 'string', pattern: '^cap-[a-z0-9-]+$' },
statement: { type: 'string' },
level: { enum: ['MUST', 'MUST NOT', 'SHOULD', 'SHOULD NOT', 'MAY'] },
},
},
'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-]+$' },
type: { enum: ['boolean', 'integer', 'number', 'string', 'enum'] },
},
},
'normative-change.schema.json': {
$id: 'https://baseline-harness.dev/spec/schemas/normative-change.schema.json',
type: 'object',
required: ['id', 'release', 'date', 'type', 'requirements', 'description'],
properties: {
id: { type: 'string', pattern: '^chg-[a-z0-9-]+$' },
release: { type: 'string' },
date: { type: 'string' },
type: { enum: ['ADDED', 'STRENGTHENED', 'RELAXED', 'CLARIFIED', 'DEPRECATED', 'REMOVED'] },
requirements: { type: 'array', items: { type: 'string' } },
description: { type: 'string' },
},
},
};
const BASE_FILES = {
'domains/dom-build.yaml':
'id: dom-build\ntitle: Сборка\ndescription: Требования к сборке проекта.\n',
'capabilities/cap-verify.yaml':
'id: cap-verify\ndomain: dom-build\ntitle: Проверка\ndescription: Требования к проверкам.\n',
'requirements/req-alpha.yaml':
'id: req-alpha\ndomain: dom-build\ncapability: cap-verify\nstatement: Проект MUST проходить проверку.\nlevel: MUST\nrelations:\n - target: req-beta\n kind: depends-on\n',
'requirements/req-beta.yaml':
'id: req-beta\ndomain: dom-build\ncapability: cap-verify\nstatement: Проект SHOULD документировать шаги.\nlevel: SHOULD\n',
'parameters/.gitkeep': '',
'CHANGELOG.yaml': 'changes: []\n',
};
function fixture(t, overrides = {}) {
const root = mkdtempSync(path.join(os.tmpdir(), 'bhl-validate-'));
const files = { ...BASE_FILES, ...overrides };
delete files['parameters/.gitkeep'];
mkdirSync(path.join(root, 'schemas'), { recursive: true });
for (const name of Object.keys(SCHEMAS)) {
writeFileSync(path.join(root, 'schemas', name), JSON.stringify(SCHEMAS[name]), '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');
}
mkdirSync(path.join(root, 'parameters'), { recursive: true });
t.after(() => rmSync(root, { recursive: true, force: true }));
return root;
}
function runValidate(root) {
const proc = spawnSync(process.execPath, [cli, 'validate', root], { encoding: 'utf8' });
return { code: proc.status, envelope: JSON.parse(proc.stdout) };
}
function codes(result) {
return result.envelope.data.errors.map((item) => item.code);
}
test('валидная спецификация: код 0 и пустые диагностики', (t) => {
const result = runValidate(fixture(t));
assert.equal(result.code, 0);
assert.equal(result.envelope.ok, true);
assert.deepEqual(result.envelope.data.errors, []);
assert.equal(result.envelope.data.files, 5);
});
test('дубликат ID и ссылка на несуществующее требование', (t) => {
const dup = fixture(t, {
'requirements/req-gamma.yaml':
'id: req-alpha\ndomain: dom-build\ncapability: cap-verify\nstatement: Gamma MUST существовать.\nlevel: MUST\n',
});
assert.ok(codes(runValidate(dup)).includes('duplicate-id'));
const dangling = fixture(t, {
'requirements/req-beta.yaml':
'id: req-beta\ndomain: dom-build\ncapability: cap-verify\nstatement: Beta MUST существовать.\nlevel: MUST\nrelations:\n - target: req-ghost\n kind: depends-on\n',
});
assert.ok(codes(runValidate(dangling)).includes('unknown-requirement'));
});
test('отсутствующие домен и возможность, несовпадение домена', (t) => {
const missingDomain = fixture(t, {
'capabilities/cap-verify.yaml':
'id: cap-verify\ndomain: dom-absent\ntitle: Проверка\ndescription: Требования к проверкам.\n',
});
assert.ok(codes(runValidate(missingDomain)).includes('missing-domain'));
const missingCapability = fixture(t, {
'requirements/req-beta.yaml':
'id: req-beta\ndomain: dom-build\ncapability: cap-ghost\nstatement: Beta MUST существовать.\nlevel: MUST\n',
});
assert.ok(codes(runValidate(missingCapability)).includes('missing-capability'));
const mismatch = fixture(t, {
'domains/dom-other.yaml': 'id: dom-other\ntitle: Другой\ndescription: Другой домен.\n',
'requirements/req-beta.yaml':
'id: req-beta\ndomain: dom-other\ncapability: cap-verify\nstatement: Beta MUST существовать.\nlevel: MUST\n',
});
assert.ok(codes(runValidate(mismatch)).includes('domain-mismatch'));
});
test('нормативное ключевое слово должно соответствовать level', (t) => {
const result = runValidate(
fixture(t, {
'requirements/req-beta.yaml':
'id: req-beta\ndomain: dom-build\ncapability: cap-verify\nstatement: Проект желает документировать шаги.\nlevel: SHOULD\n',
}),
);
assert.equal(result.code, 1);
assert.ok(codes(result).includes('keyword-mismatch'));
});
test('цикл depends-on обнаруживается', (t) => {
const result = runValidate(
fixture(t, {
'requirements/req-beta.yaml':
'id: req-beta\ndomain: dom-build\ncapability: cap-verify\nstatement: Beta MUST существовать.\nlevel: MUST\nrelations:\n - target: req-alpha\n kind: depends-on\n',
}),
);
assert.equal(result.code, 1);
assert.ok(codes(result).includes('dependency-cycle'));
});
test('схема отклоняет неверный level, журнал ссылается на известное требование', (t) => {
const badLevel = fixture(t, {
'requirements/req-beta.yaml':
'id: req-beta\ndomain: dom-build\ncapability: cap-verify\nstatement: Beta MUST существовать.\nlevel: READY\n',
});
assert.ok(codes(runValidate(badLevel)).includes('schema-error'));
const changelog = fixture(t, {
'CHANGELOG.yaml':
'changes:\n - id: chg-first\n release: 0.1.0\n date: 2026-11-28\n type: ADDED\n requirements: [req-ghost]\n description: Требование добавлено в спецификацию.\n',
});
assert.ok(codes(runValidate(changelog)).includes('unknown-requirement'));
});
test('обязательная структура корня: schemas и директории сущностей', (t) => {
const noRootArg = spawnSync(process.execPath, [cli, 'validate'], { encoding: 'utf8' });
assert.equal(noRootArg.status, 2);
assert.equal(JSON.parse(noRootArg.stdout).error.code, 'USAGE');
const root = fixture(t);
rmSync(path.join(root, 'requirements'), { recursive: true, force: true });
const result = runValidate(root);
assert.equal(result.code, 1);
assert.ok(codes(result).includes('missing-directory'));
});
+21
View File
@@ -0,0 +1,21 @@
{
"compilerOptions": {
"target": "ES2024",
"module": "NodeNext",
"moduleResolution": "NodeNext",
"strict": true,
"noUncheckedIndexedAccess": true,
"exactOptionalPropertyTypes": true,
"noImplicitReturns": true,
"noFallthroughCasesInSwitch": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"noEmit": true,
"allowImportingTsExtensions": true,
"verbatimModuleSyntax": true,
"erasableSyntaxOnly": true,
"types": ["node"],
"skipLibCheck": true
},
"include": ["src/**/*.ts", "tests/**/*.ts"]
}