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
+163 -59
View File
@@ -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 <version|validate|spec|profile|report|audit> [args]; ' +
'profile resolve <spec-root> [--profile <id>] [--preset <id>]; ' +
'JSON envelope on stdout; exit codes: 0 ok, 1 validation failed, 2 usage, ' +
'3 not implemented, 4 internal.';
const KNOWN: ReadonlySet<string> = new Set([
'version',
'validate',
'spec',
'profile',
'report',
'audit',
]);
function isRecord(value: unknown): value is Record<string, unknown> {
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<Record<string, FlagName>> = {
'--profile': 'profile',
'--preset': 'preset',
};
interface SplitState {
positional: string[];
collected: Record<FlagName, string[]>;
cursor: number;
}
function parseFlagAt(args: readonly string[], state: SplitState, arg: string): string {
const flag = FLAG_TARGETS[arg];
const value = args[state.cursor + 1];
if (flag === undefined || value === undefined) {
return `missing value for ${arg}`;
}
state.collected[flag].push(value);
state.cursor += 2;
return '';
}
function splitArgs(args: readonly string[]): { ok: SplitState } | { error: string } {
const state: SplitState = {
positional: [],
collected: { profile: [], preset: [] },
cursor: 0,
};
while (state.cursor < args.length) {
const arg = args[state.cursor] ?? '';
if (FLAG_TARGETS[arg] !== undefined) {
const error = parseFlagAt(args, state, arg);
if (error !== '') {
return { error };
}
continue;
}
if (arg.startsWith('--')) {
return { error: `unknown flag ${arg}` };
}
state.positional.push(arg);
state.cursor += 1;
}
return { ok: state };
}
function toParsedArgs(state: SplitState): ParsedArgs | { error: string } {
if (state.positional.length !== 1) {
const extra = state.positional[1];
const message =
state.positional.length === 0
? 'resolve requires a spec root path'
: `unexpected argument ${extra ?? ''}`;
return { error: message };
}
return {
root: state.positional[0] ?? '',
profiles: state.collected.profile,
presets: state.collected.preset,
};
}
function parseArgs(args: readonly string[]): ParsedArgs | { error: string } {
const split = splitArgs(args);
if ('error' in split) {
return split;
}
return toParsedArgs(split.ok);
}
function runProfile(command: string, rest: readonly string[]): number {
const [sub, ...args] = rest;
if (sub !== 'resolve') {
emit(failEnvelope(command, 'USAGE', 'profile requires the subcommand resolve'));
return ExitCode.Usage;
}
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();