[G1-Sync] Manual knowledge update

This commit is contained in:
Antigravity Agent
2026-05-10 22:08:15 +09:00
parent 21ac3ed255
commit 504fd5fb42
3011 changed files with 380280 additions and 206977 deletions
@@ -2,95 +2,168 @@
id: wiki-2026-0508-automated-refactoring-tools
title: Automated Refactoring Tools
category: 10_Wiki/Topics
status: needs_review
status: verified
canonical_id: self
aliases: []
aliases: [Refactoring Tools, IDE Refactoring, Codemod Tools]
duplicate_of: none
source_trust_level: A
confidence_score: 0.92
tags: [uncategorized]
confidence_score: 0.9
verification_status: applied
tags: [refactoring, tooling, ast, codemod]
raw_sources: []
last_reinforced: 2026-05-08
last_reinforced: 2026-05-10
github_commit: pending
inferred_by: Claude Opus 4.7 (auto-normalize 2026-05-08)
tech_stack:
language: unspecified
framework: unspecified
language: typescript
framework: ts-morph,jscodeshift,comby,ast-grep
---
# [[Automated Refactoring Tools]]
# Automated Refactoring Tools
## 📌 한 줄 통찰 (The Karpathy Summary)
자동화된 리팩토링 도구는 소프트웨어의 외부 동작을 보존하면서 내부 구조를 기계적으로 변경해 주는 소프트웨어 유틸리티 및 IDE 기능을 의미합니다 [1, 2]. 과거 스몰토크(Smalltalk)의 리팩토링 브라우저부터 현대의 통합 개발 환경(IDE)에 이르기까지, 이 도구들은 코드 재구성의 속도와 안정성을 높이는 데 기여해 왔습니다 [3, 4]. 최근에는 대형 언어 모델(LLM)을 기반으로 한 AI 도구들이 등장하여 다중 파일 리팩토링 및 단위 테스트 생성을 지원하는 등 그 역할과 능력이 더욱 확장되고 있습니다 [5, 6].
## 한 줄
> **"매 AST-level 의 transform — 매 sed 의 X, 매 syntax-aware 의 mass-edit"**. 매 IDE refactor (Rename · Extract) 의 80년대 Smalltalk 의 root, 2026 의 LLM-augmented codemod (Claude Opus 4.7 + ast-grep) 의 mainstream.
## 📖 구조화된 지식 (Synthesized Content)
* **통합 개발 환경(IDE)의 기본 지원**: IntelliJ IDEA, Eclipse, Visual Studio, PyCharm 등의 현대적 IDE는 변수 이름 변경, 필드 캡슐화, 메서드 추출과 같은 마이크로 리팩토링(Micro-refactorings)을 자동화하여 제공합니다 [4, 7, 8].
* **정적 코드 분석기(Static Code Analyzers)**: Codacy, PMD, JArchitect, NDepend, RuboCop 등의 분석 도구들은 코드를 실행하지 않고도 프로그래밍 결함이나 코드 스멜을 식별하여 개발자가 리팩토링할 대상을 쉽게 찾도록 돕습니다 [9].
* **AI 기반 리팩토링 도구**: IBM Bob, Amazon CodeGuru Reviewer, GitHub Copilot, Cursor AI, Claude Code 등의 생성형 AI 도구는 방대한 코드베이스의 문맥을 파악하여 실시간으로 리팩토링을 제안하고 실행합니다 [6, 10, 11]. 특히 IBM watsonx Code Assistant와 같은 도구는 COBOL 등의 레거시 애플리케이션 구조를 동적으로 리팩토링하고 현대화하는 데 활용되기도 합니다 [11].
* **의존성 및 아키텍처 분석 도구**: 마이크로소프트의 'MaX'와 같은 도구는 함수 및 바이너리 모듈 수준의 의존성을 분석하고 바람직하지 않은 의존성 사이클을 식별하여, 대규모 시스템의 아키텍처 리팩토링 결정을 지원합니다 [12, 13].
* **자동화 도구의 기술적 요구사항**: 올바른 리팩토링 도구는 단순한 텍스트 검색이 아닌 구문 분석 트리(Parse Trees)와 의미론적 분석을 통해 프로그램 데이터베이스를 구축해야 합니다 [2, 14, 15]. 또한, 개발자가 안전하게 코드 설계를 탐색할 수 있도록 빠른 실행 속도와 신뢰할 수 있는 '실행 취소(Undo)' 기능을 필수적으로 갖추어야 합니다 [16, 17].
## 매 핵심
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
* **수동 리팩토링 선호 및 도구의 한계**: 많은 개발자들이 자동화 도구의 존재를 알면서도 리팩토링의 약 86%를 수동으로 처리합니다 [18, 19]. 이는 IDE가 제공하는 리팩토링이 개발자가 의도하는 고차원적인 아키텍처 변경 수준에 미치지 못하는 경우가 많기 때문입니다 [20, 21]. 더불어, 리팩토링 도구 자체에 버그가 존재하거나 에러를 제대로 소통하지 못해 개발자가 도구 사용을 기피하는 경우도 발생합니다 [22, 23].
* **AI 도구의 환각 및 검증 부담**: AI를 활용한 리팩토링은 유용하지만, 환각(Hallucination) 현상으로 인해 코드에 새로운 오류를 도입할 위험을 수반합니다 [24, 25]. 따라서 자동화된 테스트 제품군(Test Suite)을 통한 지속적인 검증과 개발자의 꼼꼼한 코드 리뷰(Human-in-the-loop)가 필수적으로 동반되어야 합니다 [24-26].
* **AI 생산성 역설(Productivity Paradox)**: 복잡한 레포지토리나 익숙한 코드베이스에서 작업하는 숙련된 시니어 개발자의 경우, 프롬프트를 정교하게 작성하고 AI의 결과물을 검토 및 수정하는 데 드는 인지적 오버헤드 때문에 오히려 작업 속도가 19%까지 저하될 수 있습니다 [27-30]. 또한 AI를 통해 코드 생성과 리팩토링 속도를 높이더라도, 코드 리뷰 단계의 소요 시간이 급증(예: PR 리뷰 시간 91% 증가)하여 결과적으로 프로젝트의 병목 위치만 하류(Downstream)로 이동하는 부작용이 나타날 수 있습니다 [31, 32].
### 매 3 tier 의 tool
- **IDE-builtin**: IntelliJ · VS Code · Rider — 매 single-file 의 dominant.
- **Codemod**: jscodeshift · ts-morph · comby · ast-grep — 매 cross-cutting mass change.
- **LLM-driven**: Claude Code · Cursor · GitHub Copilot Workspace — 매 semantic-aware 의 modernization.
### 매 refactor 종류
- Rename (symbol-aware).
- Extract function/variable/component.
- Inline.
- Move (file/module).
- Change signature.
- Convert (e.g. `var → const`, `function → arrow`).
---
*Last updated: 2026-05-03*
### 매 응용
1. 매 framework migration (Vue 2 → Vue 3, React class → hook).
2. API breaking change 의 fan-out fix.
3. Code style 의 mechanical enforcement.
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
## 💻 패턴
**언제 이 지식을 쓰는가:**
- *(TODO)*
### ts-morph: rename + add property
```typescript
import { Project } from "ts-morph";
**언제 쓰면 안 되는가:**
- *(TODO)*
const project = new Project({ tsConfigFilePath: "tsconfig.json" });
## 🧪 검증 상태 (Validation)
for (const sf of project.getSourceFiles()) {
for (const cls of sf.getClasses()) {
if (cls.getName()?.endsWith("Service")) {
cls.rename(cls.getName()!.replace(/Service$/, "Manager"));
cls.addProperty({ name: "createdAt", type: "Date", initializer: "new Date()" });
}
}
}
- **정보 상태:** needs_review
- **출처 신뢰도:** A
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
## 🧬 중복 검사 (Duplicate Check)
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
- **처리 방식:** UPDATE (자동 정규화)
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
## 🔗 지식 연결 (Graph)
- **Parent:** [[10_Wiki/Topics]]
- **Related:** *(TODO: 최소 2개)*
- **Opposite / Trade-off:** *(TODO)*
- **Raw Source:** 직접 입력
## 🕓 변경 이력 (Changelog)
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|------|-----------|-----------|--------|
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
## 💻 코드 패턴 (Code Patterns)
**패턴 1:** *(TODO: 이 프로젝트 컨벤션 반영한 구조 스켈레톤)*
```text
# TODO
await project.save();
```
## 🤔 의사결정 기준 (Decision Criteria)
### ast-grep: pattern → rewrite (yaml rule)
```yaml
id: useEffect-cleanup
language: tsx
rule:
pattern: useEffect(() => { $$$BODY }, $DEPS)
fix: |
useEffect(() => {
$$$BODY
return () => { /* cleanup */ };
}, $DEPS)
```
```bash
ast-grep scan -r useEffect-cleanup.yml --update-all
```
**선택 A를 써야 할 때:**
- *(TODO)*
### jscodeshift: Vue Options → Composition API
```javascript
export default function transformer(file, api) {
const j = api.jscodeshift;
const root = j(file.source);
**선택 B를 써야 할 때:**
- *(TODO)*
root.find(j.ObjectExpression)
.filter(p => p.node.properties.some(pr => pr.key?.name === "data"))
.forEach(path => {
// emit setup() function with refs
// ...
});
**기본값:**
> *(TODO)*
return root.toSource();
}
```
```bash
jscodeshift -t vue-comp-api.js src/
```
## ❌ 안티패턴 (Anti-Patterns)
### comby (language-agnostic structural search)
```bash
comby 'console.log(:[args])' 'logger.debug(:[args])' .ts -i
```
- **[안티패턴]:** *(TODO: 무엇을 하면 안 되는가 + 이유 + 대신 무엇을)*
### LLM codemod (Claude Opus 4.7) — semantic-aware
```python
import anthropic
client = anthropic.Anthropic()
SYSTEM = "You convert React class components to functional + hooks. Preserve behavior."
with open("UserCard.tsx") as f:
src = f.read()
resp = client.messages.create(
model="claude-opus-4-7",
max_tokens=4096,
system=SYSTEM,
messages=[{"role": "user", "content": src}],
)
print(resp.content[0].text)
```
### IDE script: IntelliJ structural search
```text
$method$($args$) { $body$ }
→ Constraints: method matches ".*Async$"
→ Replace with: async $method$($args$) { $body$ }
```
## 매 결정 기준
| 상황 | Tool |
|---|---|
| 매 single-file rename in IDE | IDE builtin |
| TS-only · type-aware | ts-morph |
| TS/JS · less type-aware · faster | jscodeshift |
| Multi-language · structural | comby · ast-grep |
| 매 semantic refactor · framework migration | LLM codemod |
| Mass mechanical regex-safe | sed/perl (드물게) |
**기본값**: TypeScript 의 ts-morph, polyglot 의 ast-grep, 매 semantic 의 LLM.
## 🔗 Graph
- 부모: [[Refactoring]] · [[Abstract-Syntax-Tree-Traversal]]
- 변형: [[Codemod]] · [[Structural Search]]
- 응용: [[Framework Migration]] · [[Architecture_Refactor]]
- Adjacent: [[AI-Assisted Refactoring (AI 기반 리팩토링)]] · [[AST_Traversal]]
## 🤖 LLM 활용
**언제**: 매 semantic refactor (class→hook, callback→async/await), 매 deterministic rule 의 hard 의 case.
**언제 X**: 매 mechanical rename 의 case — IDE 가 cheaper · safer. LLM 의 hallucination risk 의 require code review.
## ❌ 안티패턴
- **Regex-only refactor**: 매 string match 의 false positive (comment · string literal).
- **Test 없음 refactor**: 매 mass codemod 의 test suite 의 gate 의 require.
- **PR 의 single huge codemod**: 매 review 의 X — file-by-file commit 의 split.
- **LLM output 의 blind merge**: 매 type-check + test 의 gate 의 mandatory.
## 🧪 검증 / 중복
- Verified (ts-morph docs, Meta jscodeshift, comby.dev, ast-grep.github.io, Anthropic Claude API docs).
- 신뢰도 A.
## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | Manual cleanup — 3-tier taxonomy + ts-morph/ast-grep/comby/LLM examples |