문제
레지스트리 호환성 분류기(scripts/lib/registry-compatibility.ts)는 값의 JS
타입이 다르면 breakingFields를 보기 전에 field-type-changed(breaking)로
판정한다. null과 문자열은 타입이 달라서, governance가 string|null로
선언하고 breaking 필드에서 뺀 필드(navigationLabel, navigationOrder, API
timeoutMs, 저장 ttl, ENV defaultValue)를 null <-> 값으로 바꾸기만 해도
breaking 증거를 요구한다. contract의 allowedValues에 값을 더하는 것도
어떤 변경이든 breaking이다. 그래서 증거 5필드에 쓸 내용이 없는 변경에
"마이그레이션·롤백"을 지어 쓰게 된다. 템플릿 자신도 VITE_BUILD_ID
defaultValue null -> "local-build"에 "the value itself did not change"라고
적은 breaking 증거를 남겼다.
고른 방법 (리뷰 최소 개선 B)
- 행 필드: 한쪽이 null이고 두 값이 모두 그 필드의 선언 타입
(contract.fieldTypes, 예 string|null)에 맞으면 타입 변경이 아니라
field-changed로 보고 breakingFields로 등급을 정한다. 선언이 없거나
선언 밖 값이면 지금처럼 field-type-changed(breaking)다.
- contract allowedValues: 필드 집합이 같고 필드마다 이전 허용값을 모두
포함하면 allowed-values-extended(additive)다. 값 하나라도 빠지거나,
새 필드를 제한하거나, 제한을 없애면 지금처럼 breaking이다. 나머지
contract 변경도 그대로 breaking이다.
- 선언 타입 판정은 check-registries.ts에 있던 runtimeType·
matchesDeclaredType을 lib로 옮겨 검사기와 분류기가 같은 함수를 쓴다.
- semantic-diff.json fixture에 nullable-field-cleared(behavior-change),
registry-contract-extension(additive)을 더하고 artifact id 목록에도
넣었다.
버린 대안
- 현 상태 + "이런 변경은 재승인하라"는 문서: 재승인이 증거를 대신하는
길을 더 넓힌다(0929/07-04).
- nullable 필드 판단 전체를 breakingFields로 옮기기(리뷰 C): 다른
레지스트리 영향을 다시 봐야 하는 넓은 변경이다.
- 제한 해제(allowedValues에서 필드 키 삭제)를 additive로 보기: 리뷰
기준("이전 값을 모두 포함")에 맞지 않고 판단이 하나 더 필요해 보수적으로
breaking에 남겼다.
위험·한계
- fail-closed 범위가 줄어든다. 선언 타입 안의 null 전환이 의미("기능
꺼짐")를 갖는 필드는 breakingFields에 넣어야 breaking으로 남는다.
paramsSchema·searchSchema는 이미 breakingFields라 그대로 breaking이다.
- 현재 기준선 diff에서 VITE_BUILD_ID defaultValue가 breaking에서
behavior-change로 바뀐다. registry-change-evidence.json의 해당 증거 행
(field-type-changed)은 이제 어떤 변경과도 맞지 않는다. 오래된 증거 정리는
0929/07-01 범위라 이번에는 지우지 않았다.
- 다운스트림의 같은 종류 증거 행도 쓰이지 않게 된다. 게이트 판정이
바뀌는 변경이라 다음 릴리스 CHANGELOG에 [계약] 행이 필요하다(이번
라운드는 CHANGELOG 미출시 절이 없어 적지 않았다).
- fieldTypes 키가 점 경로(a.b)인 필드는 행의 최상위 필드 이름과 맞지 않아
계속 breaking으로 남는다.
검증
- RED(분류기 수정 전): registry-compatibility.test.ts 새 사례 5건 실패
(null 전환 3건이 breaking/field-type-changed, nullable breaking 필드의
kind, allowlist 확장 breaking). check-registry-compatibility-fixtures:
nullable-field-cleared actual breaking, registry-contract-extension
actual breaking.
- GREEN: registry-compatibility·registry-governance·release-artifacts·
second-api-feature-registries 49/49 통과. compatibility fixtures 11 PASS.
check-registries "11 registries PASS"(남은 breaking은
REFERENCE_RESOURCE_DETAIL.path 하나, 증거 있음).
ci-artifact-contract "semantic validator" 사례 통과.
- 회귀: tsc node/test rc=0, 바꾼 파일 eslint rc=0.
- 미실행: check:architecture(pnpm). tests/system 나머지(provider guardian
exit=126 환경 문제로 이 변경과 무관하게 실패).
Refs: docs/reviews/2026-09-29-maturity-review/07-contracts.md
707 lines
22 KiB
TypeScript
707 lines
22 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[]>>;
|
|
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>();
|
|
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;
|
|
}
|
|
|
|
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 {
|
|
if (!rows) failures.push(`missing registry source ${specification.path}`);
|
|
}
|
|
|
|
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)}`,
|
|
);
|
|
}
|
|
}
|
|
}
|
|
|
|
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.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) {
|
|
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(baseline, 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(
|
|
"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`,
|
|
);
|