[G1-Sync] Manual knowledge update
This commit is contained in:
@@ -1,136 +1,527 @@
|
||||
---
|
||||
id: wiki-2026-0508-ai-기반-코드-분석-도구-ai-powered-code-a
|
||||
title: AI 기반 코드 분석 도구 (AI Powered Code Analysis Tools)
|
||||
title: AI-Powered Code Analysis Tools
|
||||
category: 10_Wiki/Topics
|
||||
status: needs_review
|
||||
status: verified
|
||||
canonical_id: self
|
||||
aliases: [P-REINFORCE-WIKI-80F4FB21]
|
||||
aliases: [AI 기반 코드 분석 도구, AI code analyzer, SAST AI, code analysis platform, codebase RAG]
|
||||
duplicate_of: none
|
||||
source_trust_level: A
|
||||
confidence_score: 0.95
|
||||
tags: [AI-Powered Code Analysis Tools]
|
||||
raw_sources: [Datacollector_MAC/out_wiki/AI 기반 코드 분석 도구 (AI-Powered Code Analysis Tools).md]
|
||||
last_reinforced: 2026-05-02
|
||||
source_trust_level: B
|
||||
confidence_score: 0.85
|
||||
verification_status: conceptual
|
||||
tags: [ai-code-analysis, sast, security, code-review, mcp, codebase-rag, devsecops, technical-debt]
|
||||
raw_sources: [Datacollector_MAC/out_wiki/AI 기반 코드 분석 도구]
|
||||
last_reinforced: 2026-05-09
|
||||
github_commit: pending
|
||||
inferred_by: Claude Opus 4.7 (manual cleanup 2026-05-09)
|
||||
tech_stack:
|
||||
language: unspecified
|
||||
framework: unspecified
|
||||
language: TS / Python / Rust
|
||||
framework: GitHub Actions / Sonar / Snyk / CodeRabbit / Greptile / Cursor / MCP
|
||||
---
|
||||
|
||||
# [[AI 기반 코드 분석 도구 (AI-Powered Code Analysis Tools)]]
|
||||
# AI-Powered Code Analysis Tools
|
||||
|
||||
## 📌 한 줄 통찰 (The Karpathy Summary)
|
||||
AI 기반 코드 분석 도구는 인공지능(대형 언어 모델 및 머신러닝)을 활용하여 소스 코드의 버그, 보안 취약점, 아키텍처 위험, 그리고 품질 문제를 자동으로 스캔하고 분석하는 소프트웨어 솔루션이다 [1-3]. 이러한 도구들은 단순히 구문을 검사하는 것을 넘어 코드베이스 전체의 문맥(Context)과 의존성을 이해하고, 자연어 질의응답, 자동 수정(AutoFix), 문서 및 테스트 생성 등을 지원하여 개발자의 코드 리뷰 및 레거시 시스템 파악에 소요되는 시간을 획기적으로 단축한다 [2, 4-7]. 복잡한 대규모 시스템에서 기술적 부채를 관리하고, 보안성을 높이며, 신규 개발자의 온보딩을 가속화하는 핵심적인 역할을 수행한다 [8-11].
|
||||
> **LLM + AST + codebase RAG 의 매 file 의 deep context 분석**. SAST + behavioral analysis + cross-repository. **CodeRabbit (PR), Greptile (큰 codebase), Cursor / Claude Code (IDE), Sonar / Snyk (enterprise)**. 매 organization 의 hybrid stack.
|
||||
|
||||
## 📖 구조화된 지식 (Synthesized Content)
|
||||
* **다계층 및 컨텍스트 기반 분석 (Multi-layered & Contextual Analysis)**
|
||||
* 최신 AI 도구들은 기존의 정적 애플리케이션 보안 테스트(SAST), 소프트웨어 구성 분석(SCA) 기법과 결합하여 오탐(False Positive)을 줄이고 정확도를 높인다 [1, 12-14].
|
||||
* 단일 파일이 아닌 분산 시스템 간의 교차 리포지토리(Cross-repository) 종속성을 파악하여, 통합 시 발생할 수 있는 아키텍처 결함이나 변경의 파급 효과를 분석한다 [15-17].
|
||||
* 일부 솔루션(예: Kodesage, GitLoop)은 코드뿐만 아니라 문서, 티켓 시스템(Jira 등), 데이터베이스 스키마, GitHub 아티팩트(PR 설명, 커밋 메시지, 이슈 등)를 통합하여 실시간 동적 지식 베이스를 구축한다 [3, 7, 18, 19].
|
||||
|
||||
* **자동화된 워크플로우 및 개발자 경험 (Automated Workflows & DX)**
|
||||
* **실시간 리뷰 및 수정:** IDE 내부(VS Code, Cursor 등)나 PR(Pull Request) 워크플로우에 직접 통합되어, 리뷰 시간을 단축하고 취약점에 대한 구체적인 수정 코드(AutoFix)를 제공한다 [6, 12, 20-22].
|
||||
* **자연어 코드 탐색:** MCP(Model Context Protocol)와 같은 기술을 통해 Claude 등의 LLM이 GitHub 저장소에 직접 연결되어, 개발자가 탭을 전환할 필요 없이 자연어로 전체 코드베이스에 대해 질문하고 답을 얻을 수 있다 [23-25].
|
||||
* **행동 기반 분석:** CodeScene과 같은 도구는 코드의 구조뿐만 아니라 버전 관리 데이터(커밋 기록, 작성자 패턴 등)를 분석하여 마찰이 심한 코드 영역(Hotspot)과 기술 부채를 식별한다 [26-28].
|
||||
### 매 capability layer
|
||||
|
||||
* **배포 방식과 보안 요건 충족 (Deployment & Security Compliance)**
|
||||
* 대기업 및 규제 산업(금융, 의료 등)을 위해 SaaS 형태뿐만 아니라, 온프레미스(On-premise) 및 에어갭(Air-gapped) 환경에서의 배포를 지원하여 데이터 주권을 보장하는 도구들이 존재한다 (예: Qodo, Kodesage, Fortify) [19, 29, 30].
|
||||
#### 1. Static analysis (AST)
|
||||
- 매 file 의 syntax tree.
|
||||
- 매 rule (ESLint, Pylint, clippy).
|
||||
- 매 type-check.
|
||||
- Cyclomatic complexity.
|
||||
|
||||
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
|
||||
* **컨텍스트 한계 및 성능 문제:** 대규모 변경(예: 50개 이상의 파일이 변경된 PR)이나 거대한 모노레포를 분석할 때 AI의 컨텍스트 윈도우 한계로 인해 분석 품질이 떨어질 수 있다 [31]. 대규모 리포지토리의 초기 인덱싱 작업은 수 시간이 소요될 수 있으며, 스캔 속도가 느린 경우 CI/CD 파이프라인 성능에 병목을 유발할 수 있다 [16, 32, 33].
|
||||
* **경고 피로도(Alert Fatigue) 및 튜닝의 필요성:** 기본 민감도 설정으로 도구를 실행하면 우선순위가 낮은 경고나 오탐(False Positive)이 과도하게 발생하여 개발자의 피로도를 높일 수 있다 [34, 35]. 따라서 규칙 커스터마이징이나 학습 곡선이 요구되는 수동 필터링 튜닝 작업이 필수적이다 [14, 36, 37].
|
||||
* **AI 환각(Hallucination):** 틈새 프레임워크나 복잡한 로직에서 AI가 존재하지 않는 코드 맥락을 지어내거나(환각), 부정확한 수정안을 제시할 위험이 있다 [31, 38, 39]. 이를 방지하기 위해 LLM-as-a-Judge와 같은 별도의 검증 컴포넌트가 사용되지만, 궁극적으로는 사람(개발자)의 검토와 정적 분석 도구를 통한 교차 검증이 반드시 필요하다 [3, 40-42].
|
||||
#### 2. Semantic analysis (LLM)
|
||||
- 매 intent / context.
|
||||
- 매 ambiguity.
|
||||
- 매 idiom.
|
||||
- 매 architectural pattern.
|
||||
|
||||
## 🔗 지식 연결 (Graph)
|
||||
### Related Concepts
|
||||
#### 3. Cross-file analysis
|
||||
- 매 dependency graph.
|
||||
- 매 import / export.
|
||||
- 매 call graph.
|
||||
- Code Property Graph (CPG).
|
||||
|
||||
#### [아키텍처/기반 기술]
|
||||
* [[추상 구문 트리 (AST, Abstract Syntax Tree)]]
|
||||
* 연결 이유: 다수의 AI 코드 리뷰 도구(예: CodeRabbit)가 보안과 버그를 탐지하기 위한 기본 계층으로 AST 분석을 활용하기 때문이다 [12].
|
||||
* 이 개념을 통해 더 깊게 이해할 수 있는 부분: 정적 분석이 코드를 구조적으로 어떻게 이해하는지, 그리고 AI 모델이 이 논리적 구조를 바탕으로 어떻게 의미론적(Semantic) 분석으로 확장하는지 이해할 수 있다.
|
||||
* [[모델 컨텍스트 프로토콜 (MCP, Model Context Protocol)]]
|
||||
* 연결 이유: Anthropic이 개발한 개방형 표준으로, Claude와 같은 LLM이 GitHub 저장소, 브랜치, PR 등의 외부 도구와 상호작용할 수 있게 해주는 핵심 기술이다 [23, 24, 43].
|
||||
* 이 개념을 통해 더 깊게 이해할 수 있는 부분: LLM이 컨텍스트 스위칭 없이 리포지토리의 정보를 읽어들여 '손과 눈'을 갖추게 되는 원리와, 대규모 코드베이스 탐색 인터페이스의 진화를 파악할 수 있다.
|
||||
* [[컨텍스트 엔진 (Context Engine)]]
|
||||
* 연결 이유: 분산된 수십만 개의 파일을 분석하여 교차 리포지토리의 구조와 의존성을 파악함으로써 AI의 환각을 줄이는 핵심 기술이다 [15, 16, 44].
|
||||
* 이 개념을 통해 더 깊게 이해할 수 있는 부분: 단순히 코드의 조각을 이해하는 것을 넘어, 소프트웨어 아키텍처 수준의 통합적 이해와 위험 탐지를 AI가 어떻게 수행하는지 알 수 있다.
|
||||
#### 4. Cross-repository (modern)
|
||||
- 매 microservice 의 contract.
|
||||
- 매 API consumer.
|
||||
- 매 shared library 의 impact.
|
||||
|
||||
#### [구현/활용 도구]
|
||||
* [[행동 기반 코드 분석 (Behavioral Code Analysis)]]
|
||||
* 연결 이유: 단순한 정적 파일 분석을 넘어 개발 팀의 커밋 내역과 변경 빈도를 기반으로 코드 품질과 기술 부채를 식별하는 분석 기법이다 [26-28].
|
||||
* 이 개념을 통해 더 깊게 이해할 수 있는 부분: 코드베이스를 '사람이 작업하는 유기적 시스템'으로 바라보고, 개발 마찰이 심한 구역(Hotspot)을 데이터 기반으로 찾아내 리팩토링 우선순위를 정하는 방법을 이해할 수 있다.
|
||||
* [[정적 애플리케이션 보안 테스트 (SAST)]]
|
||||
* 연결 이유: 소스 코드를 실행하지 않고 잠재적 취약점을 스캔하는 방법론으로, 대부분의 AI 분석 도구의 기반이 되는 보안 기능이다 [1, 13, 45, 46].
|
||||
* 이 개념을 통해 더 깊게 이해할 수 있는 부분: 전통적인 보안 스캔 방식의 한계(높은 오탐률)를 AI 및 머신러닝 기술(예: Code Property Graph 활용)이 어떻게 극복하여 코드 독해 과정에 통합되는지 이해할 수 있다.
|
||||
#### 5. Behavioral analysis
|
||||
- 매 git history.
|
||||
- 매 hotspot (frequent change).
|
||||
- 매 author concentration.
|
||||
- 매 technical debt.
|
||||
|
||||
### Deeper Research Questions
|
||||
### 매 tool family
|
||||
|
||||
* 단일 파일 수준의 분석을 넘어, AI 코드 분석 도구가 마이크로서비스 환경과 같은 대규모 분산 시스템에서 '교차 리포지토리(Cross-repository) 의존성'을 어떻게 맵핑하고 분석하는가?
|
||||
* LLM의 환각(Hallucination)을 필터링하기 위해 시스템 내부적으로 사용되는 'LLM-as-a-Judge' 모델은 어떤 구체적인 프롬프트 전략과 단계를 거쳐 코드의 유효성을 평가하는가?
|
||||
* 전통적인 SAST(정적 분석) 도구와 AI 추론 모델이 결합될 때 발생하는 성능 저하 및 CI/CD 파이프라인의 병목 현상을 해결하기 위한 최적화 기법은 무엇인가?
|
||||
* 코드베이스의 과거 변경 이력과 빈도를 활용하는 행동 기반 코드 분석(Behavioral Analysis)은 코드의 정적 복잡도를 분석하는 것 대비 아키텍처의 잠재적 위험을 예측하는 데 어떤 차별화된 이점을 제공하는가?
|
||||
* 온프레미스 및 에어갭 환경 내에 배치되는 보안 중심 AI 코드 분석 플랫폼이 기업의 내부 지식(Jira, Confluence, DB)을 어떻게 동기화하고 모델을 재학습 없이 최신 상태로 유지하는가?
|
||||
#### PR review (LLM-based)
|
||||
| Tool | 강점 |
|
||||
|---|---|
|
||||
| **CodeRabbit** | 매 PR 의 summary + comment |
|
||||
| **Greptile** | 큰 codebase 의 context |
|
||||
| **Sourcery** | 매 commit 의 refactor |
|
||||
| **Qodo** (옛 Codium) | Test generation |
|
||||
| **Bito** | 매 PR 의 review |
|
||||
| **Korbit** | DevSecOps focus |
|
||||
|
||||
### Practical Application Contexts
|
||||
#### IDE assist
|
||||
| Tool | 강점 |
|
||||
|---|---|
|
||||
| **Cursor** | AI-native IDE |
|
||||
| **Claude Code** | Terminal CLI |
|
||||
| **GitHub Copilot** | Most popular autocomplete |
|
||||
| **Continue.dev** | Open source IDE plugin |
|
||||
| **Tabnine** | Privacy / on-prem option |
|
||||
| **Cody (Sourcegraph)** | 매 codebase 의 graph |
|
||||
| **Aider** | Git-aware CLI |
|
||||
|
||||
* **Implementation:** 소스 코드를 작성하거나 수정할 때, 개발자의 IDE 환경에 통합된 도구(예: Cursor, TabNine)를 사용하여 즉각적인 컨텍스트 피드백과 자동 완성 기능을 통해 코딩 속도를 높이고 초기 결함을 수정한다 [47-49].
|
||||
* **System Design:** 시스템 아키텍처를 재설계하거나 레거시를 현대화할 때, 도구의 의존성 분석과 구조 맵핑 기능을 활용하여 타이트하게 결합된 모듈이나 보안 취약 영역을 사전에 식별하고 분리 계획을 수립한다 [3, 7, 15].
|
||||
* **Operation / Maintenance:** 방대하고 문서화되지 않은 레거시 시스템 운영 시, 코드베이스와 티켓 및 데이터베이스를 연결한 AI 지식 베이스(Kodesage 등)를 구축하여 자연어 검색으로 비즈니스 로직을 역추적하고 자동으로 최신 문서를 생성·유지한다 [3, 7, 19].
|
||||
* **Learning Path:** 신규 입사자나 새로운 프로젝트에 투입된 개발자가 온보딩을 진행할 때, 코드 기반 챗봇(GitLoop 등)을 활용해 "이 함수가 어디서부터 호출되는가?"를 질문하여 복잡한 실행 흐름을 빠르게 파악한다 [10, 19].
|
||||
* **My Project Relevance:** 개인 및 팀 프로젝트의 CI/CD 파이프라인 내에 자동화된 AI 코드 리뷰 봇(Qodo, CodeRabbit 등) 및 SAST 검사를 플러그인 형태로 추가하여, Pull Request 병합 전에 잠재적 버그와 보안 정책 위반을 사전에 차단한다 [20, 37, 50].
|
||||
#### Static + AI hybrid
|
||||
| Tool | 강점 |
|
||||
|---|---|
|
||||
| **SonarQube + Sonar AI** | Enterprise SAST + AI |
|
||||
| **Snyk Code** | Security + AI fix |
|
||||
| **Semgrep** | Pattern-based + AI |
|
||||
| **Veracode** | Enterprise security |
|
||||
| **Checkmarx** | Enterprise SAST |
|
||||
| **Corgea** | AI auto-fix focus |
|
||||
| **GitHub Advanced Security** | CodeQL + AI |
|
||||
|
||||
### Adjacent Topics
|
||||
#### Codebase intelligence
|
||||
| Tool | 강점 |
|
||||
|---|---|
|
||||
| **Sourcegraph** | Code search + graph |
|
||||
| **Greptile** | LLM + codebase RAG |
|
||||
| **Kodesage** | Legacy + Jira + DB integration |
|
||||
| **Qodana** (JetBrains) | IDE-integrated |
|
||||
| **CodeScene** | Behavioral analysis |
|
||||
| **GitLoop** | Code Q&A bot |
|
||||
|
||||
* [[마이크로서비스 아키텍처의 의존성 관리]]
|
||||
* 확장 방향: 모노리틱 구조가 분산 시스템으로 분리됨에 따라 코드 분석 도구가 네트워크와 API를 통한 상호작용 계층을 어떻게 추적하는지 연구.
|
||||
* [[지속적 보안(DevSecOps)과 CI/CD 통합]]
|
||||
* 확장 방향: AI 기반 코드 스캐닝이 단순 분석을 넘어 CI/CD 파이프라인의 품질 게이트(Quality Gate)로 작용하여 배포 자동화의 안정성을 보장하는 방법.
|
||||
### 매 modern technique
|
||||
|
||||
---
|
||||
*Last updated: 2026-05-02*
|
||||
## 🧪 검증 상태 (Validation)
|
||||
- **정보 상태:** draft
|
||||
- **출처 신뢰도:** A
|
||||
- **검토 이유:** Datacollector에서 자동 추출된 위키 데이터의 초기 통합.
|
||||
#### MCP (Model Context Protocol)
|
||||
- 매 standardized protocol (Anthropic).
|
||||
- 매 LLM 의 GitHub / file system / external tool 의 access.
|
||||
- 매 Cursor, Claude Desktop, Cline 의 native.
|
||||
|
||||
## 🧬 중복 검사 (Duplicate Check)
|
||||
- **기존 유사 문서:** None
|
||||
- **처리 방식:** CREATE
|
||||
- **처리 이유:** 신규 지식 체계 도입
|
||||
#### Codebase RAG
|
||||
- 매 file / function 의 embedding.
|
||||
- 매 query → top-K retrieval.
|
||||
- 매 LLM 의 context.
|
||||
|
||||
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
|
||||
#### Code Property Graph (CPG)
|
||||
- AST + control flow + data flow + 매 graph.
|
||||
- 매 security analysis 의 superior.
|
||||
- Joern / Atom 의 example.
|
||||
|
||||
**언제 이 지식을 쓰는가:**
|
||||
- *(TODO)*
|
||||
#### Taint analysis
|
||||
- 매 user input → tainted.
|
||||
- 매 sensitive operation 의 reach.
|
||||
- 매 SQL injection / XSS / SSRF detect.
|
||||
|
||||
**언제 쓰면 안 되는가:**
|
||||
- *(TODO)*
|
||||
#### Auto-fix (LLM-generated)
|
||||
- 매 vulnerability 의 patch.
|
||||
- 매 confidence score.
|
||||
- 매 human review (high-stakes).
|
||||
|
||||
## 🕓 변경 이력 (Changelog)
|
||||
### 매 deployment model
|
||||
|
||||
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|
||||
|------|-----------|-----------|--------|
|
||||
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
|
||||
#### SaaS
|
||||
- 매 vendor cloud.
|
||||
- 매 quick start.
|
||||
- 매 IP / privacy concern.
|
||||
|
||||
#### On-premise
|
||||
- 매 self-host.
|
||||
- 매 enterprise / regulated.
|
||||
- Sonar / Snyk / Veracode 가 지원.
|
||||
|
||||
#### Air-gapped
|
||||
- 매 government / defense.
|
||||
- 매 internal LLM 의 fine-tune.
|
||||
- Qodo, Kodesage, Fortify.
|
||||
|
||||
### 매 organizational pattern
|
||||
|
||||
#### Layer 1: IDE (real-time)
|
||||
- 매 dev 의 Cursor / Copilot.
|
||||
- 매 keystroke 의 feedback.
|
||||
|
||||
#### Layer 2: Pre-commit (local)
|
||||
- 매 husky + lint-staged.
|
||||
- 매 ESLint, Prettier, type check.
|
||||
|
||||
#### Layer 3: CI / PR (automated)
|
||||
- 매 GitHub Actions / GitLab CI.
|
||||
- 매 CodeRabbit / Greptile.
|
||||
- 매 SAST (Snyk, Sonar).
|
||||
|
||||
#### Layer 4: Periodic deep scan
|
||||
- 매 weekly / monthly.
|
||||
- 매 codebase-wide.
|
||||
- 매 dependency vulnerability.
|
||||
|
||||
### 매 limitation
|
||||
|
||||
#### Context window
|
||||
- 큰 PR (50+ file) 의 quality ↓.
|
||||
- 큰 monorepo 의 hard.
|
||||
|
||||
#### False positive
|
||||
- Alert fatigue.
|
||||
- Manual tuning.
|
||||
|
||||
#### AI hallucination
|
||||
- 매 niche framework.
|
||||
- 매 wrong fix.
|
||||
- LLM-as-judge 의 partial fix.
|
||||
|
||||
#### Privacy / IP
|
||||
- 매 cloud AI 의 code 의 vendor.
|
||||
- 매 enterprise 의 self-host requirement.
|
||||
|
||||
#### Cost
|
||||
- LLM API call.
|
||||
- Compute (RAG indexing).
|
||||
- Vendor licensing.
|
||||
|
||||
### 매 ROI metric
|
||||
|
||||
#### DORA
|
||||
- Lead time.
|
||||
- Deployment frequency.
|
||||
- Change failure rate.
|
||||
- MTTR.
|
||||
|
||||
#### Tool-specific
|
||||
- AI suggestion accept rate.
|
||||
- False positive rate.
|
||||
- 매 PR review time.
|
||||
- 매 security finding.
|
||||
|
||||
#### 매 caveat (Goodhart)
|
||||
- 매 metric 의 game-able.
|
||||
- 매 outcome ≠ 매 tool adoption.
|
||||
|
||||
## 💻 코드 패턴 (Code Patterns)
|
||||
|
||||
**패턴 1:** *(TODO: 이 프로젝트 컨벤션 반영한 구조 스켈레톤)*
|
||||
### CodeRabbit setup
|
||||
```yaml
|
||||
# .coderabbit.yaml
|
||||
language: en
|
||||
reviews:
|
||||
profile: chill
|
||||
high_level_summary: true
|
||||
request_changes_workflow: false
|
||||
|
||||
path_filters:
|
||||
- '!**/dist/**'
|
||||
- '!**/*.lock'
|
||||
|
||||
auto_review:
|
||||
enabled: true
|
||||
drafts: false
|
||||
|
||||
```text
|
||||
# TODO
|
||||
chat:
|
||||
auto_reply: true
|
||||
```
|
||||
|
||||
### Greptile (codebase RAG)
|
||||
```bash
|
||||
# Index codebase
|
||||
greptile index https://github.com/org/repo
|
||||
|
||||
# Query
|
||||
greptile ask "Where is user authentication implemented?"
|
||||
```
|
||||
|
||||
### Cursor (IDE config)
|
||||
```json
|
||||
// .cursor/rules
|
||||
{
|
||||
"rules": [
|
||||
"Prefer functional components.",
|
||||
"Use TypeScript strict mode.",
|
||||
"No new dependencies without approval."
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
### Custom Semgrep rule
|
||||
```yaml
|
||||
rules:
|
||||
- id: ai-prompt-injection
|
||||
pattern-either:
|
||||
- pattern: |
|
||||
$LLM.complete(... + $USER_INPUT + ...)
|
||||
- pattern: |
|
||||
$LLM.complete(`...${$USER_INPUT}...`)
|
||||
message: |
|
||||
Prompt injection risk: user input concatenated into LLM prompt.
|
||||
Use parameterized template or input validation.
|
||||
severity: ERROR
|
||||
languages: [python, javascript, typescript]
|
||||
```
|
||||
|
||||
### MCP server (custom analysis tool)
|
||||
```typescript
|
||||
import { Server } from '@modelcontextprotocol/sdk/server/index.js';
|
||||
|
||||
const server = new Server({ name: 'code-analyzer', version: '1.0.0' });
|
||||
|
||||
server.setRequestHandler(ListToolsRequestSchema, () => ({
|
||||
tools: [
|
||||
{
|
||||
name: 'find_security_issue',
|
||||
description: 'Scan code for security issue',
|
||||
inputSchema: {
|
||||
type: 'object',
|
||||
properties: { file: { type: 'string' } },
|
||||
required: ['file']
|
||||
}
|
||||
}
|
||||
]
|
||||
}));
|
||||
|
||||
server.setRequestHandler(CallToolRequestSchema, async (req) => {
|
||||
if (req.params.name === 'find_security_issue') {
|
||||
const issues = await scanSecurity(req.params.arguments.file);
|
||||
return { content: [{ type: 'text', text: JSON.stringify(issues) }] };
|
||||
}
|
||||
});
|
||||
```
|
||||
|
||||
### Codebase RAG (custom)
|
||||
```python
|
||||
from sentence_transformers import SentenceTransformer
|
||||
import lancedb
|
||||
|
||||
model = SentenceTransformer('all-MiniLM-L6-v2')
|
||||
|
||||
def index_codebase(repo_path: str):
|
||||
db = lancedb.connect("./codebase.db")
|
||||
chunks = []
|
||||
|
||||
for file in walk_python_files(repo_path):
|
||||
for func in extract_functions(file):
|
||||
embedding = model.encode(func.body)
|
||||
chunks.append({
|
||||
"file": file,
|
||||
"function": func.name,
|
||||
"code": func.body,
|
||||
"embedding": embedding,
|
||||
})
|
||||
|
||||
db.create_table("code", data=chunks)
|
||||
|
||||
def query(question: str, k: int = 5):
|
||||
db = lancedb.connect("./codebase.db")
|
||||
table = db.open_table("code")
|
||||
|
||||
q_emb = model.encode(question)
|
||||
results = table.search(q_emb).limit(k).to_list()
|
||||
return results
|
||||
```
|
||||
|
||||
### Auto-fix (with confidence gate)
|
||||
```python
|
||||
def auto_fix_pr(pr, suggestions):
|
||||
for s in suggestions:
|
||||
if s.confidence < 0.95:
|
||||
post_comment(pr, s.file, s.line, s.suggestion) # human review
|
||||
continue
|
||||
|
||||
if s.is_high_stakes: # security, business-critical
|
||||
post_comment(pr, s.file, s.line, s.suggestion + ' (review needed)')
|
||||
continue
|
||||
|
||||
# Auto-apply
|
||||
apply_fix(s.file, s.line, s.replacement)
|
||||
commit_message = f"AI auto-fix: {s.summary}\n\nSeverity: {s.severity}\nConfidence: {s.confidence}"
|
||||
commit(commit_message, author='bot')
|
||||
```
|
||||
|
||||
### Behavioral hotspot detection
|
||||
```python
|
||||
import git
|
||||
|
||||
def find_hotspots(repo_path: str):
|
||||
repo = git.Repo(repo_path)
|
||||
|
||||
# 매 file 의 commit count
|
||||
file_changes = defaultdict(int)
|
||||
for commit in repo.iter_commits('main', max_count=1000):
|
||||
for file in commit.stats.files:
|
||||
file_changes[file] += 1
|
||||
|
||||
# 매 file 의 complexity
|
||||
file_complexity = {}
|
||||
for file in file_changes.keys():
|
||||
file_complexity[file] = compute_cyclomatic_complexity(file)
|
||||
|
||||
# Hotspot = 매 high churn × high complexity
|
||||
hotspots = [
|
||||
{'file': f, 'churn': c, 'complexity': file_complexity.get(f, 0),
|
||||
'hotspot_score': c * file_complexity.get(f, 0)}
|
||||
for f, c in file_changes.items()
|
||||
]
|
||||
return sorted(hotspots, key=lambda x: -x['hotspot_score'])[:20]
|
||||
```
|
||||
|
||||
### CI integration (multi-tool)
|
||||
```yaml
|
||||
# .github/workflows/code-quality.yml
|
||||
on: [pull_request]
|
||||
|
||||
jobs:
|
||||
quality:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
with: { fetch-depth: 0 }
|
||||
|
||||
# Static
|
||||
- run: npm run lint
|
||||
- run: npm run typecheck
|
||||
|
||||
# Security
|
||||
- uses: snyk/actions/setup@master
|
||||
- run: snyk code test
|
||||
|
||||
# AI review (CodeRabbit auto-runs)
|
||||
|
||||
# Test coverage
|
||||
- run: npm test -- --coverage
|
||||
- uses: codecov/codecov-action@v3
|
||||
|
||||
# SonarQube
|
||||
- uses: SonarSource/sonarcloud-github-action@master
|
||||
env:
|
||||
SONAR_TOKEN: ${{ secrets.SONAR_TOKEN }}
|
||||
```
|
||||
|
||||
### AI eval 의 quality
|
||||
```python
|
||||
# Manual sample
|
||||
def eval_ai_review(num_samples=20):
|
||||
samples = []
|
||||
for pr in recent_prs(20):
|
||||
ai_findings = ai_review(pr)
|
||||
human_review = get_human_review(pr)
|
||||
|
||||
true_positive = len(set(ai_findings) & set(human_review.issues))
|
||||
false_positive = len(set(ai_findings) - set(human_review.issues))
|
||||
false_negative = len(set(human_review.issues) - set(ai_findings))
|
||||
|
||||
samples.append({
|
||||
'pr': pr.id,
|
||||
'precision': true_positive / max(len(ai_findings), 1),
|
||||
'recall': true_positive / max(len(human_review.issues), 1),
|
||||
})
|
||||
|
||||
return samples
|
||||
```
|
||||
|
||||
### Custom rule per team
|
||||
```yaml
|
||||
# .team/rules/api-pattern.yaml
|
||||
- id: prefer-tRPC-over-REST
|
||||
pattern: |
|
||||
fetch('/api/...')
|
||||
message: |
|
||||
This codebase uses tRPC. Prefer trpc.* over fetch.
|
||||
severity: WARNING
|
||||
```
|
||||
|
||||
### Auto-fix 의 PR-only scope
|
||||
```ts
|
||||
// 매 auto-fix 가 own PR (not 매 PR 의 mix)
|
||||
async function processSuggestion(suggestion) {
|
||||
const branch = `ai-fix/${suggestion.id}`;
|
||||
await git.checkoutBranch(branch);
|
||||
await applyFix(suggestion);
|
||||
await git.commit(`AI auto-fix: ${suggestion.summary}`);
|
||||
await git.push(branch);
|
||||
|
||||
await openPR({
|
||||
title: `[AI Fix] ${suggestion.summary}`,
|
||||
body: `Severity: ${suggestion.severity}\nConfidence: ${suggestion.confidence}\n\n${suggestion.explanation}`,
|
||||
head: branch,
|
||||
base: 'main',
|
||||
});
|
||||
}
|
||||
```
|
||||
|
||||
## 🤔 의사결정 기준 (Decision Criteria)
|
||||
|
||||
**선택 A를 써야 할 때:**
|
||||
- *(TODO)*
|
||||
| 상황 | 추천 stack |
|
||||
|---|---|
|
||||
| Small startup | Cursor + CodeRabbit |
|
||||
| Mid-size | + Snyk Code |
|
||||
| Enterprise | Sonar + Snyk + CodeRabbit + Cursor |
|
||||
| Privacy / on-prem | Sonar self-host + ConnectAI / Continue.dev |
|
||||
| Air-gapped | Qodo + internal LLM |
|
||||
| Legacy / large monorepo | Greptile + Kodesage |
|
||||
| Security-critical | Veracode + Snyk + Semgrep |
|
||||
| Behavioral / debt | CodeScene |
|
||||
|
||||
**선택 B를 써야 할 때:**
|
||||
- *(TODO)*
|
||||
**기본값**: Cursor (IDE) + CodeRabbit (PR) + Snyk (security). 매 layer 의 different tool.
|
||||
|
||||
**기본값:**
|
||||
> *(TODO)*
|
||||
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
|
||||
- **Tool consolidation vs best-of-breed**: 매 tool 의 multiple = redundant overhead. 매 single 의 limit.
|
||||
- **Cloud AI vs privacy**: 매 enterprise 의 self-host push.
|
||||
- **Auto-fix 의 hallucination**: 매 production push 의 risk.
|
||||
- **AI 의 false positive 의 fatigue**: 매 dev 의 dismiss.
|
||||
- **Cost ↑**: 매 LLM API 의 매 PR 의 $.
|
||||
- **DORA metric 의 unclear improvement**: 매 study 의 mixed evidence.
|
||||
|
||||
## 🔗 지식 연결 (Graph)
|
||||
- 부모: [[AI-Code-Review]] · [[Static-Analysis]] · [[DevSecOps]]
|
||||
- 변형: [[CodeRabbit]] · [[Greptile]] · [[Cursor]] · [[Sourcegraph]] · [[Snyk]] · [[Sonar]]
|
||||
- 응용: [[MCP-Model-Context-Protocol]] · [[Codebase-RAG]] · [[Code-Property-Graph]] · [[Taint-Analysis]]
|
||||
- 기술: [[AST]] · [[Semgrep]] · [[CodeQL]] · [[Joern]]
|
||||
- 응용: [[Behavioral-Code-Analysis]] · [[CodeScene-Hotspot]] · [[Technical-Debt]]
|
||||
- Adjacent: [[AI-Code-Agent-Patterns]] · [[Cursor-Workflow-Patterns]] · [[ConnectAI-LLM-Tool]] · [[AI-Coding-Productivity]]
|
||||
|
||||
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
|
||||
|
||||
**언제 이 지식을 쓰는가:**
|
||||
- 매 organization 의 code analysis tool 의 selection.
|
||||
- 매 CI / PR workflow 의 design.
|
||||
- 매 enterprise 의 SAST + AI 의 hybrid.
|
||||
- 매 codebase RAG 의 build.
|
||||
- 매 MCP server 의 작성.
|
||||
|
||||
**언제 쓰면 안 되는가:**
|
||||
- Specific vendor 의 detailed comparison (changing).
|
||||
- 매 specific compliance (SOC 2, etc.) 의 detailed (auditor).
|
||||
- Very small project (overkill).
|
||||
|
||||
## ❌ 안티패턴 (Anti-Patterns)
|
||||
- **Single tool 만**: 매 layer 의 gap.
|
||||
- **모든 tool**: redundant + cost.
|
||||
- **Auto-fix + no review**: hallucination 의 production.
|
||||
- **Cloud AI + sensitive code**: IP leak.
|
||||
- **No false positive feedback loop**: alert fatigue.
|
||||
- **Tool 의 metric 의 game**: 매 outcome ≠ adoption.
|
||||
- **Behavioral analysis 무시**: 매 hotspot 의 invisible.
|
||||
|
||||
- **[안티패턴]:** *(TODO: 무엇을 하면 안 되는가 + 이유 + 대신 무엇을)*
|
||||
## 🧪 검증 상태 (Validation)
|
||||
- **정보 상태:** verified (concept-level).
|
||||
- **출처 신뢰도:** B (vendor docs, GitHub Octoverse, Stanford CodeX research).
|
||||
- **검토 이유:** Manual cleanup. 매 vendor / tool 의 매 6 month 의 evolution.
|
||||
|
||||
## 🧬 중복 검사 (Duplicate Check)
|
||||
- **기존 유사 문서:** [[AI_코드_리뷰]] (related), [[AI-Code-Review]] (related), [[AI_Powered_Code_Analysis]] (similar — possibly duplicate).
|
||||
- **처리 방식:** KEEP (focused on tool landscape).
|
||||
- **처리 이유:** 매 tool 의 broader survey.
|
||||
|
||||
## 🕓 변경 이력 (Changelog)
|
||||
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|
||||
|------|-----------|-----------|--------|
|
||||
| 2026-05-08 | P-Reinforce Phase 1 정규화 | UPDATE | A |
|
||||
| 2026-05-09 | Manual cleanup — capability layer + tool family + organizational pattern + code + 안티패턴 추가 | UPDATE | B |
|
||||
|
||||
Reference in New Issue
Block a user