diff --git a/.gitea/workflows/quality-gates.yml b/.gitea/workflows/quality-gates.yml index 4bf9eb16..582f543e 100644 --- a/.gitea/workflows/quality-gates.yml +++ b/.gitea/workflows/quality-gates.yml @@ -41,6 +41,8 @@ jobs: if: ${{ gitea.event_name != 'workflow_dispatch' || (inputs.stage != 'documentation' && inputs.stage != 'main') }} runs-on: ubuntu-latest timeout-minutes: 45 + env: + CI_PR_BASE_REF: "${{ gitea.event_name == 'pull_request' && gitea.base_ref || '' }}" steps: - uses: https://github.com/actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 with: @@ -108,6 +110,8 @@ jobs: # FE-GATE-013 runner requirement: unprivileged user and network namespaces for bwrap (the provider sandbox runs bwrap --unshare-pid --unshare-ipc --unshare-uts --unshare-net); Ubuntu 23.10 and later refuse them while kernel.apparmor_restrict_unprivileged_userns=1 unless /usr/bin/bwrap has an AppArmor profile that allows userns; scripts/check-system-test-prerequisites.ts probes this before test:system runs and scripts/run-and-validate-provider.ts before a provider runs runs-on: ubuntu-latest timeout-minutes: 45 + env: + CI_PR_BASE_REF: "${{ gitea.event_name == 'pull_request' && gitea.base_ref || '' }}" steps: - uses: https://github.com/actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 with: @@ -178,6 +182,7 @@ jobs: options: "--shm-size=2g" env: CI_RUNNER_IMAGE: "mcr.microsoft.com/playwright:v1.62.0-noble@sha256:baed2032d533817f3dbe6425de795788430ba345e819a1201337009ba17c9d07" + CI_PR_BASE_REF: "${{ gitea.event_name == 'pull_request' && gitea.base_ref || '' }}" steps: - uses: https://github.com/actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 with: diff --git a/config/ci/gates.json b/config/ci/gates.json index 594c173d..76cd626f 100644 --- a/config/ci/gates.json +++ b/config/ci/gates.json @@ -2156,7 +2156,12 @@ "FE-GATE-012" ], "browserGateIds": [], - "environment": [], + "environment": [ + { + "name": "CI_PR_BASE_REF", + "value": "${{ gitea.event_name == 'pull_request' && gitea.base_ref || '' }}" + } + ], "steps": [ { "kind": "checkout" @@ -2200,7 +2205,12 @@ "FE-GATE-020" ], "browserGateIds": [], - "environment": [], + "environment": [ + { + "name": "CI_PR_BASE_REF", + "value": "${{ gitea.event_name == 'pull_request' && gitea.base_ref || '' }}" + } + ], "steps": [ { "kind": "checkout" @@ -2243,7 +2253,12 @@ "FE-GATE-008", "FE-GATE-009" ], - "environment": [], + "environment": [ + { + "name": "CI_PR_BASE_REF", + "value": "${{ gitea.event_name == 'pull_request' && gitea.base_ref || '' }}" + } + ], "steps": [ { "kind": "checkout" diff --git a/config/ci/pr-gate-selection.json b/config/ci/pr-gate-selection.json new file mode 100644 index 00000000..eaaade77 --- /dev/null +++ b/config/ci/pr-gate-selection.json @@ -0,0 +1,121 @@ +{ + "$comment": "PR 경로표(design-docs ci/manual.md 4.3절). PR run의 merge 게이트를 바뀐 파일로 고른다. main·release run은 늘 전부 돈다. global 파일이나 어느 줄에도 안 걸리는 파일이 하나라도 바뀌면 전부 돈다. 파일마다 rules를 위에서부터 보고 처음 맞는 줄 하나의 게이트를 always에 더한다. 판정은 scripts/lib/pr-gate-selection.ts, 계약 시험은 tests/unit/pr-gate-selection.test.ts.", + "schemaVersion": 1, + "always": [ + "FE-GATE-001", + "FE-GATE-002", + "FE-GATE-003", + "FE-GATE-010" + ], + "global": [ + ".gitea/**", + ".storybook/**", + "config/**", + "scripts/**", + "package.json", + "pnpm-lock.yaml", + "pnpm-workspace.yaml", + ".env.example", + ".nvmrc", + ".npmrc", + ".gitattributes", + ".gitignore", + ".dependency-cruiser.json", + "renovate.json", + "eslint.config.ts", + "vite.config.ts", + "vite.service-worker.config.ts", + "vitest.config.ts", + "playwright*.config.ts", + "tsconfig*.json" + ], + "rules": [ + { + "id": "accessibility-records", + "paths": [ + "docs/accessibility/**" + ], + "gates": [ + "FE-GATE-005", + "FE-GATE-009", + "FE-GATE-020" + ] + }, + { + "id": "documents", + "paths": [ + "docs/**", + "**/*.md", + ".claude/**" + ], + "gates": [ + "FE-GATE-005" + ] + }, + { + "id": "recipes", + "paths": [ + "recipes/**" + ], + "gates": [ + "FE-GATE-005", + "FE-GATE-007", + "FE-GATE-012" + ] + }, + { + "id": "scaffold", + "paths": [ + "src/features/**", + "src/contexts/**", + "tests/features/**", + "tests/mocks/**", + "tests/fixtures/typecheck/**", + "tests/component/router.test.tsx", + "tests/integration/http-execution-v3-observability.test.ts", + "tests/integration/http-scenario-catalog.test.ts", + "tests/unit/ci-workflow-generation.test.ts", + "tests/unit/external-contract-runtime.test.ts", + "tests/unit/http-execution-v3.test.ts", + "tests/unit/http-scenario-evidence.test.ts", + "tests/unit/removal-fixture.test.ts", + "tests/unit/runtime-adapters.test.ts", + "tests/unit/session-route-access.test.ts", + "tests/unit/__snapshots__/**" + ], + "gates": [ + "FE-GATE-004", + "FE-GATE-005", + "FE-GATE-006", + "FE-GATE-007", + "FE-GATE-008", + "FE-GATE-009", + "FE-GATE-011", + "FE-GATE-012", + "FE-GATE-013", + "FE-GATE-020" + ] + }, + { + "id": "application", + "paths": [ + "src/**", + "tests/**", + "public/**", + "artifacts/**", + "index.html" + ], + "gates": [ + "FE-GATE-004", + "FE-GATE-005", + "FE-GATE-006", + "FE-GATE-007", + "FE-GATE-008", + "FE-GATE-009", + "FE-GATE-011", + "FE-GATE-012", + "FE-GATE-013" + ] + } + ] +} diff --git a/docs/operations/ci-quality-gates.md b/docs/operations/ci-quality-gates.md index ae54a31d..9071ea41 100644 --- a/docs/operations/ci-quality-gates.md +++ b/docs/operations/ci-quality-gates.md @@ -12,6 +12,15 @@ 2 GB로 연다(`--shm-size=2g`). Firefox 시험 프로필을 RAM에 두기 위해서다 (`tests/support/browser/browser-test.ts`). Docker 기본값 64 MB면 프로필이 runner 디스크에 남아 Firefox의 첫 localStorage 접근이 수 초씩 기다렸다. +PR run(`pull_request`)은 merge 게이트를 바뀐 파일로 고른다(소유자 결정 2026-11-13). 경로표는 +`config/ci/pr-gate-selection.json`이다. 파일마다 `rules`를 위에서부터 보고 처음 맞는 줄의 게이트를 +`always`(FE-GATE-001·002·003·010)에 더한다. 문서만 바뀌면 FE-GATE-005까지 돌고, `src/features/`처럼 +scaffold 드릴의 입력이 바뀌면 FE-GATE-020까지 돈다. `global` 파일(`config/`, `scripts/`, `.gitea/`, +도구 설정, lockfile)이나 표에 없는 파일이 하나라도 바뀌면 전부 돈다. 안 도는 게이트는 그 step에서 +`건너뜀: <게이트 ID> — <이유>`를 찍고 성공으로 끝나며, 게이트 로그도 그 한 줄이다. diff는 base +브랜치와의 merge base에서 잰다. checkout이 얕아 첫 게이트가 history를 받는다. diff를 못 읽으면 전부 +돈다. main·release run은 늘 전부 돈다. 판정은 `scripts/lib/pr-gate-selection.ts`, 계약 시험은 +`tests/unit/pr-gate-selection.test.ts`다. merge job 셋만 의존성 캐시를 쓴다(권하는 안으로 정함 2026-11-13, 총괄). setup-node 앞에서 Node toolcache, corepack이 받은 pnpm, pnpm store와 메타데이터 캐시를 `.nvmrc`와 diff --git a/docs/work/reference/decisions.md b/docs/work/reference/decisions.md index b5bab5de..23397268 100644 --- a/docs/work/reference/decisions.md +++ b/docs/work/reference/decisions.md @@ -72,6 +72,7 @@ | round9 R9-D12 CSS·라우트 lazy 합 예산 | 2026-11-12 | 권하는 안으로 정함(2026-11-12, 총괄). 지금 값을 기록만 하고 예산은 두지 않는다. 다시 볼 때: 첫 공개 기능 라우트 lab. 버린 안: 예산 신설 | 같음, 1101/15-03 | | 결정 p 선택 runtime 제거 드릴을 main 단계로 | 2026-11-12 | FE-GATE-020의 선택 runtime 제거 드릴 셋(optional recipe, browser file/storage, realtime)을 새 게이트 FE-GATE-030으로 떼어 main 단계(`main_gate`)에서 돌린다. 기능 드릴(샘플 제거, scaffold)은 merge에 남는다. 이유: runner PR 1회 약 30분 가운데 7분쯤이고, worker를 늘리지 않고 merge 25분 목표에 닿는 길이 이것뿐이었다. 대가: 그 셋의 회귀를 병합 뒤 main run에서 본다. main이 빨강이면 다음 PR이 고친다. 짝 백엔드가 무거운 lane을 nightly로 옮긴 것과 같은 모양이다. 재검토: runner가 늘거나 드릴이 빨라져 merge에 다시 넣어도 25분 안이면 되돌린다 | 권하는 안으로 정함(2026-11-12, 총괄): 백엔드 nightly lane과 같은 모양(design-docs `template-program/README.md` 5절 p, w2-fe-2가 올린 O1) | | 의존성 캐시는 merge job만 | 2026-11-13 | merge job 셋(`merge_static`·`merge_test`·`merge_browser`)만 Node toolcache·corepack·pnpm store와 메타데이터 캐시를 `.nvmrc`·`pnpm-lock.yaml` 해시 키로 복원하고, 저장은 main run만 한다. release·promotion·provider job은 공급망 증거를 만들므로 매번 새로 설치한다. 이유: worker를 늘리지 않고 job마다 되풀이하던 내려받기와 공급망 검증 요청을 없앤다. 캐시가 없거나 깨져도 frozen install이 같은 node_modules를 만든다. 짝 백엔드의 JDK·Gradle·Trivy 캐시와 같은 저장 규칙이다. 버린 안: CI 이미지에 의존성을 굽기(레지스트리 쓰기 토큰이 든다). 규칙의 정본은 `scripts/contracts/ci-gates.ts`의 `DEPENDENCY_CACHE` | 권하는 안으로 정함(2026-11-13, 총괄): 의존성 캐시는 merge job만, 공급망 증거 job은 매번 새로 설치 | +| PR은 바뀐 범위의 merge 게이트만 | 2026-11-13 | PR run의 merge job은 `config/ci/pr-gate-selection.json` 경로표로 바뀐 파일이 닿는 게이트만 돌고, 안 도는 게이트는 `건너뜀: <게이트 ID> — <이유>` 한 줄을 남긴다. 전역 파일·표에 없는 파일·빈 diff·diff를 못 읽음이면 전부 돈다. main·release run은 늘 전부 돈다. 판정은 `scripts/lib/pr-gate-selection.ts`, 계약 시험은 `tests/unit/pr-gate-selection.test.ts`다 | 소유자 결정(2026-11-13 18:3x, design-docs `ci/manual.md` 4절). PR 경로표가 놓친 것은 main이 잡는다. main push에서 선택 때문에 놓친 실패가 나오면 경로표를 고친다 | | 구조·기술 결정 기록 | 2026-07-26~ | `VD-01`~(빈 번호 있음) | `docs/adr/` | ## 3. 결정 대기 쓰는 법 diff --git a/scripts/contracts/ci-gates.ts b/scripts/contracts/ci-gates.ts index 45f41d23..ecb748fe 100644 --- a/scripts/contracts/ci-gates.ts +++ b/scripts/contracts/ci-gates.ts @@ -4,6 +4,7 @@ import path from "node:path"; import { z } from "zod"; import { DEPENDENCY_ADVISORIES_RECORD_PATH } from "../lib/dependency-advisories.ts"; +import { PR_BASE_REF_VARIABLE } from "../lib/pr-gate-selection.ts"; import { selectRepositoryPaths } from "../lib/repository-layout.ts"; import { PROMOTION_FORMULA } from "../lib/promotion-readiness.ts"; import { @@ -999,10 +1000,16 @@ function validateContractSemantics( issue(`canonical job step sequence drift: ${jobId}`); } } + const PR_BASE_REF_BINDING = Object.freeze({ + name: PR_BASE_REF_VARIABLE, + value: "${{ gitea.event_name == 'pull_request' && gitea.base_ref || '' }}", + }); const expectedEnvironmentBindings: Readonly []>> = { - merge_static: [], - merge_test: [], - merge_browser: [], + // PR gate selection (config/ci/pr-gate-selection.json): the base branch + // of a pull_request run, empty in every other run, which runs every gate. + merge_static: [PR_BASE_REF_BINDING], + merge_test: [PR_BASE_REF_BINDING], + merge_browser: [PR_BASE_REF_BINDING], release_gate: [ // 1112/05-01 (R9-D7, release tag). FE-GATE-028 compares each signed // record's Release ID with the tag being released. A run that is not a diff --git a/scripts/lib/pr-gate-selection.ts b/scripts/lib/pr-gate-selection.ts new file mode 100644 index 00000000..f1370c68 --- /dev/null +++ b/scripts/lib/pr-gate-selection.ts @@ -0,0 +1,166 @@ +import { spawnSync } from "node:child_process"; +import { readFileSync } from "node:fs"; +import path from "node:path"; + +import { z } from "zod"; + +/** + * PR gate selection (design-docs ci/manual.md 4.3, owner decision 2026-11-13). + * A PR run's merge job runs a merge gate only when the PR changed a file the + * gate reads, by the path table `config/ci/pr-gate-selection.json`. Main and + * release runs run every gate: what a PR skips, main still checks. + * + * The selection fails open: a file no row matches, a global file, an empty + * diff or a diff that cannot be read selects every gate. + */ + +export const PR_GATE_SELECTION_PATH = "config/ci/pr-gate-selection.json"; + +/** The PR's base branch; empty (or unset) outside pull_request runs. */ +export const PR_BASE_REF_VARIABLE = "CI_PR_BASE_REF"; + +const GATE_ID = z.string().regex(/^FE-GATE-\d{3}$/u); + +const TABLE_SCHEMA = z + .object({ + $comment: z.string(), + schemaVersion: z.literal(1), + always: z.array(GATE_ID), + global: z.array(z.string().min(1)), + rules: z.array( + z + .object({ + id: z.string().regex(/^[a-z][a-z-]*$/u), + paths: z.array(z.string().min(1)).min(1), + gates: z.array(GATE_ID).min(1), + }) + .strict(), + ), + }) + .strict(); + +export type PrGateSelectionTable = z.infer; + +export function loadPrGateSelectionTable(root: string): PrGateSelectionTable { + return TABLE_SCHEMA.parse(JSON.parse(readFileSync(path.join(root, PR_GATE_SELECTION_PATH), "utf8"))); +} + +/** + * A path pattern of the table as a regular expression: `**` is any run of + * path segments, `*` and `?` stay within one segment. + */ +const compiledPatterns = new Map(); + +export function pathPatternRegExp(pattern: string): RegExp { + const compiled = compiledPatterns.get(pattern); + if (compiled) return compiled; + let source = ""; + for (let index = 0; index < pattern.length; index += 1) { + const character = pattern[index]!; + if (character === "*" && pattern[index + 1] === "*") { + const slash = pattern[index + 2] === "/"; + source += slash ? "(?:.*/)?" : ".*"; + index += slash ? 2 : 1; + } else if (character === "*") { + source += "[^/]*"; + } else if (character === "?") { + source += "[^/]"; + } else { + source += character.replace(/[.+^${}()|[\]\\]/gu, "\\$&"); + } + } + const expression = new RegExp(`^${source}$`, "u"); + compiledPatterns.set(pattern, expression); + return expression; +} + +function matchesAny(file: string, patterns: readonly string[]): boolean { + return patterns.some((pattern) => pathPatternRegExp(pattern).test(file)); +} + +export type PrGateSelection = + | Readonly<{ kind: "all"; reason: string }> + | Readonly<{ kind: "subset"; gates: ReadonlySet; changed: number }>; + +/** Which merge gates a PR that changed `changedFiles` runs. */ +export function selectPrGates(table: PrGateSelectionTable, changedFiles: readonly string[]): PrGateSelection { + if (changedFiles.length === 0) return { kind: "all", reason: "바뀐 파일이 없음(diff를 확인하지 못함)" }; + const gates = new Set(table.always); + for (const file of changedFiles) { + if (matchesAny(file, table.global)) return { kind: "all", reason: `전역 파일 ${file}이 바뀜` }; + // The first row that matches decides: a document under src/ is a document. + const rule = table.rules.find(({ paths }) => matchesAny(file, paths)); + if (!rule) return { kind: "all", reason: `경로표의 어느 줄에도 안 걸리는 ${file}이 바뀜` }; + for (const gate of rule.gates) gates.add(gate); + } + return { kind: "subset", gates, changed: changedFiles.length }; +} + +/** The log line of a skipped gate (design-docs ci/manual.md 4.1 item 3). */ +export function skippedGateLine(gateId: string, reason: string): string { + return `건너뜀: ${gateId} — ${reason}`; +} + +export const SKIPPED_GATE_LINE = /^건너뜀: (?:FE-GATE-\d{3}|merge \/ [a-z ]+) — \S.*$/u; + +type Git = (args: readonly string[]) => Readonly<{ status: number | null; stdout: string; stderr: string }>; + +const runGit: Git = (args) => { + const result = spawnSync("git", args, { encoding: "utf8" }); + return { status: result.status, stdout: result.stdout ?? "", stderr: result.stderr ?? "" }; +}; + +/** + * The files a PR changed against its base: `git diff --name-only` from the + * merge base of `origin/` and HEAD. The checkout is shallow, so the base + * branch and the history to the merge base are fetched first. + */ +export function prChangedFiles( + baseRef: string, + git: Git = runGit, +): Readonly<{ files: readonly string[] } | { error: string }> { + if (!/^[\w./-]+$/u.test(baseRef)) return { error: `base 브랜치 이름이 이상함: ${baseRef}` }; + const shallow = git(["rev-parse", "--is-shallow-repository"]).stdout.trim() === "true"; + const fetch = git([ + "fetch", + "--no-tags", + "--quiet", + ...(shallow ? ["--unshallow"] : []), + "origin", + `+refs/heads/${baseRef}:refs/remotes/origin/${baseRef}`, + ]); + if (fetch.status !== 0) return { error: `base 브랜치를 받지 못함: ${fetch.stderr.trim()}` }; + const base = git(["merge-base", `refs/remotes/origin/${baseRef}`, "HEAD"]); + if (base.status !== 0) return { error: `merge base를 찾지 못함: ${base.stderr.trim()}` }; + const diff = git(["diff", "--name-only", "--no-renames", base.stdout.trim(), "HEAD"]); + if (diff.status !== 0) return { error: `diff를 읽지 못함: ${diff.stderr.trim()}` }; + return { files: diff.stdout.split("\n").filter(Boolean) }; +} + +/** + * Why a PR run skips `gateId`, or undefined when it runs the gate. Outside a + * pull_request run (no base ref) every gate runs. + */ +export function prGateSkipReason( + gateId: string, + environment: NodeJS.ProcessEnv, + root: string, + git: Git = runGit, +): string | undefined { + const baseRef = environment[PR_BASE_REF_VARIABLE]; + if (!baseRef) return undefined; + const table = loadPrGateSelectionTable(root); + const changed = prChangedFiles(baseRef, git); + if ("error" in changed) { + process.stdout.write(`PR 게이트 선택: 전부 돈다 — ${changed.error}\n`); + return undefined; + } + const selection = selectPrGates(table, changed.files); + if (selection.kind === "all") { + process.stdout.write(`PR 게이트 선택: 전부 돈다 — ${selection.reason}\n`); + return undefined; + } + return selection.gates.has(gateId) + ? undefined + : `바뀐 파일 ${selection.changed}개가 경로표(${PR_GATE_SELECTION_PATH})에서 이 게이트에 안 걸림`; +} diff --git a/scripts/run-ci-gate.ts b/scripts/run-ci-gate.ts index 92957f43..998039f0 100644 --- a/scripts/run-ci-gate.ts +++ b/scripts/run-ci-gate.ts @@ -13,6 +13,7 @@ import { withCiGatePreflight } from "./contracts/ci-gates.ts"; import { validateCiArtifact } from "./lib/ci-artifact-validator.ts"; import { formatGateFailure } from "./lib/ci-gate-failure.ts"; import { writeCiGateLogAtomic } from "./lib/ci-gate-log.ts"; +import { prGateSkipReason, skippedGateLine } from "./lib/pr-gate-selection.ts"; const requestedGateId = process.argv .slice(2) @@ -28,6 +29,20 @@ const logSchema = contractIndex.artifactSchemas.get(logArtifact.schemaId); if (!logSchema || logSchema.kind !== "text") { throw new TypeError(`CI gate log schema must be bounded text: ${logArtifact.schemaId}`); } +// A PR run skips a merge gate whose inputs the PR did not change +// (config/ci/pr-gate-selection.json); main and release runs run it. +const skipReason = prGateSkipReason(gateId, process.env, process.cwd()); +if (skipReason !== undefined) { + const line = skippedGateLine(gateId, skipReason); + await writeCiGateLogAtomic({ + root: process.cwd(), + relativePath: logArtifact.path, + content: `${line}\n`, + maxBytes: logSchema.maxBytes, + }); + process.stdout.write(`${line}\n`); + return; +} const output: string[] = []; let outputBytes = 0; let passed = true; diff --git a/tests/unit/__snapshots__/ci-workflow-generation.test.ts.snap b/tests/unit/__snapshots__/ci-workflow-generation.test.ts.snap index cbb87091..b12b2db4 100644 --- a/tests/unit/__snapshots__/ci-workflow-generation.test.ts.snap +++ b/tests/unit/__snapshots__/ci-workflow-generation.test.ts.snap @@ -44,6 +44,8 @@ jobs: if: \${{ gitea.event_name != 'workflow_dispatch' || (inputs.stage != 'documentation' && inputs.stage != 'main') }} runs-on: ubuntu-latest timeout-minutes: 45 + env: + CI_PR_BASE_REF: "\${{ gitea.event_name == 'pull_request' && gitea.base_ref || '' }}" steps: - uses: https://github.com/actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 with: @@ -111,6 +113,8 @@ jobs: # FE-GATE-013 runner requirement: unprivileged user and network namespaces for bwrap (the provider sandbox runs bwrap --unshare-pid --unshare-ipc --unshare-uts --unshare-net); Ubuntu 23.10 and later refuse them while kernel.apparmor_restrict_unprivileged_userns=1 unless /usr/bin/bwrap has an AppArmor profile that allows userns; scripts/check-system-test-prerequisites.ts probes this before test:system runs and scripts/run-and-validate-provider.ts before a provider runs runs-on: ubuntu-latest timeout-minutes: 45 + env: + CI_PR_BASE_REF: "\${{ gitea.event_name == 'pull_request' && gitea.base_ref || '' }}" steps: - uses: https://github.com/actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 with: @@ -181,6 +185,7 @@ jobs: options: "--shm-size=2g" env: CI_RUNNER_IMAGE: "mcr.microsoft.com/playwright:v1.62.0-noble@sha256:baed2032d533817f3dbe6425de795788430ba345e819a1201337009ba17c9d07" + CI_PR_BASE_REF: "\${{ gitea.event_name == 'pull_request' && gitea.base_ref || '' }}" steps: - uses: https://github.com/actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 with: diff --git a/tests/unit/pr-gate-selection.test.ts b/tests/unit/pr-gate-selection.test.ts new file mode 100644 index 00000000..2d83f561 --- /dev/null +++ b/tests/unit/pr-gate-selection.test.ts @@ -0,0 +1,221 @@ +import { spawnSync } from "node:child_process"; +import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import path from "node:path"; + +import { describe, expect, it } from "vitest"; + +import { childProcessTimeout } from "../helpers/child-process-timeout.ts"; + +import { loadCiGateContract } from "../../scripts/contracts/ci-gates.ts"; +import { + loadPrGateSelectionTable, + pathPatternRegExp, + prChangedFiles, + prGateSkipReason, + PR_BASE_REF_VARIABLE, + selectPrGates, + SKIPPED_GATE_LINE, + skippedGateLine, +} from "../../scripts/lib/pr-gate-selection.ts"; + +const table = loadPrGateSelectionTable(process.cwd()); +/** Longest desktop run of the `git ls-files` test (2026-11-13, three runs at load 17 to 23). */ +const GIT_LS_FILES_MS = 48; +/** Longest desktop run of the shallow-clone test (2026-11-13, three runs at load 24). */ +const SHALLOW_CLONE_MS = 291; +const ALWAYS = ["FE-GATE-001", "FE-GATE-002", "FE-GATE-003", "FE-GATE-010"]; + +function covered(file: string): boolean { + const patterns = [...table.global, ...table.rules.flatMap((rule) => rule.paths)]; + return patterns.some((pattern) => pathPatternRegExp(pattern).test(file)); +} + +function selected(files: readonly string[]): readonly string[] | "all" { + const selection = selectPrGates(table, files); + return selection.kind === "all" ? "all" : [...selection.gates].sort(); +} + +type GitCall = readonly string[]; +function fakeGit(answers: Readonly>>) { + const calls: GitCall[] = []; + const git = (args: readonly string[]) => { + calls.push(args); + const answer = answers[args[0]!] ?? {}; + return { status: answer.status ?? 0, stdout: answer.stdout ?? "", stderr: answer.stderr ?? "" }; + }; + return { git, calls }; +} + +describe("PR path table (contract)", () => { + it("puts every merge gate on a row or in always", async () => { + const contract = await loadCiGateContract(process.cwd()); + const merge = contract.stages.find((stage) => stage.id === "merge")!.gateIds; + const listed = new Set([...table.always, ...table.rules.flatMap((rule) => rule.gates)]); + expect(merge.filter((gate) => !listed.has(gate))).toEqual([]); + expect([...listed].filter((gate) => !merge.includes(gate))).toEqual([]); + }); + + it("matches every tracked file with a row or the global list", () => { + const tracked = spawnSync("git", ["ls-files"], { encoding: "utf8" }).stdout.split("\n").filter(Boolean); + expect(tracked.length).toBeGreaterThan(100); + expect(tracked.filter((file) => !covered(file))).toEqual([]); + }, childProcessTimeout(GIT_LS_FILES_MS)); + + it("covers every repository path the scaffold and removal drills name with the scaffold row", () => { + const scaffold = table.rules.find((rule) => rule.id === "scaffold")!; + const drills = [ + "scripts/create-feature.ts", + "scripts/create-feature-write-slice.ts", + "scripts/lib/generated-feature.ts", + "scripts/lib/feature-scaffold-drill.ts", + "scripts/test-feature-scaffold.ts", + "scripts/test-sample-removal.ts", + ]; + const named = new Set( + drills.flatMap((file) => + [...readFileSync(file, "utf8").matchAll(/["'`]((?:src|tests)\/[\w./-]+)/gu)].map((match) => match[1]!), + ), + ); + expect(named.size).toBeGreaterThan(5); + const uncovered = [...named].filter( + (name) => + !scaffold.paths.some((pattern) => + [name, `${name.replace(/\/$/u, "")}/x`].some((candidate) => pathPatternRegExp(pattern).test(candidate)), + ), + ); + expect(uncovered).toEqual([]); + }); +}); + +describe("PR gate selection", () => { + it("runs the static gates and the unit gate for documents only", () => { + expect(selected(["docs/work/README.md", "README.md", "src/presentation/AGENTS.md", ".claude/rules/tests.md"])).toEqual( + [...ALWAYS, "FE-GATE-005"].sort(), + ); + }); + + it("adds the accessibility gate and the removal drill for the accessibility records", () => { + expect(selected(["docs/accessibility/route-reviews/APP_HOME.md"])).toEqual( + [...ALWAYS, "FE-GATE-005", "FE-GATE-009", "FE-GATE-020"].sort(), + ); + }); + + it("runs the application gates but not the scaffold drill for code outside its inputs", () => { + const gates = selected(["src/presentation/pages/home-page.tsx", "tests/e2e/app-shell.spec.ts"]); + expect(gates).not.toBe("all"); + expect(gates).toContain("FE-GATE-008"); + expect(gates).toContain("FE-GATE-013"); + expect(gates).not.toContain("FE-GATE-020"); + }); + + it("runs the scaffold drill when its inputs change", () => { + expect(selected(["src/features/reference/index.ts"])).toContain("FE-GATE-020"); + expect(selected(["src/features/reference/index.ts"])).toContain("FE-GATE-008"); + expect(selected(["tests/mocks/scenarios/catalog.ts"])).toContain("FE-GATE-020"); + }); + + it("runs every gate for a global file, an unknown file or an empty diff", () => { + expect(selectPrGates(table, ["package.json"])).toEqual({ kind: "all", reason: "전역 파일 package.json이 바뀜" }); + expect(selected(["scripts/verify.sh", "docs/x.md"])).toBe("all"); + expect(selected(["playwright.visual.config.ts"])).toBe("all"); + expect(selectPrGates(table, ["new-root-file.txt"])).toMatchObject({ kind: "all" }); + expect(selectPrGates(table, [])).toMatchObject({ kind: "all" }); + }); + + it("reads path patterns as segments", () => { + expect(pathPatternRegExp("**/*.md").test("README.md")).toBe(true); + expect(pathPatternRegExp("**/*.md").test("docs/a/b.md")).toBe(true); + expect(pathPatternRegExp("docs/**").test("docs/a/b.txt")).toBe(true); + expect(pathPatternRegExp("docs/**").test("docsx/a")).toBe(false); + expect(pathPatternRegExp("tsconfig*.json").test("tsconfig.app.json")).toBe(true); + expect(pathPatternRegExp("tsconfig*.json").test("src/tsconfig.json")).toBe(false); + expect(pathPatternRegExp("index.html").test("indexXhtml")).toBe(false); + }); +}); + +describe("skipped gate log line", () => { + it("has the fixed form of design-docs ci/manual.md 4.1", () => { + const line = skippedGateLine("FE-GATE-020", "바뀐 파일 3개가 경로표에서 이 게이트에 안 걸림"); + expect(line).toBe("건너뜀: FE-GATE-020 — 바뀐 파일 3개가 경로표에서 이 게이트에 안 걸림"); + expect(SKIPPED_GATE_LINE.test(line)).toBe(true); + expect(SKIPPED_GATE_LINE.test("건너뜀: merge / tests — 트리 abc1234가 PR #12 run 34에서 초록")).toBe(true); + expect(SKIPPED_GATE_LINE.test("skipped: FE-GATE-020")).toBe(false); + expect(SKIPPED_GATE_LINE.test("건너뜀: FE-GATE-020 —")).toBe(false); + }); +}); + +describe("PR diff and the skip decision", () => { + it("unshallows the checkout, fetches the base and diffs from the merge base", () => { + const { git, calls } = fakeGit({ + "rev-parse": { stdout: "true\n" }, + "merge-base": { stdout: "abc123\n" }, + diff: { stdout: "docs/a.md\nsrc/b.ts\n" }, + }); + expect(prChangedFiles("main", git)).toEqual({ files: ["docs/a.md", "src/b.ts"] }); + expect(calls[1]).toEqual(["fetch", "--no-tags", "--quiet", "--unshallow", "origin", "+refs/heads/main:refs/remotes/origin/main"]); + expect(calls[2]).toEqual(["merge-base", "refs/remotes/origin/main", "HEAD"]); + expect(calls[3]).toEqual(["diff", "--name-only", "--no-renames", "abc123", "HEAD"]); + }); + + it("reads a shallow PR checkout's changes from the merge base with real git", () => { + const root = mkdtempSync(path.join(tmpdir(), "pr-gate-selection-")); + try { + const git = (cwd: string, ...args: string[]) => { + const result = spawnSync( + "git", + ["-c", "user.name=t", "-c", "user.email=t@example.invalid", "-c", "init.defaultBranch=main", ...args], + { cwd, encoding: "utf8" }, + ); + if (result.status !== 0) throw new Error(`git ${args.join(" ")}: ${result.stderr}`); + return result; + }; + const origin = path.join(root, "origin"); + mkdirSync(origin); + git(origin, "init", "--quiet"); + writeFileSync(path.join(origin, "a.ts"), "1\n"); + git(origin, "add", "."); + git(origin, "commit", "--quiet", "-m", "base"); + git(origin, "switch", "--quiet", "-c", "pr"); + mkdirSync(path.join(origin, "docs")); + writeFileSync(path.join(origin, "docs", "x.md"), "x\n"); + git(origin, "add", "."); + git(origin, "commit", "--quiet", "-m", "pr"); + git(origin, "switch", "--quiet", "main"); + writeFileSync(path.join(origin, "a.ts"), "2\n"); + git(origin, "commit", "--quiet", "-am", "main moves on"); + git(root, "clone", "--quiet", "--depth", "1", "--branch", "pr", `file://${origin}`, "checkout"); + const checkout = path.join(root, "checkout"); + const inCheckout = (args: readonly string[]) => { + const result = spawnSync("git", args, { cwd: checkout, encoding: "utf8" }); + return { status: result.status, stdout: result.stdout, stderr: result.stderr }; + }; + // main's own later change (a.ts) is not the PR's. + expect(prChangedFiles("main", inCheckout)).toEqual({ files: ["docs/x.md"] }); + } finally { + rmSync(root, { recursive: true, force: true }); + } + }, childProcessTimeout(SHALLOW_CLONE_MS)); + + it("reports a fetch failure or an odd base name instead of guessing", () => { + expect(prChangedFiles("main", fakeGit({ fetch: { status: 128, stderr: "denied" } }).git)).toEqual({ + error: "base 브랜치를 받지 못함: denied", + }); + expect(prChangedFiles("main; rm -rf /", fakeGit({}).git)).toMatchObject({ error: expect.stringContaining("이상함") }); + }); + + it("skips only in a pull_request run, only gates the diff does not reach", () => { + const docsOnly = () => + fakeGit({ "rev-parse": { stdout: "false\n" }, "merge-base": { stdout: "abc\n" }, diff: { stdout: "docs/a.md\n" } }).git; + const root = process.cwd(); + expect(prGateSkipReason("FE-GATE-020", {}, root, docsOnly())).toBeUndefined(); + expect(prGateSkipReason("FE-GATE-020", { [PR_BASE_REF_VARIABLE]: "" }, root, docsOnly())).toBeUndefined(); + expect(prGateSkipReason("FE-GATE-020", { [PR_BASE_REF_VARIABLE]: "main" }, root, docsOnly())).toMatch( + /^바뀐 파일 1개가 경로표/u, + ); + expect(prGateSkipReason("FE-GATE-005", { [PR_BASE_REF_VARIABLE]: "main" }, root, docsOnly())).toBeUndefined(); + expect( + prGateSkipReason("FE-GATE-020", { [PR_BASE_REF_VARIABLE]: "main" }, root, fakeGit({ fetch: { status: 1 } }).git), + ).toBeUndefined(); + }); +});