Files
clean-architecture-frontend…/tests/unit/registry-governance.test.ts
T
DongHyeonka 84d6e526a3 fix(registries): 계약 조립 실패의 reason을 적고 읽지 못한 레지스트리를 지운 것으로 세지 않는다
문제
기능 계약 조립이 실패하면(예: 없는 authProfileId) check:registries 출력은
"missing registry source src/features/loaded-feature-runtimes.ts: Installed
contract contribution is not composable" 두 줄, "FE-REG-API is not an
object registry", "FE-REG-ROUTE references unknown registry FE-REG-SCHEMA",
"breaking change missing evidence: FE-REG-API:*:*:removed" 등이다. 원인은
ContractContributionError.reason에 있는데 검사기는 message 첫 줄만 적는다.
끝의 removed 줄은 "breaking 증거를 더하라"로 읽혀 틀린 다음 행동을
제안한다(실험 E-9).

고른 방법
- source를 읽다 난 오류에 문자열 reason이 있으면 "(reason: ...)"로 함께
  적는다.
- 읽지 못한 레지스트리는 따로 모은다. 그 레지스트리에 대해서는 행 검사
  ("is not an object registry"), 그것을 가리키는 참조 검사, 기준선 비교
  (removed 증거 요구)를 하지 않는다. 같은 실패를 다른 이름으로 다시 적지
  않기 위해서다. 게이트는 load 실패 한 줄로 그대로 실패한다.
- errors.md 레지스트리 표에 이 메시지 행을 더했다.

버린 대안
- 메시지 접두어를 "failed to load"로 바꾸기: 의미는 더 맞지만 기존 테스트와
  CI 진단 기대값이 "missing registry source"를 쓴다. 이번에는 바꾸지 않았다.

위험·한계
- source 파일을 실수로 지운 경우에도 removed 증거 요구를 건너뛴다. 그래도
  "missing registry source" 실패로 게이트는 막힌다. 레지스트리를 의도해서
  지우면 governance에서도 빠지므로 removed 증거 요구는 그대로다.
- FE-REG-API와 FE-REG-SCHEMA가 같은 source라 load 실패 줄은 두 번 나온다.

검증
- RED: registry-governance에 임시 디렉터리 fixture(두 레지스트리, 하나가
  다른 하나를 참조, 기준선 있음)를 더했다. source가 reason 있는 오류를
  던지면 출력이 load 실패 한 줄이어야 한다. 고치기 전에는 reason이 없고
  cascade 3줄이 더 나와 실패했다.
- GREEN: registry-governance 11건 통과. E-9 재실행(참조 기능 목록
  operation의 authProfileId를 NOTICE_NOPE로): 출력이 "... (reason:
  reference-feature/LIST_REFERENCE_RESOURCES: unknown authProfileId
  NOTICE_NOPE)" 두 줄뿐이고 removed 줄이 없다.
- check:registries:fixture·check:routes:fixture·baseline-fixture가 기대
  진단으로 실패한다. eslint, check:types:node, check:types:test 통과.

Refs: docs/reviews/2026-11-03-maturity-review/14-template-product-docs.md 14-06
2026-11-04 20:38:14 +09:00

652 lines
22 KiB
TypeScript

import { spawnSync } from "node:child_process";
import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import path from "node:path";
import { describe, expect, it } from "vitest";
import {
diffRegistrySnapshots,
registrySnapshotDigest,
validateBreakingEvidence,
verifyRegistryBaselineApproval,
} from "../../scripts/lib/registry-compatibility.ts";
type RegistryDefinition = Readonly<{
registryId: string;
owner: string;
requiredFields: string[];
fieldTypes: Record<string, string>;
path: string;
exportName: string;
rowsPath?: string;
rowKeyFields?: string[];
uniqueFields?: string[];
uniqueFieldSets?: string[][];
snapshotProjection?: {
singletonRowKey: string;
canonicalArrayKeyFields: Record<string, string[]>;
};
consumers?: Array<{ path: string; token: string }>;
breakingFields?: string[];
}>;
describe("registry governance manifest", () => {
it("declares eleven typed, single-owner executable registries", async () => {
const governance = JSON.parse(
await readFile("config/contracts/registry-governance.json", "utf8"),
);
const registries = governance.registries as RegistryDefinition[];
expect(governance.registries).toHaveLength(11);
expect(new Set(registries.map((entry) => entry.registryId)).size).toBe(
11,
);
expect(registries.every((entry) => entry.owner)).toBe(true);
expect(
registries.every(
(entry) =>
Array.isArray(entry.requiredFields) &&
entry.requiredFields.length > 0 &&
entry.fieldTypes &&
Object.keys(entry.fieldTypes).length > 0,
),
).toBe(true);
});
it("governs the installed invalidation graph and wire versions at their real exports", async () => {
const governance = JSON.parse(
await readFile("config/contracts/registry-governance.json", "utf8"),
) as { registries: RegistryDefinition[] };
const byId = new Map(
governance.registries.map((registry) => [registry.registryId, registry]),
);
expect(byId.get("FE-REG-QUERY-INVALIDATION")).toMatchObject({
path: "src/features/installed-feature-contracts.ts",
exportName: "INVALIDATION_REGISTRY",
rowsPath: "edges",
rowKeyFields: [
"topicId",
"namespace.namespaceId",
"namespace.namespaceVersion",
],
uniqueFieldSets: [
[
"topicId",
"namespace.namespaceId",
"namespace.namespaceVersion",
],
],
snapshotProjection: {
singletonRowKey: "invalidation-graph",
canonicalArrayKeyFields: {
topics: ["$value"],
namespaces: ["namespaceId", "namespaceVersion"],
edges: [
"topicId",
"namespace.namespaceId",
"namespace.namespaceVersion",
],
},
},
consumers: [
{
path: "src/bootstrap/runtime-adapters.ts",
token: "indexInvalidationRegistry(INVALIDATION_REGISTRY)",
},
],
breakingFields: ["topics", "namespaces", "edges"],
});
expect(byId.get("FE-REG-QUERY-INVALIDATION-TOPIC-VERSION")).toMatchObject({
path: "src/features/installed-feature-contracts.ts",
exportName: "INVALIDATION_TOPIC_VERSIONS",
rowKeyFields: ["topicId"],
uniqueFields: ["topicId"],
consumers: [
{
path: "src/bootstrap/runtime-adapters.ts",
token: "indexInvalidationTopicVersions(",
},
],
breakingFields: ["topicId", "topicVersion"],
});
});
it("projects graph and array exports into deterministic governed rows", async () => {
const directory = await mkdtemp(
path.join(tmpdir(), "registry-governance-projection-"),
);
const artifact = path.join(directory, "registries.json");
try {
const result = spawnSync(
process.execPath,
[
"scripts/check-registries.ts",
"--governance",
"tests/fixtures/registry/invalidation/governance.json",
"--artifact",
artifact,
"--no-baseline",
],
{ encoding: "utf8" },
);
expect(result.status, result.stderr).toBe(0);
const report = JSON.parse(await readFile(artifact, "utf8")) as {
registries: Array<{
registryId: string;
rows: Record<string, Record<string, unknown>>;
}>;
};
expect(
report.registries.find(
(registry) => registry.registryId === "FIXTURE-INVALIDATION-EDGES",
)?.rows,
).toEqual({
"invalidation-graph": {
topics: ["orders", "qinv.fixture.changed"],
namespaces: [
{ namespaceId: "orders", namespaceVersion: 1 },
{ namespaceId: "qinv.fixture.changed", namespaceVersion: 1 },
],
edges: [
{
topicId: "orders",
namespace: {
namespaceId: "qinv.fixture.changed",
namespaceVersion: 1,
},
},
{
topicId: "qinv.fixture.changed",
namespace: { namespaceId: "orders", namespaceVersion: 1 },
},
],
},
});
expect(
report.registries.find(
(registry) => registry.registryId === "FIXTURE-INVALIDATION-VERSIONS",
)?.rows,
).toHaveProperty('["qinv.fixture.changed"]');
} finally {
await rm(directory, { recursive: true, force: true });
}
});
it("requires explicit evidence for post-baseline graph and version drift", async () => {
const directory = await mkdtemp(
path.join(tmpdir(), "registry-governance-tamper-"),
);
const artifact = path.join(directory, "registries.json");
try {
const result = spawnSync(
process.execPath,
[
"scripts/check-registries.ts",
"--governance",
"tests/fixtures/registry/invalidation/governance.json",
"--artifact",
artifact,
"--no-baseline",
],
{ encoding: "utf8" },
);
expect(result.status, result.stderr).toBe(0);
const report = JSON.parse(await readFile(artifact, "utf8")) as {
registries: Array<{
registryId: string;
contract: Record<string, unknown>;
rows: Record<string, Record<string, unknown>>;
}>;
};
const baseline = { schemaVersion: 2, registries: report.registries };
expect(
baseline.registries.find(
(registry) => registry.registryId === "FIXTURE-INVALIDATION-EDGES",
)?.rows["invalidation-graph"],
).toBeDefined();
const tamperCases = [
{
name: "topic",
registryId: "FIXTURE-INVALIDATION-EDGES",
field: "topics",
apply(snapshot: typeof baseline) {
const graph = snapshot.registries.find(
(registry) => registry.registryId === this.registryId,
)?.rows["invalidation-graph"];
(graph?.topics as string[])[0] = "tampered-topic";
},
},
{
name: "namespace",
registryId: "FIXTURE-INVALIDATION-EDGES",
field: "namespaces",
apply(snapshot: typeof baseline) {
const graph = snapshot.registries.find(
(registry) => registry.registryId === this.registryId,
)?.rows["invalidation-graph"];
const namespaces = graph?.namespaces as Array<{
namespaceId: string;
}>;
namespaces[0]!.namespaceId = "tampered-namespace";
},
},
{
name: "edge",
registryId: "FIXTURE-INVALIDATION-EDGES",
field: "edges",
apply(snapshot: typeof baseline) {
const graph = snapshot.registries.find(
(registry) => registry.registryId === this.registryId,
)?.rows["invalidation-graph"];
const edges = graph?.edges as Array<{ topicId: string }>;
edges[0]!.topicId = "tampered-edge";
},
},
{
name: "version",
registryId: "FIXTURE-INVALIDATION-VERSIONS",
field: "topicVersion",
apply(snapshot: typeof baseline) {
const versions = snapshot.registries.find(
(registry) => registry.registryId === this.registryId,
)?.rows;
const firstVersion = versions?.[Object.keys(versions)[0] ?? ""];
if (!firstVersion) throw new Error("version fixture row missing");
firstVersion.topicVersion = 2;
},
},
];
for (const tamperCase of tamperCases) {
const current = structuredClone(baseline);
tamperCase.apply(current);
const diff = diffRegistrySnapshots(baseline, current);
expect(diff.impact, tamperCase.name).toBe("breaking");
expect(
diff.changes.some((change) => change.kind === "registry-added"),
tamperCase.name,
).toBe(false);
const breakingChanges = diff.changes.filter(
(change) => change.impact === "breaking",
);
expect(breakingChanges, tamperCase.name).toEqual(
expect.arrayContaining([
expect.objectContaining({
registryId: tamperCase.registryId,
field: tamperCase.field,
}),
]),
);
expect(
validateBreakingEvidence(diff, { changes: [] }).passed,
tamperCase.name,
).toBe(false);
expect(
validateBreakingEvidence(diff, {
changes: breakingChanges.map((change) => ({
changeId: change.changeId,
after: change.after,
versionBump: "2",
migration: `migrate ${tamperCase.name}`,
compatibilityWindow: "one release",
rollback: `restore ${tamperCase.name} baseline`,
owner: "fixture-owner",
})),
}).passed,
tamperCase.name,
).toBe(true);
}
} finally {
await rm(directory, { recursive: true, force: true });
}
});
it("pins the full invalidation graph and versions in the approved repository baseline", async () => {
const baseline = JSON.parse(
await readFile("config/contracts/registry-baseline.json", "utf8"),
) as {
schemaVersion: number;
registries: Array<{
registryId: string;
rows: Record<string, Record<string, unknown>>;
}>;
};
const approval = JSON.parse(
await readFile(
"config/contracts/registry-baseline.approval.json",
"utf8",
),
) as Record<string, unknown>;
expect(verifyRegistryBaselineApproval(baseline, approval).passed).toBe(true);
expect(baseline.registries).toHaveLength(11);
const graph = baseline.registries.find(
(registry) => registry.registryId === "FE-REG-QUERY-INVALIDATION",
);
const versions = baseline.registries.find(
(registry) =>
registry.registryId ===
"FE-REG-QUERY-INVALIDATION-TOPIC-VERSION",
);
expect(graph?.rows["invalidation-graph"]).toMatchObject({
topics: expect.any(Array),
namespaces: expect.any(Array),
edges: expect.any(Array),
});
expect(versions?.rows).toBeDefined();
// Who approved and why, not this template's wording: a project that
// re-baselines with update:registry-baseline writes its own (D-13).
expect(approval).toMatchObject({
owner: expect.stringMatching(/\S/u),
reason: expect.stringMatching(/\S/u),
});
});
// The baseline diff compares contracts and rows, not `source`, so a moved
// registry (15-01 moved FE-REG-API and FE-REG-SCHEMA) left the approved
// baseline naming a file that no longer holds it. Re-approve after a move.
it("names each registry's governed source in the approved baseline", async () => {
const governance = JSON.parse(
await readFile("config/contracts/registry-governance.json", "utf8"),
) as { registries: Array<{ registryId: string; path: string }> };
const baseline = JSON.parse(
await readFile("config/contracts/registry-baseline.json", "utf8"),
) as { registries: Array<{ registryId: string; source: string }> };
const sources = new Map(
baseline.registries.map(({ registryId, source }) => [registryId, source]),
);
expect(
governance.registries
.filter(({ registryId, path: source }) => sources.get(registryId) !== source)
.map(({ registryId }) => registryId),
"run update:registry-baseline after moving a registry",
).toEqual([]);
});
// 0929/07-01 (3). Re-approval makes the current snapshot the baseline, so it
// explains every change the evidence described. Git history keeps the rows.
it("deletes the evidence rows the new baseline explains when it re-approves", async () => {
const directory = await mkdtemp(
path.join(tmpdir(), "registry-baseline-update-"),
);
const evidencePath = path.join(
directory,
"config/contracts/registry-change-evidence.json",
);
try {
await mkdir(path.dirname(evidencePath), { recursive: true });
await writeFile(
path.join(directory, "snapshot.json"),
JSON.stringify({ registries: [] }),
);
await writeFile(
evidencePath,
JSON.stringify({
schemaVersion: 1,
changes: [
{
changeId: "FE-REG-TEST:A:*:removed",
versionBump: "2",
migration: "none",
compatibilityWindow: "none",
rollback: "restore A",
owner: "fixture-owner",
},
],
}),
);
const result = spawnSync(
process.execPath,
[path.resolve("scripts/update-registry-baseline.ts"), "snapshot.json"],
{
cwd: directory,
encoding: "utf8",
env: {
...process.env,
REGISTRY_BASELINE_OWNER: "fixture-owner",
REGISTRY_BASELINE_REASON: "fixture re-approval",
},
},
);
expect(result.status, result.stderr).toBe(0);
expect(JSON.parse(await readFile(evidencePath, "utf8"))).toEqual({
schemaVersion: 1,
changes: [],
});
expect(result.stdout).toContain("FE-REG-TEST:A:*:removed");
} finally {
await rm(directory, { recursive: true, force: true });
}
});
it("rejects duplicate composite invalidation edges after projection", async () => {
const directory = await mkdtemp(
path.join(tmpdir(), "registry-governance-duplicate-"),
);
const artifact = path.join(directory, "registries.json");
try {
const result = spawnSync(
process.execPath,
[
"scripts/check-registries.ts",
"--governance",
"tests/fixtures/registry/invalidation/duplicate-governance.json",
"--artifact",
artifact,
"--no-baseline",
],
{ encoding: "utf8" },
);
expect(result.status).toBe(1);
const report = JSON.parse(await readFile(artifact, "utf8")) as {
failures: string[];
};
expect(report.failures).toEqual([
expect.stringContaining(
"duplicates topicId+namespace.namespaceId+namespace.namespaceVersion",
),
]);
} finally {
await rm(directory, { recursive: true, force: true });
}
});
// 0929/07-03. loadingSurface is a name, checked for its form, not a list.
it("rejects a route loading surface that is not a kebab-case name", async () => {
const directory = await mkdtemp(
path.join(tmpdir(), "registry-governance-routes-"),
);
const artifact = path.join(directory, "registries.json");
try {
spawnSync(
process.execPath,
[
"scripts/check-registries.ts",
"--governance",
"tests/fixtures/registry/routes/governance.json",
"--artifact",
artifact,
],
{ encoding: "utf8" },
);
const { failures } = JSON.parse(await readFile(artifact, "utf8")) as {
failures: string[];
};
expect(
failures.filter((failure) => failure.includes(".loadingSurface ")),
).toEqual([
"ROUTES.FIRST.loadingSurface value Unknown loading does not match ^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$",
]);
} finally {
await rm(directory, { recursive: true, force: true });
}
});
it("names the load error of a registry source that exists but fails to import", async () => {
const directory = await mkdtemp(path.join(tmpdir(), "registry-source-error-"));
try {
await mkdir(path.join(directory, "src"), { recursive: true });
await writeFile(
path.join(directory, "src/broken.ts"),
'import { missingExport } from "./absent.ts";\nexport const ROWS = [missingExport];\n',
);
await writeFile(path.join(directory, "src/absent.ts"), "export const other = 1;\n");
await writeFile(
path.join(directory, "governance.json"),
JSON.stringify({
schemaVersion: 1,
sourceDirectories: [],
registries: [
{
registryId: "FIXTURE-BROKEN",
path: "src/broken.ts",
exportName: "ROWS",
owner: "fixture",
requiredFields: ["id"],
uniqueFields: ["id"],
},
],
compatibilityImpact: {
allowed: ["none", "additive", "behavior-change", "breaking"],
current: "none",
},
}),
);
const result = spawnSync(
process.execPath,
[
path.resolve("scripts/check-registries.ts"),
"--governance",
"governance.json",
"--no-baseline",
"--artifact",
"out.json",
],
{ cwd: directory, encoding: "utf8" },
);
expect(result.status).toBe(1);
expect(`${result.stdout}${result.stderr}`).toContain(
"missing registry source src/broken.ts: The requested module './absent.ts' does not provide an export named 'missingExport'",
);
} finally {
await rm(directory, { recursive: true, force: true });
}
});
// 1103/14-06. A contract contribution that fails to compose throws while
// the registry source loads. The gate names the cause the error carries in
// `reason` and does not also report the unloaded registries as deleted
// (`removed` evidence) or as unknown reference targets.
it("names a load error's reason and reports no cascade for the registries it did not load", async () => {
const directory = await mkdtemp(path.join(tmpdir(), "registry-source-reason-"));
const run = (extra: readonly string[]) =>
spawnSync(
process.execPath,
[
path.resolve("scripts/check-registries.ts"),
"--governance",
"governance.json",
"--artifact",
"out.json",
...extra,
],
{ cwd: directory, encoding: "utf8" },
);
try {
await mkdir(path.join(directory, "src"), { recursive: true });
await writeFile(
path.join(directory, "src/composed.ts"),
'export const ROWS = { A: { id: "A" } };\n',
);
await writeFile(
path.join(directory, "src/routes.ts"),
'export const ROUTES = { R: { id: "R", target: "A" } };\n',
);
await writeFile(
path.join(directory, "governance.json"),
JSON.stringify({
schemaVersion: 1,
sourceDirectories: [],
registries: [
{
registryId: "FIXTURE-COMPOSED",
path: "src/composed.ts",
exportName: "ROWS",
owner: "fixture",
keyField: "id",
requiredFields: ["id"],
fieldTypes: { id: "string" },
},
{
registryId: "FIXTURE-ROUTES",
path: "src/routes.ts",
exportName: "ROUTES",
owner: "fixture",
keyField: "id",
requiredFields: ["id", "target"],
fieldTypes: { id: "string", target: "string" },
references: [
{
field: "target",
registryId: "FIXTURE-COMPOSED",
targetField: "id",
},
],
},
],
}),
);
const healthy = run(["--no-baseline"]);
expect(healthy.status, healthy.stderr).toBe(0);
const report = JSON.parse(
await readFile(path.join(directory, "out.json"), "utf8"),
) as { registries: unknown[] };
const baseline = { schemaVersion: 2, registries: report.registries };
await writeFile(path.join(directory, "baseline.json"), JSON.stringify(baseline));
await writeFile(
path.join(directory, "approval.json"),
JSON.stringify({
schemaVersion: 1,
snapshotDigest: registrySnapshotDigest(baseline),
owner: "fixture",
reason: "fixture",
approvedAt: "2026-11-04T00:00:00.000Z",
}),
);
await writeFile(
path.join(directory, "evidence.json"),
JSON.stringify({ schemaVersion: 1, changes: [] }),
);
const withBaseline = [
"--baseline",
"baseline.json",
"--approval",
"approval.json",
"--compatibility-evidence",
"evidence.json",
];
expect(run(withBaseline).status).toBe(0);
await writeFile(
path.join(directory, "src/composed.ts"),
'throw Object.assign(new Error("Installed contract contribution is not composable"), { reason: "notice-feature/NOTICE_LIST_ITEMS: unknown authProfileId NOTICE_NOPE" });\n',
);
const broken = run(withBaseline);
const output = `${broken.stdout}${broken.stderr}`;
expect(broken.status).toBe(1);
expect(output.trim().split("\n")).toEqual([
"Registry governance failed:",
"missing registry source src/composed.ts: Installed contract contribution is not composable (reason: notice-feature/NOTICE_LIST_ITEMS: unknown authProfileId NOTICE_NOPE)",
]);
} finally {
await rm(directory, { recursive: true, force: true });
}
});
});