Files
clean-architecture-frontend…/scripts/lib/repository-layout.ts
T
DongHyeonka 7ed0af3d29 ci(gates): merge job 셋이 의존성 캐시에서 설치를 시작하고 main만 저장한다
문제: merge job 셋은 runner의 새 컨테이너에서 매번 Node(GitHub
다운로드), corepack의 pnpm, 패키지 404개를 내려받고, pnpm 11은 lockfile
542개 항목의 공급망 정책을 레지스트리에 물어 검증한다. run 169에서 job마다
setup-node 11~18초, 설치 12~29초였고 설치 시간의 대부분은 정책 검증의
메타데이터 요청이었다(10.1~27.9초). FE-GATE-013의 시스템 컨테이너는 같은
설치를 한 번 더 한다. merge 25분 목표에 0.8분 모자랐다.

고친 것(권하는 안으로 정함 2026-11-13, 총괄):
- job 단계 `dependency-cache`를 더한다. setup-node 앞에서 Node toolcache와
  `/tmp/fe-dependency-cache`(corepack, pnpm store, pnpm 메타데이터 캐시)를
  `.nvmrc`·`pnpm-lock.yaml` 해시 키로 복원한다. main run은 actions/cache로
  복원·저장하고, 그 밖의 ref는 actions/cache/restore로 복원만 한다. pin은
  짝 백엔드의 JDK·Gradle·Trivy 캐시와 같다(v4.3.0).
- 생성기가 그 job에 `COREPACK_HOME`·`PNPM_CONFIG_STORE_DIR`·
  `PNPM_CONFIG_CACHE_DIR`를 주어 job의 모든 pnpm 호출이 같은 곳을 본다.
  frozen install 단계는 그대로이고 캐시와 관계없이 돈다.
- PR run은 main이 저장한 항목을 같은 키로 읽기만 한다. 저장할 수 있는
  actions/cache 단계는 `refs/heads/main` 조건 아래에만 있고, 그 밖의 ref가
  타는 actions/cache/restore에는 저장하는 post 단계가 없다(시험으로 고정).
- 계약: merge job 셋만 이 단계를 가진다(release·promotion·provider·main
  job은 거절, 단계 순서 고정에 반영). 그 env를 job이 따로 묶으면 거절한다.
  키 입력은 `config/repository-layout.json`의 새 집합
  `dependency-cache-key`(`.nvmrc`, `pnpm-lock.yaml`)에서 고른다.
- `scripts/run-in-system-container.sh`가 그 env가 있으면 store와 메타데이터
  캐시를 같은 경로로 컨테이너에 넘긴다. 없으면(desktop) 지금과 같다.
- 결정 색인, ci-quality-gates.md, O1 출처 문구를 총괄이 정한 말로 맞춘다.

버린 대안:
- CI 이미지에 의존성 굽기: 레지스트리 쓰기 토큰이 든다.
- 브랜치 run도 저장하기: 캐시 항목은 다음 run이 믿는 입력이다. pnpm은
  같은 lockfile의 공급망 검증 기록이 캐시에 있으면 다시 검증하지 않으므로,
  브랜치가 쓴 항목이 main의 검증을 건너뛰게 할 수 있다.
- `cache-hit`일 때 설치를 건너뛰기: 결과가 캐시 상태에 달린다.
- apt 글꼴 캐시: 캐시가 없을 때 새 패키지 버전이 깔려 시각 결과가 달라질
  수 있다.

위험·한계:
- PR run은 main이 같은 키(또는 restore-keys로 앞 항목)를 저장한 뒤에야
  hit한다. 이 PR 자신의 run은 비어서 시작한다.
- runner 캐시 저장소(5GB)는 짝 백엔드와 같이 쓴다. 항목 하나는 Node·store·
  메타데이터로 압축 전 약 0.7GB다. lockfile이 바뀔 때마다 새 항목이 생긴다.
- Node toolcache 경로(`/opt/hostedtoolcache`)가 job 이미지와 다르면 그
  부분만 효과가 없고 setup-node가 내려받는다.

검증(desktop):
- 설치 실험(같은 lockfile, 새 폴더): 빈 캐시 13.9·17.2초, 캐시 있음 1.6초,
  store 파일 40개·메타데이터 40개를 망가뜨린 캐시 3.6초(27개만 다시 받음).
  다섯 번 모두 node_modules 트리 해시가 같다. pnpm 11은 대문자
  `PNPM_CONFIG_STORE_DIR`·`PNPM_CONFIG_CACHE_DIR`를 읽는다.
- FE-GATE-013 흐름을 캐시 env로 재현: 빈 캐시 설치 13.7초, 캐시 설치
  2.6초, 시스템 컨테이너 안 설치 1.5초(`Recreating node_modules` 없음, 지금은
  31.3초). 그 실행의 FE-GATE-013은 provider 묶음 시험 하나가 손 timeout
  30초에 걸려 실패했다(캐시와 무관, PR #39가 고치는 문제).
- RED: 계약·생성기를 둔 채 gates.json에서 캐시 단계를 빼면 새 시험 6개
  실패. 키 입력을 코드에 직접 적은 첫 판은 repository-layout R2 시험이
  잡았다. GREEN: repository-layout·ci-workflow-generation 456개 통과,
  check:ci·check:types·eslint rc=0, verify:documentation rc=0, 노트북
  `scripts/verify.sh docs` OK.
2026-11-13 08:26:13 +09:00

174 lines
6.7 KiB
TypeScript

import { readFileSync } from "node:fs";
/**
* The repository root registry, config/repository-layout.json (R1 in
* docs/manual/03-outside-feature-folder.md). Every tracked root item has an
* entry, and every list of root paths is a named set chosen from it (R2).
* Seven places used to keep their own literal lists of root paths, each a
* different subset, so moving one root item meant editing all seven
* (design-docs repo-structure/04-frontend-layout.md §2.4); about twenty more
* lists followed on 2026-11-11. An untracked item (node_modules, dist, other
* worktrees) has an entry only when a set names it, such as the items a copy
* of the checkout skips.
*/
export const REPOSITORY_LAYOUT_SETS = Object.freeze([
"fixture-copy",
"fixture-documents",
"secret-scan",
"history-free",
"scale-source",
"vite-build",
"typescript-only",
"checkout-copy-skip",
"provider-fixture-skip",
"supply-chain-fixture-skip",
"fixture-code",
"package-manifest",
"playwright-configs",
"visual-evidence",
"documentation-inputs",
"agent-harness",
"feature-typecheck",
"product-typecheck",
"app-typecheck",
"dependency-cache-key",
] as const);
export type RepositoryLayoutSet = (typeof REPOSITORY_LAYOUT_SETS)[number];
export const REPOSITORY_LAYOUT_KINDS = Object.freeze([
"source",
"tool-convention",
"gate-input",
"document",
"history",
"output",
"untracked",
] as const);
export type RepositoryLayoutKind = (typeof REPOSITORY_LAYOUT_KINDS)[number];
export type RepositoryLayoutEntry = Readonly<{
/** A root item name: one path segment, no slash. */
path: string;
kind: RepositoryLayoutKind;
role: string;
readBy: string;
/** A removal drill or a product copy may not have it; a selection skips it when absent. */
optional: boolean;
/** The sets that select the whole item. */
sets: readonly RepositoryLayoutSet[];
/** The sets that select only these paths inside the item. */
setPaths: Readonly<Partial<Record<RepositoryLayoutSet, readonly string[]>>>;
}>;
export const REPOSITORY_LAYOUT_FILE = "config/repository-layout.json";
export function parseRepositoryLayout(value: unknown): readonly RepositoryLayoutEntry[] {
const document = record(value, "layout");
if (document["schemaVersion"] !== 1) throw new Error("layout: schemaVersion must be 1");
// Each kind and set the code knows is described once in the file, and the file names no other.
for (const [field, known] of [
["kinds", REPOSITORY_LAYOUT_KINDS],
["sets", REPOSITORY_LAYOUT_SETS],
] as const) {
if (!(field in document)) continue;
const described = Object.keys(record(document[field], `layout.${field}`)).sort();
const expected = [...known].sort();
if (described.join() !== expected.join()) {
throw new Error(`layout.${field} must describe exactly ${expected.join(", ")}; it has ${described.join(", ")}`);
}
}
const entries = document["entries"];
if (!Array.isArray(entries) || entries.length === 0) {
throw new Error("layout: entries must be a non-empty array");
}
const seen = new Set<string>();
return Object.freeze(
entries.map((raw, index) => {
const entry = record(raw, `entries[${index}]`);
const at = `entries[${index}]`;
const itemPath = text(entry["path"], `${at}.path`);
if (itemPath.includes("/")) throw new Error(`${at}.path: a root item has no slash: ${itemPath}`);
if (seen.has(itemPath)) throw new Error(`${at}.path: duplicate root item ${itemPath}`);
seen.add(itemPath);
const kind = text(entry["kind"], `${at}.kind`);
if (!(REPOSITORY_LAYOUT_KINDS as readonly string[]).includes(kind)) {
throw new Error(`${at}.kind: unknown kind ${kind}`);
}
if (kind === "untracked" && entry["optional"] !== true) {
throw new Error(`${at}: an untracked item may be absent, so it is optional`);
}
const sets = (entry["sets"] ?? []) as unknown;
if (!Array.isArray(sets)) throw new Error(`${at}.sets must be an array`);
const setPaths = record(entry["setPaths"] ?? {}, `${at}.setPaths`);
for (const set of [...sets, ...Object.keys(setPaths)]) {
if (!(REPOSITORY_LAYOUT_SETS as readonly string[]).includes(set as string)) {
throw new Error(`${at}: unknown set ${String(set)}`);
}
}
for (const [set, paths] of Object.entries(setPaths)) {
if (!Array.isArray(paths) || paths.length === 0) {
throw new Error(`${at}.setPaths.${set} must be a non-empty array`);
}
for (const inner of paths) {
if (typeof inner !== "string" || !inner.startsWith(`${itemPath}/`)) {
throw new Error(`${at}.setPaths.${set}: ${String(inner)} is not inside ${itemPath}`);
}
}
if (sets.includes(set)) throw new Error(`${at}: ${set} selects the whole item and paths in it`);
}
return Object.freeze({
path: itemPath,
kind: kind as RepositoryLayoutKind,
role: text(entry["role"], `${at}.role`),
readBy: text(entry["readBy"], `${at}.readBy`),
optional: entry["optional"] === true,
sets: Object.freeze([...sets] as RepositoryLayoutSet[]),
setPaths: Object.freeze(setPaths as Partial<Record<RepositoryLayoutSet, readonly string[]>>),
});
}),
);
}
export const REPOSITORY_LAYOUT: readonly RepositoryLayoutEntry[] = parseRepositoryLayout(
JSON.parse(readFileSync(new URL(`../../${REPOSITORY_LAYOUT_FILE}`, import.meta.url), "utf8")),
);
/** The paths a set selects, in registry order. */
export function selectRepositoryPaths(
set: RepositoryLayoutSet,
layout: readonly RepositoryLayoutEntry[] = REPOSITORY_LAYOUT,
): readonly string[] {
return Object.freeze(
layout.flatMap((entry) =>
entry.sets.includes(set) ? [entry.path] : [...(entry.setPaths[set] ?? [])],
),
);
}
/** Like selectRepositoryPaths, with whether a drill or a copy may lack each path. */
export function selectRepositoryEntries(
set: RepositoryLayoutSet,
layout: readonly RepositoryLayoutEntry[] = REPOSITORY_LAYOUT,
): readonly Readonly<{ path: string; optional: boolean }>[] {
return Object.freeze(
layout.flatMap((entry) =>
(entry.sets.includes(set) ? [entry.path] : [...(entry.setPaths[set] ?? [])]).map(
(selected) => Object.freeze({ path: selected, optional: entry.optional }),
),
),
);
}
function record(value: unknown, at: string): Record<string, unknown> {
if (typeof value !== "object" || value === null || Array.isArray(value)) {
throw new Error(`${at} must be an object`);
}
return value as Record<string, unknown>;
}
function text(value: unknown, at: string): string {
if (typeof value !== "string" || value.trim() === "") throw new Error(`${at} must be a non-empty string`);
return value;
}