diff --git a/backlog/tasks/bhl-012 - Реализовать-профили-пресеты-и-Effective-Specification.md b/backlog/tasks/bhl-012 - Реализовать-профили-пресеты-и-Effective-Specification.md index 9124618..97c9a0c 100644 --- a/backlog/tasks/bhl-012 - Реализовать-профили-пресеты-и-Effective-Specification.md +++ b/backlog/tasks/bhl-012 - Реализовать-профили-пресеты-и-Effective-Specification.md @@ -1,9 +1,10 @@ --- id: BHL-012 title: Реализовать профили, пресеты и Effective Specification -status: To Do +status: Done assignee: [] created_date: '2026-11-28T14:25:18Z' +updated_date: '2026-11-28T20:35:33Z' labels: [] milestone: m-1 dependencies: @@ -24,15 +25,27 @@ ordinal: 12000 ## Acceptance Criteria -- [ ] #1 Результат разрешения не зависит от порядка профилей -- [ ] #2 Конфликтующие профили обнаруживаются; ослабление только явное -- [ ] #3 Каждое требование Effective Specification несёт происхождение и применимость +- [x] #1 Результат разрешения не зависит от порядка профилей +- [x] #2 Конфликтующие профили обнаруживаются; ослабление только явное +- [x] #3 Каждое требование Effective Specification несёт происхождение и применимость ## Definition of Done -- [ ] #1 npm run check пройден (для изменений материалов и документации) -- [ ] #2 Местный quality gate затронутого модуля пройден (для кода и конфигурации) -- [ ] #3 В записи нет секретов, персональных путей и непубликуемых идентификаторов -- [ ] #4 Состояние задачи в Backlog.md актуально: прогресс, блокеры, следующий шаг +- [x] #1 npm run check пройден (для изменений материалов и документации) +- [x] #2 Местный quality gate затронутого модуля пройден (для кода и конфигурации) +- [x] #3 В записи нет секретов, персональных путей и непубликуемых идентификаторов +- [x] #4 Состояние задачи в Backlog.md актуально: прогресс, блокеры, следующий шаг + +## Comments + + +created: 2026-11-28T20:35:33Z + +--- + +Схемы profile/preset (spec/schemas) + движок разрешения packages/bhl/src/resolve.ts + bhl profile resolve. Порядок не влияет (тест идентичности вывода), конфликты параметров и ослаблений обнаруживаются, relax_to только SHOULD/MAY и только слабее, provenance (sources) и applicability в Effective Specification. Пакет: 17/17 тестов, quality зелёный. + +--- + diff --git a/backlog/tasks/bhl-013 - Реализовать-разрешение-типизированных-параметров.md b/backlog/tasks/bhl-013 - Реализовать-разрешение-типизированных-параметров.md index 166f617..94d7b2d 100644 --- a/backlog/tasks/bhl-013 - Реализовать-разрешение-типизированных-параметров.md +++ b/backlog/tasks/bhl-013 - Реализовать-разрешение-типизированных-параметров.md @@ -1,9 +1,10 @@ --- id: BHL-013 title: Реализовать разрешение типизированных параметров -status: To Do +status: Done assignee: [] created_date: '2026-11-28T14:25:20Z' +updated_date: '2026-11-28T20:35:36Z' labels: [] milestone: m-1 dependencies: @@ -23,14 +24,26 @@ ordinal: 13000 ## Acceptance Criteria -- [ ] #1 Переопределение вне допустимых значений отклоняется с диагностикой -- [ ] #2 Конфликтующие параметры обнаруживаются +- [x] #1 Переопределение вне допустимых значений отклоняется с диагностикой +- [x] #2 Конфликтующие параметры обнаруживаются ## Definition of Done -- [ ] #1 npm run check пройден (для изменений материалов и документации) -- [ ] #2 Местный quality gate затронутого модуля пройден (для кода и конфигурации) -- [ ] #3 В записи нет секретов, персональных путей и непубликуемых идентификаторов -- [ ] #4 Состояние задачи в Backlog.md актуально: прогресс, блокеры, следующий шаг +- [x] #1 npm run check пройден (для изменений материалов и документации) +- [x] #2 Местный quality gate затронутого модуля пройден (для кода и конфигурации) +- [x] #3 В записи нет секретов, персональных путей и непубликуемых идентификаторов +- [x] #4 Состояние задачи в Backlog.md актуально: прогресс, блокеры, следующий шаг + +## Comments + + +created: 2026-11-28T20:35:36Z + +--- + +Параметры: тип/default/constraints в requirement+parameter схемах; разрешение в resolve.ts: default из спецификации, переопределения профилей, вне диапазона -> parameter-out-of-range, разные значения -> parameter-conflict. Порядок спецификация->профиль реализован; проектный уровень подключится с манифестом (BHL-041). + +--- + diff --git a/backlog/tasks/bhl-019 - Спроектировать-схемы-Audit-Report-Audit-Finding-и-Evidence.md b/backlog/tasks/bhl-019 - Спроектировать-схемы-Audit-Report-Audit-Finding-и-Evidence.md index 63c37c2..e9e5844 100644 --- a/backlog/tasks/bhl-019 - Спроектировать-схемы-Audit-Report-Audit-Finding-и-Evidence.md +++ b/backlog/tasks/bhl-019 - Спроектировать-схемы-Audit-Report-Audit-Finding-и-Evidence.md @@ -1,9 +1,10 @@ --- id: BHL-019 title: Спроектировать схемы Audit Report, Audit Finding и Evidence -status: To Do +status: Done assignee: [] created_date: '2026-11-28T14:25:39Z' +updated_date: '2026-11-28T17:38:32Z' labels: [] milestone: m-1 dependencies: @@ -34,3 +35,9 @@ ordinal: 19000 - [ ] #3 В записи нет секретов, персональных путей и непубликуемых идентификаторов - [ ] #4 Состояние задачи в Backlog.md актуально: прогресс, блокеры, следующий шаг + +## Final Summary + + +spec/schemas: audit-report, audit-finding, evidence (2020-12). Status PASS/FAIL/PARTIAL/EXEMPT/NOT_APPLICABLE/UNKNOWN/BLOCKED отделён от level и lifecycle (тесты); EXEMPT требует exemption_ref, semantic — confidence; evidence с классами и fingerprint sha256:; subject — отпечаток дерева + revision/dirty; процентного рейтинга в схеме нет; сверка summary — задача BHL-023. Тесты: 10 в spec-schemas. + diff --git a/packages/bhl/src/cli.ts b/packages/bhl/src/cli.ts index 51a73bb..5443474 100644 --- a/packages/bhl/src/cli.ts +++ b/packages/bhl/src/cli.ts @@ -1,90 +1,194 @@ import { readFileSync } from 'node:fs'; import { emit, ExitCode, failEnvelope, okEnvelope } from './envelope.ts'; +import { resolveProfiles } from './resolve.ts'; import { validateSpec } from './validate.ts'; -interface PackageManifest { - name: string; - version: string; -} - const USAGE_MESSAGE = 'Usage: bhl [args]; ' + + 'profile resolve [--profile ] [--preset ]; ' + 'JSON envelope on stdout; exit codes: 0 ok, 1 validation failed, 2 usage, ' + '3 not implemented, 4 internal.'; -const KNOWN: ReadonlySet = new Set([ - 'version', - 'validate', - 'spec', - 'profile', - 'report', - 'audit', -]); - function isRecord(value: unknown): value is Record { - return typeof value === 'object' && value !== null; + return typeof value === 'object' && value !== null && !Array.isArray(value); } -function manifest(): PackageManifest { - const parsed: unknown = JSON.parse( - readFileSync(new URL('../package.json', import.meta.url), 'utf8'), - ); +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 must carry string name and version'); + throw new Error('package.json is malformed'); } return { name: parsed['name'], version: parsed['version'] }; } -export function run(argv: readonly string[]): number { - const [command, ...rest] = argv; - if (command === undefined || command === '-h' || command === '--help') { - emit(failEnvelope(command ?? '', 'USAGE', USAGE_MESSAGE)); +interface ParsedArgs { + root: string; + profiles: string[]; + presets: string[]; +} + +type FlagName = 'profile' | 'preset'; + +const FLAG_TARGETS: Readonly> = { + '--profile': 'profile', + '--preset': 'preset', +}; + +interface SplitState { + positional: string[]; + collected: Record; + 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; } - if (!KNOWN.has(command)) { - emit(failEnvelope(command, 'USAGE', `Unknown command "${command}". ${USAGE_MESSAGE}`)); + 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; +} + +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; +} + +export function run(argv: readonly string[]): number { + const [command, ...rest] = argv; + if (command === undefined) { + emit(failEnvelope('none', 'USAGE', USAGE_MESSAGE)); return ExitCode.Usage; } if (command === 'version') { - const { name, version } = manifest(); - emit(okEnvelope(command, { name, version, args: rest })); + const info = readPackageInfo(); + emit(okEnvelope('version', { name: info.name, version: info.version })); return ExitCode.Ok; } - if (command === 'validate') { - const [target] = rest; - if (target === undefined) { - emit(failEnvelope(command, 'USAGE', 'validate requires a spec root path')); - return ExitCode.Usage; - } - const result = validateSpec(target); - const data = { root: target, files: result.files, errors: result.diagnostics }; - if (result.ok) { - emit(okEnvelope(command, data)); - return ExitCode.Ok; - } - emit({ - ok: false, - command, - data, - error: { - code: 'VALIDATION_FAILED', - message: `${String(result.diagnostics.length)} diagnostic(s)`, - }, - }); - return ExitCode.ValidationFailed; + if (command === 'profile') { + return runProfile(command, rest); } - emit( - failEnvelope( - command, - 'NOT_IMPLEMENTED', - `Command "${command}" is scheduled by the laboratory backlog (Wave B/C).`, - ), - ); - return ExitCode.NotImplemented; + if (command === 'validate') { + return runValidate(command, rest); + } + if (command === 'spec' || command === 'report' || command === 'audit') { + emit(failEnvelope(command, 'NOT_IMPLEMENTED', `${command} is not implemented yet`)); + return ExitCode.NotImplemented; + } + emit(failEnvelope(command, 'USAGE', USAGE_MESSAGE)); + return ExitCode.Usage; } -process.exitCode = run(process.argv.slice(2)); +export function main(argv: readonly string[] = process.argv.slice(2)): void { + process.exitCode = run(argv); +} + +main(); diff --git a/packages/bhl/src/resolve.ts b/packages/bhl/src/resolve.ts new file mode 100644 index 0000000..2e3e163 --- /dev/null +++ b/packages/bhl/src/resolve.ts @@ -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; + 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> = { + MUST: 3, + 'MUST NOT': 3, + SHOULD: 2, + 'SHOULD NOT': 2, + MAY: 1, +}; + +function isRecord(value: unknown): value is Record { + 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, + 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> { + const docs: Record> = {}; + 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, 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>, + registry: Record, +): Record { + const defs: Record = { ...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): 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): boolean { + const values = c['values']; + return !Array.isArray(values) || values.some((item) => sameValue(item, value)); +} + +function stringOk(value: unknown, c: Record): 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: string[], presetIds: 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 { + const docs = loadDocs(path.join(this.root, 'profiles'), 'profile', this.ajv, this.diagnostics); + const profiles: Record = {}; + 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: string[], + presetIds: string[], + profiles: Record, + presets: Record, + ): ProfileDoc[] { + const ids = new Set(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, + ): Map { + const applied = new Map(); + 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, + applied: Map, + ): 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>, + defs: Record, + applied: Map, + ): EffectiveRequirement[] { + const effective: EffectiveRequirement[] = []; + const ids = new Set(); + 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, + selected: ProfileDoc[], + defs: Record, + applied: Map, + ): 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(); + 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 { + const registry: Record = {}; + 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 { + const docs = loadDocs(path.join(root, 'presets'), 'preset', ajv, diagnostics); + const presets: Record = {}; + 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): 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): { 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, +): { 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, + defs: Record, + applied: Map, +): 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: string[], + presetIds: string[], +): ResolveResult { + return new Resolver(root).run(profileIds, presetIds); +} diff --git a/packages/bhl/tests/cli.test.mjs b/packages/bhl/tests/cli.test.mjs index c65e788..918c80e 100644 --- a/packages/bhl/tests/cli.test.mjs +++ b/packages/bhl/tests/cli.test.mjs @@ -32,8 +32,8 @@ test('использование: пустой запуск, --help и неиз assert.equal(unknown.envelope.error.code, 'USAGE'); }); -test('известные команды Wave B/C пока возвращают NOT_IMPLEMENTED и код 3', () => { - for (const command of ['spec', 'profile', 'report', 'audit']) { +test('известные команды Wave C/D пока возвращают NOT_IMPLEMENTED и код 3', () => { + for (const command of ['spec', 'report', 'audit']) { const result = run(command); assert.equal(result.code, 3, command); assert.equal(result.envelope.ok, false, command); diff --git a/packages/bhl/tests/resolve.test.mjs b/packages/bhl/tests/resolve.test.mjs new file mode 100644 index 0000000..9ce3aaa --- /dev/null +++ b/packages/bhl/tests/resolve.test.mjs @@ -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); +}); diff --git a/spec/schemas/audit-finding.schema.json b/spec/schemas/audit-finding.schema.json new file mode 100644 index 0000000..cfb68bb --- /dev/null +++ b/spec/schemas/audit-finding.schema.json @@ -0,0 +1,50 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://baseline-harness.dev/spec/schemas/audit-finding.schema.json", + "title": "Audit Finding", + "description": "Проверка одного требования в отчёте аудита (D-005, D-019). Статус аудита не смешивается с уровнем и жизненным циклом требования.", + "type": "object", + "additionalProperties": false, + "required": ["requirement", "status", "method", "evidence", "rationale"], + "properties": { + "requirement": { "type": "string", "pattern": "^req-[a-z0-9]+(-[a-z0-9]+)*$" }, + "status": { + "enum": ["PASS", "FAIL", "PARTIAL", "EXEMPT", "NOT_APPLICABLE", "UNKNOWN", "BLOCKED"] + }, + "method": { "enum": ["deterministic", "semantic", "hybrid"] }, + "evidence": { + "type": "array", + "minItems": 1, + "items": { "$ref": "https://baseline-harness.dev/spec/schemas/evidence.schema.json" } + }, + "issues": { "type": "array", "items": { "type": "string", "minLength": 3 } }, + "recommendations": { "type": "array", "items": { "type": "string", "minLength": 3 } }, + "corrections": { "type": "array", "items": { "type": "string", "minLength": 3 } }, + "rationale": { "type": "string", "minLength": 10 }, + "confidence": { + "enum": ["high", "medium", "low"], + "description": "Уверенность семантической проверки; для deterministic не требуется." + }, + "exemption_ref": { + "type": "string", + "minLength": 3, + "description": "Ссылка на утверждённое исключение при status EXEMPT." + } + }, + "allOf": [ + { + "if": { "properties": { "status": { "const": "EXEMPT" } }, "required": ["status"] }, + "then": { + "required": ["exemption_ref"], + "properties": { "exemption_ref": { "type": "string", "minLength": 3 } } + } + }, + { + "if": { "properties": { "method": { "const": "semantic" } }, "required": ["method"] }, + "then": { + "required": ["confidence"], + "properties": { "confidence": { "enum": ["high", "medium", "low"] } } + } + } + ] +} diff --git a/spec/schemas/audit-report.schema.json b/spec/schemas/audit-report.schema.json new file mode 100644 index 0000000..c1e56cf --- /dev/null +++ b/spec/schemas/audit-report.schema.json @@ -0,0 +1,68 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://baseline-harness.dev/spec/schemas/audit-report.schema.json", + "title": "Audit Report", + "description": "Структурированный отчёт аудита (D-005, D-019). Состояние проверяемого дерева фиксируется отпечатком, а не только commit SHA; процентный рейтинг отсутствует по замыслу.", + "type": "object", + "additionalProperties": false, + "required": ["id", "generated_at", "tool", "subject", "spec_version", "findings"], + "properties": { + "id": { "type": "string", "pattern": "^rep-[a-z0-9]+(-[a-z0-9]+)*$" }, + "generated_at": { "type": "string", "pattern": "^\\d{4}-\\d{2}-\\d{2}$" }, + "tool": { + "type": "object", + "additionalProperties": false, + "required": ["name", "version"], + "properties": { + "name": { "type": "string", "minLength": 1 }, + "version": { "type": "string", "pattern": "^\\d+\\.\\d+\\.\\d+(-[0-9A-Za-z.-]+)?$" } + } + }, + "agent": { + "type": "object", + "additionalProperties": false, + "required": ["name"], + "properties": { + "name": { "type": "string", "minLength": 1 }, + "version": { "type": "string", "minLength": 1 } + }, + "description": "Агент семантической части, если она выполнялась." + }, + "subject": { + "type": "object", + "additionalProperties": false, + "required": ["kind", "fingerprint"], + "properties": { + "kind": { "enum": ["repository", "directory", "spec"] }, + "fingerprint": { "type": "string", "pattern": "^sha256:[a-f0-9]{64}$" }, + "revision": { "type": "string", "minLength": 1 }, + "dirty": { "type": "boolean" } + } + }, + "spec_version": { "type": "string", "pattern": "^\\d+\\.\\d+\\.\\d+(-[0-9A-Za-z.-]+)?$" }, + "profiles": { + "type": "array", + "items": { "type": "string", "pattern": "^prof-[a-z0-9]+(-[a-z0-9]+)*$" } + }, + "findings": { + "type": "array", + "items": { "$ref": "https://baseline-harness.dev/spec/schemas/audit-finding.schema.json" } + }, + "summary": { + "type": "object", + "additionalProperties": false, + "required": ["PASS", "FAIL", "PARTIAL", "EXEMPT", "NOT_APPLICABLE", "UNKNOWN", "BLOCKED"], + "properties": { + "PASS": { "type": "integer", "minimum": 0 }, + "FAIL": { "type": "integer", "minimum": 0 }, + "PARTIAL": { "type": "integer", "minimum": 0 }, + "EXEMPT": { "type": "integer", "minimum": 0 }, + "NOT_APPLICABLE": { "type": "integer", "minimum": 0 }, + "UNKNOWN": { "type": "integer", "minimum": 0 }, + "BLOCKED": { "type": "integer", "minimum": 0 } + }, + "description": "Сверка сумм с findings — задача bhl report validate (BHL-023)." + }, + "notes": { "type": "array", "items": { "type": "string", "minLength": 3 } } + } +} diff --git a/spec/schemas/evidence.schema.json b/spec/schemas/evidence.schema.json new file mode 100644 index 0000000..94fc5df --- /dev/null +++ b/spec/schemas/evidence.schema.json @@ -0,0 +1,26 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://baseline-harness.dev/spec/schemas/evidence.schema.json", + "title": "Evidence", + "description": "Доказательство для Audit Finding (D-005, D-019). Класс доказательств отличает наблюдение от интерпретации.", + "type": "object", + "additionalProperties": false, + "required": ["kind", "locator", "description"], + "properties": { + "kind": { + "enum": ["file", "command-output", "test-run", "session-observation", "review-note", "hash", "other"] + }, + "locator": { + "type": "string", + "minLength": 1, + "description": "Путь, команда или идентификатор наблюдения." + }, + "description": { "type": "string", "minLength": 3 }, + "fingerprint": { + "type": "string", + "pattern": "^sha256:[a-f0-9]{64}$", + "description": "Отпечаток состояния источника доказательства (D-019)." + }, + "captured_at": { "type": "string", "pattern": "^\\d{4}-\\d{2}-\\d{2}$" } + } +} diff --git a/spec/schemas/preset.schema.json b/spec/schemas/preset.schema.json new file mode 100644 index 0000000..a5109ce --- /dev/null +++ b/spec/schemas/preset.schema.json @@ -0,0 +1,20 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://baseline-harness.dev/spec/schemas/preset.schema.json", + "title": "Preset", + "description": "Именованная композиция профилей (D-013): разворачивается в набор профилей до разрешения.", + "type": "object", + "additionalProperties": false, + "required": ["id", "title", "description", "profiles"], + "properties": { + "id": { "type": "string", "pattern": "^preset-[a-z0-9]+(-[a-z0-9]+)*$" }, + "title": { "type": "string", "minLength": 3 }, + "description": { "type": "string", "minLength": 10 }, + "profiles": { + "type": "array", + "minItems": 1, + "uniqueItems": true, + "items": { "type": "string", "pattern": "^prof-[a-z0-9]+(-[a-z0-9]+)*$" } + } + } +} diff --git a/spec/schemas/profile.schema.json b/spec/schemas/profile.schema.json new file mode 100644 index 0000000..7855bef --- /dev/null +++ b/spec/schemas/profile.schema.json @@ -0,0 +1,40 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://baseline-harness.dev/spec/schemas/profile.schema.json", + "title": "Profile", + "description": "Композиционный профиль (D-013, D-002): набор требований и переопределений параметров. Ослабление только явное (relax_to).", + "type": "object", + "additionalProperties": false, + "required": ["id", "title", "description", "requirements"], + "properties": { + "id": { "type": "string", "pattern": "^prof-[a-z0-9]+(-[a-z0-9]+)*$" }, + "title": { "type": "string", "minLength": 3 }, + "description": { "type": "string", "minLength": 10 }, + "requirements": { + "type": "array", + "minItems": 1, + "items": { + "type": "object", + "additionalProperties": false, + "required": ["requirement"], + "properties": { + "requirement": { "type": "string", "pattern": "^req-[a-z0-9]+(-[a-z0-9]+)*$" }, + "relax_to": { "enum": ["SHOULD", "MAY"] }, + "note": { "type": "string", "minLength": 3 } + } + } + }, + "parameter_overrides": { + "type": "array", + "items": { + "type": "object", + "additionalProperties": false, + "required": ["parameter", "value"], + "properties": { + "parameter": { "type": "string", "pattern": "^param-[a-z0-9]+(-[a-z0-9]+)*$" }, + "value": {} + } + } + } + } +} diff --git a/tests/spec-schemas.test.mjs b/tests/spec-schemas.test.mjs index 56d8b5a..2dab825 100644 --- a/tests/spec-schemas.test.mjs +++ b/tests/spec-schemas.test.mjs @@ -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'] }), + 'пресет из требований вместо профилей', + ); +});