Files
clean-architecture-frontend…/scripts/check-registries.ts
T
donghyeon.kang 79dc945a67 refactor(layout): 루트 경로 목록을 등록부 하나에서 고르고 schemas/를 옮긴다
루트 항목 하나를 옮기려면 코드 7곳의 루트 경로 목록을 같이 고쳐야
했다(복사 대상, 비밀값 검사 범위, 공급망 시험의 필수 입력, 이력 문서
검사, 규모 입력, vite 입력, TS 전용 규칙). 서로 다른 부분집합이고 한
곳에서 선언하지 않았다. 목록이 갈라져 공급망 생성이 깨진 적도 있다
(removal-fixture.ts 주석). 루트에는 JSON Schema 5개만 담은 `schemas/`가
`config/` 옆에 따로 있었다. `artifacts/`(출력 폴더)에는 사람이 쓴 수동
a11y 기록이, `config/hosting/`(호스트 계약)에는 시험 fixture가 섞였다.

고른 방법(design-docs repo-structure/04-frontend-layout.md 9.2절 3단계,
11절 R1·R2, 소유자 승인 2026-11-07):
- `config/repository-layout.json`이 루트 항목마다 종류·역할·읽는 곳과
  들어가는 목록(`sets`, 항목 안 경로는 `setPaths`)을 적는다.
  `scripts/lib/repository-layout.ts`가 읽고 검증한다. 6곳은 이름 붙은
  집합을 고른다. JSON인 비밀값 검사 정책은 집합의 사본을 두고 시험이
  같은지 본다(정책 파일은 릴리스 후보에 실려 형식을 바꾸지 않았다).
  공급망 시험의 필수 입력 목록은 그 시험으로 대신한다.
- `tests/unit/repository-layout.test.ts`: 등록부에 없는 루트 항목이
  추적되면 실패(R1). 7곳이 등록부 모듈을 쓰고 루트 이름 둘 이상의
  문자열 배열을 갖지 않는지(R2).
- `schemas/artifacts/` → `config/schemas/artifacts/`, recipe 카탈로그
  스키마 → `config/schemas/recipes/`. 정책 입력 순서(ASCII)에 맞춰
  `config/schemas/`가 `config/security/` 앞에 온다.
- 수동 a11y 기록 3개 → `docs/accessibility/route-reviews/`. `artifacts/`는
  `.gitkeep`만 추적한다. 기록은 단위 시험이 읽어서 drill 사본에도
  복사한다(`fixture-copy` 집합의 `docs/accessibility/route-reviews`).
- `config/hosting/response-headers.fixture.json` →
  `tests/fixtures/hosting/response-headers.json`.

버린 것: 비밀값 검사 정책이 집합 이름을 참조하게 바꾸는 방법. 정책
파일은 릴리스 후보와 로컬 증거 평가가 읽는 형식이라 바꾸면 릴리스
증거 계약이 바뀐다. 루트 항목이 지워졌는데 등록부에 남는 경우는
시험하지 않았다. drill 사본은 일부만 복사해 그 방향을 볼 수 없다.
그런 항목은 그 집합을 쓰는 곳(복사, 비밀값 검사)에서 실패한다.

위험: 하네스 작업(fe-c)이 더할 `AGENTS.md`·`.claude/`를 미리 등록했다
(optional). 등록부가 이력 문서(`SPEC.md`)와 `CLAUDE.md` 이름을 적어서
이력 문서 검사에서 등록부 파일은 뺐다. 다운스트림은 자기 루트 항목을
등록부에 더해야 한다(CHANGELOG). CI 계약 기준선을 다시 받았다(a11y
기록 산출물 id·경로).

검증(desktop): 아래 4단계 커밋까지 쌓은 트리에서 test:unit,
check:types, check:ci, lint, verify:documentation을 돌렸다(그 커밋에
적음). 이 커밋 단독으로 test:unit·check:ci·check:types를 돌렸다.

Refs: design-docs repo-structure/04-frontend-layout.md 2.4·9.2·11절, README.md 3.4절
2026-11-08 17:41:07 +09:00

778 lines
25 KiB
TypeScript

import {
access,
mkdir,
readFile,
readdir,
} from "node:fs/promises";
import path from "node:path";
import { pathToFileURL } from "node:url";
import {
canonicalizeRegistryValue,
diffRegistrySnapshots,
matchesDeclaredType,
registryRuntimeType,
registrySnapshotDigest,
validateBreakingEvidence,
verifyRegistryBaselineApproval,
} from "./lib/registry-compatibility.ts";
import { assertMatchesJsonSchema } from "./lib/json-schema.ts";
import {
registryGovernanceRunArtifactSchema,
registrySnapshotArtifactSchema,
} from "./contracts/release-artifacts.ts";
import { writeValidatedJsonArtifact } from "./lib/validated-json-artifact.ts";
type RegistryRow = Record<string, unknown>;
type RegistryRows = Record<string, RegistryRow>;
type RegistryReference = Readonly<{
registryId: string;
field: string;
targetField: string;
}>;
type RegistryConsumer = Readonly<{ path: string; token: string }>;
type RegistrySnapshotProjection = Readonly<{
singletonRowKey: string;
canonicalArrayKeyFields: Readonly<Record<string, readonly string[]>>;
}>;
type RegistrySpecification = Readonly<{
registryId: string;
owner: string;
path: string;
exportName: string;
declaredRows?: unknown;
rowsPath?: string;
rowKeyFields?: readonly string[];
requiredFields: readonly string[];
fieldTypes?: Readonly<Record<string, string>>;
keyField?: string;
uniqueFields?: readonly string[];
uniqueFieldSets?: readonly (readonly string[])[];
snapshotProjection?: RegistrySnapshotProjection;
allowedValues?: Readonly<Record<string, readonly unknown[]>>;
/** Field name to an anchored regular expression its string value matches. */
fieldPatterns?: Readonly<Record<string, string>>;
references?: readonly RegistryReference[];
breakingFields?: readonly string[];
consumers?: readonly RegistryConsumer[];
consumerIdentityField?: string;
consumerDirectories?: readonly string[];
orphanExemptRows?: readonly string[];
}>;
type RegistryGovernance = Readonly<{
registries: readonly RegistrySpecification[];
sourceDirectories?: readonly string[];
}>;
type RegistrySnapshot = Record<string, unknown>;
type CompatibilitySummary = Readonly<{
impact: string;
changes: readonly unknown[];
}>;
function argumentValue(
name: string,
fallback: string | undefined,
): string | undefined {
const index = process.argv.indexOf(name);
return index >= 0 && process.argv[index + 1]
? process.argv[index + 1]
: fallback;
}
const defaultGovernancePath = "config/contracts/registry-governance.json";
const governancePath =
argumentValue("--governance", defaultGovernancePath) ??
defaultGovernancePath;
const artifactPath =
argumentValue("--artifact", "artifacts/quality/registries.json") ??
"artifacts/quality/registries.json";
const usesRepositoryGovernance = governancePath === defaultGovernancePath;
const usesRepositoryBaseline =
usesRepositoryGovernance &&
!process.argv.includes("--no-baseline");
const baselinePath = argumentValue(
"--baseline",
usesRepositoryBaseline
? "config/contracts/registry-baseline.json"
: undefined,
);
const approvalPath = argumentValue(
"--approval",
usesRepositoryBaseline
? "config/contracts/registry-baseline.approval.json"
: undefined,
);
const evidencePath = argumentValue(
"--compatibility-evidence",
usesRepositoryBaseline
? "config/contracts/registry-change-evidence.json"
: undefined,
);
const governance = JSON.parse(
await readFile(governancePath, "utf8"),
) as RegistryGovernance;
const failures: string[] = [];
const owners = new Map<string, string>();
const snapshots: RegistrySnapshot[] = [];
const rowsByRegistry = new Map<string, RegistryRows>();
const sourcesByRegistry = new Map<string, string>();
/**
* 1103/14-06. Registries whose source did not load. Their failure is already
* reported with its cause, so the checks that read their rows (references,
* the baseline comparison) skip them instead of reporting the same failure
* again as a deleted registry.
*/
const unloadedRegistries = new Set<string>();
const registryExtensions = [".ts", ".tsx", ".mts", ".cts"];
async function resolveRegistrySource(
declaredPath: string,
): Promise<string | null> {
const extension = path.extname(declaredPath);
const basePath = extension
? declaredPath.slice(0, -extension.length)
: declaredPath;
const candidates: string[] = [];
for (const candidateExtension of registryExtensions) {
const candidate = `${basePath}${candidateExtension}`;
try {
await access(candidate);
candidates.push(candidate);
} catch {
// Continue through the supported TypeScript source extensions.
}
}
if (candidates.length > 1) {
failures.push(
`ambiguous registry source ${declaredPath}: ${candidates.join(", ")}`,
);
return null;
}
return candidates[0] ?? null;
}
/**
* 1103/14-06. A load error's cause may be only in its `reason` property, so
* it is printed after the message. 1105/09-03. `ContractContributionError`
* already ends its message with the reason (1103/09-07); that cause is
* printed once.
*/
function loadErrorText(error: Error): string {
const message = error.message.split("\n")[0] ?? "";
const reason: unknown = (error as Error & { reason?: unknown }).reason;
return typeof reason === "string" &&
reason.length > 0 &&
!message.includes(reason)
? `${message} (reason: ${reason})`
: message;
}
function withoutRegistries(
snapshot: Readonly<Record<string, unknown>>,
registryIds: ReadonlySet<string>,
): Readonly<Record<string, unknown>> {
if (registryIds.size === 0 || !Array.isArray(snapshot.registries)) {
return snapshot;
}
return {
...snapshot,
registries: (snapshot.registries as Array<{ registryId?: unknown }>).filter(
(registry) => !registryIds.has(String(registry.registryId)),
),
};
}
type FieldLookup = Readonly<{
found: boolean;
value: unknown;
}>;
function lookupField(value: unknown, fieldPath: string): FieldLookup {
let current = value;
for (const segment of fieldPath.split(".")) {
if (
!current ||
typeof current !== "object" ||
Array.isArray(current) ||
!Object.hasOwn(current, segment)
) {
return Object.freeze({ found: false, value: undefined });
}
current = (current as Record<string, unknown>)[segment];
}
return Object.freeze({ found: true, value: current });
}
function projectRegistryRows(
specification: RegistrySpecification,
exportedValue: unknown,
): RegistryRows | null {
const selected = specification.rowsPath
? lookupField(exportedValue, specification.rowsPath)
: Object.freeze({ found: true, value: exportedValue });
if (!selected.found) {
failures.push(
`${specification.registryId} is missing rows path ${specification.rowsPath}`,
);
return null;
}
if (!Array.isArray(selected.value)) {
if (
!selected.value ||
typeof selected.value !== "object"
) {
failures.push(`${specification.registryId} is not an object registry`);
return null;
}
return selected.value as RegistryRows;
}
const projected: RegistryRows = {};
const keyOccurrences = new Map<string, number>();
for (const [index, row] of selected.value.entries()) {
if (!row || typeof row !== "object" || Array.isArray(row)) {
projected[String(index)] = row as RegistryRow;
continue;
}
const keyValues = (specification.rowKeyFields ?? []).map(
(field) => lookupField(row, field).value,
);
const baseKey =
keyValues.length > 0
? JSON.stringify(keyValues.map(canonicalizeRegistryValue))
: String(index);
const occurrence = keyOccurrences.get(baseKey) ?? 0;
keyOccurrences.set(baseKey, occurrence + 1);
projected[occurrence === 0 ? baseKey : `${baseKey}#${occurrence + 1}`] =
row as RegistryRow;
}
return projected;
}
function snapshotKeyField(
value: unknown,
fieldPath: string,
): FieldLookup {
return fieldPath === "$value"
? Object.freeze({ found: true, value })
: lookupField(value, fieldPath);
}
function replaceProjectedField(
row: RegistryRow,
fieldPath: string,
value: unknown,
): boolean {
const segments = fieldPath.split(".");
const finalSegment = segments.pop();
if (!finalSegment) return false;
let current = row;
for (const segment of segments) {
const next = current[segment];
if (!next || typeof next !== "object" || Array.isArray(next)) {
return false;
}
current = next as RegistryRow;
}
current[finalSegment] = value;
return true;
}
function projectSnapshotRows(
specification: RegistrySpecification,
exportedValue: unknown,
validatedRows: RegistryRows,
): RegistryRows | null {
const projection = specification.snapshotProjection;
if (!projection) return validatedRows;
if (
!exportedValue ||
typeof exportedValue !== "object" ||
Array.isArray(exportedValue)
) {
failures.push(
`${specification.registryId} snapshot projection requires an object export`,
);
return null;
}
const canonicalRow = canonicalizeRegistryValue(exportedValue) as RegistryRow;
for (const [fieldPath, keyFields] of Object.entries(
projection.canonicalArrayKeyFields,
)) {
const selected = lookupField(exportedValue, fieldPath);
if (!selected.found || !Array.isArray(selected.value)) {
failures.push(
`${specification.registryId} snapshot field ${fieldPath} must be an array`,
);
return null;
}
const keyedItems: Array<{ identity: string; value: unknown }> = [];
const identities = new Set<string>();
for (const [index, item] of selected.value.entries()) {
const keyValues = keyFields.map((field) => snapshotKeyField(item, field));
const missingIndex = keyValues.findIndex((field) => !field.found);
if (missingIndex >= 0) {
failures.push(
`${specification.registryId} snapshot field ${fieldPath}[${index}] is missing key ${keyFields[missingIndex]}`,
);
return null;
}
const identity = JSON.stringify(
keyValues.map((field) => canonicalizeRegistryValue(field.value)),
);
if (identities.has(identity)) {
failures.push(
`${specification.registryId} snapshot field ${fieldPath} duplicates key ${identity}`,
);
return null;
}
identities.add(identity);
keyedItems.push({
identity,
value: canonicalizeRegistryValue(item),
});
}
keyedItems.sort((left, right) =>
left.identity.localeCompare(right.identity),
);
if (
!replaceProjectedField(
canonicalRow,
fieldPath,
keyedItems.map((item) => item.value),
)
) {
failures.push(
`${specification.registryId} snapshot field ${fieldPath} cannot be projected`,
);
return null;
}
}
return Object.freeze({
[projection.singletonRowKey]: canonicalRow,
});
}
/**
* 09-07. `src/features/*\/adapters` names that directory in every feature, so
* adding a feature does not mean adding it to this governance file.
*/
async function expandDirectoryPattern(pattern: string): Promise<string[]> {
const star = pattern.split("/").indexOf("*");
if (star === -1) return [pattern];
const segments = pattern.split("/");
const parent = segments.slice(0, star).join("/");
const rest = segments.slice(star + 1).join("/");
const entries = await readdir(parent, { withFileTypes: true }).catch(() => []);
const expanded = await Promise.all(
entries
.filter((entry) => entry.isDirectory())
.map((entry) =>
expandDirectoryPattern(path.join(parent, entry.name, rest)),
),
);
return expanded.flat();
}
async function filesBelow(directory: string): Promise<string[]> {
try {
const entries = await readdir(directory, { withFileTypes: true });
const groups = await Promise.all(
entries.map((entry) => {
const target = path.join(directory, entry.name);
return entry.isDirectory() ? filesBelow(target) : [target];
}),
);
return groups.flat().filter((file) =>
/\.(?:ts|tsx|mts|cts)$/.test(file),
);
} catch {
return [];
}
}
for (const specification of governance.registries) {
if (owners.has(specification.registryId)) {
failures.push(`duplicate owner for ${specification.registryId}`);
}
owners.set(specification.registryId, specification.owner);
let rows = specification.declaredRows;
const sourcePath = await resolveRegistrySource(specification.path);
try {
if (!sourcePath) throw new Error("missing registry source");
const registryModule = (await import(
`${pathToFileURL(path.resolve(sourcePath)).href}?registry-check=${Date.now()}`
)) as Record<string, unknown>;
rows = registryModule[specification.exportName];
} catch (error) {
// A source that exists but fails to load names its error, so a broken
// import in a feature contract is not reported as a missing file.
const reason = sourcePath && error instanceof Error ? `: ${loadErrorText(error)}` : "";
if (!rows) {
failures.push(`missing registry source ${specification.path}${reason}`);
unloadedRegistries.add(specification.registryId);
continue;
}
}
const registryRows = projectRegistryRows(specification, rows);
if (!registryRows) {
continue;
}
rowsByRegistry.set(specification.registryId, registryRows);
sourcesByRegistry.set(
specification.registryId,
sourcePath ?? specification.path,
);
for (const [rowName, row] of Object.entries(registryRows)) {
if (!row || typeof row !== "object" || Array.isArray(row)) {
failures.push(`${specification.registryId}.${rowName} is not an object`);
continue;
}
for (const field of specification.requiredFields) {
if (!lookupField(row, field).found) {
failures.push(`${specification.registryId}.${rowName} missing ${field}`);
}
}
for (const [field, declaredType] of Object.entries(
specification.fieldTypes ?? {},
)) {
if (
lookupField(row, field).found &&
!matchesDeclaredType(
lookupField(row, field).value,
String(declaredType),
)
) {
failures.push(
`${specification.registryId}.${rowName}.${field} expected ${declaredType}, received ${registryRuntimeType(lookupField(row, field).value)}`,
);
}
}
if (
specification.keyField &&
lookupField(row, specification.keyField).value !== rowName
) {
failures.push(
`${specification.registryId}.${rowName}.${specification.keyField} must match its registry key`,
);
}
}
for (const field of specification.uniqueFields ?? []) {
const values = new Map<string, string>();
for (const [rowName, row] of Object.entries(registryRows)) {
if (!row || typeof row !== "object" || Array.isArray(row)) continue;
const selected = lookupField(row, field);
if (!selected.found) continue;
const value = selected.value;
const identity = JSON.stringify(canonicalizeRegistryValue(value));
if (values.has(identity)) {
failures.push(
`${specification.registryId}.${rowName} duplicates ${field}=${String(value)} from ${values.get(identity)}`,
);
} else {
values.set(identity, rowName);
}
}
}
for (const fields of specification.uniqueFieldSets ?? []) {
const values = new Map<string, string>();
for (const [rowName, row] of Object.entries(registryRows)) {
if (!row || typeof row !== "object" || Array.isArray(row)) continue;
const selected = fields.map((field) => lookupField(row, field));
if (selected.some((field) => !field.found)) continue;
const identity = JSON.stringify(
selected.map((field) => canonicalizeRegistryValue(field.value)),
);
const previous = values.get(identity);
if (previous) {
failures.push(
`${specification.registryId}.${rowName} duplicates ${fields.join("+")}=${identity} from ${previous}`,
);
} else {
values.set(identity, rowName);
}
}
}
for (const [field, allowed] of Object.entries(
specification.allowedValues ?? {},
)) {
for (const [rowName, row] of Object.entries(registryRows)) {
if (!row || typeof row !== "object" || Array.isArray(row)) continue;
if (
!allowed.some((value) =>
Object.is(value, lookupField(row, field).value),
)
) {
failures.push(
`${specification.registryId}.${rowName}.${field} has unknown value ${String(lookupField(row, field).value)}`,
);
}
}
}
// 0929/07-03. A name no code branches on is checked for its form, not
// listed, so a feature adds its own value without editing governance.
for (const [field, pattern] of Object.entries(
specification.fieldPatterns ?? {},
)) {
const expression = new RegExp(pattern, "u");
for (const [rowName, row] of Object.entries(registryRows)) {
if (!row || typeof row !== "object" || Array.isArray(row)) continue;
const value = lookupField(row, field).value;
if (typeof value !== "string" || !expression.test(value)) {
failures.push(
`${specification.registryId}.${rowName}.${field} value ${String(value)} does not match ${pattern}`,
);
}
}
}
const contract = Object.freeze({
requiredFields: specification.requiredFields,
fieldTypes: specification.fieldTypes ?? {},
uniqueFields: specification.uniqueFields ?? [],
allowedValues: specification.allowedValues ?? {},
references: specification.references ?? [],
keyField: specification.keyField ?? null,
breakingFields: specification.breakingFields ?? [],
...(specification.fieldPatterns
? { fieldPatterns: specification.fieldPatterns }
: {}),
...(specification.rowsPath
? { rowsPath: specification.rowsPath }
: {}),
...(specification.rowKeyFields
? { rowKeyFields: specification.rowKeyFields }
: {}),
...(specification.uniqueFieldSets
? { uniqueFieldSets: specification.uniqueFieldSets }
: {}),
...(specification.snapshotProjection
? { snapshotProjection: specification.snapshotProjection }
: {}),
});
const snapshotRows = projectSnapshotRows(specification, rows, registryRows);
if (!snapshotRows) continue;
snapshots.push({
registryId: specification.registryId,
owner: specification.owner,
source: sourcePath ?? specification.path,
rowCount: Object.keys(snapshotRows).length,
contract,
rows: canonicalizeRegistryValue(snapshotRows),
});
}
for (const specification of governance.registries) {
const rows = rowsByRegistry.get(specification.registryId);
if (!rows) continue;
for (const reference of specification.references ?? []) {
const targetRows = rowsByRegistry.get(reference.registryId);
if (!targetRows) {
if (unloadedRegistries.has(reference.registryId)) continue;
failures.push(
`${specification.registryId} references unknown registry ${reference.registryId}`,
);
continue;
}
const targetValues = new Set(
Object.values(targetRows)
.filter((row) => row && typeof row === "object" && !Array.isArray(row))
.map((row) => lookupField(row, reference.targetField).value)
.filter((value) => value !== undefined && value !== null),
);
for (const [rowName, row] of Object.entries(rows)) {
if (!row || typeof row !== "object" || Array.isArray(row)) continue;
const value = lookupField(row, reference.field).value;
if (
value !== undefined &&
value !== null &&
!targetValues.has(value)
) {
failures.push(
`${specification.registryId}.${rowName}.${reference.field} references unknown ${reference.registryId}.${reference.targetField}=${String(value)}`,
);
}
}
}
for (const consumer of specification.consumers ?? []) {
try {
const source = await readFile(consumer.path, "utf8");
if (!source.includes(consumer.token)) {
failures.push(
`${specification.registryId} consumer ${consumer.path} is missing ${consumer.token}`,
);
}
} catch {
failures.push(
`${specification.registryId} consumer source is missing: ${consumer.path}`,
);
}
}
if (specification.consumerIdentityField) {
const consumerFiles = (
await Promise.all(
(await Promise.all(
(specification.consumerDirectories ?? []).map(expandDirectoryPattern),
))
.flat()
.map(filesBelow),
)
).flat();
const sourcePath = sourcesByRegistry.get(specification.registryId);
const consumerText = (
await Promise.all(
consumerFiles
.filter((file) => file !== sourcePath)
.map((file) => readFile(file, "utf8")),
)
).join("\n");
const exemptions = new Set(specification.orphanExemptRows ?? []);
for (const [rowName, row] of Object.entries(rows)) {
if (
!row ||
typeof row !== "object" ||
Array.isArray(row) ||
exemptions.has(rowName)
) {
continue;
}
const identity = lookupField(
row,
specification.consumerIdentityField,
).value;
if (
(typeof identity !== "string" &&
typeof identity !== "number") ||
!consumerText.includes(String(identity))
) {
failures.push(
`${specification.registryId}.${rowName} has no executable consumer for ${specification.consumerIdentityField}=${String(identity)}`,
);
}
}
}
}
const sourceFiles = governance.sourceDirectories ?? [
"src/application",
"src/presentation",
"src/domain",
];
const adHocPatterns = [
{ name: "direct fetch", expression: /\bfetch\s*\(/ },
{
name: "direct localStorage",
expression: /\blocalStorage\.(?:get|set|remove)Item/,
},
{ name: "direct import.meta.env", expression: /\bimport\.meta\.env\./ },
{ name: "raw API path", expression: /["']\/api\// },
];
for (const sourceDirectory of sourceFiles) {
for (const file of await filesBelow(sourceDirectory)) {
const content = await readFile(file, "utf8");
for (const pattern of adHocPatterns) {
if (pattern.expression.test(content)) {
failures.push(`ad-hoc ${pattern.name} in ${file}`);
}
}
}
}
const currentSnapshot = canonicalizeRegistryValue({
schemaVersion: 2,
registries: snapshots,
}) as Readonly<Record<string, unknown>>;
let baselineDigest: string | null = null;
const currentDigest = registrySnapshotDigest(currentSnapshot);
let compatibility: CompatibilitySummary = {
impact: "not-evaluated",
changes: [],
};
if (baselinePath && approvalPath && evidencePath) {
try {
const baseline = JSON.parse(
await readFile(baselinePath, "utf8"),
) as Record<string, unknown>;
const approval = JSON.parse(
await readFile(approvalPath, "utf8"),
) as Record<string, unknown>;
const approvalResult = verifyRegistryBaselineApproval(baseline, approval);
baselineDigest = approvalResult.actualDigest;
if (!approvalResult.passed) {
failures.push(
`registry baseline approval digest mismatch: approved=${approvalResult.approvedDigest} actual=${approvalResult.actualDigest}`,
);
}
const registryDiff = diffRegistrySnapshots(
withoutRegistries(baseline, unloadedRegistries),
currentSnapshot,
);
compatibility = registryDiff;
const evidence = JSON.parse(
await readFile(evidencePath, "utf8"),
) as Record<string, unknown>;
const evidenceResult = validateBreakingEvidence(registryDiff, evidence);
failures.push(...evidenceResult.failures);
} catch (error) {
failures.push(
`registry compatibility evidence unavailable: ${
error instanceof Error ? error.name : "unknown"
}`,
);
}
}
const report = {
schemaVersion: 2,
generatedAt: new Date().toISOString(),
baselineDigest,
currentDigest,
compatibility,
failures,
registries: snapshots,
};
if (usesRepositoryBaseline && failures.length === 0) {
try {
assertMatchesJsonSchema(
JSON.parse(
await readFile(
"config/schemas/artifacts/registry-snapshot.schema.json",
"utf8",
),
),
report,
"registry snapshot",
);
} catch {
failures.push("registry snapshot JSON Schema mismatch");
}
}
await mkdir(path.dirname(artifactPath), { recursive: true });
await writeValidatedJsonArtifact({
path: artifactPath,
schema: usesRepositoryGovernance
? registrySnapshotArtifactSchema
: registryGovernanceRunArtifactSchema,
value: report,
});
if (failures.length > 0) {
process.stderr.write(`Registry governance failed:\n${failures.join("\n")}\n`);
process.exit(1);
}
process.stdout.write(
`Registry governance: ${snapshots.length} registries PASS; compatibility=${compatibility.impact}\n`,
);