feat: 주제 화면을 계약에 잇고, 등록을 잊는 사고를 가드로 막는다

주제 화면은 주제 셋(`jpa`, `authentication`, `redis`)을 코드에 적어 두고 그 셋만
열었다. 제목과 설명까지 코드에 있었고, 목록에 없는 주제는 기록이 멀쩡히 있어도 404 로
갔다 — 픽스처의 `kubernetes` 가 그랬다. 계약에는 처음부터 `/topics/{slug}` 가 있었지만
아무도 부르지 않았다. 이제 그 연산을 부르고, 주제가 답하는 질문(논지)과 그 질문에 대해
실제로 만들어 본 답들(축)을 화면의 뼈대로 둔다.

프로젝트의 논지도 마찬가지다. 담을 칸이 없어 목적(`purpose`)을 대신 보여 주고
있었는데, 목적은 시작할 때 쓰는 글이라 화면에는 늘 시작할 때의 말만 남았다.

축 CRUD 네 연산은 계약에 있으면서 기여 목록에 없었다 — 등록되지 않은 연산은 타입에는
멀쩡히 보이는데 부를 수가 없다. `getPublicConcept` 과 `deleteConceptDraft` 가 정확히
그래서 못 불렸고, 개념 삭제가 질문 삭제를 불러 "질문을 찾을 수 없습니다" 가 떴다.
그래서 가드를 둘 넣는다. 공개 계약은 전수 대조하고(봉투 없이 바이트를 주는 `/media` 만
면제), 관리 계약은 **한 종류만 빠진 자리**를 본다 — 깨진 것이 늘 그 모양이었다.
개념 삭제 등록을 지워 보고 실제로 멈추는 것을 확인했다.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011nAjrqNHGPNngN4aUbcyvJ
This commit is contained in:
DongHyeonka
2026-09-01 16:57:24 +09:00
co-authored by Claude Opus 5
parent 618a228eff
commit 15e6ea8f15
18 changed files with 512 additions and 80 deletions
@@ -0,0 +1,80 @@
import assert from "node:assert/strict";
import { readFileSync } from "node:fs";
import { test } from "vitest";
import { TECH_LOG_MANAGEMENT_CONTRIBUTION } from "../../../src/features/tech-log/contracts/tech-log-management-contract-contribution.ts";
import { TECH_LOG_PUBLIC_CONTRIBUTION } from "../../../src/features/tech-log/contracts/tech-log-public-contract-contribution.ts";
/**
* 계약에 있는 연산은 전부 기여 목록에 등록되어 있어야 한다.
*
* <p>등록하지 않은 연산은 타입에는 멀쩡히 보이는데 부를 수가 없다. 그래서 화면은 그 연산이
* 없는 줄 모르고 옆 연산을 부르거나(개념 삭제가 질문 삭제를 불러 "질문을 찾을 수 없습니다"
* 가 떴다), 아무것도 못 부른 채로 조용히 빈 화면이 됐다(`getPublicConcept`). 손으로 나열한
* 목록에 새 종류를 빠뜨리는 일이 이 저장소에서만 다섯 번 넘게 났고, 매번 다섯 개의 검사를
* 다 통과했다.
*
* <p>그래서 목록을 손으로 관리하지 않고 계약 문서에서 읽어 대조한다. 새 연산을 계약에 더하고
* 등록을 잊으면 여기서 멈춘다.
*/
function contractOperationIds(path: string): string[] {
const text = readFileSync(path, "utf8");
return [...text.matchAll(/^\s+operationId:\s*(\S+)\s*$/gmu)].map((match) => match[1]!);
}
/**
* 봉투를 쓰지 않고 바이트를 그대로 돌려주는 연산. `<img src>` 가 직접 가리키므로 HTTP 기여
* 목록을 지나지 않는다 — 등록을 잊은 것이 아니라 지날 이유가 없다.
*/
const NOT_A_JSON_OPERATION = new Set(["getPublicMedia"]);
test("공개 계약의 모든 연산이 기여 목록에 등록되어 있다", () => {
const declared = contractOperationIds(
"src/features/tech-log/contracts/public/public-api.openapi.yaml",
);
assert.ok(declared.length > 0, "계약에서 연산을 하나도 읽지 못했다 — 정규식이 낡았다");
const registered = new Set(
TECH_LOG_PUBLIC_CONTRIBUTION.http.map((entry) => entry.contract.operationId),
);
const missing = declared.filter(
(operationId) => !registered.has(operationId) && !NOT_A_JSON_OPERATION.has(operationId),
);
assert.deepEqual(missing, [], `등록되지 않은 연산: ${missing.join(", ")}`);
});
/**
* 관리 계약은 다르다. Studio 는 종류마다 갈린 옛 연산 대신 작업본 하나(`/studio/documents/…`)로
* 문서를 다루므로, 계약에 있으나 화면이 부르지 않는 연산이 정상적으로 많다. 그래서 전수 대조는
* 뜻이 없고, 대신 **한 종류만 빠진 자리**를 본다 — 실제로 깨진 것이 늘 그 모양이었다.
*
* <p>주소에서 종류를 지우면 같은 일을 하는 연산들이 한 가족으로 모인다. 가족 하나가 세 종류만
* 갖고 있으면 나머지 한 종류의 화면은 조용히 옆 종류의 API 를 부르거나 아무것도 못 부른다.
*/
const KIND_SEGMENTS = ["cases", "references", "questions", "concepts"] as const;
test("문서 종류별 관리 연산에 빠진 종류가 없다", () => {
const families = new Map<string, Set<string>>();
for (const entry of TECH_LOG_MANAGEMENT_CONTRIBUTION.http) {
const { method, pathTemplate } = entry.contract;
for (const kind of KIND_SEGMENTS) {
if (!pathTemplate.includes(`/${kind}`)) continue;
const family = `${method} ${pathTemplate.replace(`/${kind}`, "/{kind}")}`;
const kinds = families.get(family) ?? new Set<string>();
kinds.add(kind);
families.set(family, kinds);
}
}
assert.ok(families.size > 0, "종류별 연산을 하나도 찾지 못했다 — 주소 규칙이 바뀌었다");
const holes: string[] = [];
for (const [family, kinds] of families) {
// 한 종류만 있는 가족은 그 종류에만 있는 일이다(예: 질문의 해결). 구멍은 여럿 중 빠진 것이다.
if (kinds.size === 1) continue;
const missing = KIND_SEGMENTS.filter((kind) => !kinds.has(kind));
if (missing.length > 0) holes.push(`${family} ← ${missing.join(", ")} 없음`);
}
assert.deepEqual(holes, [], `종류가 빠진 연산 가족:\n${holes.join("\n")}`);
});
@@ -337,17 +337,31 @@ describe("TechLog canonical Public documents", () => {
describe("TechLog topics and Public not-found routing", () => {
it.each([
["jpa", "JPA", "목록 조회, 연관 로딩과 페이지 경계를 함께 검증한 기록입니다.", "3개의 관련 기록"],
["authentication", "Authentication", "브라우저와 Edge, Resource Server 사이의 인증 책임과 신뢰 경계를 검증한 기록입니다.", "2개의 관련 기록"],
["redis", "Redis", "애플리케이션 정책과 Redis 저장 명령의 책임 경계를 검증한 기록입니다.", "1개의 관련 기록"],
])("aggregates /topics/%s with exact copy and count", async (slug, title, description, count) => {
["jpa", "JPA", "3개의 관련 기록"],
["authentication", "Authentication", "2개의 관련 기록"],
["redis", "Redis", "1개의 관련 기록"],
])("aggregates /topics/%s with its own name and count", async (slug, title, count) => {
await renderDocumentRoute("TECH_LOG_TOPIC", `/topics/${slug}`);
expect(screen.getByRole("heading", { level: 1, name: title })).toBeVisible();
expect(screen.getByText(description)).toBeVisible();
expect(screen.getByText(count)).toBeVisible();
});
/*
이 화면은 주제 셋을 코드에 적어 두고 그 셋만 열었다. 제목과 설명까지 코드에 있었고, 목록에
없는 주제는 기록이 멀쩡히 있어도 404 로 갔다 — 픽스처의 `kubernetes` 가 바로 그랬다.
계약에는 처음부터 `/topics/{slug}` 가 있었지만 아무도 부르지 않았다.
*/
it("opens a topic that was never in the hard-coded list", async () => {
await renderDocumentRoute("TECH_LOG_TOPIC", "/topics/kubernetes");
expect(screen.getByRole("heading", { level: 1, name: "Kubernetes" })).toBeVisible();
expect(screen.getByText("1개의 관련 기록")).toBeVisible();
expect(
screen.queryByRole("heading", { name: "페이지를 찾을 수 없습니다." }),
).not.toBeInTheDocument();
});
it("keeps JPA topic records in canonical published order", async () => {
const { container } = await renderDocumentRoute("TECH_LOG_TOPIC", "/topics/jpa");
@@ -91,19 +91,19 @@ test("a published Open Question maps its four point groups into the screen's fie
});
/*
관계의 이유 자리에 영문 키가 그대로 나오고 있었다 — 매퍼가 찾던 그룹 이름이 계약에 없는
묶음 이름 자리에 영문 키가 그대로 나오고 있었다 — 매퍼가 찾던 그룹 이름이 계약에 없는
것들이었기 때문이다. 그리고 `primaryProject` 는 관계가 아니라 이 질문이 속한 프로젝트다.
*/
test("a question's relations read their reason from the contract's own group names", async () => {
test("a question's relations read their label from the contract's own group names", async () => {
const gateway = gatewayReturning(DETAIL);
const record = await gateway.getRecord("QUESTION", "refresh-rotation-replica-contention");
assert.deepEqual(
[...record!.relations].map((relation) => ({ reason: relation.reason, path: relation.path })),
[...record!.relations].map((relation) => ({ label: relation.label, path: relation.path })),
[
{
reason: "이 질문에서 나온 기록",
label: "이 질문에서 나온 기록",
path: "/cases/split-custody-access-token",
},
],