Перенос CLI в продуктовое дерево products/bhl-cli (BHL-067)
packages/bhl/ перенесён целиком в products/bhl-cli/ через git mv: 28 отслеживаемых файлов, в истории — переименования, байты не менялись, второго экземпляра кода не появилось. Идентичность npm-пакета @baseline-harness/bhl 0.0.1, bin bhl, engines, files и publishConfig сохранены; node_modules и dist переехали физически, .gitignore переведён на products/bhl-cli/dist/. Основание — D-055 и уточнённая редакция D-028. Переходная запись products/bhl-cli удалена из products.yaml: проверка отвергает оставшуюся запись для уже созданного дерева, поэтому удаление обязательено факту переноса, а не договорённости. Актуализированы действующие пути: корневые интеграционные тесты audit-skill, lab-connection, spec-docs и synthetic-spec; AGENTS.md с командой перегенерации docs/spec; bhl.yaml; README.md со строками products/ и packages/; packages/README.md, где каталог объявлен пустым переходным. Относительные ссылки внутри дерева не правились: глубина packages/bhl/ и products/bhl-cli/ одинакова, ../../spec/ и ../../library/ остались разрешимыми. Находка о проверке упаковки: npm --prefix <дерево> pack упаковывает пакет текущего каталога, а не целевого — прогон из корня дал tarball лаборатории вместо пакета CLI. Проверка артефакта требует рабочего каталога внутри дерева, чем и занимается tests/pack.test.mjs. Прежняя формулировка о проверке через --prefix в исторических записях результатов не переписана. Проверки: местный quality gate из корня и из самого дерева — формат, ESLint с нулевым порогом предупреждений, строгие типы, 48/48 тестов зелёные; npm pack → установка tarball во временный каталог → bhl version отвечает конвертом (23 файла артефакта, тестов в tarball нет); корневые npm run check — 0 ошибок и 0 предупреждений, npm test — 68/68, backlog doctor — без дубликатов, самоссылок и циклов. Остаток: судьба пустого packages/ — решение владельца (BHL-073); строка AGENTS.md о программе Wave I актуализуется после BHL-068; тестовые фикстуры переезжают в дерево по BHL-069.
This commit is contained in:
@@ -0,0 +1,5 @@
|
||||
{
|
||||
"singleQuote": true,
|
||||
"printWidth": 100,
|
||||
"trailingComma": "all"
|
||||
}
|
||||
@@ -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 и тестов.
|
||||
@@ -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, до публикации контракт установки не объявляется.
|
||||
- Производительность на больших спецификациях не измерялась.
|
||||
@@ -0,0 +1,53 @@
|
||||
# bhl — CLI Baseline Harness Standard
|
||||
|
||||
`@baseline-harness/bhl` — детерминированный CLI стандарта BHS: валидация спецификации и манифестов, разрешение профилей и параметров, структурированные отчёты аудита. Без LLM, оркестрации, сервера и обязательной базы данных (D-012). Пакет создан по D-028; статус — **в разработке** (BHL-020…BHL-028), не опубликован; публикация — отдельное поручение (D-034).
|
||||
|
||||
Каталог `products/bhl-cli/` — продуктовое дерево продукта `bhl-cli` (D-054, D-055, перенос по BHL-067): код, зависимости, lockfile, проверки и тестовые данные принадлежат ему, содержимое дерева потенциально публично целиком. За пределами лаборатории продукт существует только как версионированный npm-артефакт.
|
||||
|
||||
## Запуск
|
||||
|
||||
Требуется 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) |
|
||||
| `spec` | `list` / `show` / `render` | работает (BHL-022, BHL-017) |
|
||||
| `profile resolve` | разрешение Effective Specification | работает (BHL-012, BHL-013) |
|
||||
| `report` | `validate` / `render` отчёта аудита | работает (BHL-023, BHL-025) |
|
||||
| `manifest validate` | валидация манифеста проекта | работает (BHL-014, BHL-022) |
|
||||
| `fetch` / `verify` | загрузка версии спецификации, кеш и lock | работает (BHL-021) |
|
||||
| `audit` | детерминированный аудит проекта по Effective Specification | работает (BHL-026); семантический аудит — BHL-029+ |
|
||||
| `release` | артефакты версии спецификации: tarball + manifest + сумма tarball | работает (BHL-027); публикация — BHL-027/D-034 |
|
||||
|
||||
## Зависимости и границы
|
||||
|
||||
Runtime-зависимости: `ajv` (JSON Schema 2020-12) и `yaml`. LLM-клиента, сети, сервера и БД у CLI нет; офлайн-работа после загрузки версий спецификации — требование BHL-021. Схемы спецификации живут в [spec/schemas](../../spec/schemas/) лаборатории; их версионирование — D-039.
|
||||
|
||||
## Упаковка и публикация
|
||||
|
||||
Пакет `@baseline-harness/bhl` (scope свободен в npm — перепроверено 2026-11-28), исполняемое имя `bhl`, `engines.node >= 22.19.0`. Публикуемый артефакт собирается `npm run build` (TypeScript → `dist/`, выполняется как `prepare` при `npm pack`); `bin` указывает на `dist/cli.js` — Node запрещает type-stripping внутри `node_modules`, поэтому в tarball идут готовые JS-модули. Локальная проверка артефакта: `npm pack` → `npm install <tarball> --prefix <временный каталог>` → `bhl version` (тест `tests/pack.test.mjs`). Публикация в реестр не выполнена: пакет `private`, публикация — по отдельному поручению владельца (D-034).
|
||||
|
||||
Профиль качества и границы принятия — в [QUALITY.md](QUALITY.md).
|
||||
@@ -0,0 +1,92 @@
|
||||
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',
|
||||
},
|
||||
},
|
||||
{
|
||||
files: ['src/audit.ts'],
|
||||
rules: {
|
||||
// git is optional audit metadata resolved from the operator PATH; absence yields
|
||||
// no revision fields rather than a failure. Scoped to the audit engine only.
|
||||
'sonarjs/no-os-command-from-path': 'off',
|
||||
},
|
||||
},
|
||||
);
|
||||
Generated
+2453
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,51 @@
|
||||
{
|
||||
"name": "@baseline-harness/bhl",
|
||||
"version": "0.0.1",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"description": "Детерминированный CLI Baseline Harness Standard: валидация, разрешение профилей, аудит",
|
||||
"license": "UNLICENSED",
|
||||
"bin": {
|
||||
"bhl": "./dist/cli.js"
|
||||
},
|
||||
"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",
|
||||
"build": "tsc -p tsconfig.build.json",
|
||||
"prepare": "npm run build"
|
||||
},
|
||||
"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"
|
||||
},
|
||||
"files": [
|
||||
"dist",
|
||||
"src",
|
||||
"README.md",
|
||||
"QUALITY.md"
|
||||
],
|
||||
"publishConfig": {
|
||||
"access": "public"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,358 @@
|
||||
import { createHash } from 'node:crypto';
|
||||
import { spawnSync } from 'node:child_process';
|
||||
import { existsSync, readFileSync, readdirSync, statSync, writeFileSync } from 'node:fs';
|
||||
import path from 'node:path';
|
||||
|
||||
import { resolveProfiles } from './resolve.ts';
|
||||
import type { Diagnostic } from './validate.ts';
|
||||
|
||||
export interface AuditOptions {
|
||||
projectDir: string;
|
||||
specRoot: string;
|
||||
profileIds: readonly string[];
|
||||
presetIds: readonly string[];
|
||||
generatedAt: string;
|
||||
specVersion?: string | undefined;
|
||||
}
|
||||
|
||||
export interface AuditResult {
|
||||
ok: boolean;
|
||||
report: Record<string, unknown> | undefined;
|
||||
diagnostics: readonly Diagnostic[];
|
||||
}
|
||||
|
||||
interface CheckOutcome {
|
||||
status: 'PASS' | 'FAIL';
|
||||
rationale: string;
|
||||
evidence: Record<string, unknown>[];
|
||||
}
|
||||
|
||||
function absenceEvidence(locator: string, description: string): Record<string, unknown>[] {
|
||||
return [
|
||||
{
|
||||
kind: 'other',
|
||||
locator,
|
||||
description,
|
||||
captured_at: EPOCH_DATE,
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
const SKIP_DIRS = new Set(['.git', 'node_modules', 'out', '.pi', '.artifacts', '.cache', '.tmp']);
|
||||
// captured_at по схеме — календарная дата; детерминированная эпоха для встроенных проверок.
|
||||
const EPOCH_DATE = '1970-01-01';
|
||||
const REPORT_STATUSES = [
|
||||
'PASS',
|
||||
'FAIL',
|
||||
'PARTIAL',
|
||||
'EXEMPT',
|
||||
'NOT_APPLICABLE',
|
||||
'UNKNOWN',
|
||||
'BLOCKED',
|
||||
] as const;
|
||||
const LOCKFILES = [
|
||||
'package-lock.json',
|
||||
'yarn.lock',
|
||||
'pnpm-lock.yaml',
|
||||
'npm-shrinkwrap.json',
|
||||
'Gemfile.lock',
|
||||
'go.sum',
|
||||
'uv.lock',
|
||||
'poetry.lock',
|
||||
'Cargo.lock',
|
||||
];
|
||||
|
||||
function sha256(data: Buffer | string): string {
|
||||
return `sha256:${createHash('sha256').update(data).digest('hex')}`;
|
||||
}
|
||||
|
||||
function walkFiles(dir: string, prefix: string, acc: string[]): void {
|
||||
for (const entry of readdirSync(dir, { withFileTypes: true }).sort((a, b) =>
|
||||
a.name.localeCompare(b.name),
|
||||
)) {
|
||||
const rel = prefix === '' ? entry.name : `${prefix}/${entry.name}`;
|
||||
if (entry.isDirectory()) {
|
||||
if (!SKIP_DIRS.has(entry.name)) {
|
||||
walkFiles(path.join(dir, entry.name), rel, acc);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if (entry.isFile()) {
|
||||
acc.push(rel);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export function treeFingerprint(dir: string): string {
|
||||
const files: string[] = [];
|
||||
walkFiles(dir, '', files);
|
||||
const hash = createHash('sha256');
|
||||
for (const file of files) {
|
||||
hash
|
||||
.update(file)
|
||||
.update('\u0000')
|
||||
.update(readFileSync(path.join(dir, file)))
|
||||
.update('\u0000');
|
||||
}
|
||||
return `sha256:${hash.digest('hex')}`;
|
||||
}
|
||||
|
||||
function gitInfo(dir: string): { revision?: string; dirty?: boolean } {
|
||||
// git намеренно берётся из PATH оператора: это необязательные метаданные аудита,
|
||||
// отсутствие git даёт пустой объект, а не сбой (см. eslint.config.mjs, src/audit.ts).
|
||||
const rev = spawnSync('git', ['-C', dir, 'rev-parse', 'HEAD'], { encoding: 'utf8' });
|
||||
if (rev.status !== 0) {
|
||||
return {};
|
||||
}
|
||||
const status = spawnSync('git', ['-C', dir, 'status', '--porcelain'], { encoding: 'utf8' });
|
||||
return { revision: rev.stdout.trim(), dirty: status.stdout.trim() !== '' };
|
||||
}
|
||||
|
||||
function evidenceFor(file: string, locator: string, description: string): Record<string, unknown> {
|
||||
const bytes = readFileSync(file);
|
||||
return {
|
||||
kind: 'file',
|
||||
description,
|
||||
locator,
|
||||
fingerprint: sha256(bytes),
|
||||
captured_at: EPOCH_DATE,
|
||||
};
|
||||
}
|
||||
|
||||
function readText(file: string): string {
|
||||
try {
|
||||
return readFileSync(file, 'utf8');
|
||||
} catch {
|
||||
return '';
|
||||
}
|
||||
}
|
||||
|
||||
function getProp(obj: unknown, key: string): unknown {
|
||||
if (typeof obj === 'object' && obj !== null) {
|
||||
return Reflect.get(obj, key);
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
function declaresQuality(pkg: unknown): boolean {
|
||||
const scripts = getProp(pkg, 'scripts');
|
||||
return (
|
||||
typeof scripts === 'object' && scripts !== null && ('quality' in scripts || 'check' in scripts)
|
||||
);
|
||||
}
|
||||
|
||||
function checkQualityCommand(dir: string): CheckOutcome {
|
||||
const candidates: [string, (text: string) => boolean][] = [
|
||||
[
|
||||
'package.json',
|
||||
(text) => {
|
||||
try {
|
||||
return declaresQuality(JSON.parse(text));
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
},
|
||||
],
|
||||
['Makefile', (text) => /^quality:/m.test(text)],
|
||||
];
|
||||
for (const [name, matches] of candidates) {
|
||||
const file = path.join(dir, name);
|
||||
if (existsSync(file) && matches(readText(file))) {
|
||||
return {
|
||||
status: 'PASS',
|
||||
rationale: `Воспроизводимая команда качества объявлена в ${name}.`,
|
||||
evidence: [evidenceFor(file, name, `${name} объявляет команду качества`)],
|
||||
};
|
||||
}
|
||||
}
|
||||
return {
|
||||
status: 'FAIL',
|
||||
rationale:
|
||||
'Не найдено объявленной команды качества (package.json scripts.quality|check или Makefile цель quality).',
|
||||
evidence: absenceEvidence(
|
||||
'package.json, Makefile',
|
||||
'Ни package.json с scripts.quality|check, ни Makefile с целью quality не найдены.',
|
||||
),
|
||||
};
|
||||
}
|
||||
|
||||
function checkPresence(
|
||||
dir: string,
|
||||
candidates: readonly string[],
|
||||
label: string,
|
||||
rationaleFail: string,
|
||||
): CheckOutcome {
|
||||
for (const name of candidates) {
|
||||
const file = path.join(dir, name);
|
||||
if (existsSync(file) && statSync(file).isFile()) {
|
||||
return {
|
||||
status: 'PASS',
|
||||
rationale: `${label}: найден ${name}.`,
|
||||
evidence: [evidenceFor(file, name, `${label} зафиксирован`)],
|
||||
};
|
||||
}
|
||||
}
|
||||
return {
|
||||
status: 'FAIL',
|
||||
rationale: rationaleFail,
|
||||
evidence: absenceEvidence(candidates.join(', '), `${label}: ни один из кандидатов не найден.`),
|
||||
};
|
||||
}
|
||||
|
||||
function ciCandidates(dir: string): string[] {
|
||||
const fixed = ['.gitlab-ci.yml', 'Jenkinsfile', '.buildkite/pipeline.yml'];
|
||||
const workflows = path.join(dir, '.github', 'workflows');
|
||||
const extra: string[] = [];
|
||||
if (existsSync(workflows)) {
|
||||
for (const name of readdirSync(workflows)) {
|
||||
if (/\.ya?ml$/.test(name)) {
|
||||
extra.push(`.github/workflows/${name}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
return [...extra, ...fixed];
|
||||
}
|
||||
|
||||
const CHECKS: Readonly<Record<string, (dir: string) => CheckOutcome>> = {
|
||||
'req-synth-alpha': checkQualityCommand,
|
||||
'req-single-quality-command': checkQualityCommand,
|
||||
'req-synth-beta': (dir) =>
|
||||
checkPresence(
|
||||
dir,
|
||||
LOCKFILES,
|
||||
'Блокировка зависимостей',
|
||||
'Не найден lockfile ни в одном из известных форматов.',
|
||||
),
|
||||
'req-synth-gamma': (dir) =>
|
||||
checkPresence(
|
||||
dir,
|
||||
ciCandidates(dir),
|
||||
'Конфигурация CI',
|
||||
'Не найдена конфигурация CI (.github/workflows/*.yml, .gitlab-ci.yml и др.).',
|
||||
),
|
||||
};
|
||||
|
||||
function unknownFinding(requirement: string): Record<string, unknown> {
|
||||
return {
|
||||
requirement,
|
||||
status: 'UNKNOWN',
|
||||
method: 'semantic',
|
||||
confidence: 'low',
|
||||
rationale:
|
||||
'Детерминированная проверка для этого требования не реализована; требуется семантический аудит.',
|
||||
evidence: [
|
||||
{
|
||||
kind: 'review-note',
|
||||
locator: requirement,
|
||||
description:
|
||||
'Встроенный реестр детерминированных проверок не содержит записи о требовании.',
|
||||
captured_at: EPOCH_DATE,
|
||||
},
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
function buildFinding(projectDir: string, requirement: string): Record<string, unknown> {
|
||||
const check = CHECKS[requirement];
|
||||
if (check === undefined) {
|
||||
return unknownFinding(requirement);
|
||||
}
|
||||
const outcome = check(projectDir);
|
||||
const finding: Record<string, unknown> = {
|
||||
requirement,
|
||||
status: outcome.status,
|
||||
method: 'deterministic',
|
||||
rationale: outcome.rationale,
|
||||
evidence: outcome.evidence,
|
||||
};
|
||||
return finding;
|
||||
}
|
||||
|
||||
function summarize(findings: readonly Readonly<Record<string, unknown>>[]): Record<string, number> {
|
||||
const summary: Record<string, number> = {};
|
||||
for (const status of REPORT_STATUSES) {
|
||||
summary[status] = 0;
|
||||
}
|
||||
for (const finding of findings) {
|
||||
const status = finding['status'];
|
||||
if (typeof status === 'string') {
|
||||
summary[status] = (summary[status] ?? 0) + 1;
|
||||
}
|
||||
}
|
||||
return summary;
|
||||
}
|
||||
|
||||
function packageVersion(): string {
|
||||
try {
|
||||
const version = getProp(
|
||||
JSON.parse(readFileSync(path.join(import.meta.dirname, '..', 'package.json'), 'utf8')),
|
||||
'version',
|
||||
);
|
||||
if (typeof version === 'string') {
|
||||
return version;
|
||||
}
|
||||
} catch {
|
||||
// fall through to default
|
||||
}
|
||||
return '0.0.0';
|
||||
}
|
||||
|
||||
// Версия спецификации — обязательный контекст аудита (C1/BHL-043): флаг либо lock.json кеша bhl fetch.
|
||||
function specVersionFromLock(specRoot: string): string | undefined {
|
||||
try {
|
||||
const version = getProp(
|
||||
JSON.parse(readFileSync(path.join(specRoot, '..', 'lock.json'), 'utf8')),
|
||||
'version',
|
||||
);
|
||||
return typeof version === 'string' ? version : undefined;
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
export function runAudit(options: AuditOptions): AuditResult {
|
||||
const diagnostics: Diagnostic[] = [];
|
||||
const specVersion = options.specVersion ?? specVersionFromLock(options.specRoot);
|
||||
if (specVersion === undefined) {
|
||||
diagnostics.push({
|
||||
file: options.specRoot,
|
||||
code: 'spec-version-unknown',
|
||||
message:
|
||||
'Версия спецификации не задана: передайте --spec-version или используйте кеш bhl fetch (lock.json).',
|
||||
});
|
||||
return { ok: false, report: undefined, diagnostics };
|
||||
}
|
||||
const resolution = resolveProfiles(options.specRoot, options.profileIds, options.presetIds);
|
||||
diagnostics.push(...resolution.diagnostics);
|
||||
if (!resolution.ok) {
|
||||
return { ok: false, report: undefined, diagnostics };
|
||||
}
|
||||
const requirements = resolution.effective
|
||||
.map((entry) => entry.requirement)
|
||||
.sort((a, b) => a.localeCompare(b));
|
||||
const findings = requirements.map((requirement) => buildFinding(options.projectDir, requirement));
|
||||
const fingerprint = treeFingerprint(options.projectDir);
|
||||
const git = gitInfo(options.projectDir);
|
||||
const subject: Record<string, unknown> = {
|
||||
kind: git.revision === undefined ? 'directory' : 'repository',
|
||||
fingerprint,
|
||||
};
|
||||
Object.assign(subject, git);
|
||||
const report: Record<string, unknown> = {
|
||||
id: `rep-audit-${fingerprint.slice(7, 23)}`,
|
||||
generated_at: options.generatedAt,
|
||||
tool: { name: 'bhl', version: packageVersion() },
|
||||
subject,
|
||||
spec_version: specVersion,
|
||||
profiles: resolution.profiles,
|
||||
findings,
|
||||
summary: summarize(findings),
|
||||
};
|
||||
return { ok: true, report, diagnostics };
|
||||
}
|
||||
|
||||
export function writeAuditReport(result: AuditResult, out: string): void {
|
||||
if (result.report !== undefined) {
|
||||
writeFileSync(out, `${JSON.stringify(result.report, null, 2)}\n`, 'utf8');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,811 @@
|
||||
#!/usr/bin/env node
|
||||
import { mkdirSync, readFileSync, writeFileSync } from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { runAudit, writeAuditReport } from './audit.ts';
|
||||
import { emit, ExitCode, failEnvelope, okEnvelope } from './envelope.ts';
|
||||
import { fetchSpec, verifyCache } from './fetch.ts';
|
||||
import { renderReport, renderSpec } from './render.ts';
|
||||
import { buildRelease } from './release.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|manifest|fetch|verify|audit|release> [args]; ' +
|
||||
'spec list [--spec-root <path>] [--domain <id>] [--capability <id>]; ' +
|
||||
'spec show <req-id> [--spec-root <path>]; ' +
|
||||
'spec render --spec-root <path> --out <dir>; ' +
|
||||
'profile resolve <spec-root> [--profile <id>] [--preset <id>]; ' +
|
||||
'report validate <report.json> [--spec-root <path>]; ' +
|
||||
'report render <report.json> --out <file.md>; ' +
|
||||
'manifest validate <manifest.yaml> [--spec-root <path>]; ' +
|
||||
'fetch <release-dir> --version <semver> --cache <dir>; ' +
|
||||
'verify --version <semver> --cache <dir>; ' +
|
||||
'audit <project-dir> --out <report.json> [--spec-root <path>] [--spec-version <semver>] ' +
|
||||
'[--profile <id>] [--preset <id>] [--generated-at <iso>]; ' +
|
||||
'release <spec-root> --version <semver> --out <dir>; ' +
|
||||
'JSON envelope on stdout; exit codes: 0 ok, 1 validation failed, 2 usage, ' +
|
||||
'3 not implemented, 4 internal.';
|
||||
|
||||
function isRecord(value: unknown): value is Record<string, unknown> {
|
||||
return typeof value === 'object' && value !== null && !Array.isArray(value);
|
||||
}
|
||||
|
||||
function readPackageInfo(): { name: string; version: string } {
|
||||
const raw = readFileSync(new URL('../package.json', import.meta.url), 'utf8');
|
||||
const parsed: unknown = JSON.parse(raw);
|
||||
if (
|
||||
!isRecord(parsed) ||
|
||||
typeof parsed['name'] !== 'string' ||
|
||||
typeof parsed['version'] !== 'string'
|
||||
) {
|
||||
throw new Error('package.json is malformed');
|
||||
}
|
||||
return { name: parsed['name'], version: parsed['version'] };
|
||||
}
|
||||
|
||||
interface ParsedArgs {
|
||||
root: string;
|
||||
profiles: string[];
|
||||
presets: string[];
|
||||
}
|
||||
|
||||
type FlagName = 'profile' | 'preset';
|
||||
|
||||
const FLAG_TARGETS: Readonly<Record<string, FlagName>> = {
|
||||
'--profile': 'profile',
|
||||
'--preset': 'preset',
|
||||
};
|
||||
|
||||
interface SplitState {
|
||||
positional: string[];
|
||||
collected: Record<FlagName, string[]>;
|
||||
cursor: number;
|
||||
}
|
||||
|
||||
function parseFlagAt(args: readonly string[], state: SplitState, arg: string): string {
|
||||
const flag = FLAG_TARGETS[arg];
|
||||
const value = args[state.cursor + 1];
|
||||
if (flag === undefined || value === undefined) {
|
||||
return `missing value for ${arg}`;
|
||||
}
|
||||
state.collected[flag].push(value);
|
||||
state.cursor += 2;
|
||||
return '';
|
||||
}
|
||||
|
||||
function splitArgs(args: readonly string[]): { ok: SplitState } | { error: string } {
|
||||
const state: SplitState = {
|
||||
positional: [],
|
||||
collected: { profile: [], preset: [] },
|
||||
cursor: 0,
|
||||
};
|
||||
while (state.cursor < args.length) {
|
||||
const arg = args[state.cursor] ?? '';
|
||||
if (FLAG_TARGETS[arg] !== undefined) {
|
||||
const error = parseFlagAt(args, state, arg);
|
||||
if (error !== '') {
|
||||
return { error };
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if (arg.startsWith('--')) {
|
||||
return { error: `unknown flag ${arg}` };
|
||||
}
|
||||
state.positional.push(arg);
|
||||
state.cursor += 1;
|
||||
}
|
||||
return { ok: state };
|
||||
}
|
||||
|
||||
function toParsedArgs(state: SplitState): ParsedArgs | { error: string } {
|
||||
if (state.positional.length !== 1) {
|
||||
const extra = state.positional[1];
|
||||
const message =
|
||||
state.positional.length === 0
|
||||
? 'resolve requires a spec root path'
|
||||
: `unexpected argument ${extra ?? ''}`;
|
||||
return { error: message };
|
||||
}
|
||||
return {
|
||||
root: state.positional[0] ?? '',
|
||||
profiles: state.collected.profile,
|
||||
presets: state.collected.preset,
|
||||
};
|
||||
}
|
||||
|
||||
function parseArgs(args: readonly string[]): ParsedArgs | { error: string } {
|
||||
const split = splitArgs(args);
|
||||
if ('error' in split) {
|
||||
return split;
|
||||
}
|
||||
return toParsedArgs(split.ok);
|
||||
}
|
||||
|
||||
function runProfile(command: string, rest: readonly string[]): number {
|
||||
const [sub, ...args] = rest;
|
||||
if (sub !== 'resolve') {
|
||||
emit(failEnvelope(command, 'USAGE', 'profile requires the subcommand resolve'));
|
||||
return ExitCode.Usage;
|
||||
}
|
||||
const parsed = parseArgs(args);
|
||||
if ('error' in parsed) {
|
||||
emit(failEnvelope(command, 'USAGE', parsed.error));
|
||||
return ExitCode.Usage;
|
||||
}
|
||||
const result = resolveProfiles(parsed.root, parsed.profiles, parsed.presets);
|
||||
const data = {
|
||||
root: parsed.root,
|
||||
profiles: result.profiles,
|
||||
effective: result.effective,
|
||||
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;
|
||||
}
|
||||
|
||||
const REPORT_FLAGS: Readonly<Record<string, 'spec-root' | 'out'>> = {
|
||||
'--spec-root': 'spec-root',
|
||||
'--out': 'out',
|
||||
};
|
||||
|
||||
function takeReportFlag(
|
||||
args: readonly string[],
|
||||
cursor: number,
|
||||
target: { specRoot: string; out: string | undefined },
|
||||
arg: string,
|
||||
): { next: number } | { error: string } {
|
||||
const flag = REPORT_FLAGS[arg];
|
||||
const value = args[cursor + 1];
|
||||
if (flag === undefined || value === undefined) {
|
||||
return { error: `missing value for ${arg}` };
|
||||
}
|
||||
if (flag === 'spec-root') {
|
||||
target.specRoot = value;
|
||||
} else {
|
||||
target.out = value;
|
||||
}
|
||||
return { next: cursor + 2 };
|
||||
}
|
||||
|
||||
function parseReportArgs(
|
||||
args: readonly string[],
|
||||
): { file: string; specRoot: string; out: string | undefined } | { error: string } {
|
||||
const target: { specRoot: string; out: string | undefined } = {
|
||||
specRoot: 'spec',
|
||||
out: undefined,
|
||||
};
|
||||
const positional: string[] = [];
|
||||
let cursor = 0;
|
||||
while (cursor < args.length) {
|
||||
const arg = args[cursor] ?? '';
|
||||
if (REPORT_FLAGS[arg] !== undefined) {
|
||||
const taken = takeReportFlag(args, cursor, target, arg);
|
||||
if ('error' in taken) {
|
||||
return taken;
|
||||
}
|
||||
cursor = taken.next;
|
||||
continue;
|
||||
}
|
||||
if (arg.startsWith('--')) {
|
||||
return { error: `unknown flag ${arg}` };
|
||||
}
|
||||
positional.push(arg);
|
||||
cursor += 1;
|
||||
}
|
||||
if (positional.length !== 1) {
|
||||
return { error: 'report requires exactly one report file' };
|
||||
}
|
||||
return { file: positional[0] ?? '', specRoot: target.specRoot, out: target.out };
|
||||
}
|
||||
|
||||
interface SpecFlags {
|
||||
root: string;
|
||||
domain?: string;
|
||||
capability?: string;
|
||||
out?: 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 if (arg === '--capability') {
|
||||
target.capability = value;
|
||||
} else {
|
||||
target.out = 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' || arg === '--out') {
|
||||
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 emitSpecRender(parsed: SpecFlags): number {
|
||||
const out = parsed.out;
|
||||
if (out === undefined) {
|
||||
emit(failEnvelope('spec', 'USAGE', 'spec render requires --out <dir>'));
|
||||
return ExitCode.Usage;
|
||||
}
|
||||
const result = renderSpec(parsed.root);
|
||||
if (!result.ok) {
|
||||
return emitValidationFailure(
|
||||
'spec',
|
||||
{ root: parsed.root, errors: result.diagnostics },
|
||||
result.diagnostics.length,
|
||||
);
|
||||
}
|
||||
for (const file of result.files) {
|
||||
const target = path.join(out, file.path);
|
||||
mkdirSync(path.dirname(target), { recursive: true });
|
||||
writeFileSync(target, file.content, 'utf8');
|
||||
}
|
||||
emit(
|
||||
okEnvelope('spec', { root: parsed.root, out, files: result.files.map((file) => file.path) }),
|
||||
);
|
||||
return ExitCode.Ok;
|
||||
}
|
||||
|
||||
function runSpec(command: string, rest: readonly string[]): number {
|
||||
const [sub, ...args] = rest;
|
||||
if (sub !== 'list' && sub !== 'show' && sub !== 'render') {
|
||||
emit(failEnvelope(command, 'USAGE', 'spec requires the subcommand list, show or render'));
|
||||
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);
|
||||
}
|
||||
if (sub === 'render') {
|
||||
return emitSpecRender(parsed);
|
||||
}
|
||||
return emitSpecShow(parsed);
|
||||
}
|
||||
|
||||
interface FetchFlags {
|
||||
version?: string;
|
||||
cache?: string;
|
||||
positional: string[];
|
||||
}
|
||||
|
||||
const FETCH_FLAGS: Readonly<Record<string, 'version' | 'cache'>> = {
|
||||
'--version': 'version',
|
||||
'--cache': 'cache',
|
||||
};
|
||||
|
||||
function takeFetchFlag(
|
||||
args: readonly string[],
|
||||
cursor: number,
|
||||
target: FetchFlags,
|
||||
arg: string,
|
||||
): { next: number } | { error: string } {
|
||||
const flag = FETCH_FLAGS[arg];
|
||||
const value = args[cursor + 1];
|
||||
if (flag === undefined || value === undefined) {
|
||||
return { error: `missing value for ${arg}` };
|
||||
}
|
||||
target[flag] = value;
|
||||
return { next: cursor + 2 };
|
||||
}
|
||||
|
||||
function parseFetchArgs(args: readonly string[]): FetchFlags | { error: string } {
|
||||
const target: FetchFlags = { positional: [] };
|
||||
let cursor = 0;
|
||||
while (cursor < args.length) {
|
||||
const arg = args[cursor] ?? '';
|
||||
if (FETCH_FLAGS[arg] !== undefined) {
|
||||
const taken = takeFetchFlag(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 fetchUsage(parsed: FetchFlags): string {
|
||||
if (parsed.positional.length !== 1) {
|
||||
return 'fetch requires exactly one <release-dir>';
|
||||
}
|
||||
if (parsed.version === undefined) {
|
||||
return 'fetch requires --version <semver>';
|
||||
}
|
||||
if (parsed.cache === undefined) {
|
||||
return 'fetch requires --cache <dir>';
|
||||
}
|
||||
return '';
|
||||
}
|
||||
|
||||
function runFetch(command: string, rest: readonly string[]): number {
|
||||
const parsed = parseFetchArgs(rest);
|
||||
if ('error' in parsed) {
|
||||
emit(failEnvelope(command, 'USAGE', parsed.error));
|
||||
return ExitCode.Usage;
|
||||
}
|
||||
const usageError = fetchUsage(parsed);
|
||||
if (usageError !== '') {
|
||||
emit(failEnvelope(command, 'USAGE', usageError));
|
||||
return ExitCode.Usage;
|
||||
}
|
||||
const source = parsed.positional[0] ?? '';
|
||||
const version = parsed.version ?? '';
|
||||
const cache = parsed.cache ?? '';
|
||||
const result = fetchSpec(source, cache, version);
|
||||
const data = { source, version, cache, files: result.files, errors: result.diagnostics };
|
||||
if (!result.ok) {
|
||||
return emitValidationFailure(command, data, result.diagnostics.length);
|
||||
}
|
||||
emit(okEnvelope(command, data));
|
||||
return ExitCode.Ok;
|
||||
}
|
||||
|
||||
function runVerify(command: string, rest: readonly string[]): number {
|
||||
const parsed = parseFetchArgs(rest);
|
||||
if ('error' in parsed) {
|
||||
emit(failEnvelope(command, 'USAGE', parsed.error));
|
||||
return ExitCode.Usage;
|
||||
}
|
||||
if (
|
||||
parsed.version === undefined ||
|
||||
parsed.cache === undefined ||
|
||||
parsed.positional.length !== 0
|
||||
) {
|
||||
emit(failEnvelope(command, 'USAGE', 'verify requires --version <semver> --cache <dir>'));
|
||||
return ExitCode.Usage;
|
||||
}
|
||||
const result = verifyCache(parsed.cache, parsed.version);
|
||||
const data = {
|
||||
version: parsed.version,
|
||||
cache: parsed.cache,
|
||||
files: result.files,
|
||||
errors: result.diagnostics,
|
||||
};
|
||||
if (!result.ok) {
|
||||
return emitValidationFailure(command, data, result.diagnostics.length);
|
||||
}
|
||||
emit(okEnvelope(command, data));
|
||||
return ExitCode.Ok;
|
||||
}
|
||||
|
||||
const AUDIT_FLAGS: Readonly<
|
||||
Record<string, 'spec-root' | 'out' | 'generated-at' | 'profile' | 'preset' | 'spec-version'>
|
||||
> = {
|
||||
'--spec-root': 'spec-root',
|
||||
'--out': 'out',
|
||||
'--generated-at': 'generated-at',
|
||||
'--profile': 'profile',
|
||||
'--preset': 'preset',
|
||||
'--spec-version': 'spec-version',
|
||||
};
|
||||
|
||||
interface AuditFlags {
|
||||
root: string;
|
||||
out?: string;
|
||||
generatedAt?: string;
|
||||
specVersion?: string;
|
||||
profiles: string[];
|
||||
presets: string[];
|
||||
positional: string[];
|
||||
}
|
||||
|
||||
function takeAuditFlag(
|
||||
args: readonly string[],
|
||||
cursor: number,
|
||||
target: AuditFlags,
|
||||
arg: string,
|
||||
): { next: number } | { error: string } {
|
||||
const flag = AUDIT_FLAGS[arg];
|
||||
const value = args[cursor + 1];
|
||||
if (flag === undefined || value === undefined) {
|
||||
return { error: `missing value for ${arg}` };
|
||||
}
|
||||
if (flag === 'spec-root') {
|
||||
target.root = value;
|
||||
} else if (flag === 'out') {
|
||||
target.out = value;
|
||||
} else if (flag === 'generated-at') {
|
||||
target.generatedAt = value;
|
||||
} else if (flag === 'spec-version') {
|
||||
target.specVersion = value;
|
||||
} else if (flag === 'profile') {
|
||||
target.profiles.push(value);
|
||||
} else {
|
||||
target.presets.push(value);
|
||||
}
|
||||
return { next: cursor + 2 };
|
||||
}
|
||||
|
||||
function parseAuditArgs(args: readonly string[]): AuditFlags | { error: string } {
|
||||
const target: AuditFlags = { root: 'spec', profiles: [], presets: [], positional: [] };
|
||||
let cursor = 0;
|
||||
while (cursor < args.length) {
|
||||
const arg = args[cursor] ?? '';
|
||||
if (AUDIT_FLAGS[arg] !== undefined) {
|
||||
const taken = takeAuditFlag(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;
|
||||
}
|
||||
|
||||
const RELEASE_FLAGS: Readonly<Record<string, 'version' | 'out'>> = {
|
||||
'--version': 'version',
|
||||
'--out': 'out',
|
||||
};
|
||||
|
||||
interface ReleaseFlags {
|
||||
version?: string;
|
||||
out?: string;
|
||||
positional: string[];
|
||||
}
|
||||
|
||||
function takeReleaseFlag(
|
||||
args: readonly string[],
|
||||
cursor: number,
|
||||
target: ReleaseFlags,
|
||||
arg: string,
|
||||
): { next: number } | { error: string } {
|
||||
const flag = RELEASE_FLAGS[arg];
|
||||
const value = args[cursor + 1];
|
||||
if (flag === undefined || value === undefined) {
|
||||
return { error: `missing value for ${arg}` };
|
||||
}
|
||||
target[flag] = value;
|
||||
return { next: cursor + 2 };
|
||||
}
|
||||
|
||||
function parseReleaseArgs(args: readonly string[]): ReleaseFlags | { error: string } {
|
||||
const target: ReleaseFlags = { positional: [] };
|
||||
let cursor = 0;
|
||||
while (cursor < args.length) {
|
||||
const arg = args[cursor] ?? '';
|
||||
if (RELEASE_FLAGS[arg] !== undefined) {
|
||||
const taken = takeReleaseFlag(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 runRelease(command: string, rest: readonly string[]): number {
|
||||
const parsed = parseReleaseArgs(rest);
|
||||
if ('error' in parsed) {
|
||||
emit(failEnvelope(command, 'USAGE', parsed.error));
|
||||
return ExitCode.Usage;
|
||||
}
|
||||
const specRoot = parsed.positional[0];
|
||||
const version = parsed.version;
|
||||
const out = parsed.out;
|
||||
if (
|
||||
specRoot === undefined ||
|
||||
parsed.positional.length !== 1 ||
|
||||
version === undefined ||
|
||||
out === undefined
|
||||
) {
|
||||
emit(
|
||||
failEnvelope(command, 'USAGE', 'release requires <spec-root> --version <semver> --out <dir>'),
|
||||
);
|
||||
return ExitCode.Usage;
|
||||
}
|
||||
const result = buildRelease(specRoot, version, out);
|
||||
const data = {
|
||||
spec_root: specRoot,
|
||||
version,
|
||||
out,
|
||||
files: result.files,
|
||||
errors: result.diagnostics,
|
||||
};
|
||||
if (!result.ok) {
|
||||
return emitValidationFailure(command, data, result.diagnostics.length);
|
||||
}
|
||||
emit(okEnvelope(command, data));
|
||||
return ExitCode.Ok;
|
||||
}
|
||||
|
||||
function runAuditCommand(command: string, rest: readonly string[]): number {
|
||||
const parsed = parseAuditArgs(rest);
|
||||
if ('error' in parsed) {
|
||||
emit(failEnvelope(command, 'USAGE', parsed.error));
|
||||
return ExitCode.Usage;
|
||||
}
|
||||
const projectDir = parsed.positional[0];
|
||||
const out = parsed.out;
|
||||
if (projectDir === undefined || parsed.positional.length !== 1 || out === undefined) {
|
||||
emit(failEnvelope(command, 'USAGE', 'audit requires <project-dir> and --out <report.json>'));
|
||||
return ExitCode.Usage;
|
||||
}
|
||||
const generatedAt = parsed.generatedAt ?? new Date().toISOString().slice(0, 10);
|
||||
const result = runAudit({
|
||||
projectDir,
|
||||
specRoot: parsed.root,
|
||||
profileIds: parsed.profiles,
|
||||
presetIds: parsed.presets,
|
||||
generatedAt,
|
||||
specVersion: parsed.specVersion,
|
||||
});
|
||||
if (!result.ok || result.report === undefined) {
|
||||
return emitValidationFailure(
|
||||
command,
|
||||
{ project: projectDir, errors: result.diagnostics },
|
||||
result.diagnostics.length,
|
||||
);
|
||||
}
|
||||
mkdirSync(path.dirname(out), { recursive: true });
|
||||
writeAuditReport(result, out);
|
||||
emit(
|
||||
okEnvelope(command, {
|
||||
project: projectDir,
|
||||
out,
|
||||
summary: result.report['summary'],
|
||||
}),
|
||||
);
|
||||
return ExitCode.Ok;
|
||||
}
|
||||
|
||||
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 runReportRender(parsed: { file: string; out: string | undefined }): number {
|
||||
const out = parsed.out;
|
||||
if (out === undefined) {
|
||||
emit(failEnvelope('report', 'USAGE', 'report render requires --out <file.md>'));
|
||||
return ExitCode.Usage;
|
||||
}
|
||||
let report: unknown;
|
||||
try {
|
||||
report = JSON.parse(readFileSync(parsed.file, 'utf8'));
|
||||
} catch {
|
||||
emit(failEnvelope('report', 'READ_ERROR', `report file ${parsed.file} is not readable JSON`));
|
||||
return ExitCode.ValidationFailed;
|
||||
}
|
||||
if (!isRecord(report)) {
|
||||
emit(failEnvelope('report', 'READ_ERROR', 'report must be a JSON object'));
|
||||
return ExitCode.ValidationFailed;
|
||||
}
|
||||
mkdirSync(path.dirname(out), { recursive: true });
|
||||
writeFileSync(out, renderReport(report), 'utf8');
|
||||
emit(okEnvelope('report', { file: parsed.file, out }));
|
||||
return ExitCode.Ok;
|
||||
}
|
||||
|
||||
function runReport(command: string, rest: readonly string[]): number {
|
||||
const [sub, ...args] = rest;
|
||||
if (sub !== 'validate' && sub !== 'render') {
|
||||
emit(failEnvelope(command, 'USAGE', 'report requires the subcommand validate or render'));
|
||||
return ExitCode.Usage;
|
||||
}
|
||||
const parsed = parseReportArgs(args);
|
||||
if ('error' in parsed) {
|
||||
emit(failEnvelope(command, 'USAGE', parsed.error));
|
||||
return ExitCode.Usage;
|
||||
}
|
||||
if (sub === 'render') {
|
||||
return runReportRender(parsed);
|
||||
}
|
||||
const result = validateReport(parsed.file, parsed.specRoot);
|
||||
const data = { file: parsed.file, spec_root: parsed.specRoot, 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 runValidate(command: string, rest: readonly string[]): number {
|
||||
const [root] = rest;
|
||||
if (root === undefined || root.startsWith('--')) {
|
||||
emit(failEnvelope(command, 'USAGE', 'validate requires a spec root path'));
|
||||
return ExitCode.Usage;
|
||||
}
|
||||
const result = validateSpec(root);
|
||||
const data = { root, 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;
|
||||
}
|
||||
|
||||
const COMMAND_HANDLERS: Readonly<Record<string, (rest: readonly string[]) => number>> = {
|
||||
version: () => {
|
||||
const info = readPackageInfo();
|
||||
emit(okEnvelope('version', { name: info.name, version: info.version }));
|
||||
return ExitCode.Ok;
|
||||
},
|
||||
profile: (rest) => runProfile('profile', rest),
|
||||
validate: (rest) => runValidate('validate', rest),
|
||||
spec: (rest) => runSpec('spec', rest),
|
||||
manifest: (rest) => runManifest('manifest', rest),
|
||||
report: (rest) => runReport('report', rest),
|
||||
fetch: (rest) => runFetch('fetch', rest),
|
||||
verify: (rest) => runVerify('verify', rest),
|
||||
audit: (rest) => runAuditCommand('audit', rest),
|
||||
release: (rest) => runRelease('release', rest),
|
||||
};
|
||||
|
||||
export function run(argv: readonly string[]): number {
|
||||
const [command, ...rest] = argv;
|
||||
if (command === undefined) {
|
||||
emit(failEnvelope('none', 'USAGE', USAGE_MESSAGE));
|
||||
return ExitCode.Usage;
|
||||
}
|
||||
const handler = COMMAND_HANDLERS[command];
|
||||
if (handler !== undefined) {
|
||||
return handler(rest);
|
||||
}
|
||||
emit(failEnvelope(command, 'USAGE', USAGE_MESSAGE));
|
||||
return ExitCode.Usage;
|
||||
}
|
||||
|
||||
export function main(argv: readonly string[] = process.argv.slice(2)): void {
|
||||
process.exitCode = run(argv);
|
||||
}
|
||||
|
||||
main();
|
||||
@@ -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`);
|
||||
}
|
||||
@@ -0,0 +1,188 @@
|
||||
import { createHash } from 'node:crypto';
|
||||
import {
|
||||
copyFileSync,
|
||||
existsSync,
|
||||
mkdirSync,
|
||||
readdirSync,
|
||||
readFileSync,
|
||||
statSync,
|
||||
writeFileSync,
|
||||
} from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import type { Diagnostic } from './validate.ts';
|
||||
|
||||
export interface CacheResult {
|
||||
ok: boolean;
|
||||
diagnostics: Diagnostic[];
|
||||
files: number;
|
||||
}
|
||||
|
||||
interface LockEntry {
|
||||
path: string;
|
||||
digest: string;
|
||||
}
|
||||
|
||||
interface LockDocument {
|
||||
version: string;
|
||||
algorithm: string;
|
||||
files: LockEntry[];
|
||||
}
|
||||
|
||||
function isRecord(value: unknown): value is Record<string, unknown> {
|
||||
return typeof value === 'object' && value !== null && !Array.isArray(value);
|
||||
}
|
||||
|
||||
function isLock(value: unknown): value is LockDocument {
|
||||
if (!isRecord(value)) {
|
||||
return false;
|
||||
}
|
||||
return (
|
||||
typeof value['version'] === 'string' &&
|
||||
Array.isArray(value['files']) &&
|
||||
typeof value['algorithm'] === 'string'
|
||||
);
|
||||
}
|
||||
|
||||
function walkFiles(dir: string, prefix = ''): string[] {
|
||||
const result: string[] = [];
|
||||
for (const entry of readdirSync(dir, { withFileTypes: true }).sort((a, b) =>
|
||||
a.name.localeCompare(b.name),
|
||||
)) {
|
||||
const rel = prefix === '' ? entry.name : `${prefix}/${entry.name}`;
|
||||
if (entry.isDirectory()) {
|
||||
result.push(...walkFiles(path.join(dir, entry.name), rel));
|
||||
} else if (entry.isFile()) {
|
||||
result.push(rel);
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
function digestOf(file: string): string {
|
||||
return createHash('sha256').update(readFileSync(file)).digest('hex');
|
||||
}
|
||||
|
||||
function copyTree(source: string, target: string): string[] {
|
||||
const files = walkFiles(source);
|
||||
for (const rel of files) {
|
||||
const to = path.join(target, rel);
|
||||
mkdirSync(path.dirname(to), { recursive: true });
|
||||
copyFileSync(path.join(source, rel), to);
|
||||
}
|
||||
return files;
|
||||
}
|
||||
|
||||
function lockPath(cacheDir: string, version: string): string {
|
||||
return path.join(cacheDir, version, 'lock.json');
|
||||
}
|
||||
|
||||
function specDir(cacheDir: string, version: string): string {
|
||||
return path.join(cacheDir, version, 'spec');
|
||||
}
|
||||
|
||||
export function fetchSpec(source: string, cacheDir: string, version: string): CacheResult {
|
||||
const diagnostics: Diagnostic[] = [];
|
||||
if (!existsSync(source) || !statSync(source).isDirectory()) {
|
||||
return {
|
||||
ok: false,
|
||||
diagnostics: [
|
||||
{
|
||||
file: source,
|
||||
code: 'missing-directory',
|
||||
message: 'release source directory is required',
|
||||
},
|
||||
],
|
||||
files: 0,
|
||||
};
|
||||
}
|
||||
const target = specDir(cacheDir, version);
|
||||
mkdirSync(target, { recursive: true });
|
||||
const files = copyTree(source, target);
|
||||
const lock: LockDocument = {
|
||||
version,
|
||||
algorithm: 'sha256',
|
||||
files: files
|
||||
.map((rel) => ({ path: rel, digest: digestOf(path.join(target, rel)) }))
|
||||
.sort((a, b) => a.path.localeCompare(b.path)),
|
||||
};
|
||||
writeFileSync(lockPath(cacheDir, version), `${JSON.stringify(lock, null, 2)}\n`, 'utf8');
|
||||
return { ok: true, diagnostics, files: files.length };
|
||||
}
|
||||
|
||||
function readLock(lockFile: string, diagnostics: Diagnostic[]): LockDocument | undefined {
|
||||
if (!existsSync(lockFile)) {
|
||||
diagnostics.push({ file: lockFile, code: 'missing-cache', message: 'version is not in cache' });
|
||||
return undefined;
|
||||
}
|
||||
try {
|
||||
const parsed: unknown = JSON.parse(readFileSync(lockFile, 'utf8'));
|
||||
if (!isLock(parsed)) {
|
||||
diagnostics.push({ file: lockFile, code: 'parse-error', message: 'lock.json is malformed' });
|
||||
return undefined;
|
||||
}
|
||||
return parsed;
|
||||
} catch {
|
||||
diagnostics.push({
|
||||
file: lockFile,
|
||||
code: 'parse-error',
|
||||
message: 'lock.json is not valid JSON',
|
||||
});
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
function checkEntries(lock: LockDocument, root: string, diagnostics: Diagnostic[]): void {
|
||||
for (const entry of lock.files) {
|
||||
const file = path.join(root, entry.path);
|
||||
if (!existsSync(file)) {
|
||||
diagnostics.push({
|
||||
file,
|
||||
code: 'missing-file',
|
||||
message: `cached file ${entry.path} is missing`,
|
||||
});
|
||||
continue;
|
||||
}
|
||||
if (digestOf(file) !== entry.digest) {
|
||||
diagnostics.push({
|
||||
file,
|
||||
code: 'checksum-mismatch',
|
||||
message: `cached file ${entry.path} does not match lock (sha256 of bytes)`,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function checkExtras(lock: LockDocument, root: string, diagnostics: Diagnostic[]): void {
|
||||
const expected = new Set(lock.files.map((entry) => entry.path));
|
||||
for (const rel of walkFiles(root)) {
|
||||
if (!expected.has(rel)) {
|
||||
diagnostics.push({
|
||||
file: path.join(root, rel),
|
||||
code: 'unexpected-file',
|
||||
message: `file ${rel} is not in lock`,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export function verifyCache(cacheDir: string, version: string): CacheResult {
|
||||
const diagnostics: Diagnostic[] = [];
|
||||
const lockFile = lockPath(cacheDir, version);
|
||||
const lock = readLock(lockFile, diagnostics);
|
||||
if (lock === undefined) {
|
||||
return { ok: false, diagnostics, files: 0 };
|
||||
}
|
||||
const root = specDir(cacheDir, version);
|
||||
if (!existsSync(root)) {
|
||||
diagnostics.push({
|
||||
file: root,
|
||||
code: 'missing-cache',
|
||||
message: 'cached spec directory is missing',
|
||||
});
|
||||
return { ok: false, diagnostics, files: 0 };
|
||||
}
|
||||
checkEntries(lock, root, diagnostics);
|
||||
checkExtras(lock, root, diagnostics);
|
||||
diagnostics.sort((a, b) => `${a.file} ${a.code}`.localeCompare(`${b.file} ${b.code}`));
|
||||
return { ok: diagnostics.length === 0, diagnostics, files: lock.files.length };
|
||||
}
|
||||
@@ -0,0 +1,141 @@
|
||||
import { createHash } from 'node:crypto';
|
||||
import { mkdirSync, readFileSync, readdirSync, writeFileSync } from 'node:fs';
|
||||
import path from 'node:path';
|
||||
|
||||
export interface ReleaseResult {
|
||||
ok: boolean;
|
||||
files: readonly string[];
|
||||
diagnostics: readonly { file: string; code: string; message: string }[];
|
||||
}
|
||||
|
||||
interface TarEntry {
|
||||
name: string;
|
||||
bytes: Buffer;
|
||||
}
|
||||
|
||||
function sha256(data: Buffer | string): string {
|
||||
return `sha256:${createHash('sha256').update(data).digest('hex')}`;
|
||||
}
|
||||
|
||||
function collectFiles(root: string): string[] {
|
||||
const acc: string[] = [];
|
||||
const walk = (dir: string, prefix: string): void => {
|
||||
for (const entry of readdirSync(dir, { withFileTypes: true }).sort((a, b) =>
|
||||
a.name.localeCompare(b.name),
|
||||
)) {
|
||||
const rel = prefix === '' ? entry.name : `${prefix}/${entry.name}`;
|
||||
const full = path.join(dir, entry.name);
|
||||
if (entry.isDirectory()) {
|
||||
walk(full, rel);
|
||||
} else if (entry.isFile() && /\.(yaml|yml|json|md)$/.test(entry.name)) {
|
||||
acc.push(rel);
|
||||
}
|
||||
}
|
||||
};
|
||||
walk(root, '');
|
||||
return acc.sort((a, b) => a.localeCompare(b));
|
||||
}
|
||||
|
||||
function octal(value: number, width: number): string {
|
||||
return value
|
||||
.toString(8)
|
||||
.padStart(width - 1, '0')
|
||||
.concat('\u0000');
|
||||
}
|
||||
|
||||
function tarHeader(entry: TarEntry): Buffer {
|
||||
const header = Buffer.alloc(512);
|
||||
header.write(entry.name.slice(0, 100), 0, 'utf8');
|
||||
header.write(octal(0o644, 8), 100, 'utf8');
|
||||
header.write(octal(0, 8), 108, 'utf8');
|
||||
header.write(octal(0, 8), 116, 'utf8');
|
||||
header.write(octal(entry.bytes.length, 12), 124, 'utf8');
|
||||
header.write(octal(0, 12), 136, 'utf8');
|
||||
header.write(' ', 148, 'utf8');
|
||||
header.write('0', 156, 'utf8');
|
||||
header.write('ustar\u0000', 257, 'utf8');
|
||||
header.write('00', 263, 'utf8');
|
||||
header.write('bhl', 265, 'utf8');
|
||||
header.write('bhl', 297, 'utf8');
|
||||
let sum = 0;
|
||||
for (const byte of header) {
|
||||
sum += byte;
|
||||
}
|
||||
header.write(octal(sum, 8), 148, 'utf8');
|
||||
return header;
|
||||
}
|
||||
|
||||
function tarBytes(entries: readonly TarEntry[]): Buffer {
|
||||
const parts: Buffer[] = [];
|
||||
for (const entry of entries) {
|
||||
parts.push(tarHeader(entry));
|
||||
parts.push(entry.bytes);
|
||||
const remainder = entry.bytes.length % 512;
|
||||
if (remainder !== 0) {
|
||||
parts.push(Buffer.alloc(512 - remainder));
|
||||
}
|
||||
}
|
||||
parts.push(Buffer.alloc(1024));
|
||||
return Buffer.concat(parts);
|
||||
}
|
||||
|
||||
export function buildRelease(specRoot: string, version: string, outDir: string): ReleaseResult {
|
||||
const diagnostics: { file: string; code: string; message: string }[] = [];
|
||||
if (!/^\d+\.\d+\.\d+(-[0-9A-Za-z.-]+)?$/.test(version)) {
|
||||
return {
|
||||
ok: false,
|
||||
files: [],
|
||||
diagnostics: [
|
||||
{ file: specRoot, code: 'bad-version', message: '--version must be a semver string' },
|
||||
],
|
||||
};
|
||||
}
|
||||
let names: string[];
|
||||
try {
|
||||
names = collectFiles(specRoot);
|
||||
} catch {
|
||||
return {
|
||||
ok: false,
|
||||
files: [],
|
||||
diagnostics: [{ file: specRoot, code: 'read-error', message: 'spec root is not readable' }],
|
||||
};
|
||||
}
|
||||
if (names.length === 0) {
|
||||
return {
|
||||
ok: false,
|
||||
files: [],
|
||||
diagnostics: [
|
||||
{ file: specRoot, code: 'empty-spec', message: 'spec root contains no release files' },
|
||||
],
|
||||
};
|
||||
}
|
||||
const entries: TarEntry[] = names.map((name) => ({
|
||||
name: `bhs-spec-${version}/${name}`,
|
||||
bytes: readFileSync(path.join(specRoot, name)),
|
||||
}));
|
||||
const tarball = tarBytes(entries);
|
||||
const manifest = {
|
||||
schema_version: 1,
|
||||
version,
|
||||
generated_by: 'bhl release',
|
||||
files: entries.map((entry) => ({
|
||||
path: entry.name.replace(`bhs-spec-${version}/`, ''),
|
||||
sha256: sha256(entry.bytes).slice('sha256:'.length),
|
||||
})),
|
||||
};
|
||||
const manifestText = `${JSON.stringify(manifest, null, 2)}\n`;
|
||||
const base = `bhs-spec-${version}`;
|
||||
mkdirSync(outDir, { recursive: true });
|
||||
writeFileSync(path.join(outDir, `${base}.tar`), tarball);
|
||||
writeFileSync(path.join(outDir, `${base}.manifest.json`), manifestText, 'utf8');
|
||||
writeFileSync(
|
||||
path.join(outDir, `${base}.tar.sha256`),
|
||||
`${sha256(tarball).slice('sha256:'.length)} ${base}.tar\n`,
|
||||
'utf8',
|
||||
);
|
||||
return {
|
||||
ok: true,
|
||||
files: [`${base}.tar`, `${base}.manifest.json`, `${base}.tar.sha256`],
|
||||
diagnostics,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,413 @@
|
||||
import { existsSync, readFileSync, readdirSync } from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { parseDocument } from 'yaml';
|
||||
import type { Diagnostic } from './validate.ts';
|
||||
|
||||
export interface RenderedFile {
|
||||
path: string;
|
||||
content: string;
|
||||
}
|
||||
|
||||
export interface RenderResult {
|
||||
ok: boolean;
|
||||
files: RenderedFile[];
|
||||
diagnostics: Diagnostic[];
|
||||
}
|
||||
|
||||
const GENERATED_HEADER =
|
||||
'<!-- Сгенерировано bhl spec render из машиночитаемой спецификации. Не редактировать вручную. -->\n';
|
||||
|
||||
const REPORT_HEADER =
|
||||
'<!-- Сгенерировано bhl report render из машиночитаемого отчёта аудита. Не редактировать вручную. -->\n';
|
||||
|
||||
const REPORT_STATUSES: readonly string[] = [
|
||||
'PASS',
|
||||
'FAIL',
|
||||
'PARTIAL',
|
||||
'EXEMPT',
|
||||
'NOT_APPLICABLE',
|
||||
'UNKNOWN',
|
||||
'BLOCKED',
|
||||
];
|
||||
|
||||
function isRecord(value: unknown): value is Record<string, unknown> {
|
||||
return typeof value === 'object' && value !== null && !Array.isArray(value);
|
||||
}
|
||||
|
||||
function isString(value: unknown): value is string {
|
||||
return typeof value === 'string';
|
||||
}
|
||||
|
||||
function text(value: unknown, fallback = ''): string {
|
||||
return isString(value) ? value : fallback;
|
||||
}
|
||||
|
||||
function readYaml(file: string, diagnostics: Diagnostic[]): unknown {
|
||||
try {
|
||||
const doc = parseDocument(readFileSync(file, 'utf8'), { 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 loadDocs(
|
||||
root: string,
|
||||
dir: string,
|
||||
diagnostics: Diagnostic[],
|
||||
): Record<string, Record<string, unknown>> {
|
||||
const docs: Record<string, Record<string, unknown>> = {};
|
||||
const full = path.join(root, dir);
|
||||
if (!existsSync(full)) {
|
||||
return docs;
|
||||
}
|
||||
const files = readdirSync(full, { withFileTypes: true })
|
||||
.filter((entry) => entry.isFile() && entry.name.endsWith('.yaml'))
|
||||
.map((entry) => path.join(full, entry.name))
|
||||
.sort((a, b) => a.localeCompare(b));
|
||||
for (const file of files) {
|
||||
const value = readYaml(file, diagnostics);
|
||||
if (isRecord(value) && isString(value['id'])) {
|
||||
docs[value['id']] = value;
|
||||
}
|
||||
}
|
||||
return docs;
|
||||
}
|
||||
|
||||
function sortedIds(docs: Record<string, Record<string, unknown>>): string[] {
|
||||
return Object.keys(docs).sort((a, b) => a.localeCompare(b));
|
||||
}
|
||||
|
||||
function renderDomainSection(
|
||||
domainId: string,
|
||||
domain: Record<string, unknown>,
|
||||
capabilities: Record<string, Record<string, unknown>>,
|
||||
requirements: Record<string, Record<string, unknown>>,
|
||||
): string[] {
|
||||
const lines: string[] = [
|
||||
`## ${domainId} — ${text(domain['title'])}`,
|
||||
'',
|
||||
text(domain['description']),
|
||||
'',
|
||||
];
|
||||
const caps = sortedIds(capabilities).filter((id) => capabilities[id]?.['domain'] === domainId);
|
||||
for (const capId of caps) {
|
||||
lines.push(
|
||||
`### ${capId} — ${text(capabilities[capId]?.['title'])}`,
|
||||
'',
|
||||
text(capabilities[capId]?.['description']),
|
||||
'',
|
||||
);
|
||||
}
|
||||
const reqs = sortedIds(requirements).filter((id) => requirements[id]?.['domain'] === domainId);
|
||||
if (reqs.length > 0) {
|
||||
lines.push('| Требование | Уровень | Жизненный цикл | Название |', '|---|---|---|---|');
|
||||
for (const reqId of reqs) {
|
||||
const req = requirements[reqId];
|
||||
const lifecycle = isRecord(req?.['lifecycle']) ? text(req['lifecycle']['status']) : '';
|
||||
lines.push(
|
||||
`| [${reqId}](requirements/${reqId}.md) | ${text(req?.['level'])} | ${lifecycle} | ${text(req?.['title'])} |`,
|
||||
);
|
||||
}
|
||||
lines.push('');
|
||||
}
|
||||
return lines;
|
||||
}
|
||||
|
||||
function renderIndex(
|
||||
domains: Record<string, Record<string, unknown>>,
|
||||
capabilities: Record<string, Record<string, unknown>>,
|
||||
requirements: Record<string, Record<string, unknown>>,
|
||||
): string {
|
||||
const lines: string[] = [
|
||||
GENERATED_HEADER,
|
||||
'# Спецификация — обзор',
|
||||
'',
|
||||
'Машиночитаемая спецификация остаётся нормативным источником истины.',
|
||||
'',
|
||||
];
|
||||
for (const domainId of sortedIds(domains)) {
|
||||
const domain = domains[domainId];
|
||||
if (domain !== undefined) {
|
||||
lines.push(...renderDomainSection(domainId, domain, capabilities, requirements));
|
||||
}
|
||||
}
|
||||
return lines.join('\n');
|
||||
}
|
||||
|
||||
function renderList(
|
||||
items: readonly unknown[],
|
||||
format: (item: Record<string, unknown>) => string,
|
||||
): string[] {
|
||||
const lines: string[] = [];
|
||||
for (const item of items) {
|
||||
if (isRecord(item)) {
|
||||
lines.push(`- ${format(item)}`);
|
||||
}
|
||||
}
|
||||
return lines;
|
||||
}
|
||||
|
||||
function renderParameters(requirement: Record<string, unknown>): string[] {
|
||||
const items = Array.isArray(requirement['parameters']) ? requirement['parameters'] : [];
|
||||
const known: readonly unknown[] = items;
|
||||
if (known.length === 0) {
|
||||
return [];
|
||||
}
|
||||
const lines = [
|
||||
'',
|
||||
'## Параметры',
|
||||
'',
|
||||
'| ID | Тип | Default | Ограничения |',
|
||||
'|---|---|---|---|',
|
||||
];
|
||||
for (const item of known) {
|
||||
if (!isRecord(item)) {
|
||||
continue;
|
||||
}
|
||||
const constraints = isRecord(item['constraints']) ? JSON.stringify(item['constraints']) : '';
|
||||
const def = item['default'] === undefined ? '' : JSON.stringify(item['default']);
|
||||
lines.push(`| ${text(item['id'])} | ${text(item['type'])} | ${def} | ${constraints} |`);
|
||||
}
|
||||
return lines;
|
||||
}
|
||||
|
||||
function applicabilityLine(item: Record<string, unknown>): string {
|
||||
const unless = text(item['unless']);
|
||||
return unless === ''
|
||||
? `when: ${text(item['when'])}`
|
||||
: `when: ${text(item['when'])}; unless: ${unless}`;
|
||||
}
|
||||
|
||||
function sourceLine(item: Record<string, unknown>): string {
|
||||
const note = text(item['note']);
|
||||
return note === '' ? text(item['material']) : `${text(item['material'])} — ${note}`;
|
||||
}
|
||||
|
||||
function renderRequirementCore(req: Record<string, unknown>): string[] {
|
||||
const lines: string[] = [GENERATED_HEADER, `# ${text(req['id'])} — ${text(req['title'])}`, ''];
|
||||
lines.push(`- Уровень: **${text(req['level'])}**`);
|
||||
const lifecycle = isRecord(req['lifecycle']) ? text(req['lifecycle']['status']) : '';
|
||||
lines.push(`- Жизненный цикл: ${lifecycle}`);
|
||||
lines.push(`- Домен: ${text(req['domain'])}; возможность: ${text(req['capability'])}`, '');
|
||||
lines.push('## Формулировка', '', text(req['statement']), '');
|
||||
lines.push('## Обоснование', '', text(req['rationale']), '');
|
||||
const applicability = Array.isArray(req['applicability']) ? req['applicability'] : [];
|
||||
lines.push('## Применимость', '');
|
||||
lines.push(...renderList(applicability, applicabilityLine), '');
|
||||
lines.push(...renderParameters(req), '');
|
||||
return lines;
|
||||
}
|
||||
|
||||
function renderRequirementChecks(req: Record<string, unknown>): string[] {
|
||||
const lines: string[] = [];
|
||||
const criteria = Array.isArray(req['acceptance_criteria']) ? req['acceptance_criteria'] : [];
|
||||
lines.push('## Критерии приёмки', '');
|
||||
lines.push(...renderList(criteria, (item) => text(item['criterion'])), '');
|
||||
const verification = isRecord(req['verification']) ? req['verification'] : {};
|
||||
lines.push(
|
||||
'## Проверка',
|
||||
'',
|
||||
`Вид: ${text(verification['kind'])}`,
|
||||
'',
|
||||
text(verification['procedure']),
|
||||
'',
|
||||
);
|
||||
const evidence = Array.isArray(req['expected_evidence']) ? req['expected_evidence'] : [];
|
||||
lines.push('## Ожидаемые доказательства', '');
|
||||
lines.push(
|
||||
...renderList(evidence, (item) => `${text(item['kind'])}: ${text(item['description'])}`),
|
||||
'',
|
||||
);
|
||||
return lines;
|
||||
}
|
||||
|
||||
function renderRequirementLinks(req: Record<string, unknown>): string[] {
|
||||
const lines: string[] = [];
|
||||
const relations = Array.isArray(req['relations']) ? req['relations'] : [];
|
||||
if (relations.length > 0) {
|
||||
lines.push('## Связи', '');
|
||||
lines.push(
|
||||
...renderList(relations, (item) => `${text(item['kind'])}: ${text(item['target'])}`),
|
||||
'',
|
||||
);
|
||||
}
|
||||
const antipatterns = Array.isArray(req['antipatterns']) ? req['antipatterns'] : [];
|
||||
if (antipatterns.length > 0) {
|
||||
lines.push('## Антипаттерны', '');
|
||||
for (const item of antipatterns) {
|
||||
if (isString(item)) {
|
||||
lines.push(`- [${item}](../antipatterns/${item}.md)`);
|
||||
}
|
||||
}
|
||||
lines.push('');
|
||||
}
|
||||
return lines;
|
||||
}
|
||||
|
||||
function renderRequirement(req: Record<string, unknown>): string {
|
||||
return [
|
||||
...renderRequirementCore(req),
|
||||
...renderRequirementChecks(req),
|
||||
...renderRequirementLinks(req),
|
||||
].join('\n');
|
||||
}
|
||||
|
||||
function renderAntipattern(antipattern: Record<string, unknown>): string {
|
||||
const lines: string[] = [
|
||||
GENERATED_HEADER,
|
||||
`# ${text(antipattern['id'])} — ${text(antipattern['title'])}`,
|
||||
'',
|
||||
];
|
||||
lines.push(`- Уровень: **${text(antipattern['level'])}**`);
|
||||
const lifecycle = isRecord(antipattern['lifecycle'])
|
||||
? text(antipattern['lifecycle']['status'])
|
||||
: '';
|
||||
lines.push(`- Жизненный цикл: ${lifecycle}`, '');
|
||||
lines.push(text(antipattern['description']), '');
|
||||
const relations = Array.isArray(antipattern['relations']) ? antipattern['relations'] : [];
|
||||
lines.push('## Противоречит требованиям', '');
|
||||
lines.push(
|
||||
...renderList(
|
||||
relations,
|
||||
(item) => `[${text(item['target'])}](../requirements/${text(item['target'])}.md)`,
|
||||
),
|
||||
'',
|
||||
);
|
||||
const sources = Array.isArray(antipattern['sources']) ? antipattern['sources'] : [];
|
||||
lines.push('## Происхождение', '');
|
||||
lines.push(...renderList(sources, sourceLine), '');
|
||||
return lines.join('\n');
|
||||
}
|
||||
|
||||
export function renderSpec(root: string): RenderResult {
|
||||
const diagnostics: Diagnostic[] = [];
|
||||
const domains = loadDocs(root, 'domains', diagnostics);
|
||||
const capabilities = loadDocs(root, 'capabilities', diagnostics);
|
||||
const requirements = loadDocs(root, 'requirements', diagnostics);
|
||||
const antipatterns = loadDocs(root, 'antipatterns', diagnostics);
|
||||
const files: RenderedFile[] = [
|
||||
{ path: 'index.md', content: renderIndex(domains, capabilities, requirements) },
|
||||
];
|
||||
for (const id of sortedIds(requirements)) {
|
||||
const doc = requirements[id];
|
||||
if (doc !== undefined) {
|
||||
files.push({ path: `requirements/${id}.md`, content: renderRequirement(doc) });
|
||||
}
|
||||
}
|
||||
for (const id of sortedIds(antipatterns)) {
|
||||
const doc = antipatterns[id];
|
||||
if (doc !== undefined) {
|
||||
files.push({ path: `antipatterns/${id}.md`, content: renderAntipattern(doc) });
|
||||
}
|
||||
}
|
||||
return { ok: diagnostics.length === 0, files, diagnostics };
|
||||
}
|
||||
|
||||
function renderReportMeta(report: Record<string, unknown>): string[] {
|
||||
const tool = isRecord(report['tool']) ? report['tool'] : {};
|
||||
const agent = isRecord(report['agent']) ? report['agent'] : {};
|
||||
const subject = isRecord(report['subject']) ? report['subject'] : {};
|
||||
const revision =
|
||||
subject['revision'] === undefined ? '' : `, ревизия ${text(subject['revision'])}`;
|
||||
const dirtyValue = subject['dirty'];
|
||||
const dirty = typeof dirtyValue === 'boolean' ? `, dirty=${String(dirtyValue)}` : '';
|
||||
const lines: string[] = [REPORT_HEADER, `# Отчёт аудита ${text(report['id'])}`, ''];
|
||||
lines.push(`- Сгенерирован: ${text(report['generated_at'])}`);
|
||||
lines.push(`- Инструмент: ${text(tool['name'])} ${text(tool['version'])}`);
|
||||
if (agent['name'] !== undefined) {
|
||||
lines.push(`- Агент: ${text(agent['name'])} ${text(agent['version'])}`);
|
||||
}
|
||||
lines.push(
|
||||
`- Объект: ${text(subject['kind'])}, отпечаток ${text(subject['fingerprint'])}${revision}${dirty}`,
|
||||
);
|
||||
lines.push(`- Версия спецификации: ${text(report['spec_version'])}`);
|
||||
const profiles = Array.isArray(report['profiles']) ? report['profiles'] : [];
|
||||
lines.push(`- Профили: ${profiles.filter(isString).join(', ') || '—'}`, '');
|
||||
return lines;
|
||||
}
|
||||
|
||||
function renderReportSummary(report: Record<string, unknown>): string[] {
|
||||
const findings = Array.isArray(report['findings']) ? report['findings'] : [];
|
||||
const items: readonly unknown[] = findings;
|
||||
const lines: string[] = ['## Сводка', '', '| Статус | Находок |', '|---|---|'];
|
||||
for (const status of REPORT_STATUSES) {
|
||||
const count = items.filter((item) => isRecord(item) && item['status'] === status).length;
|
||||
lines.push(`| ${status} | ${String(count)} |`);
|
||||
}
|
||||
lines.push('');
|
||||
return lines;
|
||||
}
|
||||
|
||||
function renderEvidence(evidence: readonly unknown[]): string[] {
|
||||
const lines: string[] = [];
|
||||
for (const item of evidence) {
|
||||
if (!isRecord(item)) {
|
||||
continue;
|
||||
}
|
||||
const locator = text(item['locator']);
|
||||
const fingerprint = text(item['fingerprint']);
|
||||
const parts = [`${text(item['kind'])}: ${text(item['description'])}`];
|
||||
if (locator !== '') {
|
||||
parts.push(`\`${locator}\``);
|
||||
}
|
||||
if (fingerprint !== '') {
|
||||
parts.push(fingerprint);
|
||||
}
|
||||
lines.push(` - ${parts.join(' — ')}`);
|
||||
}
|
||||
return lines;
|
||||
}
|
||||
|
||||
function renderFinding(finding: Record<string, unknown>): string[] {
|
||||
const lines: string[] = [`- Требование: ${text(finding['requirement'])}`];
|
||||
const confidence =
|
||||
finding['confidence'] === undefined ? '' : `, уверенность ${text(finding['confidence'])}`;
|
||||
lines.push(`- Метод: ${text(finding['method'])}${confidence}`);
|
||||
if (finding['exemption_ref'] !== undefined) {
|
||||
lines.push(`- Ссылка на исключение: ${text(finding['exemption_ref'])}`);
|
||||
}
|
||||
lines.push(`- Основание: ${text(finding['rationale'])}`);
|
||||
const evidence = Array.isArray(finding['evidence']) ? finding['evidence'] : [];
|
||||
lines.push('- Доказательства:');
|
||||
lines.push(...renderEvidence(evidence));
|
||||
return lines;
|
||||
}
|
||||
|
||||
function renderReportStatusSection(status: string, findings: readonly unknown[]): string[] {
|
||||
const matched = findings.filter((item) => isRecord(item) && item['status'] === status);
|
||||
if (matched.length === 0) {
|
||||
return [];
|
||||
}
|
||||
const lines: string[] = [`### ${status}`, ''];
|
||||
for (const item of matched) {
|
||||
if (isRecord(item)) {
|
||||
lines.push(...renderFinding(item), '');
|
||||
}
|
||||
}
|
||||
return lines;
|
||||
}
|
||||
|
||||
export function renderReport(report: Record<string, unknown>): string {
|
||||
const findings = Array.isArray(report['findings']) ? report['findings'] : [];
|
||||
const items: readonly unknown[] = findings;
|
||||
const lines: string[] = [
|
||||
...renderReportMeta(report),
|
||||
...renderReportSummary(report),
|
||||
'## Находки',
|
||||
'',
|
||||
];
|
||||
for (const status of REPORT_STATUSES) {
|
||||
lines.push(...renderReportStatusSection(status, items));
|
||||
}
|
||||
return lines.join('\n');
|
||||
}
|
||||
@@ -0,0 +1,225 @@
|
||||
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 ReportValidationResult {
|
||||
ok: boolean;
|
||||
diagnostics: Diagnostic[];
|
||||
}
|
||||
|
||||
const SCHEMA_BASE = 'https://baseline-harness.dev/spec/schemas/';
|
||||
|
||||
const FINDING_STATUSES: readonly string[] = [
|
||||
'PASS',
|
||||
'FAIL',
|
||||
'PARTIAL',
|
||||
'EXEMPT',
|
||||
'NOT_APPLICABLE',
|
||||
'UNKNOWN',
|
||||
'BLOCKED',
|
||||
];
|
||||
|
||||
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 schemaFiles(schemasDir: string): string[] {
|
||||
return 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));
|
||||
}
|
||||
|
||||
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 });
|
||||
for (const file of schemaFiles(schemasDir)) {
|
||||
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)) {
|
||||
ajv.addSchema(parsed);
|
||||
}
|
||||
}
|
||||
return ajv;
|
||||
}
|
||||
|
||||
function readReport(file: string, diagnostics: Diagnostic[]): unknown {
|
||||
let text: string;
|
||||
try {
|
||||
text = readFileSync(file, 'utf8');
|
||||
} catch {
|
||||
diagnostics.push({ file, code: 'read-error', message: 'report file is not readable' });
|
||||
return undefined;
|
||||
}
|
||||
try {
|
||||
return JSON.parse(text);
|
||||
} catch {
|
||||
diagnostics.push({ file, code: 'parse-error', message: 'report is not valid JSON' });
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
function requirementIds(specRoot: string, diagnostics: Diagnostic[]): Set<string> {
|
||||
const ids = new Set<string>();
|
||||
const dir = path.join(specRoot, 'requirements');
|
||||
if (!existsSync(dir)) {
|
||||
diagnostics.push({
|
||||
file: dir,
|
||||
code: 'missing-directory',
|
||||
message: 'requirements/ is required',
|
||||
});
|
||||
return ids;
|
||||
}
|
||||
for (const name of readdirSync(dir)) {
|
||||
if (!name.endsWith('.yaml')) {
|
||||
continue;
|
||||
}
|
||||
const file = path.join(dir, name);
|
||||
try {
|
||||
const doc: unknown = parseDocument(readFileSync(file, 'utf8'), { logLevel: 'silent' }).toJS({
|
||||
maxAliasCount: 5,
|
||||
});
|
||||
if (isRecord(doc) && isString(doc['id'])) {
|
||||
ids.add(doc['id']);
|
||||
}
|
||||
} catch {
|
||||
diagnostics.push({ file, code: 'parse-error', message: 'requirement file is not parseable' });
|
||||
}
|
||||
}
|
||||
return ids;
|
||||
}
|
||||
|
||||
function checkSchema(ajv: Ajv2020, report: unknown, file: string, diagnostics: Diagnostic[]): void {
|
||||
const validateFn = ajv.getSchema(`${SCHEMA_BASE}audit-report.schema.json`);
|
||||
if (validateFn === undefined) {
|
||||
diagnostics.push({
|
||||
file,
|
||||
code: 'missing-schema',
|
||||
message: 'audit-report schema is not loaded',
|
||||
});
|
||||
return;
|
||||
}
|
||||
if (validateFn(report) === true) {
|
||||
return;
|
||||
}
|
||||
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'}`,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
function checkFindingReferences(
|
||||
report: Record<string, unknown>,
|
||||
file: string,
|
||||
requirements: Set<string>,
|
||||
diagnostics: Diagnostic[],
|
||||
): void {
|
||||
const findings = Array.isArray(report['findings']) ? report['findings'] : [];
|
||||
const items: readonly unknown[] = findings;
|
||||
for (const finding of items) {
|
||||
if (!isRecord(finding) || !isString(finding['requirement'])) {
|
||||
continue;
|
||||
}
|
||||
if (!requirements.has(finding['requirement'])) {
|
||||
diagnostics.push({
|
||||
file,
|
||||
code: 'unknown-requirement',
|
||||
message: `finding references undefined requirement ${finding['requirement']}`,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function statusCounts(report: Record<string, unknown>): Map<string, number> {
|
||||
const counts = new Map<string, number>();
|
||||
const findings = Array.isArray(report['findings']) ? report['findings'] : [];
|
||||
const items: readonly unknown[] = findings;
|
||||
for (const finding of items) {
|
||||
if (isRecord(finding) && isString(finding['status'])) {
|
||||
counts.set(finding['status'], (counts.get(finding['status']) ?? 0) + 1);
|
||||
}
|
||||
}
|
||||
return counts;
|
||||
}
|
||||
|
||||
function checkSummary(
|
||||
report: Record<string, unknown>,
|
||||
file: string,
|
||||
diagnostics: Diagnostic[],
|
||||
): void {
|
||||
const summary = report['summary'];
|
||||
if (!isRecord(summary)) {
|
||||
return;
|
||||
}
|
||||
const counts = statusCounts(report);
|
||||
for (const status of FINDING_STATUSES) {
|
||||
const declared = summary[status];
|
||||
const actual = counts.get(status) ?? 0;
|
||||
if (typeof declared === 'number' && declared !== actual) {
|
||||
diagnostics.push({
|
||||
file,
|
||||
code: 'summary-mismatch',
|
||||
message: `summary ${status}=${String(declared)} but findings contain ${String(actual)}`,
|
||||
});
|
||||
}
|
||||
}
|
||||
const extra = Object.keys(summary).filter((key) => !FINDING_STATUSES.includes(key));
|
||||
for (const key of extra) {
|
||||
diagnostics.push({
|
||||
file,
|
||||
code: 'summary-mismatch',
|
||||
message: `summary has unknown status ${key}`,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
export function validateReport(reportFile: string, specRoot: string): ReportValidationResult {
|
||||
const diagnostics: Diagnostic[] = [];
|
||||
const report = readReport(reportFile, diagnostics);
|
||||
if (report === undefined) {
|
||||
return { ok: false, diagnostics };
|
||||
}
|
||||
const ajv = loadAjv(path.join(specRoot, 'schemas'), diagnostics);
|
||||
if (ajv === undefined) {
|
||||
return { ok: false, diagnostics };
|
||||
}
|
||||
checkSchema(ajv, report, reportFile, diagnostics);
|
||||
if (isRecord(report)) {
|
||||
checkFindingReferences(report, reportFile, requirementIds(specRoot, diagnostics), diagnostics);
|
||||
checkSummary(report, reportFile, diagnostics);
|
||||
}
|
||||
diagnostics.sort((a, b) =>
|
||||
`${a.file} ${a.code} ${a.pointer ?? ''}`.localeCompare(
|
||||
`${b.file} ${b.code} ${b.pointer ?? ''}`,
|
||||
),
|
||||
);
|
||||
return { ok: diagnostics.length === 0, diagnostics };
|
||||
}
|
||||
@@ -0,0 +1,574 @@
|
||||
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';
|
||||
import type { Diagnostic } from './validate.ts';
|
||||
|
||||
export interface EffectiveParameter {
|
||||
parameter: string;
|
||||
value: unknown;
|
||||
source: string;
|
||||
}
|
||||
|
||||
export interface EffectiveRequirement {
|
||||
requirement: string;
|
||||
level: string;
|
||||
sources: string[];
|
||||
applicability: { when: string; unless?: string }[];
|
||||
parameters: EffectiveParameter[];
|
||||
}
|
||||
|
||||
export interface ResolveResult {
|
||||
ok: boolean;
|
||||
profiles: string[];
|
||||
effective: EffectiveRequirement[];
|
||||
diagnostics: Diagnostic[];
|
||||
}
|
||||
|
||||
interface ParamDef {
|
||||
type: string;
|
||||
default: unknown;
|
||||
constraints: Record<string, unknown>;
|
||||
file: string;
|
||||
}
|
||||
|
||||
interface ProfileEntry {
|
||||
requirement: string;
|
||||
relax_to?: string;
|
||||
}
|
||||
|
||||
interface ProfileDoc {
|
||||
id: string;
|
||||
file: string;
|
||||
requirements: ProfileEntry[];
|
||||
overrides: { parameter: string; value: unknown }[];
|
||||
}
|
||||
|
||||
const SCHEMA_BASE = 'https://baseline-harness.dev/spec/schemas/';
|
||||
|
||||
const LEVEL_RANK: Readonly<Record<string, number>> = {
|
||||
MUST: 3,
|
||||
'MUST NOT': 3,
|
||||
SHOULD: 2,
|
||||
'SHOULD NOT': 2,
|
||||
MAY: 1,
|
||||
};
|
||||
|
||||
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 sameValue(a: unknown, b: unknown): boolean {
|
||||
return JSON.stringify(a) === JSON.stringify(b);
|
||||
}
|
||||
|
||||
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) {
|
||||
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 filesIn(dir: string, suffix: string): string[] {
|
||||
if (!existsSync(dir)) {
|
||||
return [];
|
||||
}
|
||||
return readdirSync(dir, { withFileTypes: true })
|
||||
.filter((entry) => entry.isFile() && entry.name.endsWith(suffix))
|
||||
.map((entry) => path.join(dir, entry.name))
|
||||
.sort((a, b) => a.localeCompare(b));
|
||||
}
|
||||
|
||||
function validateWith(
|
||||
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 loadDocs(
|
||||
dir: string,
|
||||
kind: string,
|
||||
ajv: Ajv2020,
|
||||
diagnostics: Diagnostic[],
|
||||
): Record<string, Record<string, unknown>> {
|
||||
const docs: Record<string, Record<string, unknown>> = {};
|
||||
for (const file of filesIn(dir, '.yaml')) {
|
||||
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;
|
||||
}
|
||||
if (!validateWith(ajv, kind, value, file, diagnostics)) {
|
||||
continue;
|
||||
}
|
||||
const id = value['id'];
|
||||
if (isString(id)) {
|
||||
docs[id] = value;
|
||||
}
|
||||
}
|
||||
return docs;
|
||||
}
|
||||
|
||||
function paramDef(value: Record<string, unknown>, file: string): ParamDef {
|
||||
return {
|
||||
type: isString(value['type']) ? value['type'] : 'string',
|
||||
default: value['default'],
|
||||
constraints: isRecord(value['constraints']) ? value['constraints'] : {},
|
||||
file,
|
||||
};
|
||||
}
|
||||
|
||||
function collectParamDefs(
|
||||
requirements: Record<string, Record<string, unknown>>,
|
||||
registry: Record<string, ParamDef>,
|
||||
): Record<string, ParamDef> {
|
||||
const defs: Record<string, ParamDef> = { ...registry };
|
||||
for (const [reqId, requirement] of Object.entries(requirements)) {
|
||||
const items = Array.isArray(requirement['parameters']) ? requirement['parameters'] : [];
|
||||
const known: readonly unknown[] = items;
|
||||
for (const item of known) {
|
||||
if (isRecord(item) && isString(item['id'])) {
|
||||
defs[item['id']] = paramDef(item, `requirement ${reqId}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
return defs;
|
||||
}
|
||||
|
||||
function numericOk(value: unknown, c: Record<string, unknown>): boolean {
|
||||
const min = c['minimum'];
|
||||
const max = c['maximum'];
|
||||
if (typeof min !== 'number' && typeof max !== 'number') {
|
||||
return true;
|
||||
}
|
||||
if (typeof value !== 'number') {
|
||||
return false;
|
||||
}
|
||||
if (typeof min === 'number' && value < min) {
|
||||
return false;
|
||||
}
|
||||
return !(typeof max === 'number' && value > max);
|
||||
}
|
||||
|
||||
function enumOk(value: unknown, c: Record<string, unknown>): boolean {
|
||||
const values = c['values'];
|
||||
return !Array.isArray(values) || values.some((item) => sameValue(item, value));
|
||||
}
|
||||
|
||||
function stringOk(value: unknown, c: Record<string, unknown>): boolean {
|
||||
const pattern = c['pattern'];
|
||||
if (
|
||||
typeof pattern === 'string' &&
|
||||
(typeof value !== 'string' || !new RegExp(pattern).test(value))
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
const min = c['minLength'];
|
||||
const max = c['maxLength'];
|
||||
if (typeof min === 'number' && (typeof value !== 'string' || value.length < min)) {
|
||||
return false;
|
||||
}
|
||||
return !(typeof max === 'number' && typeof value === 'string' && value.length > max);
|
||||
}
|
||||
|
||||
function valueInConstraints(value: unknown, def: ParamDef): boolean {
|
||||
const c = def.constraints;
|
||||
return numericOk(value, c) && enumOk(value, c) && stringOk(value, c);
|
||||
}
|
||||
|
||||
function isWeaker(base: string, relaxed: string): boolean {
|
||||
if (base !== 'MUST' && base !== 'SHOULD') {
|
||||
return false;
|
||||
}
|
||||
return (LEVEL_RANK[relaxed] ?? 0) < (LEVEL_RANK[base] ?? 0);
|
||||
}
|
||||
|
||||
class Resolver {
|
||||
private readonly ajv = new Ajv2020({ strict: true, strictTypes: false, allErrors: true });
|
||||
private readonly diagnostics: Diagnostic[] = [];
|
||||
private readonly root: string;
|
||||
|
||||
constructor(root: string) {
|
||||
this.root = root;
|
||||
}
|
||||
|
||||
run(profileIds: readonly string[], presetIds: readonly string[]): ResolveResult {
|
||||
if (!this.addSchemas()) {
|
||||
return { ok: false, profiles: [], effective: [], diagnostics: this.diagnostics };
|
||||
}
|
||||
const requirements = loadDocs(
|
||||
path.join(this.root, 'requirements'),
|
||||
'requirement',
|
||||
this.ajv,
|
||||
this.diagnostics,
|
||||
);
|
||||
const registry = loadParameterRegistry(this.root, this.diagnostics);
|
||||
const profiles = this.loadProfiles();
|
||||
const presets = loadPresets(this.root, this.ajv, this.diagnostics);
|
||||
const selected = this.selectProfiles(profileIds, presetIds, profiles, presets);
|
||||
const defs = collectParamDefs(requirements, registry);
|
||||
const applied = this.applyOverrides(selected, defs);
|
||||
const effective = this.buildEffective(selected, requirements, defs, applied);
|
||||
this.diagnostics.sort((a, b) => `${a.file}${a.code}`.localeCompare(`${b.file}${b.code}`));
|
||||
return {
|
||||
ok: this.diagnostics.length === 0,
|
||||
profiles: selected.map((profile) => profile.id),
|
||||
effective,
|
||||
diagnostics: this.diagnostics,
|
||||
};
|
||||
}
|
||||
|
||||
private push(file: string, code: string, message: string): void {
|
||||
this.diagnostics.push({ file, code, message });
|
||||
}
|
||||
|
||||
private addSchemas(): boolean {
|
||||
const schemasDir = path.join(this.root, 'schemas');
|
||||
const names = filesIn(schemasDir, '.schema.json');
|
||||
if (names.length === 0) {
|
||||
this.push(
|
||||
'schemas/',
|
||||
'missing-directory',
|
||||
'spec root must contain schemas/ with *.schema.json',
|
||||
);
|
||||
return false;
|
||||
}
|
||||
for (const file of names) {
|
||||
let parsed: unknown;
|
||||
try {
|
||||
parsed = JSON.parse(readFileSync(file, 'utf8'));
|
||||
} catch {
|
||||
this.push(file, 'parse-error', 'schema file is not valid JSON');
|
||||
continue;
|
||||
}
|
||||
if (isSchema(parsed)) {
|
||||
this.ajv.addSchema(parsed);
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
private loadProfiles(): Record<string, ProfileDoc> {
|
||||
const docs = loadDocs(path.join(this.root, 'profiles'), 'profile', this.ajv, this.diagnostics);
|
||||
const profiles: Record<string, ProfileDoc> = {};
|
||||
for (const [id, value] of Object.entries(docs)) {
|
||||
profiles[id] = {
|
||||
id,
|
||||
file: `profiles/${id}.yaml`,
|
||||
requirements: profileEntries(value),
|
||||
overrides: profileOverrides(value),
|
||||
};
|
||||
}
|
||||
return profiles;
|
||||
}
|
||||
|
||||
private selectProfiles(
|
||||
profileIds: readonly string[],
|
||||
presetIds: readonly string[],
|
||||
profiles: Record<string, ProfileDoc>,
|
||||
presets: Record<string, string[]>,
|
||||
): ProfileDoc[] {
|
||||
const ids = new Set<string>(profileIds);
|
||||
for (const presetId of presetIds) {
|
||||
const expanded = presets[presetId];
|
||||
if (expanded === undefined) {
|
||||
this.push('presets/', 'unknown-preset', `preset ${presetId} is not defined`);
|
||||
continue;
|
||||
}
|
||||
for (const profileId of expanded) {
|
||||
ids.add(profileId);
|
||||
}
|
||||
}
|
||||
const selected: ProfileDoc[] = [];
|
||||
for (const id of [...ids].sort((a, b) => a.localeCompare(b))) {
|
||||
const profile = profiles[id];
|
||||
if (profile === undefined) {
|
||||
this.push('profiles/', 'unknown-profile', `profile ${id} is not defined`);
|
||||
continue;
|
||||
}
|
||||
selected.push(profile);
|
||||
}
|
||||
return selected;
|
||||
}
|
||||
|
||||
private applyOverrides(
|
||||
selected: ProfileDoc[],
|
||||
defs: Record<string, ParamDef>,
|
||||
): Map<string, { value: unknown; source: string }> {
|
||||
const applied = new Map<string, { value: unknown; source: string }>();
|
||||
for (const profile of selected) {
|
||||
for (const override of profile.overrides) {
|
||||
this.applyOne(profile, override, defs, applied);
|
||||
}
|
||||
}
|
||||
return applied;
|
||||
}
|
||||
|
||||
private applyOne(
|
||||
profile: ProfileDoc,
|
||||
override: { parameter: string; value: unknown },
|
||||
defs: Record<string, ParamDef>,
|
||||
applied: Map<string, { value: unknown; source: string }>,
|
||||
): void {
|
||||
const def = defs[override.parameter];
|
||||
if (def === undefined) {
|
||||
this.push(
|
||||
profile.file,
|
||||
'unknown-parameter',
|
||||
`parameter ${override.parameter} is not defined`,
|
||||
);
|
||||
return;
|
||||
}
|
||||
const previous = applied.get(override.parameter);
|
||||
if (previous !== undefined && !sameValue(previous.value, override.value)) {
|
||||
this.push(
|
||||
profile.file,
|
||||
'parameter-conflict',
|
||||
`${override.parameter} overridden differently by ${previous.source} and ${profile.id}`,
|
||||
);
|
||||
return;
|
||||
}
|
||||
if (!valueInConstraints(override.value, def)) {
|
||||
this.push(
|
||||
profile.file,
|
||||
'parameter-out-of-range',
|
||||
`${override.parameter} value is outside its constraints`,
|
||||
);
|
||||
return;
|
||||
}
|
||||
applied.set(override.parameter, { value: override.value, source: profile.id });
|
||||
}
|
||||
|
||||
private buildEffective(
|
||||
selected: ProfileDoc[],
|
||||
requirements: Record<string, Record<string, unknown>>,
|
||||
defs: Record<string, ParamDef>,
|
||||
applied: Map<string, { value: unknown; source: string }>,
|
||||
): EffectiveRequirement[] {
|
||||
const effective: EffectiveRequirement[] = [];
|
||||
const ids = new Set<string>();
|
||||
for (const profile of selected) {
|
||||
for (const item of profile.requirements) {
|
||||
ids.add(item.requirement);
|
||||
}
|
||||
}
|
||||
for (const id of [...ids].sort((a, b) => a.localeCompare(b))) {
|
||||
const requirement = requirements[id];
|
||||
if (requirement === undefined) {
|
||||
this.push(
|
||||
'profiles/',
|
||||
'unknown-requirement',
|
||||
`profile references undefined requirement ${id}`,
|
||||
);
|
||||
continue;
|
||||
}
|
||||
effective.push(this.buildOne(id, requirement, selected, defs, applied));
|
||||
}
|
||||
return effective;
|
||||
}
|
||||
|
||||
private buildOne(
|
||||
id: string,
|
||||
requirement: Record<string, unknown>,
|
||||
selected: ProfileDoc[],
|
||||
defs: Record<string, ParamDef>,
|
||||
applied: Map<string, { value: unknown; source: string }>,
|
||||
): EffectiveRequirement {
|
||||
const baseLevel = isString(requirement['level']) ? requirement['level'] : 'MUST';
|
||||
return {
|
||||
requirement: id,
|
||||
level: this.effectiveLevel(id, baseLevel, selected),
|
||||
sources: selected
|
||||
.filter((profile) => profile.requirements.some((item) => item.requirement === id))
|
||||
.map((profile) => profile.id),
|
||||
applicability: requirementApplicability(requirement),
|
||||
parameters: requirementParameters(requirement, defs, applied),
|
||||
};
|
||||
}
|
||||
|
||||
private effectiveLevel(id: string, baseLevel: string, selected: ProfileDoc[]): string {
|
||||
const relaxations = new Set<string>();
|
||||
for (const profile of selected) {
|
||||
for (const item of profile.requirements) {
|
||||
if (item.requirement === id && isString(item.relax_to)) {
|
||||
relaxations.add(item.relax_to);
|
||||
}
|
||||
}
|
||||
}
|
||||
if (relaxations.size > 1) {
|
||||
this.push('profiles/', 'relaxation-conflict', `${id} relaxed in conflicting ways`);
|
||||
return baseLevel;
|
||||
}
|
||||
const only = [...relaxations][0];
|
||||
if (only === undefined) {
|
||||
return baseLevel;
|
||||
}
|
||||
if (!isWeaker(baseLevel, only)) {
|
||||
this.push(
|
||||
'profiles/',
|
||||
'invalid-relaxation',
|
||||
`${id}: ${only} is not weaker than ${baseLevel}`,
|
||||
);
|
||||
return baseLevel;
|
||||
}
|
||||
return only;
|
||||
}
|
||||
}
|
||||
|
||||
function loadParameterRegistry(root: string, diagnostics: Diagnostic[]): Record<string, ParamDef> {
|
||||
const registry: Record<string, ParamDef> = {};
|
||||
for (const file of filesIn(path.join(root, 'parameters'), '.yaml')) {
|
||||
const value = readYaml(file, diagnostics);
|
||||
if (isRecord(value) && isString(value['id'])) {
|
||||
registry[value['id']] = paramDef(value, file);
|
||||
}
|
||||
}
|
||||
return registry;
|
||||
}
|
||||
|
||||
function loadPresets(
|
||||
root: string,
|
||||
ajv: Ajv2020,
|
||||
diagnostics: Diagnostic[],
|
||||
): Record<string, string[]> {
|
||||
const docs = loadDocs(path.join(root, 'presets'), 'preset', ajv, diagnostics);
|
||||
const presets: Record<string, string[]> = {};
|
||||
for (const [id, value] of Object.entries(docs)) {
|
||||
const items = Array.isArray(value['profiles']) ? value['profiles'] : [];
|
||||
presets[id] = items.filter(isString);
|
||||
}
|
||||
return presets;
|
||||
}
|
||||
|
||||
function profileEntries(value: Record<string, unknown>): ProfileEntry[] {
|
||||
const items = Array.isArray(value['requirements']) ? value['requirements'] : [];
|
||||
const entries: ProfileEntry[] = [];
|
||||
const known: readonly unknown[] = items;
|
||||
for (const item of known) {
|
||||
if (!isRecord(item) || !isString(item['requirement'])) {
|
||||
continue;
|
||||
}
|
||||
const entry: ProfileEntry = isString(item['relax_to'])
|
||||
? { requirement: item['requirement'], relax_to: item['relax_to'] }
|
||||
: { requirement: item['requirement'] };
|
||||
entries.push(entry);
|
||||
}
|
||||
return entries;
|
||||
}
|
||||
|
||||
function profileOverrides(value: Record<string, unknown>): { parameter: string; value: unknown }[] {
|
||||
const items = Array.isArray(value['parameter_overrides']) ? value['parameter_overrides'] : [];
|
||||
const overrides: { parameter: string; value: unknown }[] = [];
|
||||
const known: readonly unknown[] = items;
|
||||
for (const item of known) {
|
||||
if (isRecord(item) && isString(item['parameter'])) {
|
||||
overrides.push({ parameter: item['parameter'], value: item['value'] });
|
||||
}
|
||||
}
|
||||
return overrides;
|
||||
}
|
||||
|
||||
function requirementApplicability(
|
||||
requirement: Record<string, unknown>,
|
||||
): { when: string; unless?: string }[] {
|
||||
const items = Array.isArray(requirement['applicability']) ? requirement['applicability'] : [];
|
||||
const result: { when: string; unless?: string }[] = [];
|
||||
const known: readonly unknown[] = items;
|
||||
for (const item of known) {
|
||||
if (!isRecord(item) || !isString(item['when'])) {
|
||||
continue;
|
||||
}
|
||||
result.push(
|
||||
isString(item['unless'])
|
||||
? { when: item['when'], unless: item['unless'] }
|
||||
: { when: item['when'] },
|
||||
);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
function requirementParameters(
|
||||
requirement: Record<string, unknown>,
|
||||
defs: Record<string, ParamDef>,
|
||||
applied: Map<string, { value: unknown; source: string }>,
|
||||
): EffectiveParameter[] {
|
||||
const result: EffectiveParameter[] = [];
|
||||
const items = Array.isArray(requirement['parameters']) ? requirement['parameters'] : [];
|
||||
const known: readonly unknown[] = items;
|
||||
for (const item of known) {
|
||||
if (!isRecord(item) || !isString(item['id'])) {
|
||||
continue;
|
||||
}
|
||||
const parameter = item['id'];
|
||||
const override = applied.get(parameter);
|
||||
if (override !== undefined) {
|
||||
result.push({ parameter, value: override.value, source: override.source });
|
||||
continue;
|
||||
}
|
||||
const def = defs[parameter];
|
||||
if (def !== undefined && def.default !== undefined) {
|
||||
result.push({ parameter, value: def.default, source: 'spec' });
|
||||
}
|
||||
}
|
||||
result.sort((a, b) => a.parameter.localeCompare(b.parameter));
|
||||
return result;
|
||||
}
|
||||
|
||||
export function resolveProfiles(
|
||||
root: string,
|
||||
profileIds: readonly string[],
|
||||
presetIds: readonly string[],
|
||||
): ResolveResult {
|
||||
return new Resolver(root).run(profileIds, presetIds);
|
||||
}
|
||||
@@ -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 };
|
||||
}
|
||||
@@ -0,0 +1,606 @@
|
||||
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; optional?: boolean }[] = [
|
||||
{ dir: 'domains', schema: 'domain' },
|
||||
{ dir: 'capabilities', schema: 'capability' },
|
||||
{ dir: 'requirements', schema: 'requirement' },
|
||||
{ dir: 'parameters', schema: 'parameter' },
|
||||
{ dir: 'antipatterns', schema: 'antipattern' },
|
||||
// Профили и пресеты — нормативный контент, но не обязательны для валидации
|
||||
// ядра спецификации: корень без них остаётся валидным (BHL-041).
|
||||
{ dir: 'profiles', schema: 'profile', optional: true },
|
||||
{ dir: 'presets', schema: 'preset', optional: true },
|
||||
];
|
||||
|
||||
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) {
|
||||
docs.push(...this.loadEntityDir(spec));
|
||||
}
|
||||
return docs;
|
||||
}
|
||||
|
||||
private loadEntityDir(spec: { dir: string; schema: string; optional?: boolean }): Doc[] {
|
||||
const dir = path.join(this.root, spec.dir);
|
||||
if (!existsSync(dir)) {
|
||||
if (spec.optional !== true) {
|
||||
this.push(`${spec.dir}/`, 'missing-directory', `directory ${spec.dir}/ is required`);
|
||||
}
|
||||
return [];
|
||||
}
|
||||
const docs: Doc[] = [];
|
||||
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();
|
||||
}
|
||||
@@ -0,0 +1,234 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { spawnSync } from 'node:child_process';
|
||||
import { mkdirSync, mkdtempSync, cpSync, readFileSync, 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 specRoot = path.join(import.meta.dirname, '..', '..', '..', 'examples', 'synthetic-spec');
|
||||
const GENERATED_AT = '2026-01-01';
|
||||
|
||||
function makeDir() {
|
||||
const dir = mkdtempSync(path.join(os.tmpdir(), 'bhl-audit-'));
|
||||
return dir;
|
||||
}
|
||||
|
||||
function writeProject(dir, files) {
|
||||
for (const [name, content] of Object.entries(files)) {
|
||||
const target = path.join(dir, name);
|
||||
mkdirSync(path.dirname(target), { recursive: true });
|
||||
writeFileSync(target, content, 'utf8');
|
||||
}
|
||||
}
|
||||
|
||||
function runAudit(t, projectFiles) {
|
||||
const dir = makeDir();
|
||||
t.after(() => rmSync(dir, { recursive: true, force: true }));
|
||||
writeProject(dir, projectFiles);
|
||||
const out = path.join(dir, 'out', 'report.json');
|
||||
const proc = spawnSync(
|
||||
process.execPath,
|
||||
[
|
||||
cli,
|
||||
'audit',
|
||||
dir,
|
||||
'--out',
|
||||
out,
|
||||
'--spec-root',
|
||||
specRoot,
|
||||
'--preset',
|
||||
'preset-synth-all',
|
||||
'--spec-version',
|
||||
'0.1.0',
|
||||
'--generated-at',
|
||||
GENERATED_AT,
|
||||
],
|
||||
{ encoding: 'utf8' },
|
||||
);
|
||||
return { dir, out, code: proc.status, stdout: JSON.parse(proc.stdout) };
|
||||
}
|
||||
|
||||
const GOOD_PROJECT = {
|
||||
'package.json': JSON.stringify({ name: 'fixture', scripts: { quality: 'node check.mjs' } }),
|
||||
'package-lock.json': JSON.stringify({ lockfileVersion: 3 }),
|
||||
'.github/workflows/ci.yml': 'name: ci\n',
|
||||
};
|
||||
|
||||
test('audit: детерминированный отчёт проходит report validate и повторяется байт-в-байт', (t) => {
|
||||
const first = runAudit(t, GOOD_PROJECT);
|
||||
assert.equal(first.code, 0);
|
||||
assert.equal(first.stdout.data.out, first.out);
|
||||
const report1 = readFileSync(first.out, 'utf8');
|
||||
const reportJson = JSON.parse(report1);
|
||||
assert.equal(reportJson.generated_at, GENERATED_AT);
|
||||
assert.ok(['directory', 'repository'].includes(reportJson.subject.kind));
|
||||
assert.match(reportJson.subject.fingerprint, /^sha256:[a-f0-9]{64}$/);
|
||||
assert.deepEqual(reportJson.summary, {
|
||||
PASS: 3,
|
||||
FAIL: 0,
|
||||
PARTIAL: 0,
|
||||
EXEMPT: 0,
|
||||
NOT_APPLICABLE: 0,
|
||||
UNKNOWN: 0,
|
||||
BLOCKED: 0,
|
||||
});
|
||||
const validate = spawnSync(
|
||||
process.execPath,
|
||||
[cli, 'report', 'validate', first.out, '--spec-root', specRoot],
|
||||
{ encoding: 'utf8' },
|
||||
);
|
||||
assert.equal(validate.status, 0, validate.stdout);
|
||||
const second = runAudit(t, GOOD_PROJECT);
|
||||
assert.equal(readFileSync(second.out, 'utf8'), report1, 'повторный аудит идентичен');
|
||||
});
|
||||
|
||||
test('audit: отсутствующие артефакты дают FAIL без обвала отчёта', (t) => {
|
||||
const run = runAudit(t, { 'README.md': 'проект без проверок\n' });
|
||||
assert.equal(run.code, 0);
|
||||
const report = JSON.parse(readFileSync(run.out, 'utf8'));
|
||||
assert.equal(report.summary.FAIL, 3);
|
||||
assert.equal(report.summary.PASS, 0);
|
||||
for (const finding of report.findings) {
|
||||
assert.equal(finding.status, 'FAIL');
|
||||
assert.ok(finding.rationale.length > 10);
|
||||
}
|
||||
const validate = spawnSync(
|
||||
process.execPath,
|
||||
[cli, 'report', 'validate', run.out, '--spec-root', specRoot],
|
||||
{
|
||||
encoding: 'utf8',
|
||||
},
|
||||
);
|
||||
assert.equal(validate.status, 0, validate.stdout);
|
||||
});
|
||||
|
||||
test('audit: usage-ошибки и нечитаемый spec-root дают понятные коды', (t) => {
|
||||
const dir = makeDir();
|
||||
t.after(() => rmSync(dir, { recursive: true, force: true }));
|
||||
const noOut = spawnSync(process.execPath, [cli, 'audit', dir], { encoding: 'utf8' });
|
||||
assert.equal(noOut.status, 2);
|
||||
assert.equal(JSON.parse(noOut.stdout).error.code, 'USAGE');
|
||||
const badSpec = spawnSync(
|
||||
process.execPath,
|
||||
[cli, 'audit', dir, '--out', path.join(dir, 'r.json'), '--spec-root', path.join(dir, 'нет')],
|
||||
{ encoding: 'utf8' },
|
||||
);
|
||||
assert.equal(badSpec.status, 1);
|
||||
assert.equal(JSON.parse(badSpec.stdout).error.code, 'VALIDATION_FAILED');
|
||||
});
|
||||
|
||||
function makeFixtureSpec(t) {
|
||||
const dir = makeDir();
|
||||
t.after(() => rmSync(dir, { recursive: true, force: true }));
|
||||
const spec = path.join(dir, 'spec');
|
||||
cpSync(specRoot, spec, { recursive: true });
|
||||
return { dir, spec };
|
||||
}
|
||||
|
||||
function auditRun(spec, projectDir, out, extraArgs) {
|
||||
return spawnSync(
|
||||
process.execPath,
|
||||
[
|
||||
cli,
|
||||
'audit',
|
||||
projectDir,
|
||||
'--out',
|
||||
out,
|
||||
'--spec-root',
|
||||
spec,
|
||||
'--generated-at',
|
||||
GENERATED_AT,
|
||||
...extraArgs,
|
||||
],
|
||||
{ encoding: 'utf8' },
|
||||
);
|
||||
}
|
||||
|
||||
test('audit: версия спецификации из флага, из lock.json или ошибка (C1/BHL-043)', (t) => {
|
||||
const { dir, spec } = makeFixtureSpec(t);
|
||||
const project = path.join(dir, 'project');
|
||||
writeProject(project, GOOD_PROJECT);
|
||||
const noVersion = auditRun(spec, project, path.join(dir, 'r1.json'), []);
|
||||
assert.equal(noVersion.status, 1);
|
||||
assert.equal(JSON.parse(noVersion.stdout).error.code, 'VALIDATION_FAILED');
|
||||
assert.match(noVersion.stdout, /spec-version-unknown/);
|
||||
writeProject(dir, { 'lock.json': JSON.stringify({ version: '9.9.9' }) });
|
||||
const fromLock = auditRun(spec, project, path.join(dir, 'r2.json'), []);
|
||||
assert.equal(fromLock.status, 0, fromLock.stdout);
|
||||
const report = JSON.parse(readFileSync(path.join(dir, 'r2.json'), 'utf8'));
|
||||
assert.equal(report.spec_version, '9.9.9');
|
||||
const flagged = auditRun(spec, project, path.join(dir, 'r3.json'), ['--spec-version', '8.8.8']);
|
||||
assert.equal(flagged.status, 0);
|
||||
assert.equal(JSON.parse(readFileSync(path.join(dir, 'r3.json'), 'utf8')).spec_version, '8.8.8');
|
||||
});
|
||||
|
||||
test('audit: UNKNOWN-находки валидны по схеме отчёта (C2/BHL-043)', (t) => {
|
||||
const { dir, spec } = makeFixtureSpec(t);
|
||||
const alpha = readFileSync(path.join(spec, 'requirements', 'req-synth-alpha.yaml'), 'utf8');
|
||||
writeProject(spec, {
|
||||
'requirements/req-plain-no-check.yaml': alpha.replace('req-synth-alpha', 'req-plain-no-check'),
|
||||
'profiles/prof-plain.yaml':
|
||||
'id: prof-plain\ntitle: Только без проверки\ndescription: Профиль фикстуры с требованием без детерминированной проверки.\nrequirements:\n - requirement: req-plain-no-check\n',
|
||||
});
|
||||
const project = path.join(dir, 'project');
|
||||
writeProject(project, GOOD_PROJECT);
|
||||
const out = path.join(dir, 'r.json');
|
||||
const run = auditRun(spec, project, out, ['--spec-version', '0.1.0', '--profile', 'prof-plain']);
|
||||
assert.equal(run.status, 0, run.stdout);
|
||||
const report = JSON.parse(readFileSync(out, 'utf8'));
|
||||
assert.equal(report.findings[0].status, 'UNKNOWN');
|
||||
const validate = spawnSync(
|
||||
process.execPath,
|
||||
[cli, 'report', 'validate', out, '--spec-root', spec],
|
||||
{
|
||||
encoding: 'utf8',
|
||||
},
|
||||
);
|
||||
assert.equal(validate.status, 0, validate.stdout);
|
||||
});
|
||||
|
||||
test('audit: отпечаток не зависит от изменчивого локального состояния .pi/.artifacts (C3/BHL-043)', (t) => {
|
||||
const { dir, spec } = makeFixtureSpec(t);
|
||||
const project = path.join(dir, 'project');
|
||||
writeProject(project, GOOD_PROJECT);
|
||||
const first = auditRun(spec, project, path.join(dir, 'r1.json'), ['--spec-version', '0.1.0']);
|
||||
assert.equal(first.status, 0, first.stdout);
|
||||
writeProject(project, {
|
||||
'.pi/transcript.jsonl': '{"turn":1}\n',
|
||||
'.artifacts/tmp.bin': 'volatile',
|
||||
});
|
||||
const second = auditRun(spec, project, path.join(dir, 'r2.json'), ['--spec-version', '0.1.0']);
|
||||
assert.equal(second.status, 0, second.stdout);
|
||||
assert.equal(
|
||||
readFileSync(path.join(dir, 'r2.json'), 'utf8'),
|
||||
readFileSync(path.join(dir, 'r1.json'), 'utf8'),
|
||||
);
|
||||
});
|
||||
|
||||
test('audit: req-single-quality-command проверяется детерминированно (C4/BHL-043)', (t) => {
|
||||
const { dir, spec } = makeFixtureSpec(t);
|
||||
const realReq = path.join(
|
||||
import.meta.dirname,
|
||||
'..',
|
||||
'..',
|
||||
'..',
|
||||
'spec',
|
||||
'requirements',
|
||||
'req-single-quality-command.yaml',
|
||||
);
|
||||
cpSync(realReq, path.join(spec, 'requirements', 'req-single-quality-command.yaml'));
|
||||
writeProject(spec, {
|
||||
'profiles/prof-real.yaml':
|
||||
'id: prof-real\ntitle: Реальное требование\ndescription: Профиль фикстуры с реальным требованием единой команды качества.\nrequirements:\n - requirement: req-single-quality-command\n',
|
||||
});
|
||||
const project = path.join(dir, 'project');
|
||||
writeProject(project, GOOD_PROJECT);
|
||||
const out = path.join(dir, 'r.json');
|
||||
const run = auditRun(spec, project, out, ['--spec-version', '0.1.0', '--profile', 'prof-real']);
|
||||
assert.equal(run.status, 0, run.stdout);
|
||||
const report = JSON.parse(readFileSync(out, 'utf8'));
|
||||
const finding = report.findings.find((f) => f.requirement === 'req-single-quality-command');
|
||||
assert.equal(finding.method, 'deterministic');
|
||||
assert.equal(finding.status, 'PASS');
|
||||
});
|
||||
@@ -0,0 +1,40 @@
|
||||
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('audit без обязательных аргументов возвращает USAGE и код 2', () => {
|
||||
const result = run('audit');
|
||||
assert.equal(result.code, 2);
|
||||
assert.equal(result.envelope.ok, false);
|
||||
assert.equal(result.envelope.error.code, 'USAGE');
|
||||
});
|
||||
@@ -0,0 +1,208 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { spawnSync } from 'node:child_process';
|
||||
import {
|
||||
appendFileSync,
|
||||
mkdirSync,
|
||||
mkdtempSync,
|
||||
readFileSync,
|
||||
rmSync,
|
||||
unlinkSync,
|
||||
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',
|
||||
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',
|
||||
required: ['id', 'domain', 'title', 'description'],
|
||||
properties: {
|
||||
id: { type: 'string', pattern: '^cap-[a-z0-9-]+$' },
|
||||
domain: { type: 'string' },
|
||||
title: { type: 'string' },
|
||||
description: { type: 'string' },
|
||||
},
|
||||
},
|
||||
'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: ['integer', 'string', 'boolean', 'enum'] },
|
||||
},
|
||||
},
|
||||
'requirement.schema.json': {
|
||||
$id: 'https://baseline-harness.dev/spec/schemas/requirement.schema.json',
|
||||
type: 'object',
|
||||
required: ['id', 'domain', 'capability', 'level', 'statement'],
|
||||
properties: {
|
||||
id: { type: 'string', pattern: '^req-[a-z0-9-]+$' },
|
||||
domain: { type: 'string' },
|
||||
capability: { type: 'string' },
|
||||
statement: { type: 'string' },
|
||||
level: { enum: ['MUST', 'MUST NOT', 'SHOULD', 'SHOULD NOT', 'MAY'] },
|
||||
},
|
||||
},
|
||||
'antipattern.schema.json': {
|
||||
$id: 'https://baseline-harness.dev/spec/schemas/antipattern.schema.json',
|
||||
type: 'object',
|
||||
required: ['id', 'level'],
|
||||
properties: {
|
||||
id: { type: 'string', pattern: '^ant-[a-z0-9-]+$' },
|
||||
level: { enum: ['SHOULD NOT', 'MUST NOT'] },
|
||||
},
|
||||
},
|
||||
'normative-change.schema.json': {
|
||||
$id: 'https://baseline-harness.dev/spec/schemas/normative-change.schema.json',
|
||||
type: 'object',
|
||||
properties: { id: { type: 'string' } },
|
||||
},
|
||||
};
|
||||
|
||||
const RELEASE_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\n',
|
||||
'parameters/.gitkeep': '',
|
||||
'antipatterns/.gitkeep': '',
|
||||
'CHANGELOG.yaml': 'changes: []\n',
|
||||
};
|
||||
|
||||
function tempDir(prefix) {
|
||||
return mkdtempSync(path.join(os.tmpdir(), prefix));
|
||||
}
|
||||
|
||||
function makeRelease(t) {
|
||||
const source = tempDir('bhl-release-');
|
||||
mkdirSync(path.join(source, 'schemas'), { recursive: true });
|
||||
for (const [name, schema] of Object.entries(SCHEMAS)) {
|
||||
writeFileSync(path.join(source, 'schemas', name), JSON.stringify(schema), 'utf8');
|
||||
}
|
||||
for (const [name, contents] of Object.entries(RELEASE_FILES)) {
|
||||
const target = path.join(source, name);
|
||||
mkdirSync(path.dirname(target), { recursive: true });
|
||||
writeFileSync(target, contents, 'utf8');
|
||||
}
|
||||
const cache = tempDir('bhl-cache-');
|
||||
t.after(() => {
|
||||
rmSync(source, { recursive: true, force: true });
|
||||
rmSync(cache, { recursive: true, force: true });
|
||||
});
|
||||
return { source, cache };
|
||||
}
|
||||
|
||||
function runCli(...args) {
|
||||
const proc = spawnSync(process.execPath, [cli, ...args], { encoding: 'utf8' });
|
||||
return { code: proc.status, envelope: JSON.parse(proc.stdout) };
|
||||
}
|
||||
|
||||
function readLockText(cache, version) {
|
||||
return readFileSync(path.join(cache, version, 'lock.json'), 'utf8');
|
||||
}
|
||||
|
||||
function fetchAndVerify(t) {
|
||||
const { source, cache } = makeRelease(t);
|
||||
const fetched = runCli('fetch', source, '--version', '0.1.0', '--cache', cache);
|
||||
assert.equal(fetched.code, 0);
|
||||
const verified = runCli('verify', '--version', '0.1.0', '--cache', cache);
|
||||
return { source, cache, fetched, verified };
|
||||
}
|
||||
|
||||
function codes(result) {
|
||||
return result.envelope.data.errors.map((item) => item.code);
|
||||
}
|
||||
|
||||
test('fetch кладёт релиз в кеш с lock из SHA-256 фактических байтов', (t) => {
|
||||
const { cache, fetched, verified } = fetchAndVerify(t);
|
||||
assert.equal(verified.code, 0);
|
||||
assert.equal(fetched.envelope.data.files, 12);
|
||||
const lock = JSON.parse(readLockText(cache, '0.1.0'));
|
||||
assert.equal(lock.algorithm, 'sha256');
|
||||
assert.equal(lock.files.length, 12);
|
||||
assert.deepEqual(
|
||||
lock.files.map((entry) => entry.path),
|
||||
[...lock.files.map((entry) => entry.path)].sort((a, b) => a.localeCompare(b)),
|
||||
);
|
||||
assert.ok(lock.files.some((entry) => entry.path === 'CHANGELOG.yaml'));
|
||||
for (const entry of lock.files) {
|
||||
assert.match(entry.digest, /^[a-f0-9]{64}$/);
|
||||
}
|
||||
});
|
||||
|
||||
test('битый кеш прерывает использование артефакта с явной диагностикой', (t) => {
|
||||
const { cache } = fetchAndVerify(t);
|
||||
appendFileSync(
|
||||
path.join(cache, '0.1.0', 'spec', 'requirements', 'req-alpha.yaml'),
|
||||
'x\n',
|
||||
'utf8',
|
||||
);
|
||||
const verified = runCli('verify', '--version', '0.1.0', '--cache', cache);
|
||||
assert.equal(verified.code, 1);
|
||||
assert.ok(codes(verified).includes('checksum-mismatch'));
|
||||
});
|
||||
|
||||
test('удалённый или лишний файл в кеше обнаруживается', (t) => {
|
||||
const { cache } = fetchAndVerify(t);
|
||||
unlinkSync(path.join(cache, '0.1.0', 'spec', 'CHANGELOG.yaml'));
|
||||
assert.ok(
|
||||
codes(runCli('verify', '--version', '0.1.0', '--cache', cache)).includes('missing-file'),
|
||||
);
|
||||
const extra = fetchAndVerify(t);
|
||||
writeFileSync(path.join(extra.cache, '0.1.0', 'spec', 'EXTRA.md'), 'лишний\n', 'utf8');
|
||||
assert.ok(
|
||||
codes(runCli('verify', '--version', '0.1.0', '--cache', extra.cache)).includes(
|
||||
'unexpected-file',
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
test('офлайн-повтор: verify и validate зафиксированной версии работают без источника', (t) => {
|
||||
const { source, cache } = fetchAndVerify(t);
|
||||
rmSync(source, { recursive: true, force: true });
|
||||
const verified = runCli('verify', '--version', '0.1.0', '--cache', cache);
|
||||
assert.equal(verified.code, 0);
|
||||
const validated = runCli('validate', path.join(cache, '0.1.0', 'spec'));
|
||||
assert.equal(validated.code, 0);
|
||||
assert.deepEqual(validated.envelope.data.errors, []);
|
||||
});
|
||||
|
||||
test('отсутствующий кеш даёт missing-cache', (t) => {
|
||||
const { cache } = makeRelease(t);
|
||||
const verified = runCli('verify', '--version', '0.9.9', '--cache', cache);
|
||||
assert.equal(verified.code, 1);
|
||||
assert.ok(codes(verified).includes('missing-cache'));
|
||||
});
|
||||
|
||||
test('fetch детерминирован: повторный fetch даёт идентичный lock', (t) => {
|
||||
const { source, cache } = makeRelease(t);
|
||||
const first = runCli('fetch', source, '--version', '0.1.0', '--cache', cache);
|
||||
const lockFirst = readLockText(cache, '0.1.0');
|
||||
const second = runCli('fetch', source, '--version', '0.1.0', '--cache', cache);
|
||||
assert.equal(first.code, 0);
|
||||
assert.equal(second.code, 0);
|
||||
assert.equal(readLockText(cache, '0.1.0'), lockFirst);
|
||||
});
|
||||
|
||||
test('использование fetch и verify', () => {
|
||||
assert.equal(runCli('fetch', '/tmp/x').code, 2);
|
||||
assert.equal(runCli('verify').code, 2);
|
||||
assert.equal(runCli('verify', '--version', '1.0.0').code, 2);
|
||||
});
|
||||
@@ -0,0 +1,44 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { spawnSync } from 'node:child_process';
|
||||
import { mkdtempSync, readdirSync, rmSync } from 'node:fs';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
|
||||
const pkgRoot = path.join(import.meta.dirname, '..');
|
||||
|
||||
test('pack: tarball устанавливается локально, bhl version отвечает конвертом', (t) => {
|
||||
const tmp = mkdtempSync(path.join(os.tmpdir(), 'bhl-pack-'));
|
||||
t.after(() => rmSync(tmp, { recursive: true, force: true }));
|
||||
const pack = spawnSync('npm', ['pack', '--pack-destination', tmp], {
|
||||
cwd: pkgRoot,
|
||||
encoding: 'utf8',
|
||||
});
|
||||
assert.equal(pack.status, 0, pack.stderr);
|
||||
const tarball = readdirSync(tmp).find((name) => name.endsWith('.tgz'));
|
||||
assert.ok(tarball, 'tarball создан');
|
||||
const installDir = path.join(tmp, 'install');
|
||||
const install = spawnSync(
|
||||
'npm',
|
||||
[
|
||||
'install',
|
||||
path.join(tmp, tarball),
|
||||
'--prefix',
|
||||
installDir,
|
||||
'--no-save',
|
||||
'--ignore-scripts',
|
||||
'--no-audit',
|
||||
'--no-fund',
|
||||
],
|
||||
{ encoding: 'utf8' },
|
||||
);
|
||||
assert.equal(install.status, 0, install.stderr);
|
||||
const bin = path.join(installDir, 'node_modules', '.bin', 'bhl');
|
||||
const run = spawnSync(bin, ['version'], { encoding: 'utf8' });
|
||||
assert.equal(run.status, 0, run.stderr);
|
||||
const envelope = JSON.parse(run.stdout);
|
||||
assert.equal(envelope.ok, true);
|
||||
assert.equal(envelope.command, 'version');
|
||||
assert.equal(envelope.data.name, '@baseline-harness/bhl');
|
||||
assert.equal(envelope.data.version, '0.0.1');
|
||||
});
|
||||
@@ -0,0 +1,76 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { spawnSync } from 'node:child_process';
|
||||
import { createHash } from 'node:crypto';
|
||||
import { mkdtempSync, readFileSync, rmSync } from 'node:fs';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
|
||||
const cli = path.join(import.meta.dirname, '..', 'src', 'cli.ts');
|
||||
const specRoot = path.join(import.meta.dirname, '..', '..', '..', 'examples', 'synthetic-spec');
|
||||
|
||||
function tmp(t) {
|
||||
const dir = mkdtempSync(path.join(os.tmpdir(), 'bhl-release-'));
|
||||
t.after(() => rmSync(dir, { recursive: true, force: true }));
|
||||
return dir;
|
||||
}
|
||||
|
||||
function runRelease(t, version) {
|
||||
const out = tmp(t);
|
||||
const proc = spawnSync(
|
||||
process.execPath,
|
||||
[cli, 'release', specRoot, '--version', version, '--out', out],
|
||||
{ encoding: 'utf8' },
|
||||
);
|
||||
return { out, code: proc.status, stdout: JSON.parse(proc.stdout) };
|
||||
}
|
||||
|
||||
function sha256(file) {
|
||||
return createHash('sha256').update(readFileSync(file)).digest('hex');
|
||||
}
|
||||
|
||||
test('release: tarball детерминирован, manifest сверяется с извлечёнными байтами', (t) => {
|
||||
const first = runRelease(t, '0.1.0');
|
||||
assert.equal(first.code, 0);
|
||||
assert.deepEqual(first.stdout.data.files, [
|
||||
'bhs-spec-0.1.0.tar',
|
||||
'bhs-spec-0.1.0.manifest.json',
|
||||
'bhs-spec-0.1.0.tar.sha256',
|
||||
]);
|
||||
const tarball = path.join(first.out, 'bhs-spec-0.1.0.tar');
|
||||
const manifest = JSON.parse(
|
||||
readFileSync(path.join(first.out, 'bhs-spec-0.1.0.manifest.json'), 'utf8'),
|
||||
);
|
||||
assert.equal(manifest.version, '0.1.0');
|
||||
assert.ok(manifest.files.some((entry) => entry.path === 'CHANGELOG.yaml'));
|
||||
const checksumLine = readFileSync(path.join(first.out, 'bhs-spec-0.1.0.tar.sha256'), 'utf8');
|
||||
assert.equal(checksumLine.split(' ')[0], sha256(tarball), 'сумма tarball совпадает');
|
||||
|
||||
const extract = tmp(t);
|
||||
const untar = spawnSync('tar', ['-xf', tarball, '-C', extract], { encoding: 'utf8' });
|
||||
assert.equal(untar.status, 0, untar.stderr);
|
||||
for (const entry of manifest.files) {
|
||||
const file = path.join(extract, 'bhs-spec-0.1.0', entry.path);
|
||||
assert.equal(sha256(file), entry.sha256, `байты ${entry.path} совпадают с manifest`);
|
||||
}
|
||||
|
||||
const second = runRelease(t, '0.1.0');
|
||||
assert.equal(
|
||||
readFileSync(path.join(second.out, 'bhs-spec-0.1.0.tar'), 'utf8'),
|
||||
readFileSync(tarball, 'utf8'),
|
||||
'повторная сборка идентична байт-в-байт',
|
||||
);
|
||||
});
|
||||
|
||||
test('release: не-semver и лишние аргументы отклоняются', (t) => {
|
||||
const bad = runRelease(t, '0.1');
|
||||
assert.equal(bad.code, 1);
|
||||
assert.equal(bad.stdout.error.code, 'VALIDATION_FAILED');
|
||||
const dir = tmp(t);
|
||||
const usage = spawnSync(process.execPath, [cli, 'release', specRoot, '--version', '1.0.0'], {
|
||||
encoding: 'utf8',
|
||||
});
|
||||
assert.equal(usage.status, 2);
|
||||
assert.equal(JSON.parse(usage.stdout).error.code, 'USAGE');
|
||||
rmSync(dir, { recursive: true, force: true });
|
||||
});
|
||||
@@ -0,0 +1,275 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { spawnSync } from 'node:child_process';
|
||||
import { mkdirSync, mkdtempSync, readFileSync, 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 REPORT_SCHEMA = {
|
||||
$schema: 'https://json-schema.org/draft/2020-12/schema',
|
||||
$id: 'https://baseline-harness.dev/spec/schemas/audit-report.schema.json',
|
||||
type: 'object',
|
||||
required: ['id', 'generated_at', 'tool', 'subject', 'spec_version', 'findings'],
|
||||
properties: {
|
||||
id: { type: 'string', pattern: '^rep-[a-z0-9-]+$' },
|
||||
generated_at: { type: 'string' },
|
||||
tool: { type: 'object' },
|
||||
subject: { type: 'object' },
|
||||
spec_version: { type: 'string' },
|
||||
profiles: { type: 'array' },
|
||||
findings: {
|
||||
type: 'array',
|
||||
items: {
|
||||
type: 'object',
|
||||
required: ['requirement', 'status', 'method', 'evidence', 'rationale'],
|
||||
properties: {
|
||||
requirement: { type: 'string' },
|
||||
status: {
|
||||
enum: ['PASS', 'FAIL', 'PARTIAL', 'EXEMPT', 'NOT_APPLICABLE', 'UNKNOWN', 'BLOCKED'],
|
||||
},
|
||||
method: { enum: ['deterministic', 'semantic', 'hybrid'] },
|
||||
confidence: { enum: ['high', 'medium', 'low'] },
|
||||
exemption_ref: { type: 'string' },
|
||||
evidence: { type: 'array', minItems: 1 },
|
||||
rationale: { type: 'string' },
|
||||
},
|
||||
allOf: [
|
||||
{
|
||||
if: { properties: { status: { const: 'EXEMPT' } }, required: ['status'] },
|
||||
then: { required: ['exemption_ref'], properties: { exemption_ref: true } },
|
||||
},
|
||||
{
|
||||
if: { properties: { method: { const: 'semantic' } }, required: ['method'] },
|
||||
then: { required: ['confidence'], properties: { confidence: true } },
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
summary: { type: 'object' },
|
||||
},
|
||||
};
|
||||
|
||||
const PASS_FINDING = {
|
||||
requirement: 'req-alpha',
|
||||
status: 'PASS',
|
||||
method: 'deterministic',
|
||||
evidence: [{ kind: 'test-run', locator: 'npm test', description: 'Прогон проверки фикстуры.' }],
|
||||
rationale: 'Проверка выполнена и зафиксирована.',
|
||||
};
|
||||
|
||||
const BASE_SPEC = {
|
||||
'schemas/audit-report.schema.json': JSON.stringify(REPORT_SCHEMA),
|
||||
'requirements/req-alpha.yaml': 'id: req-alpha\nlevel: MUST\n',
|
||||
};
|
||||
|
||||
function fixture(t, extra = {}) {
|
||||
const root = mkdtempSync(path.join(os.tmpdir(), 'bhl-report-'));
|
||||
const files = { ...BASE_SPEC, ...extra };
|
||||
for (const [name, contents] of Object.entries(files)) {
|
||||
const target = path.join(root, name);
|
||||
mkdirSync(path.dirname(target), { recursive: true });
|
||||
writeFileSync(
|
||||
target,
|
||||
typeof contents === 'string' ? contents : JSON.stringify(contents),
|
||||
'utf8',
|
||||
);
|
||||
}
|
||||
t.after(() => rmSync(root, { recursive: true, force: true }));
|
||||
return root;
|
||||
}
|
||||
|
||||
function reportDoc(findings, summary) {
|
||||
return {
|
||||
id: 'rep-fixture-2026-11-28',
|
||||
generated_at: '2026-11-28',
|
||||
tool: { name: 'bhl', version: '0.0.1' },
|
||||
subject: { kind: 'repository', fingerprint: `sha256:${'a'.repeat(64)}` },
|
||||
spec_version: '0.1.0',
|
||||
findings,
|
||||
summary,
|
||||
};
|
||||
}
|
||||
|
||||
function runReportValidate(t, report, extraSpec = {}) {
|
||||
const root = fixture(t, { 'report.json': JSON.stringify(report), ...extraSpec });
|
||||
const proc = spawnSync(
|
||||
process.execPath,
|
||||
[cli, 'report', 'validate', path.join(root, 'report.json'), '--spec-root', 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('валидный отчёт проходит report validate с кодом 0', (t) => {
|
||||
const report = reportDoc([PASS_FINDING], {
|
||||
PASS: 1,
|
||||
FAIL: 0,
|
||||
PARTIAL: 0,
|
||||
EXEMPT: 0,
|
||||
NOT_APPLICABLE: 0,
|
||||
UNKNOWN: 0,
|
||||
BLOCKED: 0,
|
||||
});
|
||||
const result = runReportValidate(t, report);
|
||||
assert.equal(result.code, 0);
|
||||
assert.deepEqual(result.envelope.data.errors, []);
|
||||
});
|
||||
|
||||
test('отчёт вне схемы отклоняется с понятной диагностикой', (t) => {
|
||||
const report = reportDoc([{ ...PASS_FINDING, status: 'MUST' }], undefined);
|
||||
const result = runReportValidate(t, report);
|
||||
assert.equal(result.code, 1);
|
||||
assert.ok(codes(result).includes('schema-error'));
|
||||
const message = result.envelope.data.errors.find((item) => item.code === 'schema-error').message;
|
||||
assert.ok(message.includes('status'), 'диагностика указывает на status');
|
||||
});
|
||||
|
||||
test('ссылка на несуществующее требование и расхождение сводки ловятся', (t) => {
|
||||
const ghost = reportDoc([{ ...PASS_FINDING, requirement: 'req-ghost' }], undefined);
|
||||
assert.ok(codes(runReportValidate(t, ghost)).includes('unknown-requirement'));
|
||||
const wrongSummary = reportDoc([PASS_FINDING], { PASS: 2, FAIL: 0 });
|
||||
const result = runReportValidate(t, wrongSummary);
|
||||
assert.ok(codes(result).includes('summary-mismatch'));
|
||||
});
|
||||
|
||||
test('EXEMPT без exemption_ref отклоняется', (t) => {
|
||||
const report = reportDoc([{ ...PASS_FINDING, status: 'EXEMPT' }], undefined);
|
||||
const result = runReportValidate(t, report);
|
||||
assert.equal(result.code, 1);
|
||||
assert.ok(codes(result).includes('schema-error'));
|
||||
});
|
||||
|
||||
test('битый JSON и недоступный файл дают диагностики чтения', (t) => {
|
||||
const root = fixture(t, { 'report.json': '{ not json' });
|
||||
const proc = spawnSync(
|
||||
process.execPath,
|
||||
[cli, 'report', 'validate', path.join(root, 'report.json'), '--spec-root', root],
|
||||
{
|
||||
encoding: 'utf8',
|
||||
},
|
||||
);
|
||||
assert.equal(proc.status, 1);
|
||||
assert.ok(JSON.parse(proc.stdout).data.errors.some((item) => item.code === 'parse-error'));
|
||||
const missing = spawnSync(
|
||||
process.execPath,
|
||||
[cli, 'report', 'validate', '/nonexistent/report.json', '--spec-root', root],
|
||||
{
|
||||
encoding: 'utf8',
|
||||
},
|
||||
);
|
||||
assert.equal(missing.status, 1);
|
||||
assert.ok(JSON.parse(missing.stdout).data.errors.some((item) => item.code === 'read-error'));
|
||||
});
|
||||
|
||||
test('использование команды report', () => {
|
||||
const noSub = spawnSync(process.execPath, [cli, 'report'], { encoding: 'utf8' });
|
||||
assert.equal(noSub.status, 2);
|
||||
assert.equal(JSON.parse(noSub.stdout).error.code, 'USAGE');
|
||||
const noFile = spawnSync(process.execPath, [cli, 'report', 'validate'], { encoding: 'utf8' });
|
||||
assert.equal(noFile.status, 2);
|
||||
});
|
||||
|
||||
function runRender(t, report) {
|
||||
const root = fixture(t, { 'report.json': JSON.stringify(report) });
|
||||
const out = path.join(root, 'out', 'report.md');
|
||||
const proc = spawnSync(
|
||||
process.execPath,
|
||||
[cli, 'report', 'render', path.join(root, 'report.json'), '--out', out],
|
||||
{
|
||||
encoding: 'utf8',
|
||||
},
|
||||
);
|
||||
return { code: proc.status, out, stdout: JSON.parse(proc.stdout) };
|
||||
}
|
||||
|
||||
test('report render: повторный рендер идентичен и показывает все статусы', (t) => {
|
||||
const findings = [
|
||||
{ ...PASS_FINDING, requirement: 'req-alpha' },
|
||||
{
|
||||
...PASS_FINDING,
|
||||
requirement: 'req-alpha',
|
||||
status: 'FAIL',
|
||||
rationale: 'Найден провал проверки фикстуры.',
|
||||
},
|
||||
{
|
||||
...PASS_FINDING,
|
||||
requirement: 'req-alpha',
|
||||
status: 'PARTIAL',
|
||||
rationale: 'Проверка выполнена частично.',
|
||||
},
|
||||
{
|
||||
...PASS_FINDING,
|
||||
requirement: 'req-alpha',
|
||||
status: 'EXEMPT',
|
||||
exemption_ref: 'ex-fixture',
|
||||
rationale: 'Снято обоснованным исключением.',
|
||||
},
|
||||
{
|
||||
...PASS_FINDING,
|
||||
requirement: 'req-alpha',
|
||||
status: 'NOT_APPLICABLE',
|
||||
rationale: 'Требование неприменимо к фикстуре.',
|
||||
},
|
||||
{
|
||||
...PASS_FINDING,
|
||||
requirement: 'req-alpha',
|
||||
status: 'UNKNOWN',
|
||||
method: 'semantic',
|
||||
confidence: 'medium',
|
||||
rationale: 'Наблюдение неполно.',
|
||||
},
|
||||
{
|
||||
...PASS_FINDING,
|
||||
requirement: 'req-alpha',
|
||||
status: 'BLOCKED',
|
||||
rationale: 'Инструмент недоступен.',
|
||||
},
|
||||
];
|
||||
const report = reportDoc(findings, undefined);
|
||||
const first = runRender(t, report);
|
||||
assert.equal(first.code, 0);
|
||||
const markdown = readFileSync(first.out, 'utf8');
|
||||
for (const status of [
|
||||
'PASS',
|
||||
'FAIL',
|
||||
'PARTIAL',
|
||||
'EXEMPT',
|
||||
'NOT_APPLICABLE',
|
||||
'UNKNOWN',
|
||||
'BLOCKED',
|
||||
]) {
|
||||
assert.ok(markdown.includes(`### ${status}`), `секция ${status}`);
|
||||
}
|
||||
assert.ok(markdown.includes('ex-fixture'), 'ссылка на исключение');
|
||||
assert.ok(markdown.includes('уверенность medium'), 'уверенность semantic');
|
||||
assert.ok(!/%\s*оцен|процент/i.test(markdown), 'процентного рейтинга нет');
|
||||
const second = runRender(t, report);
|
||||
assert.equal(readFileSync(second.out, 'utf8'), markdown, 'повторный рендер идентичен');
|
||||
});
|
||||
|
||||
test('report render: битый JSON и отсутствие --out дают понятные ошибки', (t) => {
|
||||
const root = fixture(t, { 'report.json': '{ not json' });
|
||||
const proc = spawnSync(
|
||||
process.execPath,
|
||||
[cli, 'report', 'render', path.join(root, 'report.json'), '--out', path.join(root, 'o.md')],
|
||||
{
|
||||
encoding: 'utf8',
|
||||
},
|
||||
);
|
||||
assert.equal(proc.status, 1);
|
||||
assert.equal(JSON.parse(proc.stdout).error.code, 'READ_ERROR');
|
||||
const noOut = spawnSync(
|
||||
process.execPath,
|
||||
[cli, 'report', 'render', path.join(root, 'report.json')],
|
||||
{ encoding: 'utf8' },
|
||||
);
|
||||
assert.equal(noOut.status, 2);
|
||||
});
|
||||
@@ -0,0 +1,173 @@
|
||||
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', 'level'],
|
||||
properties: {
|
||||
id: { type: 'string', pattern: '^req-[a-z0-9-]+$' },
|
||||
level: { enum: ['MUST', 'MUST NOT', 'SHOULD', 'SHOULD NOT', 'MAY'] },
|
||||
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', 'title', 'description', 'requirements'],
|
||||
properties: {
|
||||
id: { type: 'string', pattern: '^prof-[a-z0-9-]+$' },
|
||||
title: { type: 'string' },
|
||||
description: { type: 'string' },
|
||||
requirements: { type: 'array', minItems: 1 },
|
||||
parameter_overrides: { type: 'array' },
|
||||
},
|
||||
},
|
||||
'preset.schema.json': {
|
||||
$id: 'https://baseline-harness.dev/spec/schemas/preset.schema.json',
|
||||
type: 'object',
|
||||
required: ['id', 'title', 'description', 'profiles'],
|
||||
properties: {
|
||||
id: { type: 'string', pattern: '^preset-[a-z0-9-]+$' },
|
||||
title: { type: 'string' },
|
||||
description: { type: 'string' },
|
||||
profiles: { type: 'array', minItems: 1 },
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
const PARAM_P =
|
||||
'parameters:\n - id: param-p\n type: integer\n default: 2\n constraints:\n minimum: 0\n maximum: 8\n';
|
||||
|
||||
const BASE_FILES = {
|
||||
'requirements/req-alpha.yaml':
|
||||
'id: req-alpha\nlevel: MUST\napplicability:\n - when: сборка проекта\n unless: dry-run\n' +
|
||||
PARAM_P,
|
||||
'requirements/req-beta.yaml': 'id: req-beta\nlevel: SHOULD\n',
|
||||
'profiles/prof-one.yaml':
|
||||
'id: prof-one\ntitle: Первый\ndescription: Профиль один для тестов разрешения.\nrequirements:\n - requirement: req-alpha\nparameter_overrides:\n - parameter: param-p\n value: 4\n',
|
||||
'profiles/prof-two.yaml':
|
||||
'id: prof-two\ntitle: Второй\ndescription: Профиль два с явным ослаблением требования.\nrequirements:\n - requirement: req-alpha\n relax_to: SHOULD\n - requirement: req-beta\n',
|
||||
'presets/preset-all.yaml':
|
||||
'id: preset-all\ntitle: Все профили\ndescription: Пресет из обоих профилей для тестов.\nprofiles: [prof-one, prof-two]\n',
|
||||
};
|
||||
|
||||
function fixture(t, extra = {}) {
|
||||
const root = mkdtempSync(path.join(os.tmpdir(), 'bhl-resolve-'));
|
||||
const files = { ...BASE_FILES, ...extra };
|
||||
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 runResolve(root, ...flags) {
|
||||
const proc = spawnSync(process.execPath, [cli, 'profile', 'resolve', root, ...flags], {
|
||||
encoding: 'utf8',
|
||||
});
|
||||
return { code: proc.status, stdout: proc.stdout, envelope: JSON.parse(proc.stdout) };
|
||||
}
|
||||
|
||||
function codes(result) {
|
||||
return result.envelope.data.errors.map((item) => item.code);
|
||||
}
|
||||
|
||||
test('пресет разворачивается, Effective Specification собрана без учёта порядка', (t) => {
|
||||
const root = fixture(t);
|
||||
const result = runResolve(root, '--preset', 'preset-all');
|
||||
assert.equal(result.code, 0);
|
||||
const { effective, profiles } = result.envelope.data;
|
||||
assert.deepEqual(profiles, ['prof-one', 'prof-two']);
|
||||
assert.deepEqual(effective, [
|
||||
{
|
||||
requirement: 'req-alpha',
|
||||
level: 'SHOULD',
|
||||
sources: ['prof-one', 'prof-two'],
|
||||
applicability: [{ when: 'сборка проекта', unless: 'dry-run' }],
|
||||
parameters: [{ parameter: 'param-p', value: 4, source: 'prof-one' }],
|
||||
},
|
||||
{
|
||||
requirement: 'req-beta',
|
||||
level: 'SHOULD',
|
||||
sources: ['prof-two'],
|
||||
applicability: [],
|
||||
parameters: [],
|
||||
},
|
||||
]);
|
||||
const swapped = runResolve(root, '--profile', 'prof-two', '--profile', 'prof-one');
|
||||
assert.equal(swapped.stdout, result.stdout, 'порядок профилей не влияет на вывод');
|
||||
});
|
||||
|
||||
test('default спецификации сохраняется, когда переопределения нет', (t) => {
|
||||
const result = runResolve(fixture(t), '--profile', 'prof-two');
|
||||
assert.equal(result.code, 0);
|
||||
const alpha = result.envelope.data.effective.find((item) => item.requirement === 'req-alpha');
|
||||
assert.deepEqual(alpha.parameters, [{ parameter: 'param-p', value: 2, source: 'spec' }]);
|
||||
});
|
||||
|
||||
test('конфликт переопределений параметров обнаруживается', (t) => {
|
||||
const root = fixture(t, {
|
||||
'profiles/prof-three.yaml':
|
||||
'id: prof-three\ntitle: Третий\ndescription: Третий профиль с другим значением.\nrequirements:\n - requirement: req-alpha\nparameter_overrides:\n - parameter: param-p\n value: 5\n',
|
||||
});
|
||||
const result = runResolve(root, '--profile', 'prof-one', '--profile', 'prof-three');
|
||||
assert.equal(result.code, 1);
|
||||
assert.ok(codes(result).includes('parameter-conflict'));
|
||||
});
|
||||
|
||||
test('переопределение вне ограничений отклоняется', (t) => {
|
||||
const root = fixture(t, {
|
||||
'profiles/prof-four.yaml':
|
||||
'id: prof-four\ntitle: Четвёртый\ndescription: Значение вне допустимого диапазона.\nrequirements:\n - requirement: req-alpha\nparameter_overrides:\n - parameter: param-p\n value: 99\n',
|
||||
});
|
||||
const result = runResolve(root, '--profile', 'prof-four');
|
||||
assert.equal(result.code, 1);
|
||||
assert.ok(codes(result).includes('parameter-out-of-range'));
|
||||
});
|
||||
|
||||
test('ослабление только явное и только в более слабую сторону', (t) => {
|
||||
const root = fixture(t, {
|
||||
'profiles/prof-five.yaml':
|
||||
'id: prof-five\ntitle: Пятый\ndescription: Попытка ослабить SHOULD до SHOULD не ослабляет.\nrequirements:\n - requirement: req-beta\n relax_to: SHOULD\n',
|
||||
});
|
||||
const result = runResolve(root, '--profile', 'prof-five');
|
||||
assert.equal(result.code, 1);
|
||||
assert.ok(codes(result).includes('invalid-relaxation'));
|
||||
});
|
||||
|
||||
test('неизвестные профиль и пресет дают диагностики', (t) => {
|
||||
const root = fixture(t);
|
||||
const unknownProfile = runResolve(root, '--profile', 'prof-ghost');
|
||||
assert.equal(unknownProfile.code, 1);
|
||||
assert.ok(codes(unknownProfile).includes('unknown-profile'));
|
||||
const unknownPreset = runResolve(root, '--preset', 'preset-ghost');
|
||||
assert.ok(codes(unknownPreset).includes('unknown-preset'));
|
||||
});
|
||||
|
||||
test('использование команды profile', () => {
|
||||
const noSub = spawnSync(process.execPath, [cli, 'profile'], { encoding: 'utf8' });
|
||||
assert.equal(noSub.status, 2);
|
||||
assert.equal(JSON.parse(noSub.stdout).error.code, 'USAGE');
|
||||
const noRoot = spawnSync(process.execPath, [cli, 'profile', 'resolve'], { encoding: 'utf8' });
|
||||
assert.equal(noRoot.status, 2);
|
||||
});
|
||||
@@ -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);
|
||||
});
|
||||
@@ -0,0 +1,225 @@
|
||||
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' },
|
||||
},
|
||||
},
|
||||
'antipattern.schema.json': {
|
||||
$id: 'https://baseline-harness.dev/spec/schemas/antipattern.schema.json',
|
||||
type: 'object',
|
||||
required: ['id', 'level', 'relations'],
|
||||
properties: {
|
||||
id: { type: 'string', pattern: '^ant-[a-z0-9-]+$' },
|
||||
level: { enum: ['SHOULD NOT', 'MUST NOT'] },
|
||||
relations: { type: 'array', items: { type: 'object' } },
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
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 });
|
||||
mkdirSync(path.join(root, 'antipatterns'), { 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'));
|
||||
});
|
||||
|
||||
test('антипаттерны: двусторонние ссылки проходят, висячие цели падают', (t) => {
|
||||
const ok = fixture(t, {
|
||||
'requirements/req-gamma.yaml':
|
||||
'id: req-gamma\ndomain: dom-build\ncapability: cap-verify\nstatement: Проект MUST NOT молчать о провале.\nlevel: MUST NOT\nantipatterns:\n - ant-silent-fail\n',
|
||||
'antipatterns/ant-silent-fail.yaml':
|
||||
'id: ant-silent-fail\nlevel: MUST NOT\nrelations:\n - target: req-gamma\n kind: contradicts\n',
|
||||
});
|
||||
assert.equal(runValidate(ok).code, 0);
|
||||
const dangling = fixture(t, {
|
||||
'antipatterns/ant-ghost.yaml':
|
||||
'id: ant-ghost\nlevel: MUST NOT\nrelations:\n - target: req-ghost\n kind: contradicts\n',
|
||||
});
|
||||
assert.ok(codes(runValidate(dangling)).includes('unknown-requirement'));
|
||||
const orphanLink = fixture(t, {
|
||||
'requirements/req-delta.yaml':
|
||||
'id: req-delta\ndomain: dom-build\ncapability: cap-verify\nstatement: Проект SHOULD кэшировать артефакты.\nlevel: SHOULD\nantipatterns:\n - ant-never-defined\n',
|
||||
});
|
||||
assert.ok(codes(runValidate(orphanLink)).includes('unknown-antipattern'));
|
||||
});
|
||||
@@ -0,0 +1,10 @@
|
||||
{
|
||||
"extends": "./tsconfig.json",
|
||||
"compilerOptions": {
|
||||
"noEmit": false,
|
||||
"rewriteRelativeImportExtensions": true,
|
||||
"outDir": "dist",
|
||||
"rootDir": "src"
|
||||
},
|
||||
"include": ["src/**/*.ts"]
|
||||
}
|
||||
@@ -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"]
|
||||
}
|
||||
Reference in New Issue
Block a user