From 0f096eebd69459ce1f003f1838f36fb38612a1c8 Mon Sep 17 00:00:00 2001 From: opficdev <162981733+opficdev@users.noreply.github.com> Date: Fri, 13 Nov 2026 18:24:19 +0900 Subject: [PATCH 01/11] =?UTF-8?q?ci:=20=EC=88=98=EC=A0=95=20=EC=9B=8C?= =?UTF-8?q?=ED=81=AC=ED=94=8C=EB=A1=9C=EC=9D=98=20Codex=20=EC=8B=A4?= =?UTF-8?q?=ED=96=89=20=EC=A0=84=20bubblewrap=20=EC=84=A4=EC=B9=98=20?= =?UTF-8?q?=EC=B6=94=EA=B0=80?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .github/workflows/auto-fix.yml | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/.github/workflows/auto-fix.yml b/.github/workflows/auto-fix.yml index b2c4dbc..c7ae46b 100644 --- a/.github/workflows/auto-fix.yml +++ b/.github/workflows/auto-fix.yml @@ -39,6 +39,11 @@ jobs: npm ci --prefix functions npm ci --prefix nestjs-api + - name: Install bubblewrap + run: | + sudo apt-get update + sudo apt-get install -y --no-install-recommends bubblewrap + - name: Write task env: ISSUE_NUMBER: ${{ github.event.issue.number }} From 7fdb898828c3906701dc612034bb9adb05b674b1 Mon Sep 17 00:00:00 2001 From: opficdev <162981733+opficdev@users.noreply.github.com> Date: Fri, 13 Nov 2026 18:24:26 +0900 Subject: [PATCH 02/11] =?UTF-8?q?feat:=20=EC=9D=BC=EC=9D=BC=20=EC=98=A4?= =?UTF-8?q?=EB=A5=98=20=EB=B6=84=EC=84=9D=20=ED=95=A8=EC=88=98=EB=A5=BC=20?= =?UTF-8?q?=ED=95=9C=20=EB=B2=88=EC=97=90=20=ED=95=98=EB=82=98=EB=A7=8C=20?= =?UTF-8?q?=EC=8B=A4=ED=96=89=ED=95=98=EB=8F=84=EB=A1=9D=20=EC=A0=9C?= =?UTF-8?q?=ED=95=9C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- functions/src/incident/daily.ts | 1 + functions/test/incident-daily.test.js | 6 ++++++ 2 files changed, 7 insertions(+) diff --git a/functions/src/incident/daily.ts b/functions/src/incident/daily.ts index 6f44e24..d0a3b0e 100644 --- a/functions/src/incident/daily.ts +++ b/functions/src/incident/daily.ts @@ -49,6 +49,7 @@ type AnalyzedGroup = { // 어제 신규, 급증, 회귀 이슈를 분석해 Discord 일일 요약으로 전송 export const sendDailyIncidentReport = onSchedule({ maxInstances: 1, + concurrency: 1, region: LOCATION, schedule: "0 9 * * *", timeZone: "Asia/Seoul", diff --git a/functions/test/incident-daily.test.js b/functions/test/incident-daily.test.js index 9d4948b..82f50f5 100644 --- a/functions/test/incident-daily.test.js +++ b/functions/test/incident-daily.test.js @@ -143,6 +143,12 @@ function discordMessages() { } (async () => { + // 겹친 호출이 같은 인스턴스에서 동시에 실행되지 않도록 한 번에 하나만 처리 + { + assert.strictEqual(sendDailyIncidentReport.__endpoint.maxInstances, 1); + assert.strictEqual(sendDailyIncidentReport.__endpoint.concurrency, 1); + } + // 분석 결과를 근거 검증과 위험도 계산을 거쳐 사용자 수 순서의 Discord 요약으로 전송하고, 분석 입력은 마스킹 { reset(); From 62cdb5b739571bbfa5078a4c8a8b99fb44324369 Mon Sep 17 00:00:00 2001 From: opficdev <162981733+opficdev@users.noreply.github.com> Date: Fri, 13 Nov 2026 18:24:43 +0900 Subject: [PATCH 03/11] =?UTF-8?q?feat:=20=EC=9D=B4=EC=8A=88=20=EC=83=9D?= =?UTF-8?q?=EC=84=B1=20=EA=B8=B0=EB=A1=9D=EC=9C=BC=EB=A1=9C=20=EA=B0=99?= =?UTF-8?q?=EC=9D=80=20=EC=98=A4=EB=A5=98=EC=9D=98=20=EC=9D=B4=EC=8A=88=20?= =?UTF-8?q?=EC=A4=91=EB=B3=B5=20=EC=83=9D=EC=84=B1=20=EB=B0=A9=EC=A7=80?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- functions/src/common/firestorePath.ts | 8 ++- functions/src/incident/github.ts | 46 ++++++++++++- functions/src/incident/record.ts | 27 ++++++++ functions/test/incident-daily.test.js | 13 ++++ functions/test/incident-github.test.js | 91 +++++++++++++++++++++++++- 5 files changed, 182 insertions(+), 3 deletions(-) create mode 100644 functions/src/incident/record.ts diff --git a/functions/src/common/firestorePath.ts b/functions/src/common/firestorePath.ts index 5f771c6..c5db0ca 100644 --- a/functions/src/common/firestorePath.ts +++ b/functions/src/common/firestorePath.ts @@ -8,7 +8,8 @@ export namespace FirestorePath { authCredentials = "authCredentials", providers = "providers", oauthSessions = "oauthSessions", - oauthTickets = "oauthTickets" + oauthTickets = "oauthTickets", + incidentIssues = "incidentIssues" } export enum UserDataDocument { @@ -90,4 +91,9 @@ export namespace FirestorePath { export function oauthTicket(ticket: string): string { return `${oauthTickets}/${ticket}`; } + + // Crashlytics 이슈 그룹 식별 키에 대응하는 서버 전용 GitHub 이슈 기록 문서 경로 + export function incidentIssue(markerKey: string): string { + return `${Collection.incidentIssues}/${markerKey}`; + } } diff --git a/functions/src/incident/github.ts b/functions/src/incident/github.ts index 2f48e85..4c1e9f7 100644 --- a/functions/src/incident/github.ts +++ b/functions/src/incident/github.ts @@ -1,6 +1,10 @@ import axios from "axios"; import * as logger from "firebase-functions/logger"; import { toError } from "../common/error"; +import { + readIssueRecord, + writeIssueRecord +} from "./record"; // 이슈를 만드는 GitHub 저장소. 자동 수정 워크플로가 있는 저장소 하나에만 만듦 const repository = "DevLog-Labs/Firebase"; @@ -76,8 +80,9 @@ async function syncDraft( draft: IncidentIssueDraft, openIssues: Map ): Promise { - const existing = openIssues.get(draft.markerKey); try { + const existing = openIssues.get(draft.markerKey) + ?? await findRecordedOpenIssue(token, draft.markerKey); if (existing !== undefined) { await request(token, "post", `/repos/${repository}/issues/${existing}/comments`, { body: draft.updateComment @@ -90,6 +95,7 @@ async function syncDraft( body: draft.body, labels: draft.labels }) as { number: number }; + await saveIssueRecord(draft.markerKey, created.number); return { markerKey: draft.markerKey, action: "created", number: created.number }; } catch (error) { logger.error("이슈 생성 또는 갱신 실패", toError(error), { markerKey: draft.markerKey }); @@ -97,6 +103,44 @@ async function syncDraft( } } +// 목록에 아직 반영되지 않은 이슈를 찾으려고 기록된 이슈 번호를 조회해 열려 있을 때만 반환 +// 기록 조회가 실패하면 기록이 없는 것으로 처리 +async function findRecordedOpenIssue( + token: string, + markerKey: string +): Promise { + let recorded: number | undefined; + try { + recorded = await readIssueRecord(markerKey); + } catch (error) { + logger.warn("이슈 기록 조회 실패", toError(error), { markerKey }); + return undefined; + } + if (recorded === undefined) { return undefined; } + + const issue = await request( + token, + "get", + `/repos/${repository}/issues/${recorded}`, + undefined, + [404, 410] + ) as { state?: string }; + return issue.state === "open" ? recorded : undefined; +} + +// 새로 만든 이슈 번호를 기록 +// 기록이 실패해도 이슈 생성 결과는 유지하고 로그만 남김 +async function saveIssueRecord( + markerKey: string, + number: number +): Promise { + try { + await writeIssueRecord(markerKey, number); + } catch (error) { + logger.error("이슈 기록 저장 실패", toError(error), { markerKey, number }); + } +} + // 저장소에 없는 라벨을 생성. 이미 있으면 그대로 사용 async function ensureLabels(token: string): Promise { for (const spec of labelSpecs) { diff --git a/functions/src/incident/record.ts b/functions/src/incident/record.ts new file mode 100644 index 0000000..ef814b4 --- /dev/null +++ b/functions/src/incident/record.ts @@ -0,0 +1,27 @@ +import { + FieldValue, + getFirestore +} from "firebase-admin/firestore"; +import { FirestorePath } from "../common/firestorePath"; + +// 식별 키로 기록된 GitHub 이슈 번호 조회 +// 기록이 없으면 undefined 반환 +export async function readIssueRecord(markerKey: string): Promise { + const snapshot = await getFirestore().doc(FirestorePath.incidentIssue(markerKey)).get(); + const number = snapshot.get("number"); + return typeof number === "number" ? number : undefined; +} + +// 새로 만든 GitHub 이슈 번호를 식별 키로 기록 +// 이전 기록은 덮어씀 +export async function writeIssueRecord( + markerKey: string, + number: number +): Promise { + await getFirestore().doc(FirestorePath.incidentIssue(markerKey)).set({ + // 마지막으로 만든 GitHub 이슈 번호 + number, + // 기록 시각 + createdAt: FieldValue.serverTimestamp() + }); +} diff --git a/functions/test/incident-daily.test.js b/functions/test/incident-daily.test.js index 82f50f5..f88eb7d 100644 --- a/functions/test/incident-daily.test.js +++ b/functions/test/incident-daily.test.js @@ -38,6 +38,19 @@ require.cache[require.resolve("firebase-functions/logger")] = { } }; +const firestore = require("firebase-admin/firestore"); +require.cache[require.resolve("firebase-admin/firestore")] = { + exports: { + ...firestore, + getFirestore: () => ({ + doc: () => ({ + async get() { return { get: () => undefined }; }, + async set() {} + }) + }) + } +}; + const { sendDailyIncidentReport } = require("../lib/incident/daily"); const flagNames = [ diff --git a/functions/test/incident-github.test.js b/functions/test/incident-github.test.js index aae8be8..9b737c7 100644 --- a/functions/test/incident-github.test.js +++ b/functions/test/incident-github.test.js @@ -2,8 +2,31 @@ const assert = require("assert"); const axios = require("axios"); const errorLogs = []; +const warnLogs = []; require.cache[require.resolve("firebase-functions/logger")] = { - exports: { error: (...values) => errorLogs.push(values), warn() {}, info() {} } + exports: { error: (...values) => errorLogs.push(values), warn: (...values) => warnLogs.push(values), info() {} } +}; + +const records = new Map(); +let recordFailure; +const firestore = require("firebase-admin/firestore"); +require.cache[require.resolve("firebase-admin/firestore")] = { + exports: { + ...firestore, + getFirestore: () => ({ + doc: (path) => ({ + async get() { + if (recordFailure === "read") { throw new Error("read failed"); } + const data = records.get(path); + return { get: (field) => data?.[field] }; + }, + async set(data) { + if (recordFailure === "write") { throw new Error("write failed"); } + records.set(path, data); + } + }) + }) + } }; const { syncIncidentIssues } = require("../lib/incident/github"); @@ -32,6 +55,7 @@ function draft(markerKey, labels = ["crashlytics"]) { const requests = []; let openIssues = []; +let issueStates = {}; let failures = {}; axios.request = async (config) => { requests.push(config); @@ -41,6 +65,11 @@ axios.request = async (config) => { if (override === "network") { throw new Error(`failed ${config.headers.Authorization}`); } if (override) { return { status: override, data: {} }; } + const single = /\/issues\/(\d+)$/.exec(path); + if (config.method === "get" && single !== null) { + const state = issueStates[single[1]]; + return state === undefined ? { status: 404, data: {} } : { status: 200, data: { state } }; + } if (config.method === "get") { return { status: 200, data: openIssues }; } @@ -51,8 +80,12 @@ axios.request = async (config) => { function reset() { requests.length = 0; errorLogs.length = 0; + warnLogs.length = 0; openIssues = []; + issueStates = {}; failures = {}; + records.clear(); + recordFailure = undefined; } function calls(method, url) { @@ -86,6 +119,62 @@ function calls(method, url) { assert.strictEqual(created.headers["User-Agent"], "DevLog-Firebase"); assert.strictEqual(results[0].action, "created"); assert.ok(results[0].number > 100); + assert.strictEqual(records.get("incidentIssues/a:503").number, results[0].number); + } + + // 목록에 아직 반영되지 않았어도 기록된 이슈가 열려 있으면 댓글로 갱신하고 새로 만들지 않음 + { + reset(); + records.set("incidentIssues/a:503", { number: 7 }); + issueStates["7"] = "open"; + + const results = await syncIncidentIssues(token, [draft("a:503")]); + + assert.deepStrictEqual(results, [{ markerKey: "a:503", action: "commented", number: 7 }]); + assert.strictEqual(calls("post", `${firebaseUrl}/issues/7/comments`)[0].data.body, "갱신 a:503"); + assert.strictEqual(calls("post", `${firebaseUrl}/issues`).length, 0); + } + + // 기록된 이슈가 닫혔거나 삭제됐으면 새 이슈를 만들고 기록을 새 번호로 교체 + { + reset(); + records.set("incidentIssues/a:503", { number: 7 }); + records.set("incidentIssues/b:500", { number: 8 }); + issueStates["7"] = "closed"; + + const results = await syncIncidentIssues(token, [draft("a:503"), draft("b:500")]); + + assert.deepStrictEqual(results.map((result) => result.action), ["created", "created"]); + assert.strictEqual(records.get("incidentIssues/a:503").number, results[0].number); + assert.strictEqual(records.get("incidentIssues/b:500").number, results[1].number); + } + + // 기록된 이슈의 조회가 실패하면 중복을 피하려고 만들지 않고 실패로 기록 + { + reset(); + records.set("incidentIssues/a:503", { number: 7 }); + failures["get /repos/DevLog-Labs/Firebase/issues/7"] = 500; + + const results = await syncIncidentIssues(token, [draft("a:503")]); + + assert.deepStrictEqual(results, [{ markerKey: "a:503", action: "failed", number: null }]); + assert.strictEqual(calls("post", `${firebaseUrl}/issues`).length, 0); + } + + // 기록 조회가 실패하면 이슈를 만들고, 기록 저장이 실패해도 생성 결과를 유지 + { + reset(); + recordFailure = "read"; + const read = await syncIncidentIssues(token, [draft("a:503")]); + assert.strictEqual(read[0].action, "created"); + assert.strictEqual(warnLogs.length, 1); + + reset(); + recordFailure = "write"; + const written = await syncIncidentIssues(token, [draft("a:503")]); + assert.strictEqual(written[0].action, "created"); + assert.ok(written[0].number > 100); + assert.strictEqual(errorLogs.length, 1); } // 같은 식별 표식의 열린 이슈가 있으면 댓글로 갱신하고 풀 리퀘스트와 표식 없는 이슈는 무시 From 85c9fce2d31d45b948a10e9724814717bfa29224 Mon Sep 17 00:00:00 2001 From: opficdev <162981733+opficdev@users.noreply.github.com> Date: Fri, 13 Nov 2026 18:24:43 +0900 Subject: [PATCH 04/11] =?UTF-8?q?docs:=20Crashlytics=20=EC=A4=91=EB=B3=B5?= =?UTF-8?q?=20=EB=B0=A9=EC=A7=80=20=EB=8F=99=EC=9E=91=EA=B3=BC=20=EC=9A=B4?= =?UTF-8?q?=EC=98=81=20=ED=99=95=EC=9D=B8=20=EB=B0=A9=EB=B2=95=20=EB=AC=B8?= =?UTF-8?q?=EC=84=9C=ED=99=94?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 21 ++++++++++++++++++--- 1 file changed, 18 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 47cfb94..0011927 100644 --- a/README.md +++ b/README.md @@ -51,7 +51,7 @@ Cloud Run 배포와 직접 호출 검증은 [`docs/cloud-run-staging.md`](docs/c 3. 규칙으로 고칠 위치를 서버, iOS, 공동 중 하나로 정합니다. REST 응답이 없는 오류는 iOS로 분류합니다. 4. OpenAI 모델이 판단마다 근거를 인용한 JSON을 내고, 코드가 인용한 원문을 검증한 뒤 위험도를 계산합니다. 알림 등급은 영향도와 심각도 중 큰 값입니다. 5. 분석한 모든 오류를 Discord 요약으로 보냅니다. 등급 2 이상 상위 5건은 상세로, 나머지는 한 줄로 표시합니다. -6. 자동 수정 자격이 있는 오류만 이 저장소에 `auto-fix` 라벨이 붙은 이슈로 만듭니다. 같은 오류의 열린 이슈가 있으면 댓글로 갱신합니다. +6. 자동 수정 자격이 있는 오류만 이 저장소에 `auto-fix` 라벨이 붙은 이슈로 만듭니다. 같은 오류의 열린 이슈가 있으면 댓글로 갱신합니다. 새로 만든 이슈 번호는 Firestore `incidentIssues/{식별 키}`에 기록해, 목록 조회에 아직 반영되지 않은 이슈도 같은 오류의 이슈로 찾습니다. 7. `.github/workflows/auto-fix.yml`이 `auto-fix` 라벨이 붙은 이슈를 Codex로 수정하고 Draft PR을 올립니다. 머지는 사람이 합니다. 자동 수정 자격이 없는 오류는 이슈를 만들지 않고 Discord 요약에서 끝납니다. @@ -66,7 +66,7 @@ Cloud Run 배포와 직접 호출 검증은 [`docs/cloud-run-staging.md`](docs/c - 변경 위험과 불확실성이 모두 1 이하 - 데이터 손실과 보안 문제가 없다는 판단에 근거가 있음 -수정 워크플로는 변경이 300줄을 넘거나 `.github`, 인증 코드, 설정, 의존성 파일을 건드리면 PR을 만들지 않고 이슈에 사유를 댓글로 남깁니다. 같은 이름의 브랜치(`auto-fix/issue-<번호>`)가 이미 있으면 PR을 만들지 않습니다. +수정 워크플로는 Codex 실행 전에 `functions`와 `nestjs-api` 의존성, Codex 샌드박스가 쓰는 `bubblewrap`을 설치합니다. 변경이 300줄을 넘거나 `.github`, 인증 코드, 설정, 의존성 파일을 건드리면 PR을 만들지 않고 이슈에 사유를 댓글로 남깁니다. 같은 이름의 브랜치(`auto-fix/issue-<번호>`)가 이미 있으면 PR을 만들지 않습니다. ### 필요한 설정 @@ -82,7 +82,7 @@ Cloud Run 배포와 직접 호출 검증은 [`docs/cloud-run-staging.md`](docs/c ### 수동 실행 -Cloud Scheduler 작업을 직접 실행해 하루 분량을 즉시 처리할 수 있습니다. 같은 날 연달아 실행하면 방금 만든 이슈가 목록 조회에 늦게 반영되어 같은 오류의 이슈가 중복으로 생길 수 있습니다. +Cloud Scheduler 작업을 직접 실행해 하루 분량을 즉시 처리할 수 있습니다. 함수는 한 번에 하나만 실행하므로, 실행 중에 다시 실행하면 두 번째 요청은 잠시 대기한 뒤 실패합니다. 실행이 끝난 뒤 다시 실행하면 같은 오류는 새 이슈 없이 기존 이슈에 댓글로 갱신됩니다. ```bash gcloud scheduler jobs run firebase-schedule-sendDailyIncidentReport-asia-northeast3 \ @@ -90,6 +90,21 @@ gcloud scheduler jobs run firebase-schedule-sendDailyIncidentReport-asia-northea --location asia-northeast3 ``` +### 운영 확인 + +일일 실행은 다음 순서로 확인합니다. + +1. Cloud Scheduler 작업의 마지막 실행 상태가 성공인지 확인합니다. +2. Discord에 요약이 왔는지 확인합니다. 대상 오류가 없는 날은 `신규·급증·회귀 이슈가 없습니다` 메시지만 옵니다. `일일 오류 요약을 만들지 못했습니다` 메시지가 오면 `일일 오류 요약 생성 실패` 로그를 확인합니다. +3. Cloud Functions 로그에서 오류별 `이슈 분석 완료`와 `이슈 동기화 완료`의 `created`, `commented`, `failed` 수를 확인합니다. `이슈 기록 조회 실패`나 `이슈 기록 저장 실패`가 있으면 그 실행에서는 중복 방지 기록 없이 처리된 것입니다. + +자동 수정은 다음 순서로 확인합니다. + +1. 새 이슈에 `crashlytics`와 `auto-fix` 라벨이 붙었는지 확인합니다. +2. Actions에서 이슈 하나당 `Auto Fix` 실행이 하나인지 확인합니다. `crashlytics` 라벨 이벤트로 생긴 실행은 건너뜀으로 표시됩니다. +3. `codex` job에서 의존성과 `bubblewrap` 설치가 성공했는지, Codex 로그에 테스트 실행 결과가 있는지 확인합니다. +4. 변경이 있으면 `auto-fix/issue-<번호>` 브랜치와 Draft PR이 만들어지고 PR의 CI가 실행되는지 확인합니다. 제한에 걸리면 이슈에 사유 댓글이 남습니다. + ## 환경 변수 Firebase CLI의 `--project`로 staging 또는 prod Firebase project를 선택합니다. 각 project에 배포된 함수는 인자 없는 `getFirestore()`로 해당 project의 `(default)` database를 사용합니다. From 6071d84f9e2f687a47a35afd3c1d004422c481d0 Mon Sep 17 00:00:00 2001 From: opficdev <162981733+opficdev@users.noreply.github.com> Date: Fri, 13 Nov 2026 18:31:32 +0900 Subject: [PATCH 05/11] =?UTF-8?q?rollback:=20=EC=9D=B4=EC=8A=88=20?= =?UTF-8?q?=EC=83=9D=EC=84=B1=20=EA=B8=B0=EB=A1=9D=20=EA=B8=B0=EB=B0=98=20?= =?UTF-8?q?=EC=A4=91=EB=B3=B5=20=EB=B0=A9=EC=A7=80=20=EC=A0=9C=EA=B1=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 6 +- functions/src/common/firestorePath.ts | 8 +-- functions/src/incident/github.ts | 46 +------------ functions/src/incident/record.ts | 27 -------- functions/test/incident-daily.test.js | 13 ---- functions/test/incident-github.test.js | 91 +------------------------- 6 files changed, 6 insertions(+), 185 deletions(-) delete mode 100644 functions/src/incident/record.ts diff --git a/README.md b/README.md index 0011927..037b15e 100644 --- a/README.md +++ b/README.md @@ -51,7 +51,7 @@ Cloud Run 배포와 직접 호출 검증은 [`docs/cloud-run-staging.md`](docs/c 3. 규칙으로 고칠 위치를 서버, iOS, 공동 중 하나로 정합니다. REST 응답이 없는 오류는 iOS로 분류합니다. 4. OpenAI 모델이 판단마다 근거를 인용한 JSON을 내고, 코드가 인용한 원문을 검증한 뒤 위험도를 계산합니다. 알림 등급은 영향도와 심각도 중 큰 값입니다. 5. 분석한 모든 오류를 Discord 요약으로 보냅니다. 등급 2 이상 상위 5건은 상세로, 나머지는 한 줄로 표시합니다. -6. 자동 수정 자격이 있는 오류만 이 저장소에 `auto-fix` 라벨이 붙은 이슈로 만듭니다. 같은 오류의 열린 이슈가 있으면 댓글로 갱신합니다. 새로 만든 이슈 번호는 Firestore `incidentIssues/{식별 키}`에 기록해, 목록 조회에 아직 반영되지 않은 이슈도 같은 오류의 이슈로 찾습니다. +6. 자동 수정 자격이 있는 오류만 이 저장소에 `auto-fix` 라벨이 붙은 이슈로 만듭니다. 같은 오류의 열린 이슈가 있으면 댓글로 갱신합니다. 7. `.github/workflows/auto-fix.yml`이 `auto-fix` 라벨이 붙은 이슈를 Codex로 수정하고 Draft PR을 올립니다. 머지는 사람이 합니다. 자동 수정 자격이 없는 오류는 이슈를 만들지 않고 Discord 요약에서 끝납니다. @@ -82,7 +82,7 @@ Cloud Run 배포와 직접 호출 검증은 [`docs/cloud-run-staging.md`](docs/c ### 수동 실행 -Cloud Scheduler 작업을 직접 실행해 하루 분량을 즉시 처리할 수 있습니다. 함수는 한 번에 하나만 실행하므로, 실행 중에 다시 실행하면 두 번째 요청은 잠시 대기한 뒤 실패합니다. 실행이 끝난 뒤 다시 실행하면 같은 오류는 새 이슈 없이 기존 이슈에 댓글로 갱신됩니다. +Cloud Scheduler 작업을 직접 실행해 하루 분량을 즉시 처리할 수 있습니다. 함수는 한 번에 하나만 실행하므로, 실행 중에 다시 실행하면 두 번째 요청은 잠시 대기한 뒤 실패합니다. 같은 날 연달아 실행하면 방금 만든 이슈가 목록 조회에 늦게 반영되어 같은 오류의 이슈가 중복으로 생길 수 있습니다. ```bash gcloud scheduler jobs run firebase-schedule-sendDailyIncidentReport-asia-northeast3 \ @@ -96,7 +96,7 @@ gcloud scheduler jobs run firebase-schedule-sendDailyIncidentReport-asia-northea 1. Cloud Scheduler 작업의 마지막 실행 상태가 성공인지 확인합니다. 2. Discord에 요약이 왔는지 확인합니다. 대상 오류가 없는 날은 `신규·급증·회귀 이슈가 없습니다` 메시지만 옵니다. `일일 오류 요약을 만들지 못했습니다` 메시지가 오면 `일일 오류 요약 생성 실패` 로그를 확인합니다. -3. Cloud Functions 로그에서 오류별 `이슈 분석 완료`와 `이슈 동기화 완료`의 `created`, `commented`, `failed` 수를 확인합니다. `이슈 기록 조회 실패`나 `이슈 기록 저장 실패`가 있으면 그 실행에서는 중복 방지 기록 없이 처리된 것입니다. +3. Cloud Functions 로그에서 오류별 `이슈 분석 완료`와 `이슈 동기화 완료`의 `created`, `commented`, `failed` 수를 확인합니다. 자동 수정은 다음 순서로 확인합니다. diff --git a/functions/src/common/firestorePath.ts b/functions/src/common/firestorePath.ts index c5db0ca..5f771c6 100644 --- a/functions/src/common/firestorePath.ts +++ b/functions/src/common/firestorePath.ts @@ -8,8 +8,7 @@ export namespace FirestorePath { authCredentials = "authCredentials", providers = "providers", oauthSessions = "oauthSessions", - oauthTickets = "oauthTickets", - incidentIssues = "incidentIssues" + oauthTickets = "oauthTickets" } export enum UserDataDocument { @@ -91,9 +90,4 @@ export namespace FirestorePath { export function oauthTicket(ticket: string): string { return `${oauthTickets}/${ticket}`; } - - // Crashlytics 이슈 그룹 식별 키에 대응하는 서버 전용 GitHub 이슈 기록 문서 경로 - export function incidentIssue(markerKey: string): string { - return `${Collection.incidentIssues}/${markerKey}`; - } } diff --git a/functions/src/incident/github.ts b/functions/src/incident/github.ts index 4c1e9f7..2f48e85 100644 --- a/functions/src/incident/github.ts +++ b/functions/src/incident/github.ts @@ -1,10 +1,6 @@ import axios from "axios"; import * as logger from "firebase-functions/logger"; import { toError } from "../common/error"; -import { - readIssueRecord, - writeIssueRecord -} from "./record"; // 이슈를 만드는 GitHub 저장소. 자동 수정 워크플로가 있는 저장소 하나에만 만듦 const repository = "DevLog-Labs/Firebase"; @@ -80,9 +76,8 @@ async function syncDraft( draft: IncidentIssueDraft, openIssues: Map ): Promise { + const existing = openIssues.get(draft.markerKey); try { - const existing = openIssues.get(draft.markerKey) - ?? await findRecordedOpenIssue(token, draft.markerKey); if (existing !== undefined) { await request(token, "post", `/repos/${repository}/issues/${existing}/comments`, { body: draft.updateComment @@ -95,7 +90,6 @@ async function syncDraft( body: draft.body, labels: draft.labels }) as { number: number }; - await saveIssueRecord(draft.markerKey, created.number); return { markerKey: draft.markerKey, action: "created", number: created.number }; } catch (error) { logger.error("이슈 생성 또는 갱신 실패", toError(error), { markerKey: draft.markerKey }); @@ -103,44 +97,6 @@ async function syncDraft( } } -// 목록에 아직 반영되지 않은 이슈를 찾으려고 기록된 이슈 번호를 조회해 열려 있을 때만 반환 -// 기록 조회가 실패하면 기록이 없는 것으로 처리 -async function findRecordedOpenIssue( - token: string, - markerKey: string -): Promise { - let recorded: number | undefined; - try { - recorded = await readIssueRecord(markerKey); - } catch (error) { - logger.warn("이슈 기록 조회 실패", toError(error), { markerKey }); - return undefined; - } - if (recorded === undefined) { return undefined; } - - const issue = await request( - token, - "get", - `/repos/${repository}/issues/${recorded}`, - undefined, - [404, 410] - ) as { state?: string }; - return issue.state === "open" ? recorded : undefined; -} - -// 새로 만든 이슈 번호를 기록 -// 기록이 실패해도 이슈 생성 결과는 유지하고 로그만 남김 -async function saveIssueRecord( - markerKey: string, - number: number -): Promise { - try { - await writeIssueRecord(markerKey, number); - } catch (error) { - logger.error("이슈 기록 저장 실패", toError(error), { markerKey, number }); - } -} - // 저장소에 없는 라벨을 생성. 이미 있으면 그대로 사용 async function ensureLabels(token: string): Promise { for (const spec of labelSpecs) { diff --git a/functions/src/incident/record.ts b/functions/src/incident/record.ts deleted file mode 100644 index ef814b4..0000000 --- a/functions/src/incident/record.ts +++ /dev/null @@ -1,27 +0,0 @@ -import { - FieldValue, - getFirestore -} from "firebase-admin/firestore"; -import { FirestorePath } from "../common/firestorePath"; - -// 식별 키로 기록된 GitHub 이슈 번호 조회 -// 기록이 없으면 undefined 반환 -export async function readIssueRecord(markerKey: string): Promise { - const snapshot = await getFirestore().doc(FirestorePath.incidentIssue(markerKey)).get(); - const number = snapshot.get("number"); - return typeof number === "number" ? number : undefined; -} - -// 새로 만든 GitHub 이슈 번호를 식별 키로 기록 -// 이전 기록은 덮어씀 -export async function writeIssueRecord( - markerKey: string, - number: number -): Promise { - await getFirestore().doc(FirestorePath.incidentIssue(markerKey)).set({ - // 마지막으로 만든 GitHub 이슈 번호 - number, - // 기록 시각 - createdAt: FieldValue.serverTimestamp() - }); -} diff --git a/functions/test/incident-daily.test.js b/functions/test/incident-daily.test.js index f88eb7d..82f50f5 100644 --- a/functions/test/incident-daily.test.js +++ b/functions/test/incident-daily.test.js @@ -38,19 +38,6 @@ require.cache[require.resolve("firebase-functions/logger")] = { } }; -const firestore = require("firebase-admin/firestore"); -require.cache[require.resolve("firebase-admin/firestore")] = { - exports: { - ...firestore, - getFirestore: () => ({ - doc: () => ({ - async get() { return { get: () => undefined }; }, - async set() {} - }) - }) - } -}; - const { sendDailyIncidentReport } = require("../lib/incident/daily"); const flagNames = [ diff --git a/functions/test/incident-github.test.js b/functions/test/incident-github.test.js index 9b737c7..aae8be8 100644 --- a/functions/test/incident-github.test.js +++ b/functions/test/incident-github.test.js @@ -2,31 +2,8 @@ const assert = require("assert"); const axios = require("axios"); const errorLogs = []; -const warnLogs = []; require.cache[require.resolve("firebase-functions/logger")] = { - exports: { error: (...values) => errorLogs.push(values), warn: (...values) => warnLogs.push(values), info() {} } -}; - -const records = new Map(); -let recordFailure; -const firestore = require("firebase-admin/firestore"); -require.cache[require.resolve("firebase-admin/firestore")] = { - exports: { - ...firestore, - getFirestore: () => ({ - doc: (path) => ({ - async get() { - if (recordFailure === "read") { throw new Error("read failed"); } - const data = records.get(path); - return { get: (field) => data?.[field] }; - }, - async set(data) { - if (recordFailure === "write") { throw new Error("write failed"); } - records.set(path, data); - } - }) - }) - } + exports: { error: (...values) => errorLogs.push(values), warn() {}, info() {} } }; const { syncIncidentIssues } = require("../lib/incident/github"); @@ -55,7 +32,6 @@ function draft(markerKey, labels = ["crashlytics"]) { const requests = []; let openIssues = []; -let issueStates = {}; let failures = {}; axios.request = async (config) => { requests.push(config); @@ -65,11 +41,6 @@ axios.request = async (config) => { if (override === "network") { throw new Error(`failed ${config.headers.Authorization}`); } if (override) { return { status: override, data: {} }; } - const single = /\/issues\/(\d+)$/.exec(path); - if (config.method === "get" && single !== null) { - const state = issueStates[single[1]]; - return state === undefined ? { status: 404, data: {} } : { status: 200, data: { state } }; - } if (config.method === "get") { return { status: 200, data: openIssues }; } @@ -80,12 +51,8 @@ axios.request = async (config) => { function reset() { requests.length = 0; errorLogs.length = 0; - warnLogs.length = 0; openIssues = []; - issueStates = {}; failures = {}; - records.clear(); - recordFailure = undefined; } function calls(method, url) { @@ -119,62 +86,6 @@ function calls(method, url) { assert.strictEqual(created.headers["User-Agent"], "DevLog-Firebase"); assert.strictEqual(results[0].action, "created"); assert.ok(results[0].number > 100); - assert.strictEqual(records.get("incidentIssues/a:503").number, results[0].number); - } - - // 목록에 아직 반영되지 않았어도 기록된 이슈가 열려 있으면 댓글로 갱신하고 새로 만들지 않음 - { - reset(); - records.set("incidentIssues/a:503", { number: 7 }); - issueStates["7"] = "open"; - - const results = await syncIncidentIssues(token, [draft("a:503")]); - - assert.deepStrictEqual(results, [{ markerKey: "a:503", action: "commented", number: 7 }]); - assert.strictEqual(calls("post", `${firebaseUrl}/issues/7/comments`)[0].data.body, "갱신 a:503"); - assert.strictEqual(calls("post", `${firebaseUrl}/issues`).length, 0); - } - - // 기록된 이슈가 닫혔거나 삭제됐으면 새 이슈를 만들고 기록을 새 번호로 교체 - { - reset(); - records.set("incidentIssues/a:503", { number: 7 }); - records.set("incidentIssues/b:500", { number: 8 }); - issueStates["7"] = "closed"; - - const results = await syncIncidentIssues(token, [draft("a:503"), draft("b:500")]); - - assert.deepStrictEqual(results.map((result) => result.action), ["created", "created"]); - assert.strictEqual(records.get("incidentIssues/a:503").number, results[0].number); - assert.strictEqual(records.get("incidentIssues/b:500").number, results[1].number); - } - - // 기록된 이슈의 조회가 실패하면 중복을 피하려고 만들지 않고 실패로 기록 - { - reset(); - records.set("incidentIssues/a:503", { number: 7 }); - failures["get /repos/DevLog-Labs/Firebase/issues/7"] = 500; - - const results = await syncIncidentIssues(token, [draft("a:503")]); - - assert.deepStrictEqual(results, [{ markerKey: "a:503", action: "failed", number: null }]); - assert.strictEqual(calls("post", `${firebaseUrl}/issues`).length, 0); - } - - // 기록 조회가 실패하면 이슈를 만들고, 기록 저장이 실패해도 생성 결과를 유지 - { - reset(); - recordFailure = "read"; - const read = await syncIncidentIssues(token, [draft("a:503")]); - assert.strictEqual(read[0].action, "created"); - assert.strictEqual(warnLogs.length, 1); - - reset(); - recordFailure = "write"; - const written = await syncIncidentIssues(token, [draft("a:503")]); - assert.strictEqual(written[0].action, "created"); - assert.ok(written[0].number > 100); - assert.strictEqual(errorLogs.length, 1); } // 같은 식별 표식의 열린 이슈가 있으면 댓글로 갱신하고 풀 리퀘스트와 표식 없는 이슈는 무시 From 6285a093160571933de9571c8f6f34ff4659f735 Mon Sep 17 00:00:00 2001 From: opficdev <162981733+opficdev@users.noreply.github.com> Date: Fri, 13 Nov 2026 18:43:55 +0900 Subject: [PATCH 06/11] =?UTF-8?q?feat:=20Discord=20=EC=9D=BC=EC=9D=BC=20?= =?UTF-8?q?=EC=9A=94=EC=95=BD=EC=97=90=20=EB=AF=B8=ED=95=B4=EA=B2=B0=20?= =?UTF-8?q?=EC=98=A4=EB=A5=98=20=EB=AA=A9=EB=A1=9D=20=EC=B6=94=EA=B0=80?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- functions/src/incident/discord.ts | 74 +++++++++++++++++++------ functions/test/incident-discord.test.js | 21 +++++++ 2 files changed, 78 insertions(+), 17 deletions(-) diff --git a/functions/src/incident/discord.ts b/functions/src/incident/discord.ts index 42a00e8..211f197 100644 --- a/functions/src/incident/discord.ts +++ b/functions/src/incident/discord.ts @@ -44,6 +44,9 @@ const maxRetryAfterSeconds = 10; // 등급별 embed 색상 const gradeColors = [0x95a5a6, 0xf1c40f, 0xe67e22, 0xc0392b]; +// 미해결 목록 embed 색상 +const ongoingColor = 0x3498db; + // 축 이름별 표시 이름 const axisLabels: Record = { impact: "영향도", @@ -70,6 +73,18 @@ export type SummaryItem = { metrics: ImpactMetrics; }; +// 일일 요약에 올리는 미해결 이슈 하나 +export type OngoingItem = { + // 요약에 보여 줄 오류 제목 + title: string; + // 추적 중인 GitHub 이슈 주소 + url: string; + // 대상 날짜에 오류를 겪은 고유 설치 수 + affectedUsers: number; + // 대상 날짜 발생 건수 + events: number; +}; + // Discord embed 필드 하나 type DiscordEmbedField = { // 필드 이름 @@ -107,9 +122,11 @@ export type DiscordMessage = { }; // 이슈 목록을 등급 순으로 정렬해 Discord 일일 요약 메시지 목록으로 변환 +// 열린 이슈로 추적 중인 미해결 오류는 마지막 embed에 한 줄씩 추가 export function buildDailySummary( items: SummaryItem[], - dateLabel: string + dateLabel: string, + ongoing: OngoingItem[] = [] ): DiscordMessage[] { const sorted = [...items].sort((left, right) => ( right.score.grade - left.score.grade @@ -124,8 +141,11 @@ export function buildDailySummary( if (brief.length > 0) { embeds.push(briefEmbed(brief)); } + if (ongoing.length > 0) { + embeds.push(ongoingEmbed(ongoing)); + } - return splitMessages(headerContent(dateLabel, sorted.length), embeds); + return splitMessages(headerContent(dateLabel, sorted.length, ongoing.length), embeds); } // 메시지 목록을 순서대로 웹훅에 전송 @@ -141,11 +161,13 @@ export async function sendDiscordMessages( // 요약 첫 메시지의 본문 생성 function headerContent( dateLabel: string, - total: number + total: number, + ongoing: number ): string { - return total === 0 + const detected = total === 0 ? `${dateLabel} 오류 요약 · 신규·급증·회귀 이슈가 없습니다` : `${dateLabel} 오류 요약 · 신규·급증·회귀 ${total}건`; + return ongoing === 0 ? detected : `${detected} · 미해결 ${ongoing}건`; } // 등급이 높은 이슈 하나의 상세 embed 생성 @@ -196,27 +218,45 @@ function detailEmbed(item: SummaryItem): DiscordEmbed { // 등급이 낮은 이슈들을 한 줄씩 담은 embed 생성 function briefEmbed(items: SummaryItem[]): DiscordEmbed { - const lines: string[] = []; - let length = 0; - for (const item of items) { - const line = `• [${plainTitle(item.title)}](${item.url}) · 등급 ${item.score.grade} · ${item.metrics.affectedUsers}명`; - if (length + line.length + 1 > maxDescriptionLength) { - lines.push(`…외 ${items.length - lines.length}건`); - break; - } - lines.push(line); - length += line.length + 1; - } - return { title: `그 외 ${items.length}건`, - description: lines.join("\n"), + description: limitedLines(items.map((item) => ( + `• [${plainTitle(item.title)}](${item.url}) · 등급 ${item.score.grade} · ${item.metrics.affectedUsers}명` + ))), color: gradeColors[items[0].score.grade], fields: [], footer: { text: `루브릭 ${items[0].score.rubricVersion}` } }; } +// 열린 이슈로 추적 중인 미해결 오류를 한 줄씩 담은 embed 생성 +function ongoingEmbed(items: OngoingItem[]): DiscordEmbed { + return { + title: `미해결 ${items.length}건`, + description: limitedLines(items.map((item) => ( + `• [${plainTitle(item.title)}](${item.url}) · ${item.affectedUsers}명 · ${item.events}건` + ))), + color: ongoingColor, + fields: [], + footer: { text: "열린 GitHub 이슈 기준" } + }; +} + +// 설명 최대 글자 수 안에 들어가는 줄까지만 담고 나머지는 남은 개수로 표시 +function limitedLines(lines: string[]): string { + const kept: string[] = []; + let length = 0; + for (const line of lines) { + if (length + line.length + 1 > maxDescriptionLength) { + kept.push(`…외 ${lines.length - kept.length}건`); + break; + } + kept.push(line); + length += line.length + 1; + } + return kept.join("\n"); +} + // 검증된 근거를 최대 개수만큼 한 줄씩 정리 function evidenceLines(riskEvidence: RiskEvidence): string { const lines = riskEvidence.evidence.slice(0, maxEvidenceLines).map((evidence) => ( diff --git a/functions/test/incident-discord.test.js b/functions/test/incident-discord.test.js index f5f0aa1..7161949 100644 --- a/functions/test/incident-discord.test.js +++ b/functions/test/incident-discord.test.js @@ -90,6 +90,27 @@ function totalLength(embed) { assert.ok(messages[0].content.includes("이슈가 없습니다")); } +// 신규·급증·회귀가 없어도 미해결 오류는 마지막 embed에 한 줄씩 담고 본문에 개수를 표시 +{ + const ongoing = [ + { title: "a[b](c)", url: "https://github.com/DevLog-Labs/Firebase/issues/7", affectedUsers: 4, events: 11 }, + { title: "d · 500", url: "https://github.com/DevLog-Labs/Firebase/issues/8", affectedUsers: 1, events: 2 } + ]; + const messages = buildDailySummary([item("x", 1)], "2026-10-28", ongoing); + const embeds = messages[0].embeds; + + assert.strictEqual(messages[0].content, "2026-10-28 오류 요약 · 신규·급증·회귀 1건 · 미해결 2건"); + assert.strictEqual(embeds.at(-1).title, "미해결 2건"); + assert.strictEqual( + embeds.at(-1).description, + "• [ab(c)](https://github.com/DevLog-Labs/Firebase/issues/7) · 4명 · 11건\n• [d · 500](https://github.com/DevLog-Labs/Firebase/issues/8) · 1명 · 2건" + ); + + const onlyOngoing = buildDailySummary([], "2026-10-28", ongoing); + assert.ok(onlyOngoing[0].content.endsWith("이슈가 없습니다 · 미해결 2건")); + assert.deepStrictEqual(onlyOngoing[0].embeds.map((embed) => embed.title), ["미해결 2건"]); +} + // 상세 embed는 높은 등급 상위 5개로 제한하고 나머지는 "그 외" 목록에 한 줄씩 담음 { const items = Array.from({ length: 12 }, (_, index) => item(`h${index}`, 100 + index)); From 726f858eb92cdde6bf64897fd9260a3fc8213824 Mon Sep 17 00:00:00 2001 From: opficdev <162981733+opficdev@users.noreply.github.com> Date: Fri, 13 Nov 2026 18:43:55 +0900 Subject: [PATCH 07/11] =?UTF-8?q?feat:=20=EC=97=B4=EB=A6=B0=20=EC=9D=B4?= =?UTF-8?q?=EC=8A=88=EA=B0=80=20=EC=9E=88=EB=8A=94=20=EC=98=A4=EB=A5=98?= =?UTF-8?q?=EC=9D=98=20=EC=A0=84=EB=82=A0=20=EB=B0=9C=EC=83=9D=EB=9F=89?= =?UTF-8?q?=EC=9D=84=20=EB=AF=B8=ED=95=B4=EA=B2=B0=EB=A1=9C=20=EB=A7=A4?= =?UTF-8?q?=EC=9D=BC=20=EB=B3=B4=EA=B3=A0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- functions/src/incident/context.ts | 66 ++++++++++++++++++++- functions/src/incident/daily.ts | 83 ++++++++++++++++++++++++--- functions/src/incident/github.ts | 20 +++++-- functions/src/incident/report.ts | 25 +++++++- functions/test/incident-daily.test.js | 72 +++++++++++++++++++++-- 5 files changed, 246 insertions(+), 20 deletions(-) diff --git a/functions/src/incident/context.ts b/functions/src/incident/context.ts index 3995cc7..a6f6f62 100644 --- a/functions/src/incident/context.ts +++ b/functions/src/incident/context.ts @@ -113,6 +113,30 @@ ORDER BY affectedUsers DESC, eventsDay DESC LIMIT @maxGroups `; +// 열린 이슈로 추적 중인 Crashlytics 이슈들의 대상 날짜 발생량을 이슈와 상태 코드 단위로 조회하는 쿼리 +const selectOccurrencesQuery = ` +WITH events AS ( + SELECT + issue_id, + issue_subtitle, + installation_uuid, + IFNULL((SELECT value FROM UNNEST(custom_keys) WHERE key = "restStatusCode"), "") AS status + FROM \`${crashlyticsTable}\` + WHERE event_timestamp >= @dayStart + AND event_timestamp < @dayEnd + AND issue_id IN UNNEST(@issueIds) +) +SELECT + issue_id AS issueId, + status AS restStatusCode, + ANY_VALUE(issue_subtitle) AS issueSubtitle, + COUNT(DISTINCT installation_uuid) AS affectedUsers, + COUNT(*) AS events +FROM events +GROUP BY issue_id, status +ORDER BY affectedUsers DESC, events DESC +`; + // 이슈 그룹의 대표 이벤트와 스택, 사용자 정보를 조회하는 쿼리 const selectSamplesQuery = ` SELECT @@ -182,6 +206,20 @@ export type ErrorGroup = { isSurge: boolean; }; +// 열린 이슈로 추적 중인 오류의 대상 날짜 발생량 +export type Occurrence = { + // Crashlytics 이슈 ID + issueId: string; + // 오류에 기록된 HTTP 상태 코드. REST 오류가 아니면 빈 문자열 + restStatusCode: string; + // Crashlytics 이슈 부제. 오류 도메인과 코드를 담음 + issueSubtitle: string; + // 대상 날짜에 오류를 겪은 고유 설치 수 + affectedUsers: number; + // 대상 날짜 발생 건수 + events: number; +}; + // 조회한 대표 이벤트 하나 type SampleEvent = { // 이벤트 ID @@ -283,6 +321,32 @@ export async function selectErrorGroups(date: string): Promise { })); } +// 지정한 Crashlytics 이슈들의 대상 날짜 발생량을 영향 사용자 수 순으로 조회 +// 발생하지 않은 이슈는 결과에서 빠짐 +export async function selectOccurrences( + date: string, + issueIds: string[] +): Promise { + if (issueIds.length === 0) { return []; } + + const { dayStart, dayEnd } = dayWindow(date); + const [rows] = await new BigQuery().query({ + query: selectOccurrencesQuery, + params: { + dayStart, + dayEnd, + issueIds + } + }); + return (rows as Occurrence[]).map((row) => ({ + issueId: row.issueId, + restStatusCode: row.restStatusCode, + issueSubtitle: row.issueSubtitle, + affectedUsers: Number(row.affectedUsers), + events: Number(row.events) + })); +} + // 이슈 그룹의 영향도 계산 입력 생성 export function toImpactMetrics(group: ErrorGroup): ImpactMetrics { return { @@ -292,7 +356,7 @@ export function toImpactMetrics(group: ErrorGroup): ImpactMetrics { } // 이슈 그룹을 Discord 요약에 보여 줄 제목 생성 -export function groupTitle(group: ErrorGroup): string { +export function groupTitle(group: Pick): string { return group.restStatusCode === "" ? group.issueSubtitle : `${group.issueSubtitle} · ${group.restStatusCode}`; diff --git a/functions/src/incident/daily.ts b/functions/src/incident/daily.ts index d0a3b0e..be4e723 100644 --- a/functions/src/incident/daily.ts +++ b/functions/src/incident/daily.ts @@ -12,6 +12,7 @@ import { groupTitle, issueUrl, selectErrorGroups, + selectOccurrences, toImpactMetrics, yesterdayInSeoul } from "./context"; @@ -20,9 +21,21 @@ import { buildDailySummary, sendDiscordMessages } from "./discord"; -import type { SummaryItem } from "./discord"; -import { syncIncidentIssues } from "./github"; -import { buildIncidentIssue } from "./report"; +import type { + OngoingItem, + SummaryItem +} from "./discord"; +import { + commentOnIssue, + githubIssueUrl, + listOpenIncidentIssues, + syncIncidentIssues +} from "./github"; +import { + buildIncidentIssue, + buildOngoingComment, + incidentMarkerKey +} from "./report"; import type { RiskEvidence } from "./schema"; import { scoreRisk } from "./score"; import { verifyRiskEvidence } from "./verify"; @@ -62,10 +75,11 @@ export const sendDailyIncidentReport = onSchedule({ try { const date = yesterdayInSeoul(new Date()); const analyzed = await analyzeGroups(date); - await reportIssues(analyzed, date); + const synced = await reportIssues(analyzed, date); + const ongoing = await reportOngoingIssues(analyzed, synced, date); await sendDiscordMessages( webhookUrl, - buildDailySummary(analyzed.map(({ item }) => item), date) + buildDailySummary(analyzed.map(({ item }) => item), date, ongoing) ); } catch (error) { logger.error("일일 오류 요약 생성 실패", toError(error)); @@ -87,17 +101,19 @@ async function analyzeGroups(date: string): Promise { } // 자동 수정 대상인 이슈 그룹만 GitHub 이슈로 만들거나 갱신. 그 밖의 오류는 요약 알림에서 끝냄. 토큰이 없거나 실패해도 요약 전송은 계속 +// 이슈를 만들거나 댓글을 남긴 이슈 그룹의 식별 키 반환 async function reportIssues( analyzed: AnalyzedGroup[], date: string -): Promise { +): Promise> { + const synced = new Set(); const targets = analyzed.filter(({ item }) => item.score.autoFixEligible); - if (targets.length === 0) { return; } + if (targets.length === 0) { return synced; } const token = ghAutomationTokenSecret.value(); if (token === "") { logger.warn("GitHub 토큰이 없어 이슈를 만들지 않습니다."); - return; + return synced; } try { @@ -110,9 +126,60 @@ async function reportIssues( commented: results.filter((result) => result.action === "commented").length, failed: results.filter((result) => result.action === "failed").length }); + for (const result of results) { + if (result.action !== "failed") { synced.add(result.markerKey); } + } } catch (error) { logger.error("이슈 동기화 실패", toError(error)); } + return synced; +} + +// 열린 이슈가 있는 오류 중 그날 이슈 댓글이 남지 않은 오류의 대상 날짜 발생량을 이슈 댓글로 남김 +// 신규·급증·회귀로 분석되지 않은 오류만 요약의 미해결 항목으로 반환 +// 해결되지 않은 오류를 매일 보고하려는 목적이며 재분석은 하지 않음 +// 토큰이 없거나 조회가 실패해도 요약 전송은 계속 +async function reportOngoingIssues( + analyzed: AnalyzedGroup[], + synced: Set, + date: string +): Promise { + const token = ghAutomationTokenSecret.value(); + if (token === "") { return []; } + + try { + const analyzedKeys = new Set(analyzed.map(({ group }) => incidentMarkerKey(group))); + const openIssues = await listOpenIncidentIssues(token); + const trackedIssueIds = [...openIssues.keys()] + .filter((markerKey) => !synced.has(markerKey)) + .map((markerKey) => markerKey.split(":")[0]); + const occurrences = await selectOccurrences(date, [...new Set(trackedIssueIds)]); + + const items: OngoingItem[] = []; + for (const occurrence of occurrences) { + const markerKey = incidentMarkerKey(occurrence); + const number = openIssues.get(markerKey); + if (number === undefined || synced.has(markerKey)) { continue; } + + try { + await commentOnIssue(token, number, buildOngoingComment(occurrence, date)); + } catch (error) { + logger.error("미해결 이슈 댓글 실패", toError(error), { number }); + } + if (analyzedKeys.has(markerKey)) { continue; } + items.push({ + title: groupTitle(occurrence), + url: githubIssueUrl(number), + affectedUsers: occurrence.affectedUsers, + events: occurrence.events + }); + } + logger.info("미해결 이슈 갱신 완료", { count: items.length }); + return items; + } catch (error) { + logger.error("미해결 이슈 조회 실패", toError(error)); + return []; + } } // 이슈 그룹 하나를 분석하고 근거 검증과 위험도 계산을 거쳐 요약 항목으로 변환. 분석에 실패하면 판단 불가 항목으로 대체 diff --git a/functions/src/incident/github.ts b/functions/src/incident/github.ts index 2f48e85..8e94f03 100644 --- a/functions/src/incident/github.ts +++ b/functions/src/incident/github.ts @@ -79,9 +79,7 @@ async function syncDraft( const existing = openIssues.get(draft.markerKey); try { if (existing !== undefined) { - await request(token, "post", `/repos/${repository}/issues/${existing}/comments`, { - body: draft.updateComment - }); + await commentOnIssue(token, existing, draft.updateComment); return { markerKey: draft.markerKey, action: "commented", number: existing }; } @@ -104,8 +102,22 @@ async function ensureLabels(token: string): Promise { } } +// 지정한 이슈에 댓글 추가 +export async function commentOnIssue( + token: string, + number: number, + body: string +): Promise { + await request(token, "post", `/repos/${repository}/issues/${number}/comments`, { body }); +} + +// 이슈 번호에 대응하는 GitHub 이슈 주소 생성 +export function githubIssueUrl(number: number): string { + return `https://github.com/${repository}/issues/${number}`; +} + // 열린 Crashlytics 이슈의 번호를 식별 키별로 조회. 풀 리퀘스트는 제외 -async function listOpenIncidentIssues(token: string): Promise> { +export async function listOpenIncidentIssues(token: string): Promise> { const issues = await request( token, "get", diff --git a/functions/src/incident/report.ts b/functions/src/incident/report.ts index 2145b41..41f31b0 100644 --- a/functions/src/incident/report.ts +++ b/functions/src/incident/report.ts @@ -1,5 +1,8 @@ import { originLabel } from "./classify"; -import type { ErrorGroup } from "./context"; +import type { + ErrorGroup, + Occurrence +} from "./context"; import type { SummaryItem } from "./discord"; import { autoFixLabel, incidentLabel } from "./github"; import type { IncidentIssueDraft } from "./github"; @@ -22,7 +25,7 @@ export function buildIncidentIssue( item: SummaryItem, date: string ): IncidentIssueDraft { - const markerKey = `${group.issueId}:${group.restStatusCode}`; + const markerKey = incidentMarkerKey(group); const { riskEvidence, score, origin } = item; const { classification } = riskEvidence; const decidingAxes = score.decidingAxes.map((axis) => axisLabels[axis]).join(", ") || "-"; @@ -82,6 +85,24 @@ export function buildIncidentIssue( }; } +// 같은 Crashlytics 이슈 그룹을 식별하는 키 생성 +export function incidentMarkerKey(group: Pick): string { + return `${group.issueId}:${group.restStatusCode}`; +} + +// 열린 이슈로 추적 중인 오류의 대상 날짜 발생량을 담은 미해결 댓글 생성 +export function buildOngoingComment( + occurrence: Occurrence, + date: string +): string { + return [ + `### ${date} 미해결`, + "", + `- 영향 사용자: ${occurrence.affectedUsers}명`, + `- 발생 건수: ${occurrence.events}건` + ].join("\n"); +} + // 이슈 그룹이 선별된 사유 목록을 문자열로 변환 function detectionReasons(group: ErrorGroup): string { const reasons = [ diff --git a/functions/test/incident-daily.test.js b/functions/test/incident-daily.test.js index 82f50f5..5b5bc45 100644 --- a/functions/test/incident-daily.test.js +++ b/functions/test/incident-daily.test.js @@ -8,10 +8,16 @@ process.env.GH_AUTOMATION_TOKEN = "ghp_test"; let bigQueryResponses = []; let bigQueryFailure; +let occurrenceRows = []; +const occurrenceQueries = []; class FakeBigQuery { async query(options) { if (bigQueryFailure) { throw bigQueryFailure; } if (options.query.includes("AS installs")) { return [[]]; } + if (options.query.includes("@issueIds")) { + occurrenceQueries.push(options.params); + return [occurrenceRows]; + } return [bigQueryResponses.shift() ?? []]; } } @@ -116,11 +122,12 @@ const requests = []; let openAiHandler; let discordStatus = 204; let githubListStatus = 200; +let githubOpenIssues = []; axios.request = async (config) => { requests.push(config); if (config.url.startsWith("https://api.openai.com")) { return openAiHandler(config); } if (config.url.startsWith("https://api.github.com")) { - if (config.method === "get") { return { status: githubListStatus, data: [] }; } + if (config.method === "get") { return { status: githubListStatus, data: githubOpenIssues }; } return { status: 201, data: { number: 50 + requests.length } }; } return { status: discordStatus, data: "" }; @@ -133,6 +140,9 @@ function reset() { bigQueryFailure = undefined; discordStatus = 204; githubListStatus = 200; + githubOpenIssues = []; + occurrenceRows = []; + occurrenceQueries.length = 0; process.env.GH_AUTOMATION_TOKEN = "ghp_test"; } @@ -317,7 +327,7 @@ function discordMessages() { assert.deepStrictEqual(counts, { created: 1, commented: 0, failed: 0 }); } - // 자동 수정 대상이 없으면 GitHub 요청을 보내지 않고 요약만 전송 + // 자동 수정 대상이 없으면 이슈를 만들지 않고 미해결 확인을 위한 열린 이슈 조회만 수행 { reset(); bigQueryResponses = [[groupRow("a", "503", 2)], [sampleRow("ea")]]; @@ -325,10 +335,63 @@ function discordMessages() { await sendDailyIncidentReport.run({}); - assert.strictEqual(requests.filter((request) => request.url.startsWith("https://api.github.com")).length, 0); + const githubRequests = requests.filter((request) => request.url.startsWith("https://api.github.com")); + assert.deepStrictEqual(githubRequests.map((request) => request.method), ["get"]); + assert.strictEqual(occurrenceQueries.length, 0); assert.strictEqual(discordMessages().length, 1); } + // 열린 이슈가 있는 오류는 신규·급증·회귀가 아니어도 전날 발생량을 이슈 댓글과 요약의 미해결 항목으로 보고 + { + reset(); + bigQueryResponses = [[groupRow("a", "503", 2)], [sampleRow("ea")]]; + openAiHandler = () => completed(analysis()); + githubOpenIssues = [ + { number: 7, body: "\n본문" }, + { number: 8, body: "\n본문" }, + { number: 9, body: "\n본문" } + ]; + occurrenceRows = [ + { issueId: "b", restStatusCode: "500", issueSubtitle: "DevLogInfra.Service.opb (1)", affectedUsers: 4, events: 11 }, + { issueId: "b", restStatusCode: "404", issueSubtitle: "DevLogInfra.Service.opb (1)", affectedUsers: 1, events: 1 } + ]; + + await sendDailyIncidentReport.run({}); + + assert.deepStrictEqual(occurrenceQueries[0].issueIds, ["b", "a", "c"]); + const comments = requests.filter((request) => request.method === "post" && request.url.endsWith("/comments")); + assert.deepStrictEqual(comments.map((request) => request.url), ["https://api.github.com/repos/DevLog-Labs/Firebase/issues/7/comments"]); + assert.match(comments[0].data.body, /^### \d{4}-\d{2}-\d{2} 미해결\n/); + assert.ok(comments[0].data.body.includes("- 영향 사용자: 4명")); + assert.ok(comments[0].data.body.includes("- 발생 건수: 11건")); + + const [message] = discordMessages(); + const ongoing = message.embeds.find((embed) => embed.title === "미해결 1건"); + assert.ok(ongoing.description.includes("(https://github.com/DevLog-Labs/Firebase/issues/7) · 4명 · 11건")); + assert.ok(message.content.endsWith("· 미해결 1건")); + } + + // 열린 이슈가 있는 오류가 다시 선별됐지만 자동 수정 대상이 아니면 이슈에는 미해결 댓글을 남기고 요약에는 분석 항목으로만 표시 + { + reset(); + bigQueryResponses = [[groupRow("a", "503", 2)], [sampleRow("ea")]]; + openAiHandler = () => completed(analysis()); + githubOpenIssues = [{ number: 8, body: "\n본문" }]; + occurrenceRows = [ + { issueId: "a", restStatusCode: "503", issueSubtitle: "DevLogInfra.Service.opa (1)", affectedUsers: 2, events: 3 } + ]; + + await sendDailyIncidentReport.run({}); + + assert.deepStrictEqual(occurrenceQueries[0].issueIds, ["a"]); + const comments = requests.filter((request) => request.method === "post" && request.url.endsWith("/comments")); + assert.deepStrictEqual(comments.map((request) => request.url), ["https://api.github.com/repos/DevLog-Labs/Firebase/issues/8/comments"]); + + const [message] = discordMessages(); + assert.ok(!message.embeds.some((embed) => embed.title.startsWith("미해결"))); + assert.ok(!message.content.includes("미해결")); + } + // GitHub 조회가 실패해도 로그만 남기고 Discord 요약은 전송 { reset(); @@ -338,8 +401,7 @@ function discordMessages() { await sendDailyIncidentReport.run({}); - assert.strictEqual(errorLogs.length, 1); - assert.strictEqual(errorLogs[0][0], "이슈 동기화 실패"); + assert.deepStrictEqual(errorLogs.map(([text]) => text), ["이슈 동기화 실패", "미해결 이슈 조회 실패"]); assert.strictEqual(discordMessages().length, 1); assert.ok(discordMessages()[0].embeds.length > 0); } From 14790dc9d10a98182b20dc74a909dcf0ee6e5c9c Mon Sep 17 00:00:00 2001 From: opficdev <162981733+opficdev@users.noreply.github.com> Date: Fri, 13 Nov 2026 18:43:55 +0900 Subject: [PATCH 08/11] =?UTF-8?q?ci:=20=EC=88=98=EC=A0=95=20=EC=B4=88?= =?UTF-8?q?=EC=95=88=20=EB=B8=8C=EB=9E=9C=EC=B9=98=EB=A5=BC=20=EC=98=A4?= =?UTF-8?q?=EB=A5=98=20=EB=8B=A8=EC=9C=84=EB=A1=9C=20=EB=A7=8C=EB=93=A4?= =?UTF-8?q?=EC=96=B4=20=EA=B0=99=EC=9D=80=20=EC=98=A4=EB=A5=98=EC=9D=98=20?= =?UTF-8?q?Draft=20PR=20=EC=A4=91=EB=B3=B5=20=EB=B0=A9=EC=A7=80?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .github/workflows/auto-fix.yml | 47 +++++++++++++++++++++++++++++++--- 1 file changed, 43 insertions(+), 4 deletions(-) diff --git a/.github/workflows/auto-fix.yml b/.github/workflows/auto-fix.yml index c7ae46b..d392d55 100644 --- a/.github/workflows/auto-fix.yml +++ b/.github/workflows/auto-fix.yml @@ -12,9 +12,43 @@ permissions: contents: read jobs: + prepare: + name: Prepare + if: github.event.label.name == 'auto-fix' + runs-on: ubuntu-latest + outputs: + branch: ${{ steps.branch.outputs.branch }} + skip: ${{ steps.branch.outputs.skip }} + + steps: + - name: Check existing fix + id: branch + env: + GH_TOKEN: ${{ secrets.GH_AUTOMATION_TOKEN }} + ISSUE_NUMBER: ${{ github.event.issue.number }} + ISSUE_BODY: ${{ github.event.issue.body }} + run: | + marker="$(printf '%s' "$ISSUE_BODY" | sed -nE 's/.*.*/\1/p' | head -n 1)" + if [ -n "$marker" ]; then + branch="auto-fix/crashlytics-$(printf '%s' "$marker" | tr -c 'A-Za-z0-9_-' '-')" + else + branch="auto-fix/issue-${ISSUE_NUMBER}" + fi + echo "branch=$branch" >> "$GITHUB_OUTPUT" + + if gh api "repos/$GITHUB_REPOSITORY/git/ref/heads/$branch" > /dev/null 2>&1; then + pr="$(gh pr list --repo "$GITHUB_REPOSITORY" --head "$branch" --state all --json url --jq '.[0].url // empty')" + gh issue comment "$ISSUE_NUMBER" --repo "$GITHUB_REPOSITORY" \ + --body "같은 오류의 자동 수정 브랜치 \`$branch\`가 이미 있어 수정 초안을 만들지 않음${pr:+ ($pr)}" + echo "skip=true" >> "$GITHUB_OUTPUT" + else + echo "skip=false" >> "$GITHUB_OUTPUT" + fi + codex: name: Draft - if: github.event.label.name == 'auto-fix' + needs: prepare + if: needs.prepare.outputs.skip == 'false' runs-on: ubuntu-latest outputs: has_changes: ${{ steps.patch.outputs.has_changes }} @@ -105,7 +139,9 @@ jobs: open_pr: name: Pull Request - needs: codex + needs: + - prepare + - codex if: needs.codex.outputs.has_changes == 'true' runs-on: ubuntu-latest @@ -145,10 +181,13 @@ jobs: GH_TOKEN: ${{ secrets.GH_AUTOMATION_TOKEN }} ISSUE_NUMBER: ${{ github.event.issue.number }} ISSUE_TITLE: ${{ github.event.issue.title }} + BRANCH: ${{ needs.prepare.outputs.branch }} run: | - branch="auto-fix/issue-${ISSUE_NUMBER}" + branch="$BRANCH" if git ls-remote --exit-code --heads origin "$branch" > /dev/null 2>&1; then - echo "이미 같은 브랜치가 있어 건너뜀: $branch" + pr="$(gh pr list --repo "$GITHUB_REPOSITORY" --head "$branch" --state all --json url --jq '.[0].url // empty')" + gh issue comment "$ISSUE_NUMBER" --repo "$GITHUB_REPOSITORY" \ + --body "같은 오류의 자동 수정 브랜치 \`$branch\`가 먼저 만들어져 PR을 만들지 않음${pr:+ ($pr)}" exit 0 fi From 17e838ef4edadaf54de60865cedde71f7e09c146 Mon Sep 17 00:00:00 2001 From: opficdev <162981733+opficdev@users.noreply.github.com> Date: Fri, 13 Nov 2026 18:43:55 +0900 Subject: [PATCH 09/11] =?UTF-8?q?docs:=20=EB=AF=B8=ED=95=B4=EA=B2=B0=20?= =?UTF-8?q?=EB=B3=B4=EA=B3=A0=EC=99=80=20=EC=98=A4=EB=A5=98=20=EB=8B=A8?= =?UTF-8?q?=EC=9C=84=20=EC=88=98=EC=A0=95=20=EB=B8=8C=EB=9E=9C=EC=B9=98=20?= =?UTF-8?q?=EB=AC=B8=EC=84=9C=ED=99=94?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 15 ++++++++------- 1 file changed, 8 insertions(+), 7 deletions(-) diff --git a/README.md b/README.md index 037b15e..f33a004 100644 --- a/README.md +++ b/README.md @@ -52,7 +52,8 @@ Cloud Run 배포와 직접 호출 검증은 [`docs/cloud-run-staging.md`](docs/c 4. OpenAI 모델이 판단마다 근거를 인용한 JSON을 내고, 코드가 인용한 원문을 검증한 뒤 위험도를 계산합니다. 알림 등급은 영향도와 심각도 중 큰 값입니다. 5. 분석한 모든 오류를 Discord 요약으로 보냅니다. 등급 2 이상 상위 5건은 상세로, 나머지는 한 줄로 표시합니다. 6. 자동 수정 자격이 있는 오류만 이 저장소에 `auto-fix` 라벨이 붙은 이슈로 만듭니다. 같은 오류의 열린 이슈가 있으면 댓글로 갱신합니다. -7. `.github/workflows/auto-fix.yml`이 `auto-fix` 라벨이 붙은 이슈를 Codex로 수정하고 Draft PR을 올립니다. 머지는 사람이 합니다. +7. 열린 이슈가 있는 오류는 신규, 급증, 회귀가 아니어도 전날 발생했으면 미해결로 보고합니다. 다시 분석하지 않고 영향 사용자 수와 발생 건수를 이슈 댓글과 Discord 요약의 미해결 목록에 남깁니다. 그날 신규, 급증, 회귀로 분석된 오류는 요약에 분석 항목으로 나오고, 6번에서 댓글이 남지 않았으면 이슈에 미해결 댓글만 남깁니다. 이슈가 닫히면 보고를 멈춥니다. +8. `.github/workflows/auto-fix.yml`이 `auto-fix` 라벨이 붙은 이슈를 Codex로 수정하고 Draft PR을 올립니다. 머지는 사람이 합니다. 자동 수정 자격이 없는 오류는 이슈를 만들지 않고 Discord 요약에서 끝납니다. @@ -66,7 +67,7 @@ Cloud Run 배포와 직접 호출 검증은 [`docs/cloud-run-staging.md`](docs/c - 변경 위험과 불확실성이 모두 1 이하 - 데이터 손실과 보안 문제가 없다는 판단에 근거가 있음 -수정 워크플로는 Codex 실행 전에 `functions`와 `nestjs-api` 의존성, Codex 샌드박스가 쓰는 `bubblewrap`을 설치합니다. 변경이 300줄을 넘거나 `.github`, 인증 코드, 설정, 의존성 파일을 건드리면 PR을 만들지 않고 이슈에 사유를 댓글로 남깁니다. 같은 이름의 브랜치(`auto-fix/issue-<번호>`)가 이미 있으면 PR을 만들지 않습니다. +수정 워크플로는 Codex 실행 전에 `functions`와 `nestjs-api` 의존성, Codex 샌드박스가 쓰는 `bubblewrap`을 설치합니다. 변경이 300줄을 넘거나 `.github`, 인증 코드, 설정, 의존성 파일을 건드리면 PR을 만들지 않고 이슈에 사유를 댓글로 남깁니다. 수정 브랜치는 오류 단위로 `auto-fix/crashlytics--<상태 코드>` 이름을 씁니다. 같은 오류의 브랜치가 이미 있으면 Codex를 실행하지 않고 이슈에 기존 PR 링크를 댓글로 남기므로, 같은 오류의 이슈가 여러 개여도 Draft PR은 하나만 만들어집니다. 같은 오류의 이슈 두 개에 거의 동시에 라벨이 붙으면 Codex는 두 번 실행될 수 있지만, PR은 먼저 끝난 실행만 만들고 나중 실행은 이슈에 기존 PR 링크를 남깁니다. 머지된 PR의 브랜치는 자동으로 지워지므로 재발하면 다시 수정을 시도하고, 머지하지 않고 닫은 PR은 브랜치를 지워야 다시 시도합니다. ### 필요한 설정 @@ -82,7 +83,7 @@ Cloud Run 배포와 직접 호출 검증은 [`docs/cloud-run-staging.md`](docs/c ### 수동 실행 -Cloud Scheduler 작업을 직접 실행해 하루 분량을 즉시 처리할 수 있습니다. 함수는 한 번에 하나만 실행하므로, 실행 중에 다시 실행하면 두 번째 요청은 잠시 대기한 뒤 실패합니다. 같은 날 연달아 실행하면 방금 만든 이슈가 목록 조회에 늦게 반영되어 같은 오류의 이슈가 중복으로 생길 수 있습니다. +Cloud Scheduler 작업을 직접 실행해 하루 분량을 즉시 처리할 수 있습니다. 함수는 한 번에 하나만 실행하므로, 실행 중에 다시 실행하면 두 번째 요청은 잠시 대기한 뒤 실패합니다. 같은 날 연달아 실행하면 방금 만든 이슈가 목록 조회에 늦게 반영되어 같은 오류의 이슈가 중복으로 생길 수 있지만, Draft PR은 오류 단위로 하나만 만들어집니다. ```bash gcloud scheduler jobs run firebase-schedule-sendDailyIncidentReport-asia-northeast3 \ @@ -95,15 +96,15 @@ gcloud scheduler jobs run firebase-schedule-sendDailyIncidentReport-asia-northea 일일 실행은 다음 순서로 확인합니다. 1. Cloud Scheduler 작업의 마지막 실행 상태가 성공인지 확인합니다. -2. Discord에 요약이 왔는지 확인합니다. 대상 오류가 없는 날은 `신규·급증·회귀 이슈가 없습니다` 메시지만 옵니다. `일일 오류 요약을 만들지 못했습니다` 메시지가 오면 `일일 오류 요약 생성 실패` 로그를 확인합니다. -3. Cloud Functions 로그에서 오류별 `이슈 분석 완료`와 `이슈 동기화 완료`의 `created`, `commented`, `failed` 수를 확인합니다. +2. Discord에 요약이 왔는지 확인합니다. 대상 오류가 없는 날은 `신규·급증·회귀 이슈가 없습니다` 메시지가 오고, 미해결 오류가 있으면 본문 끝의 `미해결 N건`과 미해결 목록이 함께 옵니다. `일일 오류 요약을 만들지 못했습니다` 메시지가 오면 `일일 오류 요약 생성 실패` 로그를 확인합니다. +3. Cloud Functions 로그에서 오류별 `이슈 분석 완료`, `이슈 동기화 완료`의 `created`, `commented`, `failed` 수, `미해결 이슈 갱신 완료`의 `count`를 확인합니다. 자동 수정은 다음 순서로 확인합니다. 1. 새 이슈에 `crashlytics`와 `auto-fix` 라벨이 붙었는지 확인합니다. -2. Actions에서 이슈 하나당 `Auto Fix` 실행이 하나인지 확인합니다. `crashlytics` 라벨 이벤트로 생긴 실행은 건너뜀으로 표시됩니다. +2. Actions에서 이슈 하나당 `Auto Fix` 실행이 하나인지 확인합니다. `crashlytics` 라벨 이벤트로 생긴 실행은 건너뜀으로 표시됩니다. 같은 오류의 브랜치가 이미 있으면 `Prepare` job만 실행되고 이슈에 기존 PR 링크 댓글이 남습니다. 3. `codex` job에서 의존성과 `bubblewrap` 설치가 성공했는지, Codex 로그에 테스트 실행 결과가 있는지 확인합니다. -4. 변경이 있으면 `auto-fix/issue-<번호>` 브랜치와 Draft PR이 만들어지고 PR의 CI가 실행되는지 확인합니다. 제한에 걸리면 이슈에 사유 댓글이 남습니다. +4. 변경이 있으면 `auto-fix/crashlytics--<상태 코드>` 브랜치와 Draft PR이 만들어지고 PR의 CI가 실행되는지 확인합니다. 제한에 걸리면 이슈에 사유 댓글이 남습니다. ## 환경 변수 From b74fbaa507944575733ad14a9041ee6b90df6bd5 Mon Sep 17 00:00:00 2001 From: opficdev <162981733+opficdev@users.noreply.github.com> Date: Fri, 13 Nov 2026 20:20:08 +0900 Subject: [PATCH 10/11] =?UTF-8?q?ci:=20=EA=B0=99=EC=9D=80=20=EC=98=A4?= =?UTF-8?q?=EB=A5=98=EC=9D=98=20=EC=88=98=EC=A0=95=20=EB=B8=8C=EB=9E=9C?= =?UTF-8?q?=EC=B9=98=20push=EA=B0=80=20=EA=B1=B0=EB=B6=80=EB=90=98?= =?UTF-8?q?=EB=A9=B4=20=EC=9D=B4=EC=8A=88=EC=97=90=20=EA=B8=B0=EC=A1=B4=20?= =?UTF-8?q?PR=20=EB=A7=81=ED=81=AC=20=EB=8C=93=EA=B8=80?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .github/workflows/auto-fix.yml | 17 +++++++++-------- 1 file changed, 9 insertions(+), 8 deletions(-) diff --git a/.github/workflows/auto-fix.yml b/.github/workflows/auto-fix.yml index d392d55..41f2225 100644 --- a/.github/workflows/auto-fix.yml +++ b/.github/workflows/auto-fix.yml @@ -184,13 +184,6 @@ jobs: BRANCH: ${{ needs.prepare.outputs.branch }} run: | branch="$BRANCH" - if git ls-remote --exit-code --heads origin "$branch" > /dev/null 2>&1; then - pr="$(gh pr list --repo "$GITHUB_REPOSITORY" --head "$branch" --state all --json url --jq '.[0].url // empty')" - gh issue comment "$ISSUE_NUMBER" --repo "$GITHUB_REPOSITORY" \ - --body "같은 오류의 자동 수정 브랜치 \`$branch\`가 먼저 만들어져 PR을 만들지 않음${pr:+ ($pr)}" - exit 0 - fi - login="$(gh api user --jq .login)" id="$(gh api user --jq .id)" git config user.name "$login" @@ -199,7 +192,15 @@ jobs: git checkout -b "$branch" git apply --index "$RUNNER_TEMP/artifact/changes.patch" git commit -m "fix: Crashlytics 이슈 #${ISSUE_NUMBER} 대응" - git push origin "$branch" + if ! git push origin "$branch"; then + if ! git ls-remote --exit-code --heads origin "$branch" > /dev/null 2>&1; then + exit 1 + fi + pr="$(gh pr list --repo "$GITHUB_REPOSITORY" --head "$branch" --state all --json url --jq '.[0].url // empty')" + gh issue comment "$ISSUE_NUMBER" --repo "$GITHUB_REPOSITORY" \ + --body "같은 오류의 자동 수정 브랜치 \`$branch\`가 먼저 만들어져 PR을 만들지 않음${pr:+ ($pr)}" + exit 0 + fi summary="$(head -c 1500 "$RUNNER_TEMP/artifact/summary.md")" { From 0100d571af7e3228f7b282d840cebcc0806279e9 Mon Sep 17 00:00:00 2001 From: opficdev <162981733+opficdev@users.noreply.github.com> Date: Fri, 13 Nov 2026 20:30:40 +0900 Subject: [PATCH 11/11] =?UTF-8?q?ci:=20=EC=88=98=EC=A0=95=20=EC=B4=88?= =?UTF-8?q?=EC=95=88=20job=EC=9D=98=20=EB=9F=AC=EB=84=88=EB=A5=BC=20ubuntu?= =?UTF-8?q?-24.04=EB=A1=9C=20=EA=B3=A0=EC=A0=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .github/workflows/auto-fix.yml | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/.github/workflows/auto-fix.yml b/.github/workflows/auto-fix.yml index 41f2225..8460f5f 100644 --- a/.github/workflows/auto-fix.yml +++ b/.github/workflows/auto-fix.yml @@ -49,7 +49,8 @@ jobs: name: Draft needs: prepare if: needs.prepare.outputs.skip == 'false' - runs-on: ubuntu-latest + # Ubuntu 26.04에서 codex-action의 drop-sudo가 실패해 24.04 고정 (openai/codex-action#188) + runs-on: ubuntu-24.04 outputs: has_changes: ${{ steps.patch.outputs.has_changes }}