From 9f8b2c1ce58a692233171db48c04d4a4695fa5f1 Mon Sep 17 00:00:00 2001 From: DongHyeonka Date: Fri, 13 Nov 2026 19:49:25 +0900 Subject: [PATCH 1/2] =?UTF-8?q?ci(gates):=20PR=20run=EC=9D=B4=20=EA=B2=BD?= =?UTF-8?q?=EB=A1=9C=ED=91=9C=EB=A1=9C=20=EB=B0=94=EB=80=90=20=EB=B2=94?= =?UTF-8?q?=EC=9C=84=EC=9D=98=20merge=20=EA=B2=8C=EC=9D=B4=ED=8A=B8?= =?UTF-8?q?=EB=A7=8C=20=EB=8F=88=EB=8B=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit PR run은 무엇을 바꿨든 merge 게이트 14개를 전부 돈다. 문서만 고친 PR도 scaffold 드릴(FE-GATE-020, run 241 tests job 15:58 중 약 8.5분)과 브라우저 게이트를 돈다. 소유자가 「PR은 바뀐 범위만, 문서만이면 문서 검사, 공용 파일이면 전체, 건너뛴 검사는 로그에, 경로표는 계약 시험으로」를 정했다(2026-11-13, design-docs ci/manual.md 4절, 계획 FE-2). config/ci/pr-gate-selection.json이 경로표다. global 파일(config/, scripts/, .gitea/, 도구 설정, lockfile 등)이나 어느 줄에도 안 걸리는 파일이 하나라도 바뀌면 전부 돈다. 아니면 파일마다 rules를 위에서부터 보고, 처음 맞는 줄의 게이트를 always(001·002·003·010)에 더한다. - 문서(docs/**, **/*.md, .claude/**)는 FE-GATE-005까지 돈다. - 접근성 기록은 009·020까지, recipes는 007·012까지 돈다. - scaffold 드릴 입력(src/features 등)은 앱 게이트와 020을 돈다. - 그 밖의 src·tests는 020을 뺀 앱 게이트를 돈다. scripts/lib/pr-gate-selection.ts가 판정한다. run-ci-gate.ts는 CI_PR_BASE_REF(pull_request run에서만 base 브랜치, 나머지는 빈 값)가 있을 때만 판정을 부른다. 안 도는 게이트는 `건너뜀: — <이유>`를 찍고 게이트 로그도 그 한 줄로 남긴 뒤 성공으로 끝난다. diff는 base와의 merge base에서 잰다. checkout이 얕아 처음 한 번 history를 받는다. 받지 못하거나 diff를 못 읽으면 이유를 찍고 전부 돈다. merge job 셋의 env 바인딩은 계약(expectedEnvironmentBindings)과 gates.json에 두고 workflow를 다시 만들었다. 버린 대안: - workflow on.paths·job if:로 건너뛰기: 필수 검사가 보고 없이 남는다 (매뉴얼 4.4절). - 고르는 job을 따로 두기: needs job이 줄 끝으로 간다. - vitest --changed: coverage 문턱이 전체 실행을 전제한다. - 맞는 줄을 모두 합치기: src 아래 AGENTS.md 같은 문서가 앱 게이트 전부를 불렀다. 위험·한계: - 경로표가 놓친 실패는 main push가 잡는다. main은 늘 전부 돈다. - scaffold 줄은 드릴 스크립트가 이름으로 부르는 src·tests 경로를 손으로 옮긴 것이다. 계약 시험이 그 이름들이 scaffold 줄에 걸리는지 본다. - 공개 repo라 checkout의 origin에서 인증 없이 fetch한다. 비공개로 바뀌면 fetch가 실패하고 전부 돈다(로그에 이유). 검증(desktop): pr-gate-selection 시험(표가 merge 게이트 전부를 덮음, 추적 파일 1631개 전부가 줄에 걸림, scaffold 드릴 이름 범위, 문서만·접근성· 앱·scaffold·전역·모르는 파일·빈 diff 선택, 건너뜀 문구 형식, 실제 git 얕은 clone에서 merge base diff, fetch 실패면 전부)을 3회 통과했다. test-timeout-declarations 통과. 자식 프로세스 시험 둘의 timeout은 잰 값 48 ms·291 ms다. check:ci-workflow, check:types:node·test, eslint 통과. scripts/verify.sh merge(CI=true, main 950ea11a 위, 트리 e031a8a5): 14개 전부 rc=0(008 282초, 020 404초). gate FE-GATE-029 rc=0. --- .gitea/workflows/quality-gates.yml | 5 + config/ci/gates.json | 21 +- config/ci/pr-gate-selection.json | 121 ++++++++++ docs/operations/ci-quality-gates.md | 9 + docs/work/reference/decisions.md | 1 + scripts/contracts/ci-gates.ts | 13 +- scripts/lib/pr-gate-selection.ts | 166 +++++++++++++ scripts/run-ci-gate.ts | 15 ++ .../ci-workflow-generation.test.ts.snap | 5 + tests/unit/pr-gate-selection.test.ts | 221 ++++++++++++++++++ 10 files changed, 571 insertions(+), 6 deletions(-) create mode 100644 config/ci/pr-gate-selection.json create mode 100644 scripts/lib/pr-gate-selection.ts create mode 100644 tests/unit/pr-gate-selection.test.ts 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(); + }); +}); -- 2.54.0 From f0a8582c72a3e8692103d5a9805dd842333bee42 Mon Sep 17 00:00:00 2001 From: DongHyeonka Date: Sat, 14 Nov 2026 03:11:26 +0900 Subject: [PATCH 2/2] =?UTF-8?q?fix(ci):=20=EC=8B=9C=ED=97=98=20fixture?= =?UTF-8?q?=EA=B0=80=20PR=20job=EC=9D=98=20=EA=B2=8C=EC=9D=B4=ED=8A=B8=20?= =?UTF-8?q?=EC=84=A0=ED=83=9D=20env=EB=A5=BC=20=EB=AC=BC=EB=A0=A4=EB=B0=9B?= =?UTF-8?q?=EC=A7=80=20=EC=95=8A=EB=8A=94=EB=8B=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit PR run의 merge job은 CI_PR_BASE_REF=main을 둔다. 임시 폴더에서 scripts/run-ci-gate.ts를 띄우는 시험은 env를 그대로 물려줬고, 자식은 그 폴더에 없는 config/ci/pr-gate-selection.json을 열다 ENOENT로 죽었다(runner run 291, tests/unit/ci-gate-failure.test.ts:102). FE-GATE-005가 깨졌고, scaffold 사본의 test:coverage가 같은 시험을 돌려 FE-GATE-020도 깨졌다. desktop verify.sh merge는 ci_env에 이 변수가 없어 이 길을 타지 않았다. fixture는 PR의 checkout이 아니므로 그 안의 게이트는 늘 전부 돈다. FIXTURE_PNPM_ENVIRONMENT가 CI_PR_BASE_REF를 빈 값(main run과 같음)으로 둔다. scaffold 드릴·제거 드릴·provider fixture·run-ci-gate를 띄우는 시험이 모두 이 상수를 쓰므로 한 곳에서 끈다. - ci-gate-failure 시험은 바깥 env와 상관없이 PR job env(main)를 넣고 띄운다. 그래서 desktop에서도 CI의 조건을 늘 시험한다. - run-ci-gate를 띄우는 시험은 이 상수를 써야 한다는 검사를 fixture-node-modules 시험에 더했다. 그 검사가 상수 없이 띄우던 ci-workflow-generation 시험 하나를 찾았다. 그 시험은 preflight에서 먼저 막혀 지금은 가려지지 않지만, 상수를 주고 막힌 이유를 단언한다. 버린 대안: - prGateSkipReason이 경로표가 없으면 전부 돌기: 원인은 시험 env다. 진짜 checkout에서 경로표가 없으면 크게 실패하는 편이 맞다. - verify.sh ci_env에 CI_PR_BASE_REF를 두기: desktop merge가 게이트를 건너뛰게 되어 「merge 단계 전부 통과」 판정과 맞지 않는다. 위험·한계: - 시스템 컨테이너(scripts/run-in-system-container.sh)는 CI_PR_BASE_REF를 넘기지 않는다. 그래서 FE-GATE-013은 PR run에서도 늘 전부 돈다(안전한 쪽). 이 커밋은 그대로 둔다. 검증(desktop): - RED: 9f8b2c1c에서 `env CI_PR_BASE_REF=main node scripts/run-vitest.ts run tests/unit/ci-gate-failure.test.ts` rc=1, run 291과 같은 ENOENT. - 고친 뒤 시험 4파일(ci-gate-failure, fixture-node-modules, pr-gate-selection, ci-workflow-generation) 471개 통과, 바깥 CI_PR_BASE_REF=main 있을 때와 없을 때 둘 다. - 상수의 새 줄만 빼면 바깥 env 없이도 ci-gate-failure 시험이 같은 ENOENT로 실패한다. 새 검사는 상수를 안 쓰던 시험을 찾아 실패했다. --- scripts/lib/fixture-node-modules.ts | 11 +++++++++++ tests/unit/ci-gate-failure.test.ts | 7 ++++++- tests/unit/ci-workflow-generation.test.ts | 8 +++++++- tests/unit/fixture-node-modules.test.ts | 19 +++++++++++++++++++ 4 files changed, 43 insertions(+), 2 deletions(-) diff --git a/scripts/lib/fixture-node-modules.ts b/scripts/lib/fixture-node-modules.ts index 26e3e7b5..25460b12 100644 --- a/scripts/lib/fixture-node-modules.ts +++ b/scripts/lib/fixture-node-modules.ts @@ -1,6 +1,8 @@ import { copyFile, mkdir, readdir, readFile, stat, symlink, writeFile } from "node:fs/promises"; import path from "node:path"; +import { PR_BASE_REF_VARIABLE } from "./pr-gate-selection.ts"; + /** * Links the repository's installed dependencies into a throwaway fixture root. * @@ -36,9 +38,18 @@ import path from "node:path"; * shims. A fixture started through `pnpm