feat: схемы отчёта аудита, профили/пресеты и движок разрешения (BHL-019, BHL-012, BHL-013)

- spec/schemas: evidence, audit-finding, audit-report (BHL-019)
- spec/schemas: profile, preset с явным relax_to (BHL-012)
- packages/bhl: resolve.ts + bhl profile resolve — порядок не влияет,
  конфликты параметров и ослаблений, provenance и applicability (BHL-012, BHL-013)
- tests: корневые схемы 13/13, пакет 17/17
This commit is contained in:
Suslov-MD
2026-11-28 23:36:53 +03:00
parent 294bf9d68f
commit 5b514272cf
13 changed files with 1302 additions and 79 deletions
+137 -2
View File
@@ -9,7 +9,18 @@ const root = path.join(path.dirname(import.meta.dirname), 'spec', 'schemas');
const load = (name) => JSON.parse(readFileSync(path.join(root, name), 'utf8'));
const ajv = new Ajv2020({ strict: true, strictTypes: false, allErrors: true });
for (const name of ['domain', 'capability', 'parameter', 'requirement', 'normative-change']) {
for (const name of [
'domain',
'capability',
'parameter',
'requirement',
'normative-change',
'evidence',
'audit-finding',
'audit-report',
'profile',
'preset',
]) {
const schema = load(`${name}.schema.json`);
assert.ok(ajv.validateSchema(schema), `${name}: некорректная JSON Schema`);
ajv.addSchema(schema);
@@ -67,7 +78,7 @@ const requirement = {
};
test('схемы ядра спецификации корректны как JSON Schema', () => {
for (const name of ['domain', 'capability', 'parameter', 'requirement']) {
for (const name of ['domain', 'capability', 'parameter', 'requirement', 'profile', 'preset']) {
assert.ok(ajv.validateSchema(load(`${name}.schema.json`)));
}
});
@@ -155,3 +166,127 @@ test('канонический журнал изменений существу
assert.deepEqual(validate('normative-change', entry).errors ?? [], [], entry.id);
}
});
const evidence = {
kind: 'test-run',
locator: 'npm run quality',
description: 'Прогон локального gate пакета bhl с фиксированными входными данными.',
fingerprint: `sha256:${'a'.repeat(64)}`,
captured_at: '2026-11-28',
};
const finding = {
requirement: 'req-skill-verify-before-accept',
status: 'PASS',
method: 'hybrid',
evidence: [evidence],
rationale: 'Проверка описана, автоматизирована и подтверждена прогоном.',
};
const report = {
id: 'rep-bhl-2026-11-28',
generated_at: '2026-11-28',
tool: { name: 'bhl', version: '0.0.1' },
agent: { name: 'pi', version: '1.4.0' },
subject: { kind: 'repository', fingerprint: `sha256:${'b'.repeat(64)}`, revision: 'af81424', dirty: false },
spec_version: '0.1.0',
profiles: ['prof-personal'],
findings: [finding],
summary: { PASS: 1, FAIL: 0, PARTIAL: 0, EXEMPT: 0, NOT_APPLICABLE: 0, UNKNOWN: 0, BLOCKED: 0 },
};
test('отчёт аудита: фикстура проходит схему', () => {
assert.deepEqual(validate('evidence', evidence).errors ?? [], []);
assert.deepEqual(validate('audit-finding', finding).errors ?? [], []);
assert.deepEqual(validate('audit-report', report).errors ?? [], []);
});
test('отчёт аудита: статусы не смешиваются с уровнем и жизненным циклом', () => {
assert.ok(!validate('audit-finding', { ...finding, status: 'MUST' }), 'нормативный уровень в status');
assert.ok(!validate('audit-finding', { ...finding, status: 'accepted' }), 'жизненный цикл в status');
assert.ok(!validate('audit-finding', { ...finding, status: 'EXEMPT' }), 'EXEMPT без exemption_ref');
assert.ok(
!validate('audit-finding', { ...finding, method: 'semantic' }),
'semantic без confidence',
);
assert.ok(validate('audit-finding', { ...finding, method: 'semantic', confidence: 'medium' }));
assert.ok(!validate('audit-finding', { ...finding, evidence: [] }), 'нахождение без доказательств');
assert.ok(!validate('evidence', { ...evidence, kind: 'vibes' }), 'неизвестный класс доказательств');
assert.ok(!validate('evidence', { ...evidence, fingerprint: 'deadbeef' }), 'неформатный отпечаток');
});
test('отчёт аудита: обязательные поля и версии', () => {
for (const field of ['id', 'generated_at', 'tool', 'subject', 'spec_version', 'findings']) {
const broken = structuredClone(report);
delete broken[field];
assert.ok(!validate('audit-report', broken), `обязательное поле ${field}`);
}
assert.ok(!validate('audit-report', { ...report, spec_version: 'v0.1' }), 'нестрогая версия спецификации');
assert.ok(!validate('audit-report', { ...report, score: 97 }), 'процентного рейтинга в схеме нет');
assert.ok(!validate('audit-report', { ...report, subject: { kind: 'repository' } }), 'дерево без отпечатка');
});
const profile = {
id: 'prof-skill-light',
title: 'Облегчённый профиль навыков',
description: 'Требования навыков с явным ослаблением проверки до рекомендации.',
requirements: [
{ requirement: 'req-skill-verify-before-accept', relax_to: 'SHOULD', note: 'для черновиков' },
],
parameter_overrides: [{ parameter: 'param-prep-budget', value: 1 }],
};
const preset = {
id: 'preset-skill-defaults',
title: 'Композиция профилей навыков',
description: 'Именованная композиция профиля навыков для типовых прогонов.',
profiles: ['prof-skill-light'],
};
test('profile и preset: фикстуры проходят схемы', () => {
assert.deepEqual(validate('profile', profile).errors ?? [], []);
assert.deepEqual(validate('preset', preset).errors ?? [], []);
});
test('profile: ослабление только явное и только в слабую сторону', () => {
assert.ok(!validate('profile', { ...profile, id: 'skill-light' }), 'ID профиля без префикса prof-');
assert.ok(!validate('profile', { ...profile, requirements: [] }), 'профиль без требований');
assert.ok(
!validate('profile', { ...profile, requirements: [{ requirement: 'cap-skill-verification' }] }),
'ссылка на возможность вместо требования',
);
assert.ok(
!validate('profile', {
...profile,
requirements: [{ requirement: 'req-skill-verify-before-accept', relax_to: 'MUST' }],
}),
'relax_to MUST не является ослаблением',
);
assert.ok(
!validate('profile', {
...profile,
requirements: [{ requirement: 'req-skill-verify-before-accept', strengthen_to: 'MUST' }],
}),
'поля неявного усиления в схеме нет',
);
assert.ok(
!validate('profile', {
...profile,
parameter_overrides: [{ parameter: 'param-prep-budget', value: 1, reason: 'меньше' }],
}),
'неизвестное поле в переопределении',
);
});
test('preset: только непустые уникальные наборы профилей', () => {
assert.ok(!validate('preset', { ...preset, id: 'skill-defaults' }), 'ID пресета без префикса preset-');
assert.ok(!validate('preset', { ...preset, profiles: [] }), 'пресет без профилей');
assert.ok(
!validate('preset', { ...preset, profiles: ['prof-skill-light', 'prof-skill-light'] }),
'дубликат профиля в пресете',
);
assert.ok(
!validate('preset', { ...preset, profiles: ['req-skill-verify-before-accept'] }),
'пресет из требований вместо профилей',
);
});