Skip to content

PR 파일별 알고리즘 패턴 태깅 추가 (#4)#5

Merged
sounmind merged 1 commit intomainfrom
4-알고리즘-패턴-태깅
Apr 4, 2026

Hidden character warning

The head ref may contain hidden characters: "4-\uc54c\uace0\ub9ac\uc998-\ud328\ud134-\ud0dc\uae45"
Merged

PR 파일별 알고리즘 패턴 태깅 추가 (#4)#5
sounmind merged 1 commit intomainfrom
4-알고리즘-패턴-태깅

Conversation

@sounmind
Copy link
Copy Markdown
Member

@sounmind sounmind commented Apr 1, 2026

개요

DaleStudy/leetcode-study PR에 스터디원들이 솔루션을 제출하면, 각 파일에 어떤 알고리즘 패턴이 쓰였는지 자동으로 파악하기 어렵다. PR 파일 단위로 OpenAI가 패턴을 분석하고 review comment를 남겨서, 리뷰어들이 코드를 빠르게 파악할 수 있게 한다.

Closes #4

변경 파일

파일 변경 종류
utils/openai.js 함수 추가 (generatePatternAnalysis)
handlers/tag-patterns.js 신규 생성
handlers/webhooks.js handlePullRequestEvent 리팩토링

Step 1. utils/openai.jsgeneratePatternAnalysis() 추가

기존 generateCodeReview()와 동일한 패턴으로 신규 함수 추가.

  • 모델: gpt-4.1-nano (기존과 동일)
  • response_format: { type: "json_object" } 사용해서 JSON 파싱 안정성 확보
  • temperature: 0.3 (결정적인 분석)
  • 반환 형식:
    { "patterns": ["Sliding Window", "Hash Map"], "description": "설명 텍스트" }

감지 대상 16개 패턴:

Two Pointers, Sliding Window, Fast & Slow Pointers, BFS, DFS, Backtracking, Dynamic Programming, Binary Search, Monotonic Stack, Heap / Priority Queue, Hash Map / Hash Set, Greedy, Divide and Conquer, Union Find, Trie, Bit Manipulation


Step 2. handlers/tag-patterns.js — 신규 핸들러 생성

export async function tagPatterns(repoOwner, repoName, prNumber, headSha, prData, appToken, openaiApiKey)

2-1. 스킵 조건 확인

  • prData.draft === true → skip
  • prData.labelsmaintenance 포함 → skip

2-2. PR 변경 파일 목록 조회 + 필터링

  • GET /repos/{owner}/{repo}/pulls/{pr_number}/files?per_page=100
  • statusadded 또는 modified
  • 파일 경로가 {problem-name}/{username}.{extension} 패턴 (정규식: /^[^/]+\/[^/]+\.[^.]+$/)

2-3. 기존 Bot 패턴 태그 코멘트 삭제

  • comment.user.type === \"Bot\" && comment.body.includes(\"<!-- dalestudy-pattern-tag -->\") 조건 만족하는 코멘트만 삭제
  • 다른 사람 코멘트는 절대 건드리지 않음

2-4. 파일별 OpenAI 분석 + 코멘트 작성

  • file.raw_url로 파일 내용 가져오기 (20K 문자 초과 시 truncate)
  • generatePatternAnalysis() 호출
  • POST /repos/{owner}/{repo}/pulls/{pr_number}/comments with subject_type: \"file\" → 특정 라인이 아닌 파일 전체에 comment

Step 3. handlers/webhooks.jshandlePullRequestEvent() 리팩토링

3-1. synchronize 액션 추가

기존 [\"opened\", \"reopened\"][\"opened\", \"reopened\", \"synchronize\"]

3-2. Week check 최적화

  • opened/reopened: 기존대로 3초 대기 + week check + 패턴 태깅
  • synchronize (재push): week check 스킵 (이미 설정됐을 가능성 높음) → 패턴 태깅만 실행

3-3. 패턴 태깅 호출

  • OPENAI_API_KEY 있을 때만 실행
  • 전체 try/catch 래핑 → 실패해도 webhook 성공 응답

구현 중 반영한 안전장치

  1. 파일별 try/catch 래핑: 한 파일 OpenAI 분석 실패 시 다른 파일 계속 진행
  2. 파일 크기 제한: 20K 문자 초과 시 truncate (OpenAI 토큰 안전장치)
  3. JSON 파싱 fallback: patterns 배열 아니면 빈 배열, description 문자열 아니면 빈 문자열

재사용한 기존 함수

함수 파일
getGitHubHeaders(token) utils/github.js
hasMaintenanceLabel(labels) utils/validation.js
generateGitHubAppToken(env) utils/github.js (webhooks.js에서 호출)

검증 방법

  1. 이 브랜치 머지 → Cloudflare Workers 자동 배포
  2. 테스트 PR에 빈 커밋 push → synchronize 이벤트 트리거
  3. 실제 PR Files 탭에서 파일별 🏷️ 패턴 코멘트가 달리는지 확인
  4. 재push 시 기존 Bot 코멘트가 삭제되고 새 코멘트로 교체되는지 확인
  5. 다른 사람의 코멘트는 유지되는지 확인

@sounmind sounmind linked an issue Apr 1, 2026 that may be closed by this pull request
@cloudflare-workers-and-pages
Copy link
Copy Markdown

cloudflare-workers-and-pages bot commented Apr 1, 2026

Deploying with  Cloudflare Workers  Cloudflare Workers

The latest updates on your project. Learn more about integrating Git with Workers.

Status Name Latest Commit Preview URL Updated (UTC)
✅ Deployment successful!
View logs
github 42e8778 Commit Preview URL Apr 04 2026, 07:02 PM

@sounmind sounmind marked this pull request as draft April 1, 2026 02:21
Analyze solution files with OpenAI and post per-file review comments
tagging the algorithm patterns used (Two Pointers, DP, BFS/DFS, etc.).

- utils/openai.js: add generatePatternAnalysis() using gpt-4.1-nano
  with JSON response format
- handlers/tag-patterns.js: new handler that filters solution files,
  replaces stale bot comments, and posts pattern analysis per file
- handlers/webhooks.js: handle synchronize action and skip week check
  on re-push to avoid unnecessary latency
- wrap per-file analysis in try/catch so one failure does not block
  other files

Closes #4

Co-Authored-By: jylee2033 <jylee2033@gmail.com>
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
@sounmind sounmind force-pushed the 4-알고리즘-패턴-태깅 branch from c9b7518 to 42e8778 Compare April 4, 2026 19:02
@sounmind sounmind requested a review from jylee2033 April 4, 2026 19:02
@sounmind sounmind changed the title 테스트 PR feat: add algorithm pattern tagging for PR files (#4) Apr 4, 2026
@sounmind sounmind changed the title feat: add algorithm pattern tagging for PR files (#4) feat: PR 파일별 알고리즘 패턴 태깅 추가 (#4) Apr 4, 2026
@sounmind sounmind changed the title feat: PR 파일별 알고리즘 패턴 태깅 추가 (#4) PR 파일별 알고리즘 패턴 태깅 추가 (#4) Apr 4, 2026
@sounmind sounmind marked this pull request as ready for review April 4, 2026 19:07
@sounmind sounmind merged commit c11c641 into main Apr 4, 2026
1 check passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

알고리즘 패턴 태깅

2 participants