Files
clean-architecture-frontend…/tests/scale/global-local-independence.test.ts
T
DongHyeonka b26517e6f2 fix(docs): 설계 주석에 문서 이름을 붙이고 지운 뒤 끊기는 링크를 없앤다 (1101/14-01)
문제: 코드 주석 87곳(74파일, .dependency-cruiser.json 포함)이 "Spec §N"
처럼 문서 이름 없이 절 번호만 적는다(대문자 83, 소문자 "spec §" 4).
가리키는 설계서는 README가 복사 뒤 지워도 된다고 한 docs/reviews/ 안에
있었다. 지울 수 있는 기록 검사는 경로 문자열만 찾아 이 참조를 잡지
못했다. 현재 계약 문서도 지울 수 있는 파일로 링크한다:
docs/reviews/adapters/INVENTORY.md 145행이 옆의 adapter 리뷰로,
docs/operations/adapter-remediation-ledger.md가 adapter 리뷰와
docs/superpowers/plans의 계획으로.

고른 방법:
- 주석의 "Spec §"/"spec §"를 "scale-architecture.md §"로 바꾼다(앞
  커밋이 옮긴 docs/architecture/scale-architecture.md). 설명 문장과 절
  번호는 그대로다. 절 번호가 없는 "Spec §"는 없었다.
- tests/unit/deletable-history-documents.test.ts에 "spec" + 선택 공백 +
  "§"(대소문자 무시)를 거부하는 검사를 더하고, 검사 대상에
  .dependency-cruiser.json을 넣는다.
- README "Files you can delete after copying"에서 INVENTORY.md 한 파일
  대신 docs/reviews/adapters/ 폴더를 남기게 하고 이유(INVENTORY 행과
  ledger가 그 리뷰로 링크한다)를 적는다. docs/README.md §3도 같게 고친다.
  INVENTORY의 행 구조는 바꾸지 않는다.
- 남긴 adapter 리뷰와 ledger가 docs/superpowers/plans로 거는 링크 5곳은
  링크를 풀고 "작업 이력 계획, 복사본은 지울 수 있다"로 적는다.
버린 대안: INVENTORY 145칸의 링크를 그룹 이름으로 바꾸기. 템플릿에서도
상세 리뷰로 가는 길이 없어지고 수정이 145곳이다. 계획 3개도 지우기
목록에서 빼기. 지울 수 있는 폴더 안에 예외가 흩어지고, 계획이 다시
다른 이력을 가리키면 남길 목록이 계속 커진다.

위험·한계: 검사는 "HTML spec §4"처럼 다른 명세를 "spec §"로 부르는
주석도 거부한다. 그때는 "HTML Standard §4"처럼 이름을 쓴다.
src/contracts/storage-keys.ts:79의 "release-coherence plan Task 6"처럼
이름 없는 계획 참조는 이 검사가 잡지 않는다. 복사한 프로젝트가 이미
docs/reviews/adapters/를 지웠다면 링크는 계속 끊겨 있다. CHANGELOG.md의
이력 언급 4곳(:15 두 경로, :75 PRODUCT.md, :93)은 고치지 않았다.
check:remediation-ledger는 이 변경 전후 같은 4줄로 실패한다(이미 있던
실패, 게이트 밖). tests/unit/telemetry.test.ts의 describe 이름 하나가
바뀐다.

검증:
- RED: 치환 전 새 검사가 87줄을 들어 실패(1 failed | 1 passed).
- GREEN: 같은 테스트 2 passed. 변이 "// Spec §4. budgets live here"를
  src/platform/errors/app-error.ts에 넣으면 그 한 줄로 실패, 되돌림.
- 치환 diff: 바뀐 87줄 쌍이 토큰 외에 같음(스크립트 대조, 불일치 0).
- 삭제 실험(작업 트리 복사본에서 README 목록대로 지움): 끊긴 링크
  148→0, 끊긴 경로 언급 10→4(남은 4는 CHANGELOG.md), 이름 없는 설계
  참조 87→0, scale-architecture.md §N 87곳 중 없는 절 0. 같은 복사본에서
  verify-documentation-readiness PASS_SCOPED, 지울 수 있는 기록 테스트
  2 passed.
- node scripts/verify-documentation-readiness.ts: PASS_SCOPED
- node scripts/check-adapter-inventory.ts: PASS
- node scripts/run-vitest.ts run tests/unit/deletable-history-documents.test.ts
  tests/unit/documentation-readiness.test.ts tests/unit/telemetry.test.ts:
  50 passed. tests/architecture: 39 passed.
- npx tsc --noEmit (app·node·test): 모두 통과. 바꾼 TS 74파일 eslint 통과.
  .dependency-cruiser.json JSON 파싱 통과.
- 미실행: check:architecture(pnpm 필요).
2026-11-03 07:17:49 +09:00

173 lines
7.8 KiB
TypeScript

import { spawnSync } from "node:child_process";
import { createHash } from "node:crypto";
import { mkdtemp, readFile, rm } from "node:fs/promises";
import { tmpdir } from "node:os";
import path from "node:path";
import { afterAll, describe, expect, it } from "vitest";
import {
generateAppIndexes,
selectAppIndexes,
} from "../../scripts/generate-product-feature-index.ts";
import {
APP_A,
reachableSourceGraph,
writeFilesystemTopology,
writeSyntheticApps,
} from "./filesystem-topology.ts";
import { APP_CONTEXT_BUDGET, CONTEXT_FEATURE_BUDGET, SCALE_PROFILES } from "./scale-profile.ts";
import {
createSyntheticTopology,
declarationSource,
selectAppInputs,
} from "./synthetic-topology.ts";
/**
* scale-architecture.md §37. The central 1M architectural proof, on the production path.
*
* - S0-S2: real on-disk repositories, generated by the production command
* (`scripts/generate-product-feature-index.ts --app=`), whose discovery reads
* app/context/feature ownership declarations.
* - S3/S4: the same production selection (`selectAppIndexes`) over a
* declaration source that models 100k/1M logical features without writing
* them; an equivalence test pins that source to the filesystem one.
*/
const GENERATOR = path.resolve("scripts/generate-product-feature-index.ts");
const OUTPUTS = [
"src/.generated/product-feature-index.ts",
"src/.generated/product-context-index.ts",
"src/.generated/product-app.ts",
] as const;
const roots: string[] = [];
afterAll(async () => {
await Promise.all(roots.map((root) => rm(root, { recursive: true, force: true })));
});
async function productionBuildInputs(globalFeatures: number) {
const root = await mkdtemp(path.join(tmpdir(), `topology-${globalFeatures}-`));
roots.push(root);
const written = await writeFilesystemTopology(root, { globalFeatures });
const run = spawnSync(process.execPath, [GENERATOR, `--root=${root}`, `--app=${APP_A.id}`], {
encoding: "utf8",
});
if (run.status !== 0) throw new Error(`generator failed: ${run.stderr}`);
const generated = await Promise.all(
OUTPUTS.map((file) => readFile(path.join(root, file), "utf8")),
);
const graph = await reachableSourceGraph(root, OUTPUTS);
return { written, generated, graph };
}
describe("global-to-local independence on the production generator path", () => {
it(
"keeps App A's generated indexes and reachable source graph identical from S0 to S2 on disk",
async () => {
const s0 = await productionBuildInputs(SCALE_PROFILES.S0);
const s1 = await productionBuildInputs(SCALE_PROFILES.S1);
const s2 = await productionBuildInputs(SCALE_PROFILES.S2);
expect(s2.written.features).toBe(SCALE_PROFILES.S2);
expect(s2.written.apps).toBeGreaterThan(s0.written.apps);
expect(s1.generated).toEqual(s0.generated);
expect(s2.generated).toEqual(s0.generated);
expect(s2.graph).toEqual(s0.graph);
const hash = (texts: readonly string[]) =>
texts.map((text) => createHash("sha256").update(text).digest("hex"));
expect(hash(s2.generated)).toEqual(hash(s0.generated));
const localFeatures = APP_A.contexts * APP_A.featuresPerContext;
// Generated indexes + (feature-module, context-routes, page) per local feature.
expect(s2.graph).toHaveLength(OUTPUTS.length + localFeatures * 3);
expect(s2.graph.some((file) => file.includes("other-"))).toBe(false);
expect(s2.generated[1]?.match(/defineBoundedContextModule\(\{/gu)).toHaveLength(APP_A.contexts);
},
120_000,
);
it("selects another app from the same repository without App A's features", async () => {
const root = await mkdtemp(path.join(tmpdir(), "topology-select-"));
roots.push(root);
await writeFilesystemTopology(root, { globalFeatures: 1_100 });
const other = await generateAppIndexes(root, "other-0");
expect(other.app.id).toBe("other-0");
expect(other.entries.every((entry) => entry.contextId.startsWith("other-0-"))).toBe(true);
await expect(generateAppIndexes(root, undefined)).rejects.toThrow(/Select a deployable app/);
await expect(generateAppIndexes(root, "missing")).rejects.toThrow(/Unknown deployable app/);
});
it("produces the same output from the filesystem source and the S3/S4 declaration source", async () => {
const topology = createSyntheticTopology({ globalFeatures: SCALE_PROFILES.S0 * 3 });
const root = await mkdtemp(path.join(tmpdir(), "topology-equivalence-"));
roots.push(root);
await writeSyntheticApps(
root,
["app-0", "app-1", "app-2"].map((id) => ({
id,
maxContexts: APP_CONTEXT_BUDGET,
contexts: topology.app(id).contexts.map((context) => ({
...context,
maxFeatures: CONTEXT_FEATURE_BUDGET,
})),
})),
);
const fromDisk = await generateAppIndexes(root, "app-0");
const fromModel = selectAppIndexes(declarationSource(topology), "app-0");
expect(fromModel.featureIndex).toBe(fromDisk.featureIndex);
expect(fromModel.contextIndex).toBe(fromDisk.contextIndex);
expect(fromModel.appIndex).toBe(fromDisk.appIndex);
});
it("keeps one unchanged app's production indexes identical from S0 to S4", () => {
const s0 = selectAppInputs(createSyntheticTopology({ globalFeatures: SCALE_PROFILES.S0 }), "app-0");
for (const globalFeatures of Object.values(SCALE_PROFILES)) {
const current = selectAppInputs(createSyntheticTopology({ globalFeatures }), "app-0");
expect(current.contextIds).toEqual(s0.contextIds);
expect(current.featureIds).toEqual(s0.featureIds);
expect(current.routeRootIds).toEqual(s0.routeRootIds);
expect(current.generatedFeatureIndex).toBe(s0.generatedFeatureIndex);
expect(current.generatedContextIndex).toBe(s0.generatedContextIndex);
expect(current.generatedAppIndex).toBe(s0.generatedAppIndex);
expect(current.generatedHashes).toEqual(s0.generatedHashes);
expect(current.compileInputPaths).toEqual(s0.compileInputPaths);
}
// The compile input is App A's own modules only: one feature module and
// one lazy route module per local feature, plus the context descriptor.
const featureOwned = s0.compileInputPaths.filter((file) => /^src\/features\/[^/]+\//u.test(file));
expect(featureOwned).toHaveLength(s0.featureIds.length * 2);
expect(featureOwned.every((file) => file.startsWith("src/features/app0-"))).toBe(true);
});
it("reads only the selected app's declarations, even at 1,000,000 logical features", () => {
const inputs = selectAppInputs(
createSyntheticTopology({ globalFeatures: SCALE_PROFILES.S4 }),
"app-0",
);
expect(inputs.reads.apps).toBe(1);
expect(inputs.reads.contexts).toBe(inputs.contextIds.length);
expect(inputs.reads.features).toBe(inputs.featureIds.length);
expect(inputs.featureIds.length).toBeLessThan(SCALE_PROFILES.S0 + 1);
});
it("boots only direct context roots, never the global feature table", () => {
const inputs = selectAppInputs(
createSyntheticTopology({ globalFeatures: SCALE_PROFILES.S4 }),
"app-0",
);
expect(inputs.routeRootIds.length).toBe(inputs.contextIds.length);
expect(inputs.routeRootIds.length).toBeLessThanOrEqual(inputs.contextBudget);
// Feature executables sit behind the lazy context loader, not in boot imports.
expect(inputs.generatedContextIndex).toContain("async loadRoutes()");
expect(inputs.generatedContextIndex).toMatch(/import\("\.\.\/features\//u);
});
it("keeps an app deep in the S4 topology within the same local shape", () => {
const topology = createSyntheticTopology({ globalFeatures: SCALE_PROFILES.S4 });
const first = selectAppInputs(topology, "app-0");
const last = selectAppInputs(topology, `app-${topology.appCount - 1}`);
expect(last.featureIds.length).toBe(first.featureIds.length);
expect(last.contextIds.length).toBe(first.contextIds.length);
});
});