Skip to content

chore: Antigravity AI 코드 리뷰 워크플로우 설정 (#95)#96

Merged
KTH1007 merged 5 commits into
developfrom
chore/#95-antigravity-review-workflow
May 22, 2026
Merged

chore: Antigravity AI 코드 리뷰 워크플로우 설정 (#95)#96
KTH1007 merged 5 commits into
developfrom
chore/#95-antigravity-review-workflow

Conversation

@KTH1007

@KTH1007 KTH1007 commented May 22, 2026

Copy link
Copy Markdown
Owner

관련 이슈

closes #95

작업 내용

  • antigravity 코드 리뷰 설정

테스트

  • 로컬 테스트 완료

참고 사항

@KTH1007 KTH1007 self-assigned this May 22, 2026
@KTH1007 KTH1007 added the chore label May 22, 2026

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request introduces a Python script, .github/scripts/antigravity_review.py, which automates code reviews by sending Git diffs to an AI agent and saving the results to a markdown file. The review feedback suggests two key improvements: escaping triple backticks within the diff content to prevent breaking the prompt's markdown structure, and implementing error handling around the AI agent interaction to ensure the script handles network or API failures gracefully.


Git Diff:
```diff
{git_diff}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

git_diff 내용에 마크다운 코드 블록 구분자인 트리플 백틱(```)이 포함되어 있을 경우, 프롬프트의 마크다운 구조가 깨져 AI가 입력을 잘못 해석할 수 있습니다. 이를 방지하기 위해 백틱 문자열을 치환하여 전달하는 것이 안전합니다.

Suggested change
{git_diff}
{git_diff.replace(chr(96)*3, chr(96) + ' ' + chr(96) + ' ' + chr(96))}

Comment thread .github/scripts/antigravity_review.py Outdated
Comment on lines +34 to +36
async with Agent(config) as agent:
response = await agent.chat(review_prompt)
review_text = await response.text()

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

AI 에이전트 호출 및 응답 처리 과정에서 예외(네트워크 오류, API 할당량 초과 등)가 발생할 경우 스크립트가 비정상 종료될 수 있습니다. 예외 처리를 통해 오류 상황을 review_result.md에 기록함으로써 사용자에게 피드백을 제공하고 CI 워크플로우의 안정성을 높이는 것이 좋습니다.

Suggested change
async with Agent(config) as agent:
response = await agent.chat(review_prompt)
review_text = await response.text()
try:
async with Agent(config) as agent:
response = await agent.chat(review_prompt)
review_text = await response.text()
except Exception as e:
review_text = f"AI 리뷰 생성 중 오류가 발생했습니다: {e}"

@github-actions

Copy link
Copy Markdown

Antigravity AI Code Review

제공해주신 Git Diff(변경 사항)를 분석하여 시니어 소프트웨어 엔지니어 관점에서 깊이 있는 코드 리뷰를 진행했습니다.

이번 리뷰는 Python 3.13 표준 및 비동기(Async) 어플리케이션 설계 가이드라인, 그리고 GitHub Actions 보안 및 성능 최적화 모범 사례(Best Practice)를 기준으로 작성되었습니다.


🛠️ Antigravity AI Code Review Report

1. 치명적인 버그 및 보안 취약점 (Security & Reliability)

pull_request 이벤트에서의 Secrets 접근 제한 가용성 문제 ⚠️

  • 분석: 작성된 워크플로우는 on: pull_request에서 동작하며 GEMINI_API_KEYGITHUB_TOKEN을 요구합니다. Fork된 외부 저장소에서 PR이 올 경우, GitHub의 기본 보안 정책상 Secrets에 접근할 수 없어 API 호출 및 PR 코멘트 작성이 전부 실패하게 됩니다.
  • 해결 제안: 프라이빗(Private) 저장소라면 문제가 없으나, 퍼블릭(Public) 오픈소스 저장소이거나 외부 협업자가 있다면 pull_request_target 이벤트로의 전환을 고려해야 합니다. 다만, pull_request_target을 쓸 때는 PR 브랜치의 임의 스크립트가 실행되지 않도록 체크아웃 대상 브랜치를 엄격히 통제해야 합니다.

대규모 Diff 발생 시 API 및 리소스 고갈 취약점 (Token Overflow & Context Exhaustion)

  • 분석: 만약 개발자가 대량의 이미지 파일, 빌드 결과물, 또는 의존성 락 파일(package-lock.json, poetry.lock 등)을 추가할 경우 git diff 결과물(pr_diff.txt)의 크기가 수 메가바이트(MB)에 이를 수 있습니다. 이는 AI SDK 호출 시 Context Window 초과 에러를 유발하거나 불필요한 API 비용을 무한대로 발생시킵니다.
  • 해결 제안: git diff 생성 시 불필요한 파일 패턴이나 자동 생성 바이너리 파일을 필터링하는 로직을 추가해야 합니다.
    # 예시: 특정 락 파일 및 미디어 파일 제외
    git diff origin/${{ github.base_ref }}...HEAD -- . ':(exclude)*.lock' ':(exclude)*.json' > pr_diff.txt

2. 성능 병목 및 리소스 최적화 (Performance Optimization)

비동기(Asyncio) 루프 내의 동기식 디스크 I/O (Blocking Disk I/O) 🐢

  • 분석: antigravity_review.pyasync def main() 비동기 함수 구조를 취하고 있으나 open(diff_path, "r")open("review_result.md", "w")와 같은 무거운 파일 디스크 입출력 처리를 **동기식(blocking)**으로 처리하고 있습니다. 파일이 극도로 커질 경우 이벤트 루프가 차단(blocking)되어 전체 비동기 성능이 저하됩니다.
  • 해결 제안: Python 비동기 스키마 내에서 디스크 I/O를 비동기로 수행할 수 있도록 aiofiles 패키지를 도입하거나, 표준 라이브러리인 asyncio.to_thread()를 사용해 I/O 작업을 별도 워커 스레드로 위임하십시오.
    # standard asyncio.to_thread 적용 예시
    git_diff = await asyncio.to_thread(read_file_func, diff_path)

GitHub Actions의 의존성 캐싱 부재 및 Shallow Clone 미적용

  • 분석:
    1. actions/checkout@v4에서 fetch-depth: 0을 사용하여 전체 Git 히스토리를 다 받아오고 있습니다. 이 방식은 대규모 저장소에서 체크아웃 성능을 기하급수적으로 느리게 만듭니다. Diff 비교에는 공통 조상(Merge Base)과의 관계만 필요하므로, 이력을 무제한으로 복제할 필요가 없습니다.
    2. 매번 실행 시 pip install google-antigravity를 수행하며, 캐싱 레이어가 없어 워크플로우 속도가 지연됩니다.
  • 해결 제안:
    • fetch-depth를 합리적인 수준(예: 50~100)으로 축소하거나 원격 브랜치 명시 체크아웃을 정의합니다.
    • actions/setup-python 단계에서 라이브러리 pip 캐싱을 활성화합니다.
    - name: Set up Python
      uses: actions/setup-python@v5
      with:
        python-version: '3.13'
        cache: 'pip' # 패키지 설치 속도 향상

3. 코드 품질 및 유지보수성 (Clean Code & Maintainability)

시스템 프롬프트(Role)와 유저 데이터(Diff Input)의 분리 설계 결여

  • 분석: 현재 구조는 역할 지시문("당신은 모든 프로그래밍 언어와 아키텍처에 능통한...") 뒤에 곧바로 유저 소스코드의 Diff를 하나의 문자열 블록 안에 합쳐두었습니다. 언어 모델 입장에서 지시 방향성과 동적 데이터를 혼동하기 쉬우며, 프롬프트 주입(Prompt Injection) 공격에脆弱해집니다.
  • 해결 제안: 최신 AI API 설계 관례에 따라 System InstructionUser Prompt를 격리하는 구조로 google-antigravity 라이브러리의 시스템 선언부를 재설계하는 편이 좋습니다. 만약 물리적인 구분이 힘들다면 프롬프트와 컨텍스트 사이에 명확한 구분자(Delimiter) 지정을 생활화해야 합니다.

유연하지 못한 오류 제어 설계 (Silent Fail with Output)

  • 분석: Python 코드 내에서 API 통신의 오류가 발생하면 Exception을 캐치한 후 문자열로 오류 메시지를 씁니다. 이때 스크립트는 **정상 종료(exit code: 0)**하게 되고, 워크플로우 단계는 성공으로 끝납니다. 이로 인해 PR에는 어설픈 오류 텍스트 코멘트만 남고, 실제 워크플로우가 실패했는지 개발자가 추적하기 어렵습니다.
  • 해결 제안: 오류 발생 시 로깅을 세분화하고, 시스템 개발 도구나 PR 파이프라인의 명확성을 위해 중요 시스템 오류는 적절히 sys.exit(1)을 통해 실패 신호를 전달할 수 있는 옵션을 열어두어야 합니다.

Refactored Code Proposals (권장 개선 코드)

위의 피드백을 적용하여 한 단계 높은 수준으로 리팩토링한 결과물입니다.

1. antigravity_review.py (비동기 파일 처리 및 모던 에러 롤백 가미)

import asyncio
import os
import sys
from google.antigravity import Agent, LocalAgentConfig

# 비동기 파일 읽기를 위한 동기 래퍼 도우미
def read_file_sync(path: str) -> str:
    with open(path, "r", encoding="utf-8") as f:
        return f.read()

def write_file_sync(path: str, content: str) -> None:
    with open(path, "w", encoding="utf-8") as f:
        f.write(content)

async def main():
    diff_path = os.environ.get("PR_DIFF_PATH", "pr_diff.txt")
    result_path = os.environ.get("REVIEW_RESULT_PATH", "review_result.md")

    # 1. 파일 존부 체크 및 비동기적 읽기 처리
    if not os.path.exists(diff_path) or os.path.getsize(diff_path) == 0:
        await asyncio.to_thread(
            write_file_sync, 
            result_path, 
            "변경된 코드 내역을 찾을 수 없거나 Git diff 생성에 실패했습니다."
        )
        sys.exit(0)

    git_diff = await asyncio.to_thread(read_file_sync, diff_path)

    # 2. Markdown 백틱 주입 대비 이스케이프 강화
    safe_diff = git_diff.replace("```", "'' '")

    # 3. 프롬프트 시스템 분리를 가정한 구조화
    review_prompt = f"""당신은 모든 프로그래밍 언어와 아키텍처에 능통한 '시니어 소프트웨어 엔지니어'입니다.
아래 제공된 Git Diff(변경 사항)를 분석하여 깊이 있는 코드 리뷰를 진행해 주세요.
해당 코드가 어떤 언어(Java, Python, JS, Go 등)인지 스스로 파악하고 그 언어의 최신 모범 사례(Best Practice)를 기준으로 평가하세요.

다음 3가지 영역을 중점적으로 검토해 주세요:
1. 치명적인 버그 및 보안 취약점 (로직 오류, 인젝션, 메모리 누수 등)
2. 성능 병목 (비효율적인 알고리즘, N+1 쿼리 등 불필요한 DB/네트워크 호출)
3. 코드 품질 및 유지보수성 (가독성 향상을 위한 리팩토링 제안, 네이밍 일관성 등)

단순한 오타 지적보다는 아키텍처나 성능 관점의 유의미한 피드백을 우선시해 주세요.
결과는 한국어로, 깔끔한 마크다운 형식으로 작성해 주세요.

[Git Diff Source]
{safe_diff}
"""

    config = LocalAgentConfig()
    try:
        async with Agent(config) as agent:
            response = await agent.chat(review_prompt)
            review_text = await response.text()
    except Exception as e:
        review_text = f"AI 리뷰 생성 중 오류가 발생했습니다.\n\n```\nError Details: {e}\n```"
        # CI 빌드가 에러 상태임을 전파할 지, 메시지만 쓸 지 선택 가능한 유연 구조 확보
        # sys.exit(1) # 활성화 시 무력화 대신 에러 상향 전달 가능

    output_content = f"## Antigravity AI Code Review\n\n{review_text}"
    await asyncio.to_thread(write_file_sync, result_path, output_content)

if __name__ == "__main__":
    asyncio.run(main())

2. antigravity-review.yml (캐싱 탑재 및 안정적인 Git Diff 수집)

name: Universal AI Code Review

on:
  pull_request:
    types: [opened, synchronize]

jobs:
  review:
    runs-on: ubuntu-latest
    permissions:
      pull-requests: write
      contents: read

    steps:
      - name: Checkout Code
        uses: actions/checkout@v4
        with:
          fetch-depth: 100 # 전체 히스토리가 아닌 필요한 만큼만 Shallow-Clone 수행

      - name: Set up Python
        uses: actions/setup-python@v5
        with:
          python-version: '3.13'
          cache: 'pip' # pip 가상 패키지 캐싱 추가

      - name: Install Antigravity SDK
        run: |
          python -m pip install --upgrade pip
          pip install google-antigravity

      - name: Fetch Target Branch for Diff comparison
        run: |
          git fetch origin ${{ github.base_ref }} --depth=100

      - name: Generate Git Diff
        run: |
          # 불필요한 lock 파일이나 정적 리소스를 비교군에서 제외하여 토큰 절약
          git diff origin/${{ github.base_ref }}...HEAD -- . ':(exclude)*.lock' ':(exclude)*.json' ':(exclude)*.min.js' > pr_diff.txt

      - name: Run Antigravity Agent Review
        env:
          GEMINI_API_KEY: ${{ secrets.GEMINI_API_KEY }}
          PR_DIFF_PATH: pr_diff.txt
          REVIEW_RESULT_PATH: review_result.md
        run: |
          python .github/scripts/antigravity_review.py

      - name: Post Review Comment to PR
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
        run: |
          if [ -s review_result.md ]; then
            gh pr comment ${{ github.event.pull_request.number }} -F review_result.md
          fi

요약 및 종합 의견

작성된 파일들은 AI 기반의 Pull Request 코드 리뷰 자동화 파이프라인을 구축하는 훌륭한 시도입니다. 다만, 비동기 Python 환경에서의 완벽한 Non-blocking I/O 보장과 GitHub 저장소 특성에 맞춤 설계된 Secrets 보안정책 대응(Forked PR 고려), 그리고 토큰 허용량 제한을 피하기 위한 Diff 최적화가 병행된다면 프로덕션급 협업 환경에서도 오동작 없이 신뢰도

@KTH1007 KTH1007 merged commit 61f1190 into develop May 22, 2026
3 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

chore: Antigravity AI 코드 리뷰 GitHub Actions 워크플로우 설정

1 participant