fix: ремедиация аудита лаборатории — решения и исправления (BHL-043)
- решения владельца: D-039 принято (SemVer), D-044 (BLOCKED — седьмой статус), D-045 (у param-coverage-threshold нет глобального default), D-046 (уточнение D-040: обезличенные производные выводы разрешены) - chg-018 STRENGTHENED + migration: значение задаёт профиль/манифест - C1: bhl audit --spec-version (fallback на lock.json кеша, иначе ошибка) - C2: UNKNOWN-находки валидны по схеме evidence (review-note, locator, дата) - C3: treeFingerprint игнорирует .pi/.artifacts/.cache/.tmp - C4: req-single-quality-command — детерминированная проверка - L1: порог длины id вынесен в именованную константу MAX_ID_LENGTH - пакет: 48/48 тестов, корень зелёный
This commit is contained in:
@@ -12,6 +12,7 @@ export interface AuditOptions {
|
||||
profileIds: readonly string[];
|
||||
presetIds: readonly string[];
|
||||
generatedAt: string;
|
||||
specVersion?: string | undefined;
|
||||
}
|
||||
|
||||
export interface AuditResult {
|
||||
@@ -37,7 +38,7 @@ function absenceEvidence(locator: string, description: string): Record<string, u
|
||||
];
|
||||
}
|
||||
|
||||
const SKIP_DIRS = new Set(['.git', 'node_modules', 'out']);
|
||||
const SKIP_DIRS = new Set(['.git', 'node_modules', 'out', '.pi', '.artifacts', '.cache', '.tmp']);
|
||||
// captured_at по схеме — календарная дата; детерминированная эпоха для встроенных проверок.
|
||||
const EPOCH_DATE = '1970-01-01';
|
||||
const REPORT_STATUSES = [
|
||||
@@ -214,6 +215,7 @@ function ciCandidates(dir: string): string[] {
|
||||
|
||||
const CHECKS: Readonly<Record<string, (dir: string) => CheckOutcome>> = {
|
||||
'req-synth-alpha': checkQualityCommand,
|
||||
'req-single-quality-command': checkQualityCommand,
|
||||
'req-synth-beta': (dir) =>
|
||||
checkPresence(
|
||||
dir,
|
||||
@@ -240,10 +242,11 @@ function unknownFinding(requirement: string): Record<string, unknown> {
|
||||
'Детерминированная проверка для этого требования не реализована; требуется семантический аудит.',
|
||||
evidence: [
|
||||
{
|
||||
kind: 'observation',
|
||||
kind: 'review-note',
|
||||
locator: requirement,
|
||||
description:
|
||||
'Встроенный реестр детерминированных проверок не содержит записи о требовании.',
|
||||
captured_at: new Date(0).toISOString(),
|
||||
captured_at: EPOCH_DATE,
|
||||
},
|
||||
],
|
||||
};
|
||||
@@ -294,8 +297,31 @@ function packageVersion(): string {
|
||||
return '0.0.0';
|
||||
}
|
||||
|
||||
// Версия спецификации — обязательный контекст аудита (C1/BHL-043): флаг либо lock.json кеша bhl fetch.
|
||||
function specVersionFromLock(specRoot: string): string | undefined {
|
||||
try {
|
||||
const version = getProp(
|
||||
JSON.parse(readFileSync(path.join(specRoot, '..', 'lock.json'), 'utf8')),
|
||||
'version',
|
||||
);
|
||||
return typeof version === 'string' ? version : undefined;
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
export function runAudit(options: AuditOptions): AuditResult {
|
||||
const diagnostics: Diagnostic[] = [];
|
||||
const specVersion = options.specVersion ?? specVersionFromLock(options.specRoot);
|
||||
if (specVersion === undefined) {
|
||||
diagnostics.push({
|
||||
file: options.specRoot,
|
||||
code: 'spec-version-unknown',
|
||||
message:
|
||||
'Версия спецификации не задана: передайте --spec-version или используйте кеш bhl fetch (lock.json).',
|
||||
});
|
||||
return { ok: false, report: undefined, diagnostics };
|
||||
}
|
||||
const resolution = resolveProfiles(options.specRoot, options.profileIds, options.presetIds);
|
||||
diagnostics.push(...resolution.diagnostics);
|
||||
if (!resolution.ok) {
|
||||
@@ -317,7 +343,7 @@ export function runAudit(options: AuditOptions): AuditResult {
|
||||
generated_at: options.generatedAt,
|
||||
tool: { name: 'bhl', version: packageVersion() },
|
||||
subject,
|
||||
spec_version: '0.0.0',
|
||||
spec_version: specVersion,
|
||||
profiles: resolution.profiles,
|
||||
findings,
|
||||
summary: summarize(findings),
|
||||
|
||||
@@ -22,8 +22,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>]; ' +
|
||||
'audit <project-dir> --out <report.json> [--spec-root <path>] [--spec-version <semver>] ' +
|
||||
'[--profile <id>] [--preset <id>] [--generated-at <iso>]; ' +
|
||||
'release <spec-root> --version <semver> --out <dir>; ' +
|
||||
'JSON envelope on stdout; exit codes: 0 ok, 1 validation failed, 2 usage, ' +
|
||||
'3 not implemented, 4 internal.';
|
||||
@@ -468,19 +468,21 @@ function runVerify(command: string, rest: readonly string[]): number {
|
||||
}
|
||||
|
||||
const AUDIT_FLAGS: Readonly<
|
||||
Record<string, 'spec-root' | 'out' | 'generated-at' | 'profile' | 'preset'>
|
||||
Record<string, 'spec-root' | 'out' | 'generated-at' | 'profile' | 'preset' | 'spec-version'>
|
||||
> = {
|
||||
'--spec-root': 'spec-root',
|
||||
'--out': 'out',
|
||||
'--generated-at': 'generated-at',
|
||||
'--profile': 'profile',
|
||||
'--preset': 'preset',
|
||||
'--spec-version': 'spec-version',
|
||||
};
|
||||
|
||||
interface AuditFlags {
|
||||
root: string;
|
||||
out?: string;
|
||||
generatedAt?: string;
|
||||
specVersion?: string;
|
||||
profiles: string[];
|
||||
presets: string[];
|
||||
positional: string[];
|
||||
@@ -503,6 +505,8 @@ function takeAuditFlag(
|
||||
target.out = value;
|
||||
} else if (flag === 'generated-at') {
|
||||
target.generatedAt = value;
|
||||
} else if (flag === 'spec-version') {
|
||||
target.specVersion = value;
|
||||
} else if (flag === 'profile') {
|
||||
target.profiles.push(value);
|
||||
} else {
|
||||
@@ -635,6 +639,7 @@ function runAuditCommand(command: string, rest: readonly string[]): number {
|
||||
profileIds: parsed.profiles,
|
||||
presetIds: parsed.presets,
|
||||
generatedAt,
|
||||
specVersion: parsed.specVersion,
|
||||
});
|
||||
if (!result.ok || result.report === undefined) {
|
||||
return emitValidationFailure(
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
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 { mkdirSync, mkdtempSync, cpSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
|
||||
@@ -39,6 +39,8 @@ function runAudit(t, projectFiles) {
|
||||
specRoot,
|
||||
'--preset',
|
||||
'preset-synth-all',
|
||||
'--spec-version',
|
||||
'0.1.0',
|
||||
'--generated-at',
|
||||
GENERATED_AT,
|
||||
],
|
||||
@@ -115,3 +117,118 @@ test('audit: usage-ошибки и нечитаемый spec-root дают по
|
||||
assert.equal(badSpec.status, 1);
|
||||
assert.equal(JSON.parse(badSpec.stdout).error.code, 'VALIDATION_FAILED');
|
||||
});
|
||||
|
||||
function makeFixtureSpec(t) {
|
||||
const dir = makeDir();
|
||||
t.after(() => rmSync(dir, { recursive: true, force: true }));
|
||||
const spec = path.join(dir, 'spec');
|
||||
cpSync(specRoot, spec, { recursive: true });
|
||||
return { dir, spec };
|
||||
}
|
||||
|
||||
function auditRun(spec, projectDir, out, extraArgs) {
|
||||
return spawnSync(
|
||||
process.execPath,
|
||||
[
|
||||
cli,
|
||||
'audit',
|
||||
projectDir,
|
||||
'--out',
|
||||
out,
|
||||
'--spec-root',
|
||||
spec,
|
||||
'--generated-at',
|
||||
GENERATED_AT,
|
||||
...extraArgs,
|
||||
],
|
||||
{ encoding: 'utf8' },
|
||||
);
|
||||
}
|
||||
|
||||
test('audit: версия спецификации из флага, из lock.json или ошибка (C1/BHL-043)', (t) => {
|
||||
const { dir, spec } = makeFixtureSpec(t);
|
||||
const project = path.join(dir, 'project');
|
||||
writeProject(project, GOOD_PROJECT);
|
||||
const noVersion = auditRun(spec, project, path.join(dir, 'r1.json'), []);
|
||||
assert.equal(noVersion.status, 1);
|
||||
assert.equal(JSON.parse(noVersion.stdout).error.code, 'VALIDATION_FAILED');
|
||||
assert.match(noVersion.stdout, /spec-version-unknown/);
|
||||
writeProject(dir, { 'lock.json': JSON.stringify({ version: '9.9.9' }) });
|
||||
const fromLock = auditRun(spec, project, path.join(dir, 'r2.json'), []);
|
||||
assert.equal(fromLock.status, 0, fromLock.stdout);
|
||||
const report = JSON.parse(readFileSync(path.join(dir, 'r2.json'), 'utf8'));
|
||||
assert.equal(report.spec_version, '9.9.9');
|
||||
const flagged = auditRun(spec, project, path.join(dir, 'r3.json'), ['--spec-version', '8.8.8']);
|
||||
assert.equal(flagged.status, 0);
|
||||
assert.equal(JSON.parse(readFileSync(path.join(dir, 'r3.json'), 'utf8')).spec_version, '8.8.8');
|
||||
});
|
||||
|
||||
test('audit: UNKNOWN-находки валидны по схеме отчёта (C2/BHL-043)', (t) => {
|
||||
const { dir, spec } = makeFixtureSpec(t);
|
||||
const alpha = readFileSync(path.join(spec, 'requirements', 'req-synth-alpha.yaml'), 'utf8');
|
||||
writeProject(spec, {
|
||||
'requirements/req-plain-no-check.yaml': alpha.replace('req-synth-alpha', 'req-plain-no-check'),
|
||||
'profiles/prof-plain.yaml':
|
||||
'id: prof-plain\ntitle: Только без проверки\ndescription: Профиль фикстуры с требованием без детерминированной проверки.\nrequirements:\n - requirement: req-plain-no-check\n',
|
||||
});
|
||||
const project = path.join(dir, 'project');
|
||||
writeProject(project, GOOD_PROJECT);
|
||||
const out = path.join(dir, 'r.json');
|
||||
const run = auditRun(spec, project, out, ['--spec-version', '0.1.0', '--profile', 'prof-plain']);
|
||||
assert.equal(run.status, 0, run.stdout);
|
||||
const report = JSON.parse(readFileSync(out, 'utf8'));
|
||||
assert.equal(report.findings[0].status, 'UNKNOWN');
|
||||
const validate = spawnSync(
|
||||
process.execPath,
|
||||
[cli, 'report', 'validate', out, '--spec-root', spec],
|
||||
{
|
||||
encoding: 'utf8',
|
||||
},
|
||||
);
|
||||
assert.equal(validate.status, 0, validate.stdout);
|
||||
});
|
||||
|
||||
test('audit: отпечаток не зависит от изменчивого локального состояния .pi/.artifacts (C3/BHL-043)', (t) => {
|
||||
const { dir, spec } = makeFixtureSpec(t);
|
||||
const project = path.join(dir, 'project');
|
||||
writeProject(project, GOOD_PROJECT);
|
||||
const first = auditRun(spec, project, path.join(dir, 'r1.json'), ['--spec-version', '0.1.0']);
|
||||
assert.equal(first.status, 0, first.stdout);
|
||||
writeProject(project, {
|
||||
'.pi/transcript.jsonl': '{"turn":1}\n',
|
||||
'.artifacts/tmp.bin': 'volatile',
|
||||
});
|
||||
const second = auditRun(spec, project, path.join(dir, 'r2.json'), ['--spec-version', '0.1.0']);
|
||||
assert.equal(second.status, 0, second.stdout);
|
||||
assert.equal(
|
||||
readFileSync(path.join(dir, 'r2.json'), 'utf8'),
|
||||
readFileSync(path.join(dir, 'r1.json'), 'utf8'),
|
||||
);
|
||||
});
|
||||
|
||||
test('audit: req-single-quality-command проверяется детерминированно (C4/BHL-043)', (t) => {
|
||||
const { dir, spec } = makeFixtureSpec(t);
|
||||
const realReq = path.join(
|
||||
import.meta.dirname,
|
||||
'..',
|
||||
'..',
|
||||
'..',
|
||||
'spec',
|
||||
'requirements',
|
||||
'req-single-quality-command.yaml',
|
||||
);
|
||||
cpSync(realReq, path.join(spec, 'requirements', 'req-single-quality-command.yaml'));
|
||||
writeProject(spec, {
|
||||
'profiles/prof-real.yaml':
|
||||
'id: prof-real\ntitle: Реальное требование\ndescription: Профиль фикстуры с реальным требованием единой команды качества.\nrequirements:\n - requirement: req-single-quality-command\n',
|
||||
});
|
||||
const project = path.join(dir, 'project');
|
||||
writeProject(project, GOOD_PROJECT);
|
||||
const out = path.join(dir, 'r.json');
|
||||
const run = auditRun(spec, project, out, ['--spec-version', '0.1.0', '--profile', 'prof-real']);
|
||||
assert.equal(run.status, 0, run.stdout);
|
||||
const report = JSON.parse(readFileSync(out, 'utf8'));
|
||||
const finding = report.findings.find((f) => f.requirement === 'req-single-quality-command');
|
||||
assert.equal(finding.method, 'deterministic');
|
||||
assert.equal(finding.status, 'PASS');
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user