diff --git a/.gitea/workflows/quality-gates.yml b/.gitea/workflows/quality-gates.yml index 35dacb99..d79228a8 100644 --- a/.gitea/workflows/quality-gates.yml +++ b/.gitea/workflows/quality-gates.yml @@ -46,6 +46,7 @@ jobs: steps: - uses: https://github.com/actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 with: + fetch-depth: 2 persist-credentials: false - name: Choose the dependency cache folder id: dependency-cache-root @@ -77,29 +78,35 @@ jobs: run: | corepack enable corepack pnpm install --frozen-lockfile --ignore-scripts + - name: Check main push reuse + id: main-push-reuse + if: ${{ gitea.event_name == 'push' && gitea.ref == 'refs/heads/main' }} + env: + GITEA_TOKEN: ${{ gitea.token }} + run: node scripts/ci/main-push-reuse.ts --job "merge / static checks" --github-output "$GITHUB_OUTPUT" - name: "FE-GATE-001 / manifest-lockfile" - if: ${{ !cancelled() }} + if: ${{ steps.main-push-reuse.outputs.reuse != 'true' && !cancelled() }} run: corepack pnpm ci:gate -- FE-GATE-001 - name: "FE-GATE-002 / lint" - if: ${{ !cancelled() }} + if: ${{ steps.main-push-reuse.outputs.reuse != 'true' && !cancelled() }} run: corepack pnpm ci:gate -- FE-GATE-002 - name: "FE-GATE-003 / typecheck" - if: ${{ !cancelled() }} + if: ${{ steps.main-push-reuse.outputs.reuse != 'true' && !cancelled() }} run: corepack pnpm ci:gate -- FE-GATE-003 - name: "FE-GATE-010 / architecture" - if: ${{ !cancelled() }} + if: ${{ steps.main-push-reuse.outputs.reuse != 'true' && !cancelled() }} run: corepack pnpm ci:gate -- FE-GATE-010 - name: "FE-GATE-011 / build" - if: ${{ !cancelled() }} + if: ${{ steps.main-push-reuse.outputs.reuse != 'true' && !cancelled() }} run: corepack pnpm ci:gate -- FE-GATE-011 - name: "FE-GATE-012 / bundle" - if: ${{ !cancelled() }} + if: ${{ steps.main-push-reuse.outputs.reuse != 'true' && !cancelled() }} run: corepack pnpm ci:gate -- FE-GATE-012 - name: Harness self-tests (scripts/tests) - if: ${{ !cancelled() }} + if: ${{ steps.main-push-reuse.outputs.reuse != 'true' && !cancelled() }} run: python3 -I -m unittest discover -s scripts/tests - name: Upload merge static evidence - if: always() + if: ${{ always() && steps.main-push-reuse.outputs.reuse != 'true' }} uses: https://github.com/ChristopherHX/gitea-upload-artifact@81f940d004763f986ba3582c007fd842dd5cb0d7 with: name: "merge-static-${{ gitea.run_id }}" @@ -118,6 +125,7 @@ jobs: steps: - uses: https://github.com/actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 with: + fetch-depth: 2 persist-credentials: false - name: Choose the dependency cache folder id: dependency-cache-root @@ -149,26 +157,32 @@ jobs: run: | corepack enable corepack pnpm install --frozen-lockfile --ignore-scripts + - name: Check main push reuse + id: main-push-reuse + if: ${{ gitea.event_name == 'push' && gitea.ref == 'refs/heads/main' }} + env: + GITEA_TOKEN: ${{ gitea.token }} + run: node scripts/ci/main-push-reuse.ts --job "merge / tests" --github-output "$GITHUB_OUTPUT" - name: "FE-GATE-004 / runtime-schema" - if: ${{ !cancelled() }} + if: ${{ steps.main-push-reuse.outputs.reuse != 'true' && !cancelled() }} run: corepack pnpm ci:gate -- FE-GATE-004 - name: "FE-GATE-005 / unit" - if: ${{ !cancelled() }} + if: ${{ steps.main-push-reuse.outputs.reuse != 'true' && !cancelled() }} run: corepack pnpm ci:gate -- FE-GATE-005 - name: "FE-GATE-006 / component" - if: ${{ !cancelled() }} + if: ${{ steps.main-push-reuse.outputs.reuse != 'true' && !cancelled() }} run: corepack pnpm ci:gate -- FE-GATE-006 - name: "FE-GATE-007 / integration" - if: ${{ !cancelled() }} + if: ${{ steps.main-push-reuse.outputs.reuse != 'true' && !cancelled() }} run: corepack pnpm ci:gate -- FE-GATE-007 - name: "FE-GATE-013 / security" - if: ${{ !cancelled() }} + if: ${{ steps.main-push-reuse.outputs.reuse != 'true' && !cancelled() }} run: corepack pnpm ci:gate -- FE-GATE-013 --enter-host-environment - name: "FE-GATE-020 / removability" - if: ${{ !cancelled() }} + if: ${{ steps.main-push-reuse.outputs.reuse != 'true' && !cancelled() }} run: corepack pnpm ci:gate -- FE-GATE-020 - name: Upload merge test evidence - if: always() + if: ${{ always() && steps.main-push-reuse.outputs.reuse != 'true' }} uses: https://github.com/ChristopherHX/gitea-upload-artifact@81f940d004763f986ba3582c007fd842dd5cb0d7 with: name: "merge-test-${{ gitea.run_id }}" @@ -189,6 +203,7 @@ jobs: steps: - uses: https://github.com/actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 with: + fetch-depth: 2 persist-credentials: false - name: Choose the dependency cache folder id: dependency-cache-root @@ -220,18 +235,25 @@ jobs: run: | corepack enable corepack pnpm install --frozen-lockfile --ignore-scripts + - name: Check main push reuse + id: main-push-reuse + if: ${{ gitea.event_name == 'push' && gitea.ref == 'refs/heads/main' }} + env: + GITEA_TOKEN: ${{ gitea.token }} + run: node scripts/ci/main-push-reuse.ts --job "merge / browser tests" --github-output "$GITHUB_OUTPUT" - name: Install visual-test fonts + if: ${{ steps.main-push-reuse.outputs.reuse != 'true' }} run: | $(command -v sudo || true) apt-get update $(command -v sudo || true) apt-get install -y fonts-noto-core fonts-noto-cjk fonts-noto-cjk-extra fonts-liberation - name: "FE-GATE-008 / e2e" - if: ${{ !cancelled() }} + if: ${{ steps.main-push-reuse.outputs.reuse != 'true' && !cancelled() }} run: corepack pnpm ci:gate -- FE-GATE-008 - name: "FE-GATE-009 / accessibility" - if: ${{ !cancelled() }} + if: ${{ steps.main-push-reuse.outputs.reuse != 'true' && !cancelled() }} run: corepack pnpm ci:gate -- FE-GATE-009 - name: Upload merge browser evidence - if: always() + if: ${{ always() && steps.main-push-reuse.outputs.reuse != 'true' }} uses: https://github.com/ChristopherHX/gitea-upload-artifact@81f940d004763f986ba3582c007fd842dd5cb0d7 with: name: "merge-browser-${{ gitea.run_id }}" diff --git a/CHANGELOG.md b/CHANGELOG.md index 1d25bb56..c630f507 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -185,6 +185,7 @@ Gitea runner에서 merge 단계를 초록으로 만들고, worker를 늘리지 | [계약] | telemetry와 diagnostics의 `build_id`·`release_id`·`active_release_id`가 Service Worker manifest의 `releaseId`와 같은 규칙(제어문자 없는 1~512자, code point)을 읽는다. 다른 속성의 규칙은 그대로다. 전에는 `+`·한글이 있거나 64자를 넘는 build id는 부팅·렌더 실패, Service Worker 시작, release 불일치 기록을, 그런 release id는 release 불일치 기록을 통째로 버렸다. diagnostics는 이 세 속성에 숫자·boolean을 더는 받지 않으니 자기 호출이 그렇게 넘기면 문자열로 바꾼다 (REV-FE-0042) | `src/contracts/deployment-id.ts`, `src/contracts/telemetry.ts`, `src/contracts/diagnostics.ts`, `src/contracts/service-worker-static-manifest.ts` | `b02ebb85` | | [계약] | `check:bundle`(FE-GATE-012)이 Service Worker와 manifest 밖 JavaScript를 예산으로 보고, `public/`에서 복사된 JavaScript는 이름과 자리에 상관없이 실패한다. `config/performance/budgets.json`에 `bundle.serviceWorkerGzipBytes`가 있어야 한다. `artifacts/performance/bundle.json`에 칸이 는다(`measurements.serviceWorkerGzipBytes`, `classification.publicFiles`, `unbudgetedOutputs`, `results.serviceWorkerPassed`, 자기 검사 fixture 하나). 위 "먼저 할 일" (REV-FE-0010) | `scripts/check-bundle.ts`, `scripts/lib/classify-vite-bundle.ts`, `scripts/lib/performance-budgets.ts`, `scripts/contracts/release-artifacts.ts`, `config/performance/budgets.json`, `docs/operations/performance-evidence.md` | `81447354` | | [계약] | merge static job이 게이트 뒤에 `scripts/tests` 시험(`.claude/` 지침, 편집 훅, `scripts/verify.sh`)을 `python3 -I -m unittest discover -s scripts/tests`로 돈다. 계약에 step 종류 `run-script-tests`를 더하고 `merge_static`에만 둔다. 자기 runner job 이미지에 python3가 있어야 한다 | `config/ci/gates.json`, `scripts/contracts/ci-gates.ts`, `scripts/generate-ci-workflow.ts`, `tests/unit/ci-workflow-generation.test.ts` | `91c03b49` | +| [계약] | `refs/heads/main` push의 merge job 셋(`merge_static`·`merge_test`·`merge_browser`)이 `Frozen install` 다음 `main-push-reuse` step에서 직전 PR 실행을 재사용할 수 있는지 본다. checkout이 `fetch-depth: 2`로 부모 둘을 받고, 여섯 조건(main push, 부모 둘 병합 커밋·`tree(HEAD)==tree(HEAD^2)`, `.nvmrc`·`pnpm-lock.yaml` 무변경, `HEAD^2` 최신 PR run의 같은 job `success`, 그 job 로그에 `건너뜀:` 없음, Gitea API 읽기 성공)이 모두 참이면 뒤 step(글꼴·게이트·`scripts/tests`·증거 업로드)을 건너뛰고 `건너뜀:` 한 줄로 성공 종료한다. 하나라도 모르거나 읽지 못하면 전부 돈다. `main_gate`(FE-GATE-029·030)와 release·tag run은 늘 돈다 (CI-FE-0004) | `config/ci/gates.json`, `scripts/contracts/ci-gates.ts`, `scripts/generate-ci-workflow.ts`, `.gitea/workflows/quality-gates.yml`, `scripts/lib/main-push-reuse.ts`, `scripts/ci/main-push-reuse.ts`, `tests/unit/main-push-reuse.test.ts`, `tests/unit/ci-workflow-generation.test.ts`, `docs/operations/ci-quality-gates.md`, `docs/work/reference/decisions.md` | `b2b92dc6` | ### 그 밖의 변경 diff --git a/config/ci/gates.json b/config/ci/gates.json index b35c3c4f..ad468ba6 100644 --- a/config/ci/gates.json +++ b/config/ci/gates.json @@ -2183,6 +2183,9 @@ { "kind": "frozen-install" }, + { + "kind": "main-push-reuse" + }, { "kind": "run-gate" }, @@ -2235,6 +2238,9 @@ { "kind": "frozen-install" }, + { + "kind": "main-push-reuse" + }, { "kind": "run-gate" }, @@ -2283,6 +2289,9 @@ { "kind": "frozen-install" }, + { + "kind": "main-push-reuse" + }, { "kind": "browser-install", "image": "mcr.microsoft.com/playwright:v1.62.0-noble@sha256:baed2032d533817f3dbe6425de795788430ba345e819a1201337009ba17c9d07" diff --git a/docs/operations/ci-quality-gates.md b/docs/operations/ci-quality-gates.md index 35c4cc99..82286b88 100644 --- a/docs/operations/ci-quality-gates.md +++ b/docs/operations/ci-quality-gates.md @@ -25,6 +25,20 @@ scaffold 드릴의 입력이 바뀌면 FE-GATE-020까지 돈다. `global` 파일 돈다. main·release run은 늘 전부 돈다. 판정은 `scripts/lib/pr-gate-selection.ts`, 계약 시험은 `tests/unit/pr-gate-selection.test.ts`다. +`refs/heads/main` push의 merge job 셋(`merge_static`·`merge_test`·`merge_browser`)은 +`Frozen install` 바로 뒤 `main-push-reuse` step에서 직전 PR 실행을 재사용할 수 있는지 본다 +(결정 D-1 (가), `scripts/lib/main-push-reuse.ts`, `scripts/ci/main-push-reuse.ts`, +`tests/unit/main-push-reuse.test.ts`). checkout은 `fetch-depth: 2`로 부모 둘을 받는다. +여섯 조건이 모두 참일 때만 뒤 step(글꼴·게이트·`scripts/tests`·증거 업로드)을 건너뛰고 +`건너뜀: — 트리 <해시 12자>가 PR #<번호> run <번호>에서 초록` 한 줄을 찍어 성공으로 +끝낸다: (1) `push` 이벤트이고 `refs/heads/main`, (2) 부모 둘인 병합 커밋이고 +`tree(HEAD) == tree(HEAD^2)`, (3) `HEAD^1..HEAD`에서 `pnpm-lock.yaml`·`.nvmrc`가 안 바뀜, +(4) `HEAD^2`의 최신 `pull_request` run에서 같은 이름 job이 `success`, (5) 그 job 로그가 비어 있지 +않고 `SKIPPED_GATE_LINE` 형식의 `건너뜀:` 줄이 없음(PR에서 그 job 게이트를 전부 돌았음), +(6) Gitea API(`actions/runs`·`actions/runs/{id}/jobs`·`actions/jobs/{id}/logs`)를 오류·시간 초과 +없이 읽음. 하나라도 거짓이거나 읽지 못하면 게이트를 전부 돈다. `main_gate`(FE-GATE-029·030)와 +release·tag run은 이 step을 두지 않아 늘 돈다. + merge job 셋과 main job(`main_gate`)이 의존성 캐시를 쓴다(merge job 셋은 권하는 안으로 정함 2026-11-13, main job은 2026-11-20에 더함, 총괄). setup-node 앞에서 Node toolcache, corepack이 받은 pnpm, pnpm store와 메타데이터 캐시를 `.nvmrc`와 diff --git a/docs/work/reference/decisions.md b/docs/work/reference/decisions.md index 9d54396e..6be803fd 100644 --- a/docs/work/reference/decisions.md +++ b/docs/work/reference/decisions.md @@ -81,6 +81,7 @@ | DES-DEC-0010 시각 기준선 | 2026-11-22 | 모양은 중립(토큰으로만 브랜드). 조작부는 44px이 기본이고 예외는 다섯(작은 버튼·Menu 항목·접기·셸 헤더 select 36px, Alert·Dialog(Drawer 포함) 닫기 32px)이다. 글자 링크는 WCAG 24px·간격 기준만 본다. 그 밖의 조작부가 44px 미만이면 결함이다. 라이트와 다크는 동급이라 같은 의미 색 역할·같은 AA 기준·같은 상태 구분으로 판정하고, 한쪽에서만 깨져도 결함이다(같은 색·같은 대비 수치·같은 골든 수를 뜻하지 않는다). 서비스는 토큰과 페이지 템플릿으로 밀도를 조절한다. 재검토: `PRODUCT.md`의 세 축 문장이나 서비스 우선순위가 바뀌거나, 기본 조작부 토큰이 44px 미만이 되거나, 44px 미만 조작부 자리(CSS 최소 높이 규칙 수)가 44px 자리의 2배(추정)를 넘는다 | design 허브 DES-DEC-0010(repo 밖, 항목 DES-FE-0008), project-docs `README.md` 7절 1(권하는 안으로 정함) | | CI 계획 D-3 판정용 재시도 | 2026-11-13 | CI(`CI=true`)에서만 Playwright가 실패한 시험을 한 번 더 돌고, 재시도에서 통과해도 게이트는 실패한다. 0925의 D-3(Web Lock 직렬화)과 다른 결정이다. 재시도는 설정 helper `flakyJudgement()`로만 주고(`scripts/lib/playwright-flaky-judgement.ts`), `scripts/check-test-evidence.ts`는 `config/repository-layout.json`의 `playwright-configs`에 든 설정(dev 설정은 없다)에서 객체 key로 직접 쓴 두 옵션을 거절한다. 펼침·변수·helper 인자로 바뀐 값과 dev 설정은 `tests/unit/playwright-flaky-judgement.test.ts`가 루트 설정마다 계산된 값으로 잡는다. spec 안의 `describe.configure({ retries })`는 둘 다 보지 않는다. `failOnFlakyTests`만으로는 본문의 `test.fail()`이 재시도에서만 불린 시험의 첫 실패가 통과로 바뀐다. 그래서 같은 파일의 reporter가 실패한 시도가 있으면 run을 실패로 끝내고, 다른 보고에 없는 그 오류를 찍는다(2026-11-22 구현에서 확인). 재시도는 e2e 공유 fixture 빌드의 앞 시도 실패 기록을 다시 쓰지 않는다(CI-FE-0001 C9). 이유: 흔들림과 회귀를 같은 run에서 가린다. 전에는 세션이 desktop에서 손으로 세 번 돌렸다. 대가: 실패한 시험만큼 시간이 든다. 많이 깨진 PR은 FE-GATE-008이 최대 약 두 배 걸린다(추정). 버린 안: 재시도 없음 그대로(판정 근거가 run에 없다), `retries`만 켜기(흔들림을 덮는다), package script·`config/ci/gates.json` args로 주기(FE-GATE-029가 부분 실행으로 세거나 Playwright에 닿지 않는다). 재검토: Playwright를 올려 `tests/unit/playwright-flaky-judgement.test.ts`가 실패하거나, 재시도 때문에 browser job이 시간 상한에 닿는다 | 권하는 안으로 정함(총괄, 2026-11-13): design-docs `ci/03-time-reduction-plan.md` 5절. 위임: 소유자 원문(2026-11-11 23:09 KST, 백엔드 세션 직접 입력) 「앞으로 카드 띄우지 말고 너가 판단하고 바로바로 진행할 수 있도록」·「최종 보고만 받을 수 있게」. 이 결정을 따로 묻고 받은 소유자 답은 없다 | | REV-FE-0004 abort ratchet을 호출 위치·파일별 개수로 | 2026-11-22 | `check:adapter-inventory`(FE-GATE-010)의 손수 짠 abort 배선 ratchet은 AST로 센 호출 위치를 `scripts/check-adapter-inventory.ts`의 `HAND_ROLLED_ABORT_SITES`(파일 → 개수)와 같게 고정한다. 표에 없는 파일, 늘어난 수, 줄어든 수가 모두 실패한다(`!==`). 면제는 import 여부나 폴더가 아니라 이름을 댄 kernel 네 파일뿐이다(`src/adapters/platform/`의 `abortable-operation.ts`·`indexeddb-connection.ts`·`indexeddb-transaction.ts`·`system-clock.ts`). 첫 인자의 맨 왼쪽 피연산자가 문자열 "abort"이고 불리는 이름이 `addEventListener`로 끝나는 호출(`new` 포함)을 센다. 13파일 → 29곳은 세는 단위를 바꾼 것이고 이번 한 번뿐이다. 뒤에 수를 올리는 근거로 쓰지 못한다. 이유(확인한 사실): 옛 검사는 primitive를 import한 파일과 줄을 나눈 호출에 리스너를 더해도 통과했다. 버린 안: 줄바꿈 정규식만 더하기(면제 빈틈이 남는다), 합계 하나만 고정(파일 사이로 옮기면 통과한다). 한계: 리스너 수가 그대로인 import 제거, 주석·문자열·문서 글자는 옛 검사가 실패시킬 수 있었지만 새 검사는 통과시킨다. 변수 첫 인자도 세지 않는다. 재검토: 한계에 적지 않은 꼴로 실행되고 타입·lint를 지나는 abort 배선이 이 검사를 지나가는 꼴이 나오면 세는 경계를 다시 본다 | review 허브, 위임: project-docs README 7절 1번(소유자 지시 2026-11-22) 「결정이 필요하면 권하는 안대로 바로 한다.」. 출처 REV-FE-0004(repo 밖 카드) | +| CI 계획 D-1 main push merge job 재사용 | 2026-11-13 | `refs/heads/main` push의 merge job 셋(`merge_static`·`merge_test`·`merge_browser`)은 `Frozen install` 다음 `main-push-reuse` step에서 여섯 조건(main push, 부모 둘 병합 커밋·`tree(HEAD)==tree(HEAD^2)`, `pnpm-lock.yaml`·`.nvmrc` 무변경, `HEAD^2` PR run의 같은 job `success`, 그 job 로그에 `건너뜀:` 없음, API 읽기 성공)이 모두 참이면 뒤 step(글꼴·게이트·`scripts/tests`·업로드)을 건너뛰고 `건너뜀:` 한 줄로 성공 종료한다. 하나라도 모르거나 실패하면 전부 돈다(`scripts/lib/main-push-reuse.ts`, `scripts/ci/main-push-reuse.ts`, `tests/unit/main-push-reuse.test.ts`). `main_gate`(FE-GATE-029·030)와 release·tag run은 늘 돈다. 이유: 최근 병합 대부분이 PR과 같은 트리인데 merge job 셋을 두 번 돌고 있었다. 대가: 같은 트리 두 번째 실행 표본이 줄어든다(CI 계획 D-3 판정용 재시도가 PR run 안에서 흔들림 판정을 대신한다). 버린 안: main에서 경로표 재계산(PR 기준 main과 HEAD^1 사이 되돌림을 놓친다), 보호 규칙만 믿고 조건 4 생략(우회 병합을 못 막는다), 게이트 단위 건너뛰기(D-1 범위 밖). 재검토: 건너뛴 main push 뒤 다음 main push에서 같은 트리에 의존하는 회귀나 비결정 시험 실패가 나오면 끄고 원인을 고친다 | 권하는 안으로 정함(총괄, 2026-11-13, design-docs `ci/03-time-reduction-plan.md` 4.2·5절 D-1 (가)); CI-FE-0004 정정(2026-11-22, CI-X-0003 (바))으로 `now` 우선 | | 구조·기술 결정 기록 | 2026-07-26~ | `VD-01`~(빈 번호 있음) | `docs/adr/` | ## 3. 결정 대기 쓰는 법 diff --git a/scripts/ci/main-push-reuse.ts b/scripts/ci/main-push-reuse.ts new file mode 100644 index 00000000..915c4b0d --- /dev/null +++ b/scripts/ci/main-push-reuse.ts @@ -0,0 +1,81 @@ +import { appendFile } from "node:fs/promises"; + +import { isEntryModule } from "../lib/entry-module.ts"; +import { + evaluateMainPushReuse, + type MainPushReuseFetch, + type MainPushReuseGit, + type ReuseDecision, +} from "../lib/main-push-reuse.ts"; + +/** + * FE-1 (CI-FE-0004) CLI step for merge jobs on refs/heads/main push runs. + * Writes `reuse=true|false` to `$GITHUB_OUTPUT` and logs either the canonical + * `건너뜀:` line or the reason the job will run. Fails open on any error so a + * reuse lookup problem never fails a main push build. + */ + +export type MainPushReuseCliOptions = Readonly<{ + argv?: readonly string[] | undefined; + environment?: NodeJS.ProcessEnv | undefined; + git?: MainPushReuseGit | undefined; + fetcher?: MainPushReuseFetch | undefined; + timeoutMs?: number | undefined; + stdout?: Pick | undefined; +}>; + +function parseArgs(argv: readonly string[]): Readonly<{ jobName?: string; githubOutput?: string }> { + let jobName: string | undefined; + let githubOutput: string | undefined; + for (let index = 0; index < argv.length; index += 1) { + const token = argv[index]!; + if (token === "--job") { + jobName = argv[index + 1]; + index += 1; + } else if (token === "--github-output") { + githubOutput = argv[index + 1]; + index += 1; + } + } + return { + ...(jobName !== undefined ? { jobName } : {}), + ...(githubOutput !== undefined ? { githubOutput } : {}), + }; +} + +export async function runMainPushReuseCli(options: MainPushReuseCliOptions = {}): Promise { + const argv = options.argv ?? process.argv.slice(2); + const environment = options.environment ?? process.env; + const stdout = options.stdout ?? process.stdout; + const parsed = parseArgs(argv); + const jobName = parsed.jobName?.trim() ?? ""; + const githubOutput = parsed.githubOutput ?? environment["GITHUB_OUTPUT"] ?? ""; + + let decision: ReuseDecision; + if (jobName.length === 0) { + decision = { reuse: false, reason: "--job 인자가 없음" }; + } else { + try { + decision = await evaluateMainPushReuse({ + jobName, + environment, + git: options.git, + fetcher: options.fetcher, + timeoutMs: options.timeoutMs, + }); + } catch (error) { + const detail = error instanceof Error ? error.message : String(error); + decision = { reuse: false, reason: `예기치 않은 오류: ${detail}` }; + } + } + + stdout.write(decision.reuse ? `${decision.line}\n` : `main push 재사용 안 함: ${decision.reason}\n`); + if (githubOutput.trim().length > 0) { + await appendFile(githubOutput, `reuse=${decision.reuse ? "true" : "false"}\n`, "utf8"); + } + return decision; +} + +if (isEntryModule(import.meta)) { + await runMainPushReuseCli(); +} diff --git a/scripts/contracts/ci-gates.ts b/scripts/contracts/ci-gates.ts index 1748c85e..7ce626fa 100644 --- a/scripts/contracts/ci-gates.ts +++ b/scripts/contracts/ci-gates.ts @@ -155,6 +155,18 @@ export const DEPENDENCY_CACHE = Object.freeze({ jobIds: Object.freeze(["merge_static", "merge_test", "merge_browser", "main_gate"] as const), }); +/** + * FE-1 (CI-FE-0004, D-1 (가)): on a push to refs/heads/main whose merge commit + * tree equals its PR head (HEAD^2) and did not change dependency-cache inputs, + * each merge job checks whether that PR head already passed the same job with + * no skipped gates. Any unknown or unreadable input fails open to running. + */ +export const MAIN_PUSH_REUSE = Object.freeze({ + stepId: "main-push-reuse", + script: "scripts/ci/main-push-reuse.ts", + jobIds: Object.freeze(["merge_static", "merge_test", "merge_browser"] as const), +}); + export function resolveCiStepActionUses(stepKind: string): string | null { const actionId = actionIdByStepKind[stepKind as keyof typeof actionIdByStepKind]; return actionId ? resolveCiActionUses(actionId) : null; @@ -412,6 +424,7 @@ const checkoutStep = z.object({ kind: z.literal("checkout") }).strict(); const setupNodeStep = z.object({ kind: z.literal("setup-node") }).strict(); const frozenInstallStep = z.object({ kind: z.literal("frozen-install") }).strict(); const dependencyCacheStep = z.object({ kind: z.literal("dependency-cache") }).strict(); +const mainPushReuseStep = z.object({ kind: z.literal("main-push-reuse") }).strict(); /** * `image`: the job runs in Playwright's own image for the pinned * @playwright/test version, which already holds the browsers and their OS @@ -493,6 +506,7 @@ const jobStepSchema = z.discriminatedUnion("kind", [ dependencyCacheStep, setupNodeStep, frozenInstallStep, + mainPushReuseStep, browserInstallStep, runGateStep, runScriptTestsStep, @@ -914,6 +928,11 @@ function validateContractSemantics( } } } + if (job.steps.some(({ kind }) => kind === "main-push-reuse")) { + if (!(MAIN_PUSH_REUSE.jobIds as readonly string[]).includes(job.id)) { + issue(`main-push-reuse is for the merge jobs only: ${job.id}`); + } + } for (const step of job.steps) { const uses = resolveCiStepActionUses(step.kind); if (uses && !/^https:\/\/github\.com\/[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+@[0-9a-f]{40}$/u.test(uses)) { @@ -1007,9 +1026,9 @@ function validateContractSemantics( } } const expectedStepKinds: Readonly> = { - merge_static: ["checkout", "dependency-cache", "setup-node", "frozen-install", "run-gate", "run-script-tests", "upload"], - merge_test: ["checkout", "dependency-cache", "setup-node", "frozen-install", "run-gate", "upload"], - merge_browser: ["checkout", "dependency-cache", "setup-node", "frozen-install", "browser-install", "run-gate", "upload"], + merge_static: ["checkout", "dependency-cache", "setup-node", "frozen-install", "main-push-reuse", "run-gate", "run-script-tests", "upload"], + merge_test: ["checkout", "dependency-cache", "setup-node", "frozen-install", "main-push-reuse", "run-gate", "upload"], + merge_browser: ["checkout", "dependency-cache", "setup-node", "frozen-install", "main-push-reuse", "browser-install", "run-gate", "upload"], release_gate: ["checkout", "setup-node", "frozen-install", "browser-install", "run-gate", "upload"], immutable_build: ["checkout", "setup-node", "frozen-install", "run-gate", "archive-candidate", "upload", "upload"], vulnerability_provider: ["checkout", "setup-node", "frozen-install", "download", "run-provider", "validate-provider-evidence", "upload"], @@ -1433,7 +1452,7 @@ function validateJobStepKinds( ): void { const allowed: Readonly["kind"], ReadonlySet>> = { "gate-matrix": new Set(["checkout", "setup-node", "frozen-install", "browser-install", "download", "extract", "run-gate", "upload"]), - "gate-sequence": new Set(["checkout", "dependency-cache", "setup-node", "frozen-install", "browser-install", "run-gate", "run-script-tests", "upload"]), + "gate-sequence": new Set(["checkout", "dependency-cache", "setup-node", "frozen-install", "main-push-reuse", "browser-install", "run-gate", "run-script-tests", "upload"]), "gate-single": new Set(["checkout", "setup-node", "frozen-install", "run-gate", "upload"]), immutable: new Set(["checkout", "setup-node", "frozen-install", "run-gate", "archive-candidate", "upload"]), provider: new Set(["checkout", "setup-node", "frozen-install", "download", "extract", "run-provider", "validate-provider-evidence", "upload"]), diff --git a/scripts/generate-ci-workflow.ts b/scripts/generate-ci-workflow.ts index cca9622a..e9197dc4 100644 --- a/scripts/generate-ci-workflow.ts +++ b/scripts/generate-ci-workflow.ts @@ -15,6 +15,7 @@ import { ENTER_HOST_ENVIRONMENT_FLAG, indexCiGateContract, loadCiGateContract, + MAIN_PUSH_REUSE, resolveCiStepActionUses, resolveCiSubActionUses, type CiGateContract, @@ -323,6 +324,14 @@ function jobImage(job: CiWorkflowJob): string | undefined { return undefined; } +function hasMainPushReuse(job: CiWorkflowJob): boolean { + return job.steps.some(({ kind }) => kind === "main-push-reuse"); +} + +function notMainPushReused(): string { + return `steps.${MAIN_PUSH_REUSE.stepId}.outputs.reuse != 'true'`; +} + function renderStep( job: CiWorkflowJob, step: CiWorkflowStep, @@ -334,6 +343,7 @@ function renderStep( return [ ` - uses: ${requiredStepActionUses(step.kind)}`, " with:", + ...(hasMainPushReuse(job) ? [" fetch-depth: 2"] : []), " persist-credentials: false", ]; case "setup-node": @@ -376,12 +386,24 @@ function renderStep( " corepack enable", " corepack pnpm install --frozen-lockfile --ignore-scripts", ]; + case "main-push-reuse": + // FE-1 (CI-FE-0004): decide on refs/heads/main push whether this merge + // job can reuse the PR run's green result for the same git tree. + return [ + " - name: Check main push reuse", + ` id: ${MAIN_PUSH_REUSE.stepId}`, + " if: ${{ gitea.event_name == 'push' && gitea.ref == 'refs/heads/main' }}", + " env:", + " GITEA_TOKEN: ${{ gitea.token }}", + ` run: node ${MAIN_PUSH_REUSE.script} --job ${shellDoubleQuoted(job.displayName)} --github-output "$GITHUB_OUTPUT"`, + ]; case "browser-install": if (step.image) { // The job image holds the browsers and their OS libraries; the goldens' // faces are still OS packages it lacks, and it ships no package lists. return [ " - name: Install visual-test fonts", + ...(hasMainPushReuse(job) ? [` if: \${{ ${notMainPushReused()} }}`] : []), " run: |", " $(command -v sudo || true) apt-get update", ` $(command -v sudo || true) ${VISUAL_TEST_FONT_INSTALL_ARGUMENTS}`, @@ -406,9 +428,12 @@ function renderStep( // shares one install; each gate is a step named by its id, and a failed // gate does not skip the ones after it, as the matrix entries did not. if (job.kind === "gate-sequence") { + const condition = hasMainPushReuse(job) + ? ` if: \${{ ${notMainPushReused()} && !cancelled() }}` + : " if: ${{ !cancelled() }}"; return job.gateIds.flatMap((gateId) => [ ` - name: ${yamlScalar(`${gateId} / ${index.gates.get(gateId)?.name ?? ""}`)}`, - " if: ${{ !cancelled() }}", + condition, ` run: ${gateRunCommand(gateId, index.gates.get(gateId))}`, ]); } @@ -424,7 +449,9 @@ function renderStep( case "run-script-tests": return [ " - name: Harness self-tests (scripts/tests)", - " if: ${{ !cancelled() }}", + hasMainPushReuse(job) + ? ` if: \${{ ${notMainPushReused()} && !cancelled() }}` + : " if: ${{ !cancelled() }}", " run: python3 -I -m unittest discover -s scripts/tests", ]; case "archive-candidate": { @@ -514,9 +541,16 @@ function renderStep( ]; } case "upload": { + const uploadCondition = step.always + ? hasMainPushReuse(job) + ? [` if: \${{ always() && ${notMainPushReused()} }}`] + : [" if: always()"] + : hasMainPushReuse(job) + ? [` if: \${{ ${notMainPushReused()} }}`] + : []; const lines = [ ` - name: Upload ${humanize(step.transferId)}`, - ...(step.always ? [" if: always()"] : []), + ...uploadCondition, ` uses: ${requiredStepActionUses(step.kind)}`, " with:", ` name: ${yamlScalar(step.name)}`, diff --git a/scripts/lib/main-push-reuse.ts b/scripts/lib/main-push-reuse.ts new file mode 100644 index 00000000..b5e81d02 --- /dev/null +++ b/scripts/lib/main-push-reuse.ts @@ -0,0 +1,422 @@ +import { spawnSync } from "node:child_process"; + +import { SKIPPED_GATE_LINE } from "./pr-gate-selection.ts"; +import { selectRepositoryPaths } from "./repository-layout.ts"; + +/** + * FE-1 (design-docs ci/03-time-reduction-plan.md 4.2 "FE-1 조건", D-1 (가)). + * When a push to refs/heads/main is a merge commit whose tree equals its + * pull-request head (HEAD^2), did not change dependency-cache key inputs + * (.nvmrc, pnpm-lock.yaml), and that PR head already passed the same merge job + * in Gitea Actions without skipping any gate, the merge job logs a skipped + * line and exits green without re-running its gates. + * + * Any missing, unreadable or ambiguous input fails open to running the job. + */ + +export const DEFAULT_MAIN_PUSH_REUSE_TIMEOUT_MS = 15_000; +const WORKFLOW_FILE_PREFIX = "quality-gates.yml@"; +const DEPENDENCY_CACHE_KEY_INPUTS = selectRepositoryPaths("dependency-cache-key"); +const REPOSITORY_PATTERN = /^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/u; +const SHA_PATTERN = /^[0-9a-f]{40}$/u; +const PR_REF_PATTERN = /refs\/pull\/(\d+)\//u; + +export type MainPushReusePrJob = + | Readonly<{ + runId: number; + prNumber: number; + conclusion: string; + status?: string | undefined; + log: string; + }> + | Readonly<{ error: string }>; + +export type MainPushReuseInput = Readonly<{ + event: string; + ref: string; + jobName: string; + parents: readonly string[]; + headTree: string; + prHeadTree?: string | undefined; + lockOrNodeChanged: boolean; + prJob?: MainPushReusePrJob | undefined; +}>; + +export type ReuseDecision = + | Readonly<{ reuse: true; line: string }> + | Readonly<{ reuse: false; reason: string }>; + +export function mainPushReuse(input: MainPushReuseInput): ReuseDecision { + if (input.event !== "push" || input.ref !== "refs/heads/main") { + return { reuse: false, reason: "main push가 아님" }; + } + if (input.parents.length !== 2) { + return { reuse: false, reason: "부모 둘인 병합 커밋이 아님" }; + } + if (!input.headTree || !input.prHeadTree || input.prHeadTree !== input.headTree) { + return { reuse: false, reason: "트리가 PR head와 다름" }; + } + if (input.lockOrNodeChanged) { + return { reuse: false, reason: "pnpm-lock.yaml 또는 .nvmrc가 바뀜" }; + } + if (!input.prJob || "error" in input.prJob) { + return { reuse: false, reason: `PR run을 못 읽음: ${input.prJob?.error ?? "없음"}` }; + } + if (input.prJob.status && input.prJob.status !== "completed" && input.prJob.status !== "success") { + return { reuse: false, reason: `PR run ${input.prJob.runId}의 이 job 상태가 ${input.prJob.status}` }; + } + if (input.prJob.conclusion !== "success") { + return { reuse: false, reason: `PR run ${input.prJob.runId}의 이 job이 ${input.prJob.conclusion}` }; + } + if (input.prJob.log.trim().length === 0) { + return { reuse: false, reason: `PR run ${input.prJob.runId}의 이 job 로그가 비어 있음` }; + } + const skipped = input.prJob.log + .split(/\r?\n/u) + .some((line) => SKIPPED_GATE_LINE.test(line.replace(/^\S+Z /u, ""))); + if (skipped) { + return { reuse: false, reason: `PR run ${input.prJob.runId}가 이 job의 게이트를 건너뜀` }; + } + const line = + `건너뜀: ${input.jobName} — 트리 ${input.headTree.slice(0, 12)}가 ` + + `PR #${input.prJob.prNumber} run ${input.prJob.runId}에서 초록`; + if (!SKIPPED_GATE_LINE.test(line)) { + return { reuse: false, reason: `job 이름이 건너뜀 형식에 안 맞음: ${input.jobName}` }; + } + return { reuse: true, line }; +} + +export type MainPushReuseGit = ( + args: readonly string[], +) => Readonly<{ status: number | null; stdout: string; stderr: string }>; + +const runGit: MainPushReuseGit = (args) => { + const result = spawnSync("git", args, { encoding: "utf8" }); + return { status: result.status, stdout: result.stdout ?? "", stderr: result.stderr ?? "" }; +}; + +export type MainPushReuseFetch = ( + input: string, + init?: RequestInit, +) => Promise>; + +type GiteaWorkflowRun = Readonly<{ + id?: unknown; + event?: unknown; + head_sha?: unknown; + path?: unknown; + ref?: unknown; + pull_requests?: unknown; +}>; + +type GiteaActionJob = Readonly<{ + id?: unknown; + name?: unknown; + status?: unknown; + conclusion?: unknown; +}>; + +function extractPrNumber(run: GiteaWorkflowRun): number | undefined { + if (Array.isArray(run.pull_requests)) { + for (const entry of run.pull_requests) { + if ( + entry && + typeof entry === "object" && + "number" in entry && + typeof entry.number === "number" && + Number.isInteger(entry.number) && + entry.number > 0 + ) { + return entry.number; + } + } + } + for (const candidate of [run.path, run.ref]) { + if (typeof candidate !== "string") continue; + const match = PR_REF_PATTERN.exec(candidate); + if (!match) continue; + const parsed = Number.parseInt(match[1]!, 10); + if (Number.isInteger(parsed) && parsed > 0) return parsed; + } + return undefined; +} + +function formatFetchError(label: string, error: unknown): string { + if (error instanceof Error) { + if (error.name === "TimeoutError" || error.name === "AbortError") { + return `${label} 시간 초과`; + } + return `${label} 호출 실패: ${error.message}`; + } + return `${label} 호출 실패`; +} + +async function fetchWithTimeout( + fetcher: MainPushReuseFetch, + url: string, + token: string, + accept: string, + timeoutMs: number, + label: string, +): Promise } | { error: string }>> { + try { + const response = await fetcher(url, { + method: "GET", + headers: { + Authorization: `token ${token}`, + Accept: accept, + }, + signal: AbortSignal.timeout(timeoutMs), + }); + if (!response.ok) { + return { error: `${label} HTTP ${response.status}` }; + } + return { response }; + } catch (error) { + return { error: formatFetchError(label, error) }; + } +} + +export async function fetchPrJobForMainPushReuse( + options: Readonly<{ + apiBaseUrl: string; + repository: string; + token: string; + prHeadSha: string; + jobName: string; + fetcher?: MainPushReuseFetch | undefined; + timeoutMs?: number | undefined; + }>, +): Promise { + const fetcher = options.fetcher ?? globalThis.fetch; + const timeoutMs = options.timeoutMs ?? DEFAULT_MAIN_PUSH_REUSE_TIMEOUT_MS; + const base = options.apiBaseUrl.replace(/\/+$/u, ""); + if (!/^https?:\/\/[^/\s]+/u.test(base)) { + return { error: `API 주소가 올바르지 않음: ${options.apiBaseUrl || "(비어 있음)"}` }; + } + if (!REPOSITORY_PATTERN.test(options.repository)) { + return { error: `저장소 이름이 올바르지 않음: ${options.repository || "(비어 있음)"}` }; + } + if (options.token.trim().length === 0) { + return { error: "GITEA_TOKEN이 없음" }; + } + if (!SHA_PATTERN.test(options.prHeadSha)) { + return { error: `PR head SHA가 올바르지 않음: ${options.prHeadSha}` }; + } + + const repoBase = `${base}/repos/${options.repository}`; + const runsResult = await fetchWithTimeout( + fetcher, + `${repoBase}/actions/runs?head_sha=${encodeURIComponent(options.prHeadSha)}&event=pull_request`, + options.token, + "application/json", + timeoutMs, + "actions/runs", + ); + if ("error" in runsResult) return runsResult; + + let runsPayload: unknown; + try { + runsPayload = await runsResult.response.json(); + } catch (error) { + return { error: formatFetchError("actions/runs JSON", error) }; + } + const rawRuns = + runsPayload && typeof runsPayload === "object" && "workflow_runs" in runsPayload && Array.isArray(runsPayload.workflow_runs) + ? (runsPayload.workflow_runs as GiteaWorkflowRun[]) + : undefined; + if (!rawRuns) { + return { error: "actions/runs 응답에 workflow_runs 배열이 없음" }; + } + + const matchingRuns = rawRuns + .filter((run) => { + if (typeof run.id !== "number" || !Number.isInteger(run.id) || run.id <= 0) return false; + if (run.event !== "pull_request") return false; + if (run.head_sha !== options.prHeadSha) return false; + if (typeof run.path === "string" && run.path.length > 0 && !run.path.startsWith(WORKFLOW_FILE_PREFIX)) { + return false; + } + return true; + }) + .sort((left, right) => (right.id as number) - (left.id as number)); + + const latestRun = matchingRuns[0]; + if (!latestRun) { + return { error: `head_sha ${options.prHeadSha.slice(0, 12)}의 pull_request run이 없음` }; + } + const runId = latestRun.id as number; + const prNumber = extractPrNumber(latestRun); + if (prNumber === undefined) { + return { error: `PR run ${runId}에서 PR 번호를 찾지 못함` }; + } + + const jobsResult = await fetchWithTimeout( + fetcher, + `${repoBase}/actions/runs/${runId}/jobs?limit=50`, + options.token, + "application/json", + timeoutMs, + `actions/runs/${runId}/jobs`, + ); + if ("error" in jobsResult) return jobsResult; + + let jobsPayload: unknown; + try { + jobsPayload = await jobsResult.response.json(); + } catch (error) { + return { error: formatFetchError(`actions/runs/${runId}/jobs JSON`, error) }; + } + const rawJobs = + jobsPayload && typeof jobsPayload === "object" && "jobs" in jobsPayload && Array.isArray(jobsPayload.jobs) + ? (jobsPayload.jobs as GiteaActionJob[]) + : undefined; + if (!rawJobs) { + return { error: `PR run ${runId}의 jobs 응답에 jobs 배열이 없음` }; + } + + const matchingJobs = rawJobs.filter( + (job) => job.name === options.jobName && typeof job.id === "number" && Number.isInteger(job.id) && job.id > 0, + ); + if (matchingJobs.length !== 1) { + return { error: `PR run ${runId}에서 job "${options.jobName}"을 ${matchingJobs.length}건 찾음` }; + } + const job = matchingJobs[0]!; + const status = typeof job.status === "string" ? job.status : undefined; + const conclusion = typeof job.conclusion === "string" && job.conclusion.length > 0 ? job.conclusion : (status ?? "unknown"); + if ((status && status !== "completed" && status !== "success") || conclusion !== "success") { + return { runId, prNumber, status, conclusion, log: "" }; + } + + const logResult = await fetchWithTimeout( + fetcher, + `${repoBase}/actions/jobs/${job.id as number}/logs`, + options.token, + "text/plain", + timeoutMs, + `actions/jobs/${job.id as number}/logs`, + ); + if ("error" in logResult) return logResult; + + let logText: string; + try { + logText = await logResult.response.text(); + } catch (error) { + return { error: formatFetchError(`actions/jobs/${job.id as number}/logs 본문`, error) }; + } + return { runId, prNumber, status, conclusion, log: logText }; +} + +export function resolveApiBaseUrl(environment: NodeJS.ProcessEnv): string { + const direct = environment["GITHUB_API_URL"] ?? environment["GITEA_API_URL"]; + if (direct && direct.trim().length > 0) return direct.trim().replace(/\/+$/u, ""); + const server = environment["GITHUB_SERVER_URL"] ?? environment["GITEA_SERVER_URL"]; + if (server && server.trim().length > 0) return `${server.trim().replace(/\/+$/u, "")}/api/v1`; + return ""; +} + +export async function evaluateMainPushReuse( + options: Readonly<{ + jobName: string; + environment?: NodeJS.ProcessEnv | undefined; + git?: MainPushReuseGit | undefined; + fetcher?: MainPushReuseFetch | undefined; + timeoutMs?: number | undefined; + cacheKeyInputs?: readonly string[] | undefined; + }>, +): Promise { + const environment = options.environment ?? process.env; + const event = environment["GITHUB_EVENT_NAME"] ?? environment["GITEA_EVENT_NAME"] ?? ""; + const ref = environment["GITHUB_REF"] ?? environment["GITEA_REF"] ?? ""; + if (event !== "push" || ref !== "refs/heads/main") { + return mainPushReuse({ + event, + ref, + jobName: options.jobName, + parents: [], + headTree: "", + lockOrNodeChanged: false, + }); + } + + const git = options.git ?? runGit; + const parentsResult = git(["rev-list", "--parents", "-n", "1", "HEAD"]); + if (parentsResult.status !== 0) { + return { reuse: false, reason: `git 부모 커밋을 읽지 못함: ${parentsResult.stderr.trim() || `rc=${parentsResult.status}`}` }; + } + const [, ...parents] = parentsResult.stdout.trim().split(/\s+/u).filter(Boolean); + if (parents.length !== 2) { + return mainPushReuse({ + event, + ref, + jobName: options.jobName, + parents, + headTree: "", + lockOrNodeChanged: false, + }); + } + + const headTreeResult = git(["rev-parse", "HEAD^{tree}"]); + const prHeadTreeResult = git(["rev-parse", "HEAD^2^{tree}"]); + if (headTreeResult.status !== 0 || prHeadTreeResult.status !== 0) { + return { + reuse: false, + reason: `git 트리를 읽지 못함: ${(headTreeResult.stderr || prHeadTreeResult.stderr).trim() || "fetch-depth 확인 필요"}`, + }; + } + const headTree = headTreeResult.stdout.trim(); + const prHeadTree = prHeadTreeResult.stdout.trim(); + if (!headTree || !prHeadTree || headTree !== prHeadTree) { + return mainPushReuse({ + event, + ref, + jobName: options.jobName, + parents, + headTree, + prHeadTree, + lockOrNodeChanged: false, + }); + } + + const cacheKeyInputs = options.cacheKeyInputs ?? DEPENDENCY_CACHE_KEY_INPUTS; + const diffResult = git(["diff", "--name-only", "HEAD^1", "HEAD", "--", ...cacheKeyInputs]); + if (diffResult.status !== 0) { + return { + reuse: false, + reason: `의존성 캐시 입력 변경 여부를 읽지 못함: ${diffResult.stderr.trim() || `rc=${diffResult.status}`}`, + }; + } + const lockOrNodeChanged = diffResult.stdout.trim().length > 0; + if (lockOrNodeChanged) { + return mainPushReuse({ + event, + ref, + jobName: options.jobName, + parents, + headTree, + prHeadTree, + lockOrNodeChanged, + }); + } + + const prJob = await fetchPrJobForMainPushReuse({ + apiBaseUrl: resolveApiBaseUrl(environment), + repository: environment["GITHUB_REPOSITORY"] ?? environment["GITEA_REPOSITORY"] ?? "", + token: environment["GITEA_TOKEN"] ?? "", + prHeadSha: parents[1]!, + jobName: options.jobName, + fetcher: options.fetcher, + timeoutMs: options.timeoutMs, + }); + + return mainPushReuse({ + event, + ref, + jobName: options.jobName, + parents, + headTree, + prHeadTree, + lockOrNodeChanged, + prJob, + }); +} diff --git a/tests/unit/__snapshots__/ci-workflow-generation.test.ts.snap b/tests/unit/__snapshots__/ci-workflow-generation.test.ts.snap index 30cc9bf9..9ba7123b 100644 --- a/tests/unit/__snapshots__/ci-workflow-generation.test.ts.snap +++ b/tests/unit/__snapshots__/ci-workflow-generation.test.ts.snap @@ -49,6 +49,7 @@ jobs: steps: - uses: https://github.com/actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 with: + fetch-depth: 2 persist-credentials: false - name: Choose the dependency cache folder id: dependency-cache-root @@ -80,29 +81,35 @@ jobs: run: | corepack enable corepack pnpm install --frozen-lockfile --ignore-scripts + - name: Check main push reuse + id: main-push-reuse + if: \${{ gitea.event_name == 'push' && gitea.ref == 'refs/heads/main' }} + env: + GITEA_TOKEN: \${{ gitea.token }} + run: node scripts/ci/main-push-reuse.ts --job "merge / static checks" --github-output "$GITHUB_OUTPUT" - name: "FE-GATE-001 / manifest-lockfile" - if: \${{ !cancelled() }} + if: \${{ steps.main-push-reuse.outputs.reuse != 'true' && !cancelled() }} run: corepack pnpm ci:gate -- FE-GATE-001 - name: "FE-GATE-002 / lint" - if: \${{ !cancelled() }} + if: \${{ steps.main-push-reuse.outputs.reuse != 'true' && !cancelled() }} run: corepack pnpm ci:gate -- FE-GATE-002 - name: "FE-GATE-003 / typecheck" - if: \${{ !cancelled() }} + if: \${{ steps.main-push-reuse.outputs.reuse != 'true' && !cancelled() }} run: corepack pnpm ci:gate -- FE-GATE-003 - name: "FE-GATE-010 / architecture" - if: \${{ !cancelled() }} + if: \${{ steps.main-push-reuse.outputs.reuse != 'true' && !cancelled() }} run: corepack pnpm ci:gate -- FE-GATE-010 - name: "FE-GATE-011 / build" - if: \${{ !cancelled() }} + if: \${{ steps.main-push-reuse.outputs.reuse != 'true' && !cancelled() }} run: corepack pnpm ci:gate -- FE-GATE-011 - name: "FE-GATE-012 / bundle" - if: \${{ !cancelled() }} + if: \${{ steps.main-push-reuse.outputs.reuse != 'true' && !cancelled() }} run: corepack pnpm ci:gate -- FE-GATE-012 - name: Harness self-tests (scripts/tests) - if: \${{ !cancelled() }} + if: \${{ steps.main-push-reuse.outputs.reuse != 'true' && !cancelled() }} run: python3 -I -m unittest discover -s scripts/tests - name: Upload merge static evidence - if: always() + if: \${{ always() && steps.main-push-reuse.outputs.reuse != 'true' }} uses: https://github.com/ChristopherHX/gitea-upload-artifact@81f940d004763f986ba3582c007fd842dd5cb0d7 with: name: "merge-static-\${{ gitea.run_id }}" @@ -121,6 +128,7 @@ jobs: steps: - uses: https://github.com/actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 with: + fetch-depth: 2 persist-credentials: false - name: Choose the dependency cache folder id: dependency-cache-root @@ -152,26 +160,32 @@ jobs: run: | corepack enable corepack pnpm install --frozen-lockfile --ignore-scripts + - name: Check main push reuse + id: main-push-reuse + if: \${{ gitea.event_name == 'push' && gitea.ref == 'refs/heads/main' }} + env: + GITEA_TOKEN: \${{ gitea.token }} + run: node scripts/ci/main-push-reuse.ts --job "merge / tests" --github-output "$GITHUB_OUTPUT" - name: "FE-GATE-004 / runtime-schema" - if: \${{ !cancelled() }} + if: \${{ steps.main-push-reuse.outputs.reuse != 'true' && !cancelled() }} run: corepack pnpm ci:gate -- FE-GATE-004 - name: "FE-GATE-005 / unit" - if: \${{ !cancelled() }} + if: \${{ steps.main-push-reuse.outputs.reuse != 'true' && !cancelled() }} run: corepack pnpm ci:gate -- FE-GATE-005 - name: "FE-GATE-006 / component" - if: \${{ !cancelled() }} + if: \${{ steps.main-push-reuse.outputs.reuse != 'true' && !cancelled() }} run: corepack pnpm ci:gate -- FE-GATE-006 - name: "FE-GATE-007 / integration" - if: \${{ !cancelled() }} + if: \${{ steps.main-push-reuse.outputs.reuse != 'true' && !cancelled() }} run: corepack pnpm ci:gate -- FE-GATE-007 - name: "FE-GATE-013 / security" - if: \${{ !cancelled() }} + if: \${{ steps.main-push-reuse.outputs.reuse != 'true' && !cancelled() }} run: corepack pnpm ci:gate -- FE-GATE-013 --enter-host-environment - name: "FE-GATE-020 / removability" - if: \${{ !cancelled() }} + if: \${{ steps.main-push-reuse.outputs.reuse != 'true' && !cancelled() }} run: corepack pnpm ci:gate -- FE-GATE-020 - name: Upload merge test evidence - if: always() + if: \${{ always() && steps.main-push-reuse.outputs.reuse != 'true' }} uses: https://github.com/ChristopherHX/gitea-upload-artifact@81f940d004763f986ba3582c007fd842dd5cb0d7 with: name: "merge-test-\${{ gitea.run_id }}" @@ -192,6 +206,7 @@ jobs: steps: - uses: https://github.com/actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 with: + fetch-depth: 2 persist-credentials: false - name: Choose the dependency cache folder id: dependency-cache-root @@ -223,18 +238,25 @@ jobs: run: | corepack enable corepack pnpm install --frozen-lockfile --ignore-scripts + - name: Check main push reuse + id: main-push-reuse + if: \${{ gitea.event_name == 'push' && gitea.ref == 'refs/heads/main' }} + env: + GITEA_TOKEN: \${{ gitea.token }} + run: node scripts/ci/main-push-reuse.ts --job "merge / browser tests" --github-output "$GITHUB_OUTPUT" - name: Install visual-test fonts + if: \${{ steps.main-push-reuse.outputs.reuse != 'true' }} run: | $(command -v sudo || true) apt-get update $(command -v sudo || true) apt-get install -y fonts-noto-core fonts-noto-cjk fonts-noto-cjk-extra fonts-liberation - name: "FE-GATE-008 / e2e" - if: \${{ !cancelled() }} + if: \${{ steps.main-push-reuse.outputs.reuse != 'true' && !cancelled() }} run: corepack pnpm ci:gate -- FE-GATE-008 - name: "FE-GATE-009 / accessibility" - if: \${{ !cancelled() }} + if: \${{ steps.main-push-reuse.outputs.reuse != 'true' && !cancelled() }} run: corepack pnpm ci:gate -- FE-GATE-009 - name: Upload merge browser evidence - if: always() + if: \${{ always() && steps.main-push-reuse.outputs.reuse != 'true' }} uses: https://github.com/ChristopherHX/gitea-upload-artifact@81f940d004763f986ba3582c007fd842dd5cb0d7 with: name: "merge-browser-\${{ gitea.run_id }}" diff --git a/tests/unit/ci-workflow-generation.test.ts b/tests/unit/ci-workflow-generation.test.ts index 99d29d0e..fee0321c 100644 --- a/tests/unit/ci-workflow-generation.test.ts +++ b/tests/unit/ci-workflow-generation.test.ts @@ -1774,7 +1774,7 @@ describe("CI workflow generation", () => { const workflow = renderCiWorkflow(await loadCiGateContract(process.cwd())); const step = [ " - name: Harness self-tests (scripts/tests)", - " if: ${{ !cancelled() }}", + " if: ${{ steps.main-push-reuse.outputs.reuse != 'true' && !cancelled() }}", " run: python3 -I -m unittest discover -s scripts/tests", ].join("\n"); expect(workflow.split(step)).toHaveLength(2); @@ -1976,6 +1976,102 @@ describe("CI workflow generation", () => { }); }); + // FE-1 (CI-FE-0004, D-1 (가)): on a main push whose merge commit tree equals + // its PR head's tree and whose PR run passed the full job without skipping + // gates, each merge job skips its gates after frozen install. + describe("main push reuse", () => { + const jobSection = (workflow: string, jobId: string) => { + const start = workflow.indexOf(`\n ${jobId}:\n`); + expect(start, jobId).toBeGreaterThan(0); + const next = workflow.slice(start + 1).search(/\n {2}[a-z_]+:\n/u); + return workflow.slice(start + 1, next < 0 ? undefined : start + 1 + next + 1); + }; + const mergeJobs = [ + ["merge_static", "merge / static checks"], + ["merge_test", "merge / tests"], + ["merge_browser", "merge / browser tests"], + ] as const; + + it("checks main-push-reuse right after Frozen install in all three merge jobs and gates later steps on it", async () => { + const workflow = renderCiWorkflow(await loadCiGateContract(process.cwd())); + for (const [jobId, displayName] of mergeJobs) { + const job = jobSection(workflow, jobId); + const steps = job.split("\n - "); + const checkoutIndex = steps.findIndex((step) => step.startsWith("uses: https://github.com/actions/checkout@")); + const installIndex = steps.findIndex((step) => step.startsWith("name: Frozen install")); + const reuseIndex = steps.findIndex((step) => step.startsWith("name: Check main push reuse")); + const uploadIndex = steps.findIndex((step) => step.startsWith("name: Upload ")); + + expect(checkoutIndex, jobId).toBeGreaterThan(0); + expect(steps[checkoutIndex], jobId).toContain(" fetch-depth: 2"); + expect(steps[checkoutIndex], jobId).toContain(" persist-credentials: false"); + expect(installIndex, jobId).toBeGreaterThan(checkoutIndex); + expect(reuseIndex, jobId).toBe(installIndex + 1); + expect(steps[reuseIndex], jobId).toBe( + [ + "name: Check main push reuse", + " id: main-push-reuse", + " if: ${{ gitea.event_name == 'push' && gitea.ref == 'refs/heads/main' }}", + " env:", + " GITEA_TOKEN: ${{ gitea.token }}", + ` run: node scripts/ci/main-push-reuse.ts --job ${JSON.stringify(displayName)} --github-output "$GITHUB_OUTPUT"`, + ].join("\n"), + ); + + expect(uploadIndex, jobId).toBeGreaterThan(reuseIndex); + for (const step of steps.slice(reuseIndex + 1, uploadIndex)) { + expect(step, `${jobId}: ${step.split("\n")[0]}`).toContain( + "steps.main-push-reuse.outputs.reuse != 'true'", + ); + if (step.startsWith('name: "FE-GATE-') || step.startsWith("name: Harness self-tests")) { + expect(step, `${jobId}: ${step.split("\n")[0]}`).toContain( + "if: ${{ steps.main-push-reuse.outputs.reuse != 'true' && !cancelled() }}", + ); + } + } + expect(steps[uploadIndex], jobId).toContain( + "if: ${{ always() && steps.main-push-reuse.outputs.reuse != 'true' }}", + ); + } + }); + + it("never adds main-push-reuse or fetch-depth: 2 to main_gate or non-merge jobs", async () => { + const contract = await loadCiGateContract(process.cwd()); + const workflow = renderCiWorkflow(contract); + const mergeJobIds = new Set(mergeJobs.map(([id]) => id)); + for (const job of contract.jobs) { + if (mergeJobIds.has(job.id)) continue; + const section = jobSection(workflow, job.id); + expect(section, job.id).not.toContain("main-push-reuse"); + expect(section, job.id).not.toContain("fetch-depth: 2"); + } + const mainGate = jobSection(workflow, "main_gate"); + expect(mainGate).toContain("if: ${{ !cancelled() }}"); + expect(mainGate).toContain("if: always()"); + }); + + it("refuses main-push-reuse outside the three merge jobs or missing from a merge job", async () => { + const inMain = JSON.parse(JSON.stringify(await loadCiGateContract(process.cwd()))) as Record; + const mainJob = inMain.jobs.find((job: Record) => job.id === "main_gate"); + const mainInstall = mainJob.steps.findIndex((step: Record) => step.kind === "frozen-install"); + mainJob.steps.splice(mainInstall + 1, 0, { kind: "main-push-reuse" }); + expect(() => parseCiGateContract(inMain)).toThrow(/main-push-reuse is for the merge jobs only: main_gate/u); + + const inRelease = JSON.parse(JSON.stringify(await loadCiGateContract(process.cwd()))) as Record; + inRelease.jobs.find((job: Record) => job.id === "release_gate").steps.splice(3, 0, { + kind: "main-push-reuse", + }); + expect(() => parseCiGateContract(inRelease)).toThrow( + /step kind main-push-reuse is forbidden for gate-matrix job release_gate/u, + ); + + const dropped = JSON.parse(JSON.stringify(await loadCiGateContract(process.cwd()))) as Record; + const testJob = dropped.jobs.find((job: Record) => job.id === "merge_test"); + testJob.steps = testJob.steps.filter((step: Record) => step.kind !== "main-push-reuse"); + expect(() => parseCiGateContract(dropped)).toThrow(/canonical job step sequence drift: merge_test/u); + }); + }); + // The job container has neither systemd nor bubblewrap, so FE-GATE-013 runs // in the system container its contract names (hostEnvironment). ci:gate // enters it from the job, after the PR selection (fe-ci-next (2); the run diff --git a/tests/unit/main-push-reuse.test.ts b/tests/unit/main-push-reuse.test.ts new file mode 100644 index 00000000..a4ddee2d --- /dev/null +++ b/tests/unit/main-push-reuse.test.ts @@ -0,0 +1,403 @@ +import { mkdtemp, readFile, rm } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import path from "node:path"; + +import { afterEach, describe, expect, it } from "vitest"; + +import { runMainPushReuseCli } from "../../scripts/ci/main-push-reuse.ts"; +import { + evaluateMainPushReuse, + fetchPrJobForMainPushReuse, + mainPushReuse, + resolveApiBaseUrl, + type MainPushReuseFetch, + type MainPushReuseGit, + type MainPushReuseInput, +} from "../../scripts/lib/main-push-reuse.ts"; +import { SKIPPED_GATE_LINE } from "../../scripts/lib/pr-gate-selection.ts"; + +const HEAD_TREE = "79e288cd71a8448963c45d354cc4ac1f4bea7e08"; +const PARENT_1 = "1d7c92add17b97c43159d91404c323caa249695d"; +const PARENT_2 = "2b6e832c6767e1daef760253f2b513065d381145"; +const FULL_LOG = [ + "2026-12-02T17:49:53.6250769Z desktop-runner(version:v5.4.1)", + "2026-12-02T17:50:02.0000000Z PASS FE-GATE-001 manifest-lockfile", + "2026-12-02T17:50:22.0000000Z PASS FE-GATE-002 lint", +].join("\n"); + +function matchingInput(overrides: Partial = {}): MainPushReuseInput { + return { + event: "push", + ref: "refs/heads/main", + jobName: "merge / static checks", + parents: [PARENT_1, PARENT_2], + headTree: HEAD_TREE, + prHeadTree: HEAD_TREE, + lockOrNodeChanged: false, + prJob: { + runId: 688, + prNumber: 111, + status: "completed", + conclusion: "success", + log: FULL_LOG, + }, + ...overrides, + }; +} + +function jsonResponse(status: number, body: unknown): Pick { + return { + ok: status >= 200 && status < 300, + status, + json: async () => body, + text: async () => JSON.stringify(body), + }; +} + +function textResponse(status: number, body: string): Pick { + return { + ok: status >= 200 && status < 300, + status, + json: async () => { + throw new SyntaxError("not json"); + }, + text: async () => body, + }; +} + +function fakeGit(overrides: Readonly>> = {}): MainPushReuseGit { + return (args) => { + const key = args.join(" "); + const hit = overrides[key]; + if (hit) return { status: hit.status, stdout: hit.stdout ?? "", stderr: hit.stderr ?? "" }; + if (key === "rev-list --parents -n 1 HEAD") { + return { status: 0, stdout: `e5f7ac67d3c442827b15a212222aef4f4e83ef03 ${PARENT_1} ${PARENT_2}\n`, stderr: "" }; + } + if (key === "rev-parse HEAD^{tree}" || key === "rev-parse HEAD^2^{tree}") { + return { status: 0, stdout: `${HEAD_TREE}\n`, stderr: "" }; + } + if (args[0] === "diff") { + return { status: 0, stdout: "", stderr: "" }; + } + return { status: 1, stdout: "", stderr: `unexpected git args: ${key}` }; + }; +} + +function giteaFetcher( + overrides: Readonly<{ + runsResponse?: Pick | Error; + jobsResponse?: Pick | Error; + logsResponse?: Pick | Error; + calls?: string[]; + }> = {}, +): MainPushReuseFetch { + return async (url) => { + overrides.calls?.push(url); + if (url.includes("/actions/runs?")) { + if (overrides.runsResponse instanceof Error) throw overrides.runsResponse; + return ( + overrides.runsResponse ?? + jsonResponse(200, { + workflow_runs: [ + { + id: 688, + event: "pull_request", + head_sha: PARENT_2, + path: "quality-gates.yml@refs/pull/111/head", + pull_requests: [{ number: 111 }], + }, + ], + }) + ); + } + if (url.includes("/actions/runs/688/jobs")) { + if (overrides.jobsResponse instanceof Error) throw overrides.jobsResponse; + return ( + overrides.jobsResponse ?? + jsonResponse(200, { + jobs: [ + { id: 7797, name: "merge / static checks", status: "completed", conclusion: "success" }, + { id: 7798, name: "merge / tests", status: "completed", conclusion: "success" }, + { id: 7799, name: "merge / browser tests", status: "completed", conclusion: "success" }, + ], + }) + ); + } + if (url.includes("/actions/jobs/7797/logs")) { + if (overrides.logsResponse instanceof Error) throw overrides.logsResponse; + return overrides.logsResponse ?? textResponse(200, FULL_LOG); + } + throw new Error(`unexpected URL: ${url}`); + }; +} + +const temporaryDirectories: string[] = []; +afterEach(async () => { + await Promise.all(temporaryDirectories.splice(0).map((directory) => rm(directory, { recursive: true, force: true }))); +}); + +describe("mainPushReuse (FE-1 / CI-FE-0004)", () => { + it.each([ + "merge / static checks", + "merge / tests", + "merge / browser tests", + ])("reuses when all six conditions hold and formats a SKIPPED_GATE_LINE for %s", (jobName) => { + const decision = mainPushReuse(matchingInput({ jobName })); + expect(decision).toEqual({ + reuse: true, + line: `건너뜀: ${jobName} — 트리 79e288cd71a8가 PR #111 run 688에서 초록`, + }); + expect(decision.reuse && SKIPPED_GATE_LINE.test(decision.line)).toBe(true); + }); + + it.each([ + ["condition 1: non-push event", { event: "pull_request" }, /main push가 아님/u], + ["condition 1: non-main ref", { ref: "refs/heads/develop" }, /main push가 아님/u], + ["condition 1: release tag", { ref: "refs/tags/v1.0.0" }, /main push가 아님/u], + ["condition 2: single-parent commit", { parents: [PARENT_1] }, /부모 둘인 병합 커밋이 아님/u], + ["condition 2: octopus merge", { parents: [PARENT_1, PARENT_2, "0".repeat(40)] }, /부모 둘인 병합 커밋이 아님/u], + ["condition 2: different tree", { prHeadTree: "a".repeat(40) }, /트리가 PR head와 다름/u], + ["condition 2: missing prHeadTree", { prHeadTree: undefined }, /트리가 PR head와 다름/u], + ["condition 3: lockfile or .nvmrc changed", { lockOrNodeChanged: true }, /pnpm-lock\.yaml 또는 \.nvmrc가 바뀜/u], + ["condition 4: PR job failed", { prJob: { runId: 688, prNumber: 111, conclusion: "failure", log: FULL_LOG } }, /이 job이 failure/u], + ["condition 4: PR job cancelled", { prJob: { runId: 688, prNumber: 111, conclusion: "cancelled", log: FULL_LOG } }, /이 job이 cancelled/u], + ["condition 4: PR job still in progress", { prJob: { runId: 688, prNumber: 111, status: "in_progress", conclusion: "success", log: FULL_LOG } }, /상태가 in_progress/u], + [ + "condition 5: PR job skipped a gate (with ISO timestamp and CRLF)", + { + prJob: { + runId: 678, + prNumber: 109, + conclusion: "success", + log: "2026-12-02T14:05:00.6729233Z 건너뜀: FE-GATE-011 — 바뀐 파일 4개가 경로표에서 안 걸림\r\n", + }, + }, + /게이트를 건너뜀/u, + ], + [ + "condition 5: PR job skipped a gate (without timestamp)", + { + prJob: { + runId: 678, + prNumber: 109, + conclusion: "success", + log: "건너뜀: FE-GATE-020 — 바뀐 파일 2개가 경로표에서 안 걸림\n", + }, + }, + /게이트를 건너뜀/u, + ], + [ + "condition 5: empty PR job log", + { + prJob: { + runId: 688, + prNumber: 111, + conclusion: "success", + log: " \n", + }, + }, + /로그가 비어 있음/u, + ], + ["condition 6: PR job missing", { prJob: undefined }, /PR run을 못 읽음: 없음/u], + ["condition 6: API error", { prJob: { error: "actions/runs HTTP 403" } }, /PR run을 못 읽음: actions\/runs HTTP 403/u], + ["defensive: non-merge job name", { jobName: "main / self-tests and removal drills" }, /건너뜀 형식에 안 맞음/u], + ] as const)("returns reuse=false when %s", (_label, overrides, pattern) => { + const decision = mainPushReuse(matchingInput(overrides)); + expect(decision.reuse).toBe(false); + if (!decision.reuse) expect(decision.reason).toMatch(pattern); + }); +}); + +describe("fetchPrJobForMainPushReuse (condition 6 API errors and run selection)", () => { + const baseOptions = { + apiBaseUrl: "https://git.learn.hyeonworks.com/api/v1", + repository: "donghyeon.kang/clean-architecture-frontend-template", + token: "test-job-token", + prHeadSha: PARENT_2, + jobName: "merge / static checks", + } as const; + + it.each([ + ["HTTP 403 on actions/runs", { runsResponse: textResponse(403, "Forbidden") }, /actions\/runs HTTP 403/u], + ["HTTP 500 on actions/runs", { runsResponse: textResponse(500, "Internal Server Error") }, /actions\/runs HTTP 500/u], + ["HTTP 403 on jobs", { jobsResponse: textResponse(403, "Forbidden") }, /actions\/runs\/688\/jobs HTTP 403/u], + ["HTTP 500 on logs", { logsResponse: textResponse(500, "Error") }, /actions\/jobs\/7797\/logs HTTP 500/u], + [ + "timeout on actions/runs", + { runsResponse: Object.assign(new Error("timed out"), { name: "TimeoutError" }) }, + /actions\/runs 시간 초과/u, + ], + [ + "abort timeout on logs", + { logsResponse: Object.assign(new Error("aborted"), { name: "AbortError" }) }, + /actions\/jobs\/7797\/logs 시간 초과/u, + ], + ["network failure", { runsResponse: new Error("ECONNREFUSED") }, /ECONNREFUSED/u], + ] as const)("fails open on %s", async (_label, overrides, expectedError) => { + const prJob = await fetchPrJobForMainPushReuse({ + ...baseOptions, + fetcher: giteaFetcher(overrides), + }); + expect("error" in prJob).toBe(true); + if ("error" in prJob) expect(prJob.error).toMatch(expectedError); + const decision = mainPushReuse(matchingInput({ prJob })); + expect(decision.reuse).toBe(false); + }); + + it("picks the newest pull_request run for quality-gates.yml and tolerates a waiting run whose merge job succeeded", async () => { + const calls: string[] = []; + const fetcher = giteaFetcher({ + calls, + runsResponse: jsonResponse(200, { + workflow_runs: [ + { + id: 680, + event: "pull_request", + head_sha: PARENT_2, + status: "completed", + conclusion: "failure", + path: "quality-gates.yml@refs/pull/111/head", + pull_requests: [], + }, + { + id: 688, + event: "pull_request", + head_sha: PARENT_2, + status: "waiting", + conclusion: "", + path: "quality-gates.yml@refs/pull/111/head", + pull_requests: [], + }, + { + id: 690, + event: "pull_request", + head_sha: PARENT_2, + path: "other.yml@refs/pull/111/head", + pull_requests: [{ number: 111 }], + }, + ], + }), + }); + const prJob = await fetchPrJobForMainPushReuse({ ...baseOptions, fetcher }); + expect(prJob).toEqual({ + runId: 688, + prNumber: 111, + status: "completed", + conclusion: "success", + log: FULL_LOG, + }); + expect(calls).toHaveLength(3); + }); + + it("skips fetching logs when the matched PR job did not succeed", async () => { + const calls: string[] = []; + const prJob = await fetchPrJobForMainPushReuse({ + ...baseOptions, + fetcher: giteaFetcher({ + calls, + jobsResponse: jsonResponse(200, { + jobs: [{ id: 7797, name: "merge / static checks", status: "completed", conclusion: "failure" }], + }), + }), + }); + expect(prJob).toEqual({ + runId: 688, + prNumber: 111, + status: "completed", + conclusion: "failure", + log: "", + }); + expect(calls).toHaveLength(2); + }); +}); + +describe("evaluateMainPushReuse and CLI", () => { + const mainEnv: NodeJS.ProcessEnv = { + GITHUB_EVENT_NAME: "push", + GITHUB_REF: "refs/heads/main", + GITHUB_API_URL: "https://git.learn.hyeonworks.com/api/v1", + GITHUB_REPOSITORY: "donghyeon.kang/clean-architecture-frontend-template", + GITEA_TOKEN: "job-token", + }; + + it("resolves API base URL from GITHUB_API_URL or falls back to GITHUB_SERVER_URL/api/v1", () => { + expect(resolveApiBaseUrl({ GITHUB_API_URL: "https://git.example/api/v1/" })).toBe("https://git.example/api/v1"); + expect(resolveApiBaseUrl({ GITHUB_SERVER_URL: "https://git.example/" })).toBe("https://git.example/api/v1"); + expect(resolveApiBaseUrl({})).toBe(""); + }); + + it("short-circuits before API calls when lockfile changed or trees differ", async () => { + const lockCalls: string[] = []; + const lockChanged = await evaluateMainPushReuse({ + jobName: "merge / static checks", + environment: mainEnv, + git: fakeGit({ + "diff --name-only HEAD^1 HEAD -- .nvmrc pnpm-lock.yaml": { status: 0, stdout: "pnpm-lock.yaml\n" }, + }), + fetcher: giteaFetcher({ calls: lockCalls }), + }); + expect(lockChanged).toEqual({ reuse: false, reason: "pnpm-lock.yaml 또는 .nvmrc가 바뀜" }); + expect(lockCalls).toHaveLength(0); + + const treeCalls: string[] = []; + const treesDiffer = await evaluateMainPushReuse({ + jobName: "merge / static checks", + environment: mainEnv, + git: fakeGit({ + "rev-parse HEAD^2^{tree}": { status: 0, stdout: `${"a".repeat(40)}\n` }, + }), + fetcher: giteaFetcher({ calls: treeCalls }), + }); + expect(treesDiffer).toEqual({ reuse: false, reason: "트리가 PR head와 다름" }); + expect(treeCalls).toHaveLength(0); + }); + + it("writes reuse=true and prints the canonical skipped line via CLI", async () => { + const directory = await mkdtemp(path.join(tmpdir(), "main-push-reuse-cli-")); + temporaryDirectories.push(directory); + const outputFile = path.join(directory, "github-output"); + let printed = ""; + + const decision = await runMainPushReuseCli({ + argv: ["--job", "merge / static checks", "--github-output", outputFile], + environment: mainEnv, + git: fakeGit(), + fetcher: giteaFetcher(), + stdout: { + write(chunk: string | Uint8Array) { + printed += String(chunk); + return true; + }, + }, + }); + + expect(decision.reuse).toBe(true); + expect(SKIPPED_GATE_LINE.test(printed.trim())).toBe(true); + expect(await readFile(outputFile, "utf8")).toBe("reuse=true\n"); + }); + + it("writes reuse=false and never throws on API 403 via CLI", async () => { + const directory = await mkdtemp(path.join(tmpdir(), "main-push-reuse-cli-")); + temporaryDirectories.push(directory); + const outputFile = path.join(directory, "github-output"); + let printed = ""; + + const decision = await runMainPushReuseCli({ + argv: ["--job", "merge / static checks", "--github-output", outputFile], + environment: mainEnv, + git: fakeGit(), + fetcher: giteaFetcher({ runsResponse: textResponse(403, "Forbidden") }), + stdout: { + write(chunk: string | Uint8Array) { + printed += String(chunk); + return true; + }, + }, + }); + + expect(decision.reuse).toBe(false); + expect(printed).toContain("main push 재사용 안 함:"); + expect(printed).toContain("HTTP 403"); + expect(await readFile(outputFile, "utf8")).toBe("reuse=false\n"); + }); +});