Перенос 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,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'));
|
||||
});
|
||||
Reference in New Issue
Block a user