문제
FE-REG-ROUTE governance가 paramsSchema·searchSchema·loadingSurface를 참조
기능 값까지 적은 닫힌 목록으로 둔다. 기능이 자기 search 스키마나 자기
로딩 화면 이름을 가진 라우트를 더하면 check:registries가 "has unknown
value"로 실패하고, 템플릿 소유 파일인 registry-governance.json을 고쳐야
한다. 목록은 contract 일부라 고치면 breaking 증거나 재승인도 필요하다.
두 다운스트림 모두 여기서 충돌했다. 스키마 id는 이미 references가
FE-REG-SCHEMA와 대조하므로 목록은 같은 사실의 세 번째 사본이고,
loadingSurface는 data-surface 속성 말고 읽는 코드가 없다. 문서는
"governance file do not change"라고 적지만 그 약속을 고정하는 테스트는
라우트 없는 기능만 넣었다.
고른 방법 (2026-11-03 결정, 리뷰 (B))
- paramsSchema·searchSchema를 FE-REG-ROUTE allowedValues에서 뺐다.
references 검사는 그대로라 등록되지 않은 스키마 id는 계속 실패한다.
- loadingSurface는 목록 대신 이름 형식만 본다. governance에 선언형 키
fieldPatterns(필드 → 고정된 정규식)를 더하고 check-registries가 문자열
값을 대조한다. FE-REG-ROUTE는 kebab-case
^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$를 쓴다. fieldPatterns는 선언한
레지스트리에서만 contract 스냅샷에 들어가므로 다른 레지스트리의
contract는 바뀌지 않고, 정규식을 바꾸면 contract 변경(breaking)으로
잡힌다.
- second-api-feature-registries 테스트의 두 번째 기능에 자기 search 스키마
(SecondItemListQuery)와 전용 loading surface(second-item-list)를 가진
라우트를 넣었다. 저장소 사본에 기능 디렉터리와 context만 더하고
check-registries가 PASS인지 본다. 지시의 two-feature-install-typecheck는
app 타입 검사만 돌려 governance를 보지 않으므로, check-registries를 돌리는
이 테스트를 확장했다.
- 라우트 fixture(check:routes:fixture)의 governance도 같은 모양으로 바꾸고,
형식에 맞지 않는 이름("Unknown loading")이 거절되는 단위 테스트를 더했다.
- starter-experience.md가 이 테스트를 가리키고, 라우트의 스키마·로딩 화면이
governance 수정 없이 들어가는 이유를 적는다.
- 두 contract 변경(allowedValues 축소, fieldPatterns 추가)은 breaking이다.
이 커밋에서는 증거 2건으로 게이트를 통과시키고, 기준선 재승인은 이번
작업 묶음 끝에서 한 번에 한다.
이유: 기능 하나를 추가할 때 템플릿 파일을 고치게 만드는 지점이다. 두
다운스트림 모두에서 충돌했다.
버린 대안
- 문서만 "allowlist를 고치고 증거를 쓴다"로 정정: 기능마다 비용이
반복된다.
- 기능 계약이 자기 allowlist 값을 기여하는 확장 메커니즘: 등록 규약이
하나 더 생긴다.
위험·한계
- loadingSurface 오타는 이제 형식만 맞으면 통과한다. 이 값은 로딩
요소의 data-surface 속성일 뿐이라 동작이 바뀌지 않는다. loadingSurface가
로딩 컴포넌트 선택 같은 실행 의미를 갖게 되면 닫힌 목록을 다시 둔다.
- errorSurface·access는 라우터가 의미로 읽으므로 닫힌 목록을 유지한다.
기능이 새 errorSurface를 쓰려면 지금처럼 governance를 고친다.
- 다운스트림은 다음 동기화에서 자기가 이 목록에 더한 값을 지운다.
CHANGELOG [계약] 행이 필요하다.
검증
- RED(수정 전): 확장한 second-api-feature-registries 테스트가
"FE-REG-ROUTE.SECOND_ITEM_LIST.searchSchema has unknown value
SecondItemListQuery", "...loadingSurface has unknown value
second-item-list"로 실패. 새 형식 테스트는 수정 전 checker로
"expected [] to deeply equal [ Array(1) ]"로 실패.
- GREEN: 두 테스트 통과. 증거 없이 check-registries는 "breaking change
missing evidence" 2건(allowedValues contract-field-changed,
fieldPatterns contract-field-added)으로 실패, 증거를 넣은 뒤
"11 registries PASS".
- 회귀: registry-compatibility·registry-governance·second-api-feature-
registries·release-artifacts·two-feature-install-typecheck 57/57.
compatibility fixtures 11 PASS. check:routes:fixture는 기대대로
"duplicates routeId=DUPLICATE"로 실패. verify-documentation-readiness
PASS_SCOPED. tsc node·test rc=0, 바꾼 파일 eslint rc=0.
- 미실행: check:architecture, test:sample-removal(pnpm 필요).
Refs: docs/reviews/2026-09-29-maturity-review/07-contracts.md
729 lines
23 KiB
TypeScript
729 lines
23 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>();
|
|
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)}`,
|
|
);
|
|
}
|
|
}
|
|
}
|
|
|
|
// 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) {
|
|
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`,
|
|
);
|