feat: bhl audit — детерминированный движок аудита (BHL-026)
- встроенные проверки: команда качества, lockfile, CI-конфиг по Effective Spec - subject: отпечаток дерева SHA-256 + git revision/dirty (git из PATH — узкое исключение sonarjs/no-os-command-from-path в eslint.config.mjs) - evidence с fingerprint байтов; FAIL доказателен (отсутствие — наблюдение) - отчёт проходит report validate; повторный аудит идентичен (тесты) - требования без проверки → UNKNOWN/semantic/low; пакет 41/41
This commit is contained in:
@@ -31,11 +31,13 @@ npm run bhl -- version
|
||||
| Команда | Назначение | Статус |
|
||||
|---|---|---|
|
||||
| `version` | имя и версия пакета | работает |
|
||||
| `validate` | валидация спецификации и манифеста | работает (BHL-011); манифест проекта — BHL-014 |
|
||||
| `spec` | `list` / `show` требований | BHL-022 |
|
||||
| `profile` | разрешение Effective Specification | BHL-022 |
|
||||
| `report` | `validate` / `render` отчёта аудита | BHL-023, BHL-025 |
|
||||
| `audit` | детерминированный аудит | BHL-026 |
|
||||
| `validate` | валидация спецификации | работает (BHL-011) |
|
||||
| `spec` | `list` / `show` / `render` | работает (BHL-022, BHL-017) |
|
||||
| `profile resolve` | разрешение Effective Specification | работает (BHL-012, BHL-013) |
|
||||
| `report` | `validate` / `render` отчёта аудита | работает (BHL-023, BHL-025) |
|
||||
| `manifest validate` | валидация манифеста проекта | работает (BHL-014, BHL-022) |
|
||||
| `fetch` / `verify` | загрузка версии спецификации, кеш и lock | работает (BHL-021) |
|
||||
| `audit` | детерминированный аудит проекта по Effective Specification | работает (BHL-026); семантический аудит — BHL-029+ |
|
||||
|
||||
## Зависимости и границы
|
||||
|
||||
|
||||
@@ -81,4 +81,12 @@ export default defineConfig(
|
||||
'max-lines-per-function': 'off',
|
||||
},
|
||||
},
|
||||
{
|
||||
files: ['src/audit.ts'],
|
||||
rules: {
|
||||
// git is optional audit metadata resolved from the operator PATH; absence yields
|
||||
// no revision fields rather than a failure. Scoped to the audit engine only.
|
||||
'sonarjs/no-os-command-from-path': 'off',
|
||||
},
|
||||
},
|
||||
);
|
||||
|
||||
@@ -0,0 +1,332 @@
|
||||
import { createHash } from 'node:crypto';
|
||||
import { spawnSync } from 'node:child_process';
|
||||
import { existsSync, readFileSync, readdirSync, statSync, writeFileSync } from 'node:fs';
|
||||
import path from 'node:path';
|
||||
|
||||
import { resolveProfiles } from './resolve.ts';
|
||||
import type { Diagnostic } from './validate.ts';
|
||||
|
||||
export interface AuditOptions {
|
||||
projectDir: string;
|
||||
specRoot: string;
|
||||
profileIds: readonly string[];
|
||||
presetIds: readonly string[];
|
||||
generatedAt: string;
|
||||
}
|
||||
|
||||
export interface AuditResult {
|
||||
ok: boolean;
|
||||
report: Record<string, unknown> | undefined;
|
||||
diagnostics: readonly Diagnostic[];
|
||||
}
|
||||
|
||||
interface CheckOutcome {
|
||||
status: 'PASS' | 'FAIL';
|
||||
rationale: string;
|
||||
evidence: Record<string, unknown>[];
|
||||
}
|
||||
|
||||
function absenceEvidence(locator: string, description: string): Record<string, unknown>[] {
|
||||
return [
|
||||
{
|
||||
kind: 'other',
|
||||
locator,
|
||||
description,
|
||||
captured_at: EPOCH_DATE,
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
const SKIP_DIRS = new Set(['.git', 'node_modules', 'out']);
|
||||
// captured_at по схеме — календарная дата; детерминированная эпоха для встроенных проверок.
|
||||
const EPOCH_DATE = '1970-01-01';
|
||||
const REPORT_STATUSES = [
|
||||
'PASS',
|
||||
'FAIL',
|
||||
'PARTIAL',
|
||||
'EXEMPT',
|
||||
'NOT_APPLICABLE',
|
||||
'UNKNOWN',
|
||||
'BLOCKED',
|
||||
] as const;
|
||||
const LOCKFILES = [
|
||||
'package-lock.json',
|
||||
'yarn.lock',
|
||||
'pnpm-lock.yaml',
|
||||
'npm-shrinkwrap.json',
|
||||
'Gemfile.lock',
|
||||
'go.sum',
|
||||
'uv.lock',
|
||||
'poetry.lock',
|
||||
'Cargo.lock',
|
||||
];
|
||||
|
||||
function sha256(data: Buffer | string): string {
|
||||
return `sha256:${createHash('sha256').update(data).digest('hex')}`;
|
||||
}
|
||||
|
||||
function walkFiles(dir: string, prefix: string, acc: string[]): void {
|
||||
for (const entry of readdirSync(dir, { withFileTypes: true }).sort((a, b) =>
|
||||
a.name.localeCompare(b.name),
|
||||
)) {
|
||||
const rel = prefix === '' ? entry.name : `${prefix}/${entry.name}`;
|
||||
if (entry.isDirectory()) {
|
||||
if (!SKIP_DIRS.has(entry.name)) {
|
||||
walkFiles(path.join(dir, entry.name), rel, acc);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if (entry.isFile()) {
|
||||
acc.push(rel);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export function treeFingerprint(dir: string): string {
|
||||
const files: string[] = [];
|
||||
walkFiles(dir, '', files);
|
||||
const hash = createHash('sha256');
|
||||
for (const file of files) {
|
||||
hash
|
||||
.update(file)
|
||||
.update('\u0000')
|
||||
.update(readFileSync(path.join(dir, file)))
|
||||
.update('\u0000');
|
||||
}
|
||||
return `sha256:${hash.digest('hex')}`;
|
||||
}
|
||||
|
||||
function gitInfo(dir: string): { revision?: string; dirty?: boolean } {
|
||||
// git намеренно берётся из PATH оператора: это необязательные метаданные аудита,
|
||||
// отсутствие git даёт пустой объект, а не сбой (см. eslint.config.mjs, src/audit.ts).
|
||||
const rev = spawnSync('git', ['-C', dir, 'rev-parse', 'HEAD'], { encoding: 'utf8' });
|
||||
if (rev.status !== 0) {
|
||||
return {};
|
||||
}
|
||||
const status = spawnSync('git', ['-C', dir, 'status', '--porcelain'], { encoding: 'utf8' });
|
||||
return { revision: rev.stdout.trim(), dirty: status.stdout.trim() !== '' };
|
||||
}
|
||||
|
||||
function evidenceFor(file: string, locator: string, description: string): Record<string, unknown> {
|
||||
const bytes = readFileSync(file);
|
||||
return {
|
||||
kind: 'file',
|
||||
description,
|
||||
locator,
|
||||
fingerprint: sha256(bytes),
|
||||
captured_at: EPOCH_DATE,
|
||||
};
|
||||
}
|
||||
|
||||
function readText(file: string): string {
|
||||
try {
|
||||
return readFileSync(file, 'utf8');
|
||||
} catch {
|
||||
return '';
|
||||
}
|
||||
}
|
||||
|
||||
function getProp(obj: unknown, key: string): unknown {
|
||||
if (typeof obj === 'object' && obj !== null) {
|
||||
return Reflect.get(obj, key);
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
function declaresQuality(pkg: unknown): boolean {
|
||||
const scripts = getProp(pkg, 'scripts');
|
||||
return (
|
||||
typeof scripts === 'object' && scripts !== null && ('quality' in scripts || 'check' in scripts)
|
||||
);
|
||||
}
|
||||
|
||||
function checkQualityCommand(dir: string): CheckOutcome {
|
||||
const candidates: [string, (text: string) => boolean][] = [
|
||||
[
|
||||
'package.json',
|
||||
(text) => {
|
||||
try {
|
||||
return declaresQuality(JSON.parse(text));
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
},
|
||||
],
|
||||
['Makefile', (text) => /^quality:/m.test(text)],
|
||||
];
|
||||
for (const [name, matches] of candidates) {
|
||||
const file = path.join(dir, name);
|
||||
if (existsSync(file) && matches(readText(file))) {
|
||||
return {
|
||||
status: 'PASS',
|
||||
rationale: `Воспроизводимая команда качества объявлена в ${name}.`,
|
||||
evidence: [evidenceFor(file, name, `${name} объявляет команду качества`)],
|
||||
};
|
||||
}
|
||||
}
|
||||
return {
|
||||
status: 'FAIL',
|
||||
rationale:
|
||||
'Не найдено объявленной команды качества (package.json scripts.quality|check или Makefile цель quality).',
|
||||
evidence: absenceEvidence(
|
||||
'package.json, Makefile',
|
||||
'Ни package.json с scripts.quality|check, ни Makefile с целью quality не найдены.',
|
||||
),
|
||||
};
|
||||
}
|
||||
|
||||
function checkPresence(
|
||||
dir: string,
|
||||
candidates: readonly string[],
|
||||
label: string,
|
||||
rationaleFail: string,
|
||||
): CheckOutcome {
|
||||
for (const name of candidates) {
|
||||
const file = path.join(dir, name);
|
||||
if (existsSync(file) && statSync(file).isFile()) {
|
||||
return {
|
||||
status: 'PASS',
|
||||
rationale: `${label}: найден ${name}.`,
|
||||
evidence: [evidenceFor(file, name, `${label} зафиксирован`)],
|
||||
};
|
||||
}
|
||||
}
|
||||
return {
|
||||
status: 'FAIL',
|
||||
rationale: rationaleFail,
|
||||
evidence: absenceEvidence(candidates.join(', '), `${label}: ни один из кандидатов не найден.`),
|
||||
};
|
||||
}
|
||||
|
||||
function ciCandidates(dir: string): string[] {
|
||||
const fixed = ['.gitlab-ci.yml', 'Jenkinsfile', '.buildkite/pipeline.yml'];
|
||||
const workflows = path.join(dir, '.github', 'workflows');
|
||||
const extra: string[] = [];
|
||||
if (existsSync(workflows)) {
|
||||
for (const name of readdirSync(workflows)) {
|
||||
if (/\.ya?ml$/.test(name)) {
|
||||
extra.push(`.github/workflows/${name}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
return [...extra, ...fixed];
|
||||
}
|
||||
|
||||
const CHECKS: Readonly<Record<string, (dir: string) => CheckOutcome>> = {
|
||||
'req-synth-alpha': checkQualityCommand,
|
||||
'req-synth-beta': (dir) =>
|
||||
checkPresence(
|
||||
dir,
|
||||
LOCKFILES,
|
||||
'Блокировка зависимостей',
|
||||
'Не найден lockfile ни в одном из известных форматов.',
|
||||
),
|
||||
'req-synth-gamma': (dir) =>
|
||||
checkPresence(
|
||||
dir,
|
||||
ciCandidates(dir),
|
||||
'Конфигурация CI',
|
||||
'Не найдена конфигурация CI (.github/workflows/*.yml, .gitlab-ci.yml и др.).',
|
||||
),
|
||||
};
|
||||
|
||||
function unknownFinding(requirement: string): Record<string, unknown> {
|
||||
return {
|
||||
requirement,
|
||||
status: 'UNKNOWN',
|
||||
method: 'semantic',
|
||||
confidence: 'low',
|
||||
rationale:
|
||||
'Детерминированная проверка для этого требования не реализована; требуется семантический аудит.',
|
||||
evidence: [
|
||||
{
|
||||
kind: 'observation',
|
||||
description:
|
||||
'Встроенный реестр детерминированных проверок не содержит записи о требовании.',
|
||||
captured_at: new Date(0).toISOString(),
|
||||
},
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
function buildFinding(projectDir: string, requirement: string): Record<string, unknown> {
|
||||
const check = CHECKS[requirement];
|
||||
if (check === undefined) {
|
||||
return unknownFinding(requirement);
|
||||
}
|
||||
const outcome = check(projectDir);
|
||||
const finding: Record<string, unknown> = {
|
||||
requirement,
|
||||
status: outcome.status,
|
||||
method: 'deterministic',
|
||||
rationale: outcome.rationale,
|
||||
evidence: outcome.evidence,
|
||||
};
|
||||
return finding;
|
||||
}
|
||||
|
||||
function summarize(findings: readonly Readonly<Record<string, unknown>>[]): Record<string, number> {
|
||||
const summary: Record<string, number> = {};
|
||||
for (const status of REPORT_STATUSES) {
|
||||
summary[status] = 0;
|
||||
}
|
||||
for (const finding of findings) {
|
||||
const status = finding['status'];
|
||||
if (typeof status === 'string') {
|
||||
summary[status] = (summary[status] ?? 0) + 1;
|
||||
}
|
||||
}
|
||||
return summary;
|
||||
}
|
||||
|
||||
function packageVersion(): string {
|
||||
try {
|
||||
const version = getProp(
|
||||
JSON.parse(readFileSync(path.join(import.meta.dirname, '..', 'package.json'), 'utf8')),
|
||||
'version',
|
||||
);
|
||||
if (typeof version === 'string') {
|
||||
return version;
|
||||
}
|
||||
} catch {
|
||||
// fall through to default
|
||||
}
|
||||
return '0.0.0';
|
||||
}
|
||||
|
||||
export function runAudit(options: AuditOptions): AuditResult {
|
||||
const diagnostics: Diagnostic[] = [];
|
||||
const resolution = resolveProfiles(options.specRoot, options.profileIds, options.presetIds);
|
||||
diagnostics.push(...resolution.diagnostics);
|
||||
if (!resolution.ok) {
|
||||
return { ok: false, report: undefined, diagnostics };
|
||||
}
|
||||
const requirements = resolution.effective
|
||||
.map((entry) => entry.requirement)
|
||||
.sort((a, b) => a.localeCompare(b));
|
||||
const findings = requirements.map((requirement) => buildFinding(options.projectDir, requirement));
|
||||
const fingerprint = treeFingerprint(options.projectDir);
|
||||
const git = gitInfo(options.projectDir);
|
||||
const subject: Record<string, unknown> = {
|
||||
kind: git.revision === undefined ? 'directory' : 'repository',
|
||||
fingerprint,
|
||||
};
|
||||
Object.assign(subject, git);
|
||||
const report: Record<string, unknown> = {
|
||||
id: `rep-audit-${fingerprint.slice(7, 23)}`,
|
||||
generated_at: options.generatedAt,
|
||||
tool: { name: 'bhl', version: packageVersion() },
|
||||
subject,
|
||||
spec_version: '0.0.0',
|
||||
profiles: resolution.profiles,
|
||||
findings,
|
||||
summary: summarize(findings),
|
||||
};
|
||||
return { ok: true, report, diagnostics };
|
||||
}
|
||||
|
||||
export function writeAuditReport(result: AuditResult, out: string): void {
|
||||
if (result.report !== undefined) {
|
||||
writeFileSync(out, `${JSON.stringify(result.report, null, 2)}\n`, 'utf8');
|
||||
}
|
||||
}
|
||||
+110
-3
@@ -1,5 +1,6 @@
|
||||
import { mkdirSync, readFileSync, writeFileSync } from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { runAudit, writeAuditReport } from './audit.ts';
|
||||
import { emit, ExitCode, failEnvelope, okEnvelope } from './envelope.ts';
|
||||
import { fetchSpec, verifyCache } from './fetch.ts';
|
||||
import { renderReport, renderSpec } from './render.ts';
|
||||
@@ -9,7 +10,7 @@ import { validateReport } from './report.ts';
|
||||
import { validateSpec } from './validate.ts';
|
||||
|
||||
const USAGE_MESSAGE =
|
||||
'Usage: bhl <version|validate|spec|profile|report|manifest|audit> [args]; ' +
|
||||
'Usage: bhl <version|validate|spec|profile|report|manifest|fetch|verify|audit> [args]; ' +
|
||||
'spec list [--spec-root <path>] [--domain <id>] [--capability <id>]; ' +
|
||||
'spec show <req-id> [--spec-root <path>]; ' +
|
||||
'spec render --spec-root <path> --out <dir>; ' +
|
||||
@@ -19,6 +20,8 @@ const USAGE_MESSAGE =
|
||||
'manifest validate <manifest.yaml> [--spec-root <path>]; ' +
|
||||
'fetch <release-dir> --version <semver> --cache <dir>; ' +
|
||||
'verify --version <semver> --cache <dir>; ' +
|
||||
'audit <project-dir> --out <report.json> [--spec-root <path>] [--profile <id>] ' +
|
||||
'[--preset <id>] [--generated-at <iso>]; ' +
|
||||
'JSON envelope on stdout; exit codes: 0 ok, 1 validation failed, 2 usage, ' +
|
||||
'3 not implemented, 4 internal.';
|
||||
|
||||
@@ -461,6 +464,111 @@ function runVerify(command: string, rest: readonly string[]): number {
|
||||
return ExitCode.Ok;
|
||||
}
|
||||
|
||||
const AUDIT_FLAGS: Readonly<
|
||||
Record<string, 'spec-root' | 'out' | 'generated-at' | 'profile' | 'preset'>
|
||||
> = {
|
||||
'--spec-root': 'spec-root',
|
||||
'--out': 'out',
|
||||
'--generated-at': 'generated-at',
|
||||
'--profile': 'profile',
|
||||
'--preset': 'preset',
|
||||
};
|
||||
|
||||
interface AuditFlags {
|
||||
root: string;
|
||||
out?: string;
|
||||
generatedAt?: string;
|
||||
profiles: string[];
|
||||
presets: string[];
|
||||
positional: string[];
|
||||
}
|
||||
|
||||
function takeAuditFlag(
|
||||
args: readonly string[],
|
||||
cursor: number,
|
||||
target: AuditFlags,
|
||||
arg: string,
|
||||
): { next: number } | { error: string } {
|
||||
const flag = AUDIT_FLAGS[arg];
|
||||
const value = args[cursor + 1];
|
||||
if (flag === undefined || value === undefined) {
|
||||
return { error: `missing value for ${arg}` };
|
||||
}
|
||||
if (flag === 'spec-root') {
|
||||
target.root = value;
|
||||
} else if (flag === 'out') {
|
||||
target.out = value;
|
||||
} else if (flag === 'generated-at') {
|
||||
target.generatedAt = value;
|
||||
} else if (flag === 'profile') {
|
||||
target.profiles.push(value);
|
||||
} else {
|
||||
target.presets.push(value);
|
||||
}
|
||||
return { next: cursor + 2 };
|
||||
}
|
||||
|
||||
function parseAuditArgs(args: readonly string[]): AuditFlags | { error: string } {
|
||||
const target: AuditFlags = { root: 'spec', profiles: [], presets: [], positional: [] };
|
||||
let cursor = 0;
|
||||
while (cursor < args.length) {
|
||||
const arg = args[cursor] ?? '';
|
||||
if (AUDIT_FLAGS[arg] !== undefined) {
|
||||
const taken = takeAuditFlag(args, cursor, target, arg);
|
||||
if ('error' in taken) {
|
||||
return taken;
|
||||
}
|
||||
cursor = taken.next;
|
||||
continue;
|
||||
}
|
||||
if (arg.startsWith('--')) {
|
||||
return { error: `unknown flag ${arg}` };
|
||||
}
|
||||
target.positional.push(arg);
|
||||
cursor += 1;
|
||||
}
|
||||
return target;
|
||||
}
|
||||
|
||||
function runAuditCommand(command: string, rest: readonly string[]): number {
|
||||
const parsed = parseAuditArgs(rest);
|
||||
if ('error' in parsed) {
|
||||
emit(failEnvelope(command, 'USAGE', parsed.error));
|
||||
return ExitCode.Usage;
|
||||
}
|
||||
const projectDir = parsed.positional[0];
|
||||
const out = parsed.out;
|
||||
if (projectDir === undefined || parsed.positional.length !== 1 || out === undefined) {
|
||||
emit(failEnvelope(command, 'USAGE', 'audit requires <project-dir> and --out <report.json>'));
|
||||
return ExitCode.Usage;
|
||||
}
|
||||
const generatedAt = parsed.generatedAt ?? new Date().toISOString().slice(0, 10);
|
||||
const result = runAudit({
|
||||
projectDir,
|
||||
specRoot: parsed.root,
|
||||
profileIds: parsed.profiles,
|
||||
presetIds: parsed.presets,
|
||||
generatedAt,
|
||||
});
|
||||
if (!result.ok || result.report === undefined) {
|
||||
return emitValidationFailure(
|
||||
command,
|
||||
{ project: projectDir, errors: result.diagnostics },
|
||||
result.diagnostics.length,
|
||||
);
|
||||
}
|
||||
mkdirSync(path.dirname(out), { recursive: true });
|
||||
writeAuditReport(result, out);
|
||||
emit(
|
||||
okEnvelope(command, {
|
||||
project: projectDir,
|
||||
out,
|
||||
summary: result.report['summary'],
|
||||
}),
|
||||
);
|
||||
return ExitCode.Ok;
|
||||
}
|
||||
|
||||
function runManifest(command: string, rest: readonly string[]): number {
|
||||
const [sub, ...args] = rest;
|
||||
if (sub !== 'validate') {
|
||||
@@ -607,8 +715,7 @@ export function run(argv: readonly string[]): number {
|
||||
return runVerify(command, rest);
|
||||
}
|
||||
if (command === 'audit') {
|
||||
emit(failEnvelope(command, 'NOT_IMPLEMENTED', `${command} is not implemented yet`));
|
||||
return ExitCode.NotImplemented;
|
||||
return runAuditCommand(command, rest);
|
||||
}
|
||||
emit(failEnvelope(command, 'USAGE', USAGE_MESSAGE));
|
||||
return ExitCode.Usage;
|
||||
|
||||
@@ -243,7 +243,7 @@ class Resolver {
|
||||
this.root = root;
|
||||
}
|
||||
|
||||
run(profileIds: string[], presetIds: string[]): ResolveResult {
|
||||
run(profileIds: readonly string[], presetIds: readonly string[]): ResolveResult {
|
||||
if (!this.addSchemas()) {
|
||||
return { ok: false, profiles: [], effective: [], diagnostics: this.diagnostics };
|
||||
}
|
||||
@@ -314,8 +314,8 @@ class Resolver {
|
||||
}
|
||||
|
||||
private selectProfiles(
|
||||
profileIds: string[],
|
||||
presetIds: string[],
|
||||
profileIds: readonly string[],
|
||||
presetIds: readonly string[],
|
||||
profiles: Record<string, ProfileDoc>,
|
||||
presets: Record<string, string[]>,
|
||||
): ProfileDoc[] {
|
||||
@@ -567,8 +567,8 @@ function requirementParameters(
|
||||
|
||||
export function resolveProfiles(
|
||||
root: string,
|
||||
profileIds: string[],
|
||||
presetIds: string[],
|
||||
profileIds: readonly string[],
|
||||
presetIds: readonly string[],
|
||||
): ResolveResult {
|
||||
return new Resolver(root).run(profileIds, presetIds);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,117 @@
|
||||
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 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',
|
||||
'--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');
|
||||
});
|
||||
@@ -32,11 +32,9 @@ test('использование: пустой запуск, --help и неиз
|
||||
assert.equal(unknown.envelope.error.code, 'USAGE');
|
||||
});
|
||||
|
||||
test('известные команды Wave D/E пока возвращают NOT_IMPLEMENTED и код 3', () => {
|
||||
for (const command of ['audit']) {
|
||||
const result = run(command);
|
||||
assert.equal(result.code, 3, command);
|
||||
assert.equal(result.envelope.ok, false, command);
|
||||
assert.equal(result.envelope.error.code, 'NOT_IMPLEMENTED', command);
|
||||
}
|
||||
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');
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user