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.
174 lines
7.6 KiB
JavaScript
174 lines
7.6 KiB
JavaScript
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);
|
|
});
|