Claude Code 완전 정복 가이드 Part 6: 고급 패턴과 Best Practices
이 글은 Claude Opus 4.5 을 이용해 초안이 작성되었으며, 이후 퇴고를 거쳤습니다.
예상 소요 시간: 1시간 30분 난이도: ⭐⭐⭐⭐⭐ 사전 요구사항: Part 1-5 완료 Claude Code 버전: 2.1.x (Opus 4.5)
0. Claude Code 2.1 주요 신기능#
본격적인 내용에 앞서, Claude Code 2.1에서 추가된 핵심 기능들을 정리합니다:
| 기능 | 설명 |
|---|---|
| Session Teleportation | /teleport, /remote-env로 로컬↔클라우드 세션 이동 |
| Hot Reload for Skills | Skills 수정 시 재시작 없이 즉시 반영 |
| Setup Hook | --init, --init-only, --maintenance CLI 플래그용 훅 |
| Task Management | 의존성 추적이 포함된 태스크 관리 시스템 |
| Language Output | language 설정으로 출력 언어 지정 |
| Opus 4.5 | Pro 사용자에게 Opus 4.5 모델 제공 |
| respectGitignore | @-mention 파일 선택에서 gitignore 적용 |
| showTurnDuration | 턴 소요 시간 표시 설정 |
1. Hooks: 예외 없는 강제 자동화#
1.1 CLAUDE.md vs Hooks의 근본적 차이#
flowchart TB
subgraph Comparison["CLAUDE.md vs Hooks"]
direction TB
subgraph Advisory["📄 CLAUDE.md = '권고' (Advisory)"]
A1["'테스트를 실행해주세요'<br/>'린트를 돌려주세요'"]
A2["→ Claude가 따를 수도 있고, 잊을 수도 있음<br/>→ 복잡한 대화에서 규칙이 희석될 수 있음"]
end
subgraph Enforcement["⚡ Hooks = '강제' (Enforcement)"]
E1["파일 저장 시 → 자동으로 린트 실행<br/>대화 시작 시 → 자동으로 컨텍스트 로드"]
E2["→ 예외 없이 항상 실행됨<br/>→ Claude의 판단과 무관하게 트리거"]
end
end
style Advisory fill:#fff9c4,color:#000000
style Enforcement fill:#c8e6c9,color:#000000
style A1 fill:#fffde7,color:#000000
style A2 fill:#ffecb3,color:#000000
style E1 fill:#e8f5e9,color:#000000
style E2 fill:#a5d6a7,color:#000000
1.2 Hooks 이벤트 종류#
| 이벤트 | 트리거 시점 | 사용 예시 |
|---|---|---|
PreToolUse |
도구 실행 직전 | 위험한 명령 차단, 로깅 |
PostToolUse |
도구 실행 직후 | 린트 자동 실행, 검증 |
Notification |
알림 발생 시 | 외부 시스템 연동 |
Stop |
작업 완료/중단 시 | 정리 작업, 리포트 |
Setup |
--init, --init-only, --maintenance 실행 시 |
저장소 초기화, 유지보수 (2.1+ 신규) |
💡 Claude Code 2.1+ 변경사항:
- Hook 실행 타임아웃이 60초에서 10분으로 증가했습니다.
- Permission 프롬프트에서 피드백을 제공할 수 있습니다.
1.3 Hook 설정 방법#
.claude/settings.json:
{
"hooks": {
"PreToolUse": [
{
"matcher": "Write|Edit",
"hooks": [
{
"type": "command",
"command": "echo 'File modification detected: $CLAUDE_FILE_PATH'"
}
]
}
],
"PostToolUse": [
{
"matcher": "Write|Edit",
"hooks": [
{
"type": "command",
"command": "if [[ \"$CLAUDE_FILE_PATH\" == *.go ]]; then gofmt -w \"$CLAUDE_FILE_PATH\"; fi"
}
]
},
{
"matcher": "Write|Edit",
"hooks": [
{
"type": "command",
"command": "if [[ \"$CLAUDE_FILE_PATH\" == *.kt ]]; then ktlint -F \"$CLAUDE_FILE_PATH\" 2>/dev/null || true; fi"
}
]
}
]
}
}
1.4 실용적인 Hook 예제#
예제 1: Go 파일 저장 시 자동 포맷팅
{
"hooks": {
"PostToolUse": [
{
"matcher": "Write|Edit",
"hooks": [
{
"type": "command",
"command": "if [[ \"$CLAUDE_FILE_PATH\" == *.go ]]; then gofmt -w \"$CLAUDE_FILE_PATH\" && echo '✓ Formatted'; fi"
}
]
}
]
}
}
예제 2: 테스트 파일 수정 시 해당 테스트 자동 실행
{
"hooks": {
"PostToolUse": [
{
"matcher": "Write|Edit",
"hooks": [
{
"type": "command",
"command": "if [[ \"$CLAUDE_FILE_PATH\" == *_test.go ]]; then go test -v \"$(dirname $CLAUDE_FILE_PATH)/...\" -run \"$(basename $CLAUDE_FILE_PATH .go)\" 2>&1 | head -50; fi"
}
]
}
]
}
}
예제 3: 위험한 파일 수정 방지
{
"hooks": {
"PreToolUse": [
{
"matcher": "Write|Edit",
"hooks": [
{
"type": "command",
"command": "if [[ \"$CLAUDE_FILE_PATH\" == **/production/** ]] || [[ \"$CLAUDE_FILE_PATH\" == *.env ]]; then echo 'ERROR: Protected file' && exit 1; fi"
}
]
}
]
}
}
1.5 Hook vs CLAUDE.md 선택 기준#
flowchart TB
subgraph Choice["🤔 언제 무엇을 사용할까?"]
Q1["'이 규칙은 절대로<br/>예외가 없어야 한다'"] --> A1["⚡ Hook 사용 (강제)<br/>예: 프로덕션 파일 보호, 자동 포맷팅"]
Q2["'이 규칙은 가이드라인이고,<br/>상황에 따라 유연해도 된다'"] --> A2["📄 CLAUDE.md 사용 (권고)<br/>예: 코딩 스타일 선호, 커밋 메시지 형식"]
Q3["'특정 작업 후 자동으로<br/>무언가를 실행해야 한다'"] --> A3["⚡ Hook 사용<br/>예: 파일 저장 후 린트, 테스트 자동 실행"]
Q4["'Claude에게 컨텍스트나<br/>지식을 제공해야 한다'"] --> A4["📄 CLAUDE.md 또는 Skill 사용<br/>예: 프로젝트 구조 설명, API 패턴"]
end
style Q1 fill:#e3f2fd,color:#000000
style Q2 fill:#e3f2fd,color:#000000
style Q3 fill:#e3f2fd,color:#000000
style Q4 fill:#e3f2fd,color:#000000
style A1 fill:#c8e6c9,color:#000000
style A2 fill:#fff9c4,color:#000000
style A3 fill:#c8e6c9,color:#000000
style A4 fill:#fff9c4,color:#000000
2. Subagents 활용 패턴#
2.1 Subagent의 핵심 가치#
Subagents는 격리된 컨텍스트 윈도우에서 작업합니다. 이것이 중요한 이유:
flowchart TB
subgraph Problem["❌ 메인 대화만 사용할 때"]
direction TB
P1["👤 사용자: '이 코드베이스 분석해줘'"]
P2["🤖 Claude: (수백 개 파일 읽기)"]
P3["📊 메인 컨텍스트: ████████████ (가득 참)"]
P4["👤 사용자: '간단한 함수 하나 만들어줘'"]
P5["😰 Claude: (컨텍스트 부족으로 이전 대화 일부 잊음)"]
P1 --> P2 --> P3 --> P4 --> P5
end
subgraph Solution["✅ Subagent 사용할 때"]
direction TB
S1["👤 사용자: '이 코드베이스 분석해줘'"]
S2["🤖 Claude: '분석 작업을 Explore subagent에게 위임합니다'"]
subgraph Subagent["👨💼 Explore Subagent (격리된 컨텍스트)"]
SA1["수백 개 파일 읽기"]
SA2["분석 수행"]
SA3["요약 결과만 반환"]
end
S3["📊 메인 컨텍스트: ████░░░░░░ (여유 있음)"]
S4["👤 사용자: '간단한 함수 하나 만들어줘'"]
S5["😊 Claude: (이전 대화 기억, 정상 작업)"]
S1 --> S2 --> Subagent
Subagent -->|"요약만 전달"| S3
S3 --> S4 --> S5
end
style Problem fill:#ffcdd2,color:#000000
style Solution fill:#c8e6c9,color:#000000
style Subagent fill:#fff9c4,color:#000000
style P5 fill:#ef9a9a,color:#000000
style S5 fill:#a5d6a7,color:#000000
2.2 Built-in Subagents#
Claude Code는 기본 Subagent를 제공합니다:
| Subagent | 용도 | 도구 권한 |
|---|---|---|
Explore |
코드베이스 탐색, 분석 | Read, Grep, Glob (읽기 전용) |
Plan |
계획 수립, 설계 | 제한적 |
claude-code-guide |
Claude Code 문서 조회 | 문서 접근 |
2.3 Custom Subagent 만들기#
.claude/agents/code-reviewer.md:
---
name: code-reviewer
description: 코드 품질과 보안을 검토합니다. PR 리뷰, 코드 분석 요청 시 사용.
tools: Read, Grep, Glob
---
# Code Reviewer Agent
당신은 시니어 개발자로서 코드 리뷰를 수행합니다.
## 리뷰 체크리스트
### 1. 코드 품질
- [ ] 함수가 단일 책임을 가지는가?
- [ ] 네이밍이 명확한가?
- [ ] 중복 코드가 있는가?
- [ ] 복잡도가 적절한가?
### 2. 보안
- [ ] SQL Injection 가능성
- [ ] XSS 가능성
- [ ] 민감 정보 노출
- [ ] 입력 검증
### 3. 성능
- [ ] N+1 쿼리 문제
- [ ] 불필요한 메모리 할당
- [ ] 적절한 인덱스 사용
### 4. 테스트
- [ ] 테스트 커버리지 적절한가?
- [ ] 엣지 케이스 테스트가 있는가?
## 출력 형식
---
## 리뷰 요약
**전체 평가**: [APPROVE / REQUEST_CHANGES / COMMENT]
### 주요 발견 사항
1. **[심각도]** 파일명:라인 - 설명
### 개선 제안
- 제안 1
- 제안 2
### 칭찬할 점
- 잘한 점 1
---
2.4 Subagent 아키텍처 패턴#
패턴 1: Master-Clone (동일 작업 병렬화)
flowchart TB
subgraph MasterClone["🔄 Master-Clone 패턴"]
direction TB
Task["👤 '프로젝트의 모든 TODO 주석을 찾아서 정리해줘'"]
Task --> Master1["🤖 Master Claude"]
Master1 --> Clone1["👥 Clone 1<br/>(src/)<br/>Explore"]
Master1 --> Clone2["👥 Clone 2<br/>(test/)<br/>Explore"]
Master1 --> Clone3["👥 Clone 3<br/>(docs/)<br/>Explore"]
Clone1 --> Master2
Clone2 --> Master2
Clone3 --> Master2
Master2["🤖 Master<br/>결과 통합"]
Benefits["✨ 장점: 병렬 처리로 속도 향상<br/>📁 적합: 대규모 코드베이스 검색, 분석"]
end
style Task fill:#e3f2fd,color:#000000
style Master1 fill:#bbdefb,color:#000000
style Master2 fill:#bbdefb,color:#000000
style Clone1 fill:#c8e6c9,color:#000000
style Clone2 fill:#c8e6c9,color:#000000
style Clone3 fill:#c8e6c9,color:#000000
style Benefits fill:#f5f5f5,color:#000000
패턴 2: Lead-Specialist (전문가 분업)
flowchart TB
subgraph LeadSpecialist["👔 Lead-Specialist 패턴"]
direction TB
Task["👤 '새로운 결제 API 기능을 구현해줘'"]
Task --> Lead1["🎯 Lead Claude"]
Lead1 --> Spec1["📐 API Design<br/>Specialist"]
Lead1 --> Spec2["🔒 Security<br/>Auditor"]
Lead1 --> Spec3["🧪 Test<br/>Writer"]
Spec1 --> Out1["API 설계서"]
Spec2 --> Out2["보안 검토"]
Spec3 --> Out3["테스트 코드"]
Out1 --> Lead2
Out2 --> Lead2
Out3 --> Lead2
Lead2["🎯 Lead<br/>최종 구현"]
Benefits["✨ 장점: 각 전문가의 깊은 지식 활용<br/>📁 적합: 복잡한 기능 구현, 다양한 관점 필요 시"]
end
style Task fill:#e3f2fd,color:#000000
style Lead1 fill:#ffccbc,color:#000000
style Lead2 fill:#ffccbc,color:#000000
style Spec1 fill:#c8e6c9,color:#000000
style Spec2 fill:#fff9c4,color:#000000
style Spec3 fill:#bbdefb,color:#000000
style Benefits fill:#f5f5f5,color:#000000
2.5 Subagent 호출 방법#
# 자연어로 위임
"Explore subagent를 사용해서 이 코드베이스의 인증 로직을 찾아줘"
# 명시적 지시
"code-reviewer subagent에게 이 PR의 변경사항을 리뷰하도록 해줘"
# 병렬 실행 요청
"5개의 Explore subagent를 병렬로 실행해서 각 모듈의 TODO를 찾아줘"
3. MCP (Model Context Protocol) 통합#
3.1 MCP란?#
MCP는 Claude Code를 외부 시스템과 연결하는 프로토콜입니다.
flowchart TB
subgraph MCPOverview["🔌 MCP 개요"]
direction TB
subgraph ClaudeCode["Claude Code"]
CC1["'데이터베이스에서 사용자 목록 조회해줘'"]
CC2["'Slack에 메시지 보내줘'"]
CC3["'GitHub 이슈 생성해줘'"]
end
ClaudeCode -->|"MCP Protocol"| MCP1
ClaudeCode -->|"MCP Protocol"| MCP2
ClaudeCode -->|"MCP Protocol"| MCP3
MCP1["🗄️ PostgreSQL<br/>MCP Server"]
MCP2["💬 Slack<br/>MCP Server"]
MCP3["🐙 GitHub<br/>MCP Server"]
MCP1 --> DB["🗄️ Database"]
MCP2 --> Slack["💬 Slack API"]
MCP3 --> GitHub["🐙 GitHub API"]
end
style ClaudeCode fill:#bbdefb,color:#000000
style MCP1 fill:#c8e6c9,color:#000000
style MCP2 fill:#fff9c4,color:#000000
style MCP3 fill:#ffccbc,color:#000000
style DB fill:#e8f5e9,color:#000000
style Slack fill:#fffde7,color:#000000
style GitHub fill:#fbe9e7,color:#000000
3.2 MCP 서버 설정#
.mcp.json (프로젝트 루트):
{
"mcpServers": {
"filesystem": {
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-filesystem", "/path/to/project"]
},
"postgres": {
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-postgres"],
"env": {
"DATABASE_URL": "postgresql://user:pass@localhost:5432/mydb"
}
},
"github": {
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-github"],
"env": {
"GITHUB_TOKEN": "${GITHUB_TOKEN}"
}
}
}
}
3.3 유용한 MCP 서버들#
| MCP Server | 용도 |
|---|---|
server-filesystem |
파일 시스템 접근 |
server-postgres |
PostgreSQL 쿼리 |
server-github |
GitHub API (이슈, PR, 코드) |
server-slack |
Slack 메시지 |
server-memory |
장기 메모리 저장 |
server-puppeteer |
웹 브라우저 자동화 |
3.4 MCP 디버깅#
# MCP 디버그 모드로 Claude Code 실행
claude --mcp-debug
# 특정 MCP 서버 로그 확인
cat ~/.claude/mcp-logs/postgres.log
3.5. Session Teleportation (2.1+ 신기능)#
3.5.1 세션 이동이란?#
Claude Code 2.1에서 추가된 Session Teleportation을 사용하면 로컬 터미널 세션을 클라우드(claude.ai/code)로 이동하거나, 그 반대로 이동할 수 있습니다.
flowchart LR
subgraph Teleportation["🚀 Session Teleportation"]
direction TB
subgraph Transfer["세션 이동"]
direction LR
Local["💻 로컬 터미널<br/>Claude Code<br/>Session"]
Cloud["☁️ claude.ai/code<br/>Claude Web<br/>Session"]
Local -->|"/teleport"| Cloud
Cloud -->|"/remote-env"| Local
end
subgraph UseCases["활용 사례"]
UC1["🏠↔🏢 디바이스 간 작업 이동 (집 ↔ 회사)"]
UC2["👥 팀원과 세션 공유"]
UC3["⏳ 긴 작업을 클라우드에서 계속 실행"]
end
end
style Local fill:#bbdefb,color:#000000
style Cloud fill:#c8e6c9,color:#000000
style UC1 fill:#f5f5f5,color:#000000
style UC2 fill:#f5f5f5,color:#000000
style UC3 fill:#f5f5f5,color:#000000
3.5.2 사용 방법#
# 현재 세션을 claude.ai로 이동
/teleport
# 원격 환경 설정
/remote-env
3.5.3 VS Code에서의 세션 관리#
Claude Code 2.1.16+에서는 VS Code 확장에서:
- OAuth 사용자가 원격 Claude 세션을 탐색하고 재개할 수 있음
- Sessions 다이얼로그에서 세션 관리 가능
4. Plan Mode와 대규모 작업 관리#
4.1 Plan Mode 활성화#
대규모 작업은 계획 먼저, 실행 나중에 접근이 효과적입니다.
# Plan Mode 진입 (Shift + Tab + Tab)
# 또는 명시적 요청:
"이 리팩토링을 계획만 먼저 세워줘. 실행은 내가 확인 후에."
4.2 plan.md 체크리스트 패턴#
복잡한 작업은 plan.md 파일로 진행 상황을 추적합니다:
plan.md:
# 결제 시스템 리팩토링 계획
## 목표
- 모놀리식 PaymentService를 도메인별로 분리
- 테스트 커버리지 80% 이상 달성
## 단계별 계획
### Phase 1: 분석 (Day 1)
- [x] 현재 PaymentService 의존성 분석
- [x] 도메인 경계 식별
- [ ] 영향 받는 클라이언트 코드 목록화
### Phase 2: 인터페이스 설계 (Day 2)
- [ ] PaymentProcessor 인터페이스 정의
- [ ] RefundHandler 인터페이스 정의
- [ ] PaymentRepository 인터페이스 정의
### Phase 3: 구현 (Day 3-4)
- [ ] CardPaymentProcessor 구현
- [ ] BankTransferProcessor 구현
- [ ] RefundService 분리
- [ ] 기존 코드 마이그레이션
### Phase 4: 테스트 (Day 5)
- [ ] 단위 테스트 작성
- [ ] 통합 테스트 작성
- [ ] 기존 테스트 수정
### Phase 5: 배포 (Day 6)
- [ ] Feature flag 설정
- [ ] Canary 배포
- [ ] 모니터링 설정
## 리스크
- 기존 API 호환성 유지 필요
- 트랜잭션 경계 재설계 필요
## 진행 상황
- 현재 단계: Phase 1
- 마지막 업데이트: 2025-01-23
4.3 Claude와 함께 계획 실행하기#
사용자: "@plan.md 를 참고해서 Phase 2의 첫 번째 작업을 진행해줘"
Claude: plan.md를 확인했습니다. Phase 2의 첫 번째 작업인
"PaymentProcessor 인터페이스 정의"를 시작하겠습니다.
[작업 수행...]
완료되었습니다. plan.md를 업데이트하겠습니다.
- [x] PaymentProcessor 인터페이스 정의
5. ⭐ 실전 레이어링 아키텍처#
5.1 전체 구조 복습#
Part 4에서 배운 3-Layer Stacking을 실전 예제와 함께 정리합니다:
flowchart TB
subgraph Layering["🏗️ 실전 레이어링 아키텍처"]
direction TB
subgraph L4["Layer 4: Hooks (강제 자동화)"]
L4_1["파일 저장 시 자동 포맷팅"]
L4_2["위험 파일 수정 방지"]
end
subgraph L3["Layer 3: 프로젝트 CLAUDE.md (프로젝트 특화)"]
L3_1["빌드/테스트 명령어"]
L3_2["이 프로젝트만의 특수 규칙"]
end
subgraph L2["Layer 2: Custom Skills (팀 공통)"]
L2_1["팀 코딩 컨벤션"]
L2_2["팀 테스트 패턴"]
L2_3["팀 에러 처리 규칙"]
end
subgraph L1["Layer 1: Community Plugins (일반 지식)"]
L1_1["언어 베스트 프랙티스 (golang-pro, java-architect)"]
L1_2["프레임워크 패턴"]
end
subgraph L0["Layer 0: Claude 기본 지식"]
L0_1["프로그래밍 언어 기본"]
L0_2["일반적인 소프트웨어 엔지니어링"]
end
L0 --> L1 --> L2 --> L3 --> L4
end
style L4 fill:#ef9a9a,color:#000000
style L3 fill:#ffcc80,color:#000000
style L2 fill:#fff59d,color:#000000
style L1 fill:#a5d6a7,color:#000000
style L0 fill:#90caf9,color:#000000
5.2 Java/Kotlin 프로젝트 완전한 설정 예제#
디렉토리 구조:
~/.claude/
├── CLAUDE.md # 전역 개인 설정
├── skills/
│ ├── kotlin-team-style/
│ │ └── SKILL.md # 팀 Kotlin 스타일
│ └── spring-patterns/
│ └── SKILL.md # 팀 Spring 패턴
└── agents/
└── code-reviewer.md # 코드 리뷰어
my-spring-project/
├── CLAUDE.md # 프로젝트 설정
├── CLAUDE.local.md # 개인 오버라이드 (.gitignore)
└── .claude/
├── settings.json # Hooks 설정
└── skills/
└── payment-domain/
└── SKILL.md # 이 프로젝트 도메인 지식
~/.claude/CLAUDE.md (전역):
# 개인 전역 설정
## 커뮤니케이션
- 한국어로 응답
- 코드 변경 시 이유 설명
- 불확실한 부분은 먼저 질문
## 선호 도구
- 테스트: JUnit 5 + MockK
- 빌드: Gradle Kotlin DSL
my-spring-project/CLAUDE.md:
# Payment Gateway Service
Spring Boot 3.2 기반 결제 게이트웨이
## 빌드 및 테스트
- 빌드: `./gradlew build`
- 테스트: `./gradlew test`
- 단일 테스트: `./gradlew test --tests "ClassName.methodName"`
## 이 프로젝트 특수 규칙
IMPORTANT: 다음 규칙은 이 프로젝트에만 적용됩니다.
1. PG사 연동 코드는 `infrastructure/pg/` 에만 위치
2. 결제 금액은 반드시 BigDecimal 사용 (Double 금지)
3. 모든 외부 API 호출은 Circuit Breaker 적용 필수
## 환경
- Java 21
- Spring Boot 3.2
- PostgreSQL 15
my-spring-project/.claude/settings.json (Hooks):
{
"hooks": {
"PostToolUse": [
{
"matcher": "Write|Edit",
"hooks": [
{
"type": "command",
"command": "if [[ \"$CLAUDE_FILE_PATH\" == *.kt ]]; then ./gradlew ktlintFormat -q; fi"
}
]
}
],
"PreToolUse": [
{
"matcher": "Write|Edit",
"hooks": [
{
"type": "command",
"command": "if [[ \"$CLAUDE_FILE_PATH\" == **/production/** ]]; then echo 'ERROR: production 폴더 수정 금지' && exit 1; fi"
}
]
}
]
}
}
5.3 Go 프로젝트 완전한 설정 예제#
디렉토리 구조:
~/.claude/
├── CLAUDE.md
├── skills/
│ ├── go-team-conventions/
│ │ └── SKILL.md
│ └── go-error-handling/
│ └── SKILL.md
└── agents/
└── go-reviewer.md
my-go-service/
├── CLAUDE.md
├── CLAUDE.local.md
└── .claude/
├── settings.json
└── skills/
└── kafka-patterns/
└── SKILL.md
~/.claude/skills/go-team-conventions/SKILL.md:
---
name: go-team-conventions
description: Go 팀 코딩 컨벤션. Go 코드 작성 시 자동 활성화.
---
# Go Team Conventions
## 프로젝트 구조 (Hexagonal)
cmd/
├── api/ # REST API 서버
└── worker/ # 백그라운드 워커
internal/
├── domain/ # 도메인 모델, 비즈니스 로직
├── port/
│ ├── in/ # 유스케이스 인터페이스
│ └── out/ # 레포지토리 인터페이스
├── adapter/
│ ├── in/ # HTTP 핸들러
│ └── out/ # DB, 외부 API 구현
└── config/
pkg/ # 외부 공개 패키지
## 네이밍
| 대상 | 규칙 | 예시 |
|------|------|------|
| 패키지 | lowercase, 단수 | `user`, `payment` |
| 인터페이스 | -er 또는 역할명 | `Reader`, `UserRepository` |
| 함수 | 동사로 시작, exported는 대문자 | `GetUser`, `processPayment` |
## 에러 처리
// 에러 코드 형식: {도메인}{숫자}
var ErrUserNotFound = NewError("USR001", "user not found")
// 래핑 시 컨텍스트 추가
return fmt.Errorf("[%s] failed to get user %d: %w", ErrUserNotFound.Code, id, err)
my-go-service/CLAUDE.md:
# User Notification Service
Go 1.22 기반 사용자 알림 서비스
## 빌드 및 테스트
- 빌드: `go build -o bin/server ./cmd/api`
- 테스트: `go test ./...`
- 린트: `golangci-lint run`
## 이 프로젝트 특수 규칙
1. Kafka 토픽 네이밍: `notification.{event-type}.v1`
2. Redis 키 프리픽스: `notif:`
3. 외부 API 타임아웃: 5초 (context.WithTimeout)
## 외부 의존성
- Kafka: localhost:9092
- Redis: localhost:6379
- PostgreSQL: localhost:5432
my-go-service/.claude/settings.json:
{
"hooks": {
"PostToolUse": [
{
"matcher": "Write|Edit",
"hooks": [
{
"type": "command",
"command": "if [[ \"$CLAUDE_FILE_PATH\" == *.go ]]; then gofmt -w \"$CLAUDE_FILE_PATH\" && goimports -w \"$CLAUDE_FILE_PATH\"; fi"
}
]
}
]
}
}
5.4 레이어 간 충돌 해결#
레이어 간 규칙이 충돌할 때의 우선순위:
높음 ▲ Hooks (강제 실행, 우회 불가)
│ 프로젝트 CLAUDE.md
│ Custom Skills
│ Community Plugins
낮음 ▼ Claude 기본 지식
충돌 예시와 해결:
Community Plugin (golang-pro): "에러는 errors.New()로 생성"
Custom Skill (go-team-conventions): "에러는 NewError(code, msg)로 생성"
→ Custom Skill이 우선 적용됨
→ 팀 규칙에 따라 NewError() 사용
6. 팀 협업 워크플로우#
6.1 Git으로 설정 공유#
프로젝트/
├── CLAUDE.md # ✓ Git 커밋 (팀 공유)
├── CLAUDE.local.md # ✗ .gitignore (개인용)
└── .claude/
├── settings.json # ✓ Git 커밋 (Hooks 공유)
├── skills/ # ✓ Git 커밋 (프로젝트 Skills)
└── agents/ # ✓ Git 커밋 (프로젝트 Agents)
.gitignore:
# Claude Code 개인 설정
CLAUDE.local.md
.claude/settings.local.json
6.2 PR 리뷰 워크플로우#
flowchart TD
subgraph PRWorkflow["🔄 PR 리뷰 자동화 워크플로우"]
direction TB
Step1["1️⃣ 개발자가 기능 구현"]
Step2["2️⃣ /conventional-commit 으로 커밋"]
Step3["3️⃣ /pr-create 로 PR 생성"]
Step4["4️⃣ CI가 code-reviewer subagent 실행<br/>(선택적)"]
Step5["5️⃣ 리뷰 코멘트 자동 생성"]
Step1 --> Step2 --> Step3 --> Step4 --> Step5
end
style Step1 fill:#e3f2fd,color:#000000
style Step2 fill:#bbdefb,color:#000000
style Step3 fill:#90caf9,color:#000000
style Step4 fill:#64b5f6,color:#000000
style Step5 fill:#42a5f5,color:#ffffff
6.3 CI/CD 통합 (GitHub Actions 예시)#
.github/workflows/claude-review.yml:
name: Claude Code Review
on:
pull_request:
types: [opened, synchronize]
jobs:
review:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
with:
fetch-depth: 0
- name: Get changed files
id: changed
run: |
echo "files=$(git diff --name-only origin/main...HEAD | tr '\n' ' ')" >> $GITHUB_OUTPUT
- name: Run Claude Code Review
env:
ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }}
run: |
# Claude Code CLI로 리뷰 실행
claude --print "Review these changed files for code quality and security: ${{ steps.changed.outputs.files }}" > review.md
- name: Post Review Comment
uses: actions/github-script@v7
with:
script: |
const fs = require('fs');
const review = fs.readFileSync('review.md', 'utf8');
github.rest.issues.createComment({
owner: context.repo.owner,
repo: context.repo.repo,
issue_number: context.issue.number,
body: review
});
7. 문제 해결 & 디버깅#
7.1 Claude가 지시를 무시할 때#
flowchart TB
subgraph Troubleshoot["🔧 지시 무시 문제 해결"]
direction TB
Symptom["😰 증상: Claude가 CLAUDE.md의 규칙을 따르지 않음"]
subgraph Checklist["📋 체크리스트"]
C1["☐ CLAUDE.md가 너무 길지 않은가? (100줄 이내 권장)"]
C2["☐ 규칙이 모호하지 않고 구체적인가?"]
C3["☐ 상충되는 규칙이 있는가?"]
C4["☐ 강조가 필요한 규칙에 IMPORTANT 키워드를 사용했는가?"]
end
subgraph Solutions["✅ 해결 방법"]
S1["1. CLAUDE.md 간소화 (Part 2 참조)"]
S2["2. 중요 규칙에 강조 추가"]
S3["3. 세부 규칙은 Skills로 분리 (Part 3 참조)"]
S4["4. 강제가 필요하면 Hooks 사용"]
end
Symptom --> Checklist --> Solutions
end
style Symptom fill:#ffcdd2,color:#000000
style C1 fill:#fff9c4,color:#000000
style C2 fill:#fff9c4,color:#000000
style C3 fill:#fff9c4,color:#000000
style C4 fill:#fff9c4,color:#000000
style S1 fill:#c8e6c9,color:#000000
style S2 fill:#c8e6c9,color:#000000
style S3 fill:#c8e6c9,color:#000000
style S4 fill:#c8e6c9,color:#000000
7.2 플러그인 로딩 오류#
# 플러그인 오류 확인
/plugin
# → Errors 탭 확인
# 일반적인 오류와 해결:
# 1. "Plugin not found"
# → Marketplace가 추가되었는지 확인
/plugin marketplace add {org}/{repo}
# 2. "Invalid plugin.json"
# → JSON 문법 오류 확인
# → 필수 필드(name, version) 확인
# 3. "Skill loading failed"
# → SKILL.md의 YAML frontmatter 확인
# → name, description 필드 존재 확인
7.3 MCP 서버 디버깅#
# MCP 디버그 모드 실행
claude --mcp-debug
# 로그 확인
tail -f ~/.claude/logs/mcp-*.log
# 일반적인 오류:
# 1. "Connection refused"
# → MCP 서버 프로세스 실행 확인
# → 포트/경로 설정 확인
# 2. "Authentication failed"
# → 환경 변수 설정 확인
# → API 키 유효성 확인
# 3. "Timeout"
# → 네트워크 연결 확인
# → MCP 서버 응답 시간 확인
7.4 컨텍스트 윈도우 관리#
flowchart TD
subgraph Context["🧠 컨텍스트 관리 팁"]
Problem["😰 문제: 긴 대화 후 Claude가 이전 내용을 잊음"]
subgraph Solutions["✅ 해결 방법"]
S1["1️⃣ /compact 명령으로 대화 압축"]
S1D["→ 중요 내용만 요약하여 컨텍스트 확보"]
S2["2️⃣ 대규모 분석은 Subagent에 위임"]
S2D["→ 메인 컨텍스트 오염 방지"]
S3["3️⃣ 긴 파일은 부분만 참조"]
S3D["→ UserService.kt의 createUser 메서드만 봐줘"]
S4["4️⃣ 주기적으로 새 대화 시작"]
S4D["→ CLAUDE.md가 있으면 컨텍스트 자동 복원"]
end
Problem --> Solutions
S1 --> S1D
S2 --> S2D
S3 --> S3D
S4 --> S4D
end
style Context fill:#e3f2fd,color:#000000
style Problem fill:#ffcdd2,color:#000000
style Solutions fill:#c8e6c9,color:#000000
style S1 fill:#a5d6a7,color:#000000
style S1D fill:#e8f5e9,color:#000000
style S2 fill:#a5d6a7,color:#000000
style S2D fill:#e8f5e9,color:#000000
style S3 fill:#a5d6a7,color:#000000
style S3D fill:#e8f5e9,color:#000000
style S4 fill:#a5d6a7,color:#000000
style S4D fill:#e8f5e9,color:#000000
7.5 성능 최적화#
flowchart TB
subgraph Performance["⚡ 성능 최적화 팁"]
subgraph Skill["1️⃣ Skills 최적화"]
SK1["description을 명확하게 작성"]
SK2["불필요한 Skill 비활성화"]
SK3["disable-model-invocation으로 자동 호출 제한"]
end
subgraph Codebase["2️⃣ 대규모 코드베이스"]
CB1[".claudeignore로 불필요한 파일 제외"]
CB2["node_modules, build/, .git/ 등"]
end
subgraph Subagent["3️⃣ Subagent 효율적 사용"]
SA1["병렬 실행 시 적절한 수 유지"]
SA1D["5개 이하 권장"]
SA2["각 Subagent에 명확한 범위 지정"]
end
subgraph Hook["4️⃣ Hook 최적화"]
HK1["matcher를 구체적으로 설정"]
HK2["빠른 명령만 Hook에 사용"]
end
SA1 --> SA1D
end
style Performance fill:#e3f2fd,color:#000000
style Skill fill:#fff9c4,color:#000000
style SK1 fill:#fffde7,color:#000000
style SK2 fill:#fffde7,color:#000000
style SK3 fill:#fffde7,color:#000000
style Codebase fill:#c8e6c9,color:#000000
style CB1 fill:#e8f5e9,color:#000000
style CB2 fill:#e8f5e9,color:#000000
style Subagent fill:#bbdefb,color:#000000
style SA1 fill:#e3f2fd,color:#000000
style SA1D fill:#e3f2fd,color:#000000
style SA2 fill:#e3f2fd,color:#000000
style Hook fill:#ffccbc,color:#000000
style HK1 fill:#fbe9e7,color:#000000
style HK2 fill:#fbe9e7,color:#000000
8. 정리: Claude Code 마스터 체크리스트#
8.1 설정 체크리스트#
□ CLAUDE.md
□ 프로젝트 루트에 CLAUDE.md 생성
□ 빌드/테스트 명령어 포함
□ 핵심 규칙만 간결하게 (100줄 이내)
□ 중요 규칙에 IMPORTANT 강조
□ Skills
□ 반복되는 상세 규칙은 Skills로 분리
□ description에 트리거 조건 명시
□ 팀 공통 Skills는 ~/.claude/skills/
□ Plugins
□ 유용한 커뮤니티 플러그인 설치
□ 팀 Marketplace 구축 (필요시)
□ Hooks
□ 자동 포맷팅 Hook 설정
□ 위험 파일 보호 Hook 설정
□ 팀 협업
□ CLAUDE.md Git 커밋
□ CLAUDE.local.md .gitignore
□ .claude/settings.json Git 커밋
8.2 일일 워크플로우#
1. 프로젝트 시작
claude
2. 작업 수행
- Claude가 CLAUDE.md, Skills 자동 로드
- Hooks가 자동으로 포맷팅/검증
3. 대규모 분석 필요 시
"Explore subagent로 분석해줘"
4. 커밋
/conventional-commit
5. PR 생성
/pr-create
8.3 주간 유지보수#
□ CLAUDE.md가 너무 커지지 않았는지 확인
□ 새로운 팀 규칙을 Skills로 추가
□ 플러그인 업데이트 확인
□ 불필요한 Skills/Plugins 정리
9. 최종 정리#
이 가이드에서 배운 것#
| Part | 핵심 내용 |
|---|---|
| Part 1 | CLAUDE.md 기초, 계층적 구조, 기본 템플릿 |
| Part 2 | CLAUDE.md 최적화, 토큰 절약, 강조 기법 |
| Part 3 | Skills 시스템, Progressive Disclosure, Skills vs Subagents |
| Part 4 | Plugins & Marketplace, 3-Layer Stacking |
| Part 5 | Custom Marketplace 구축, 팀 배포 |
| Part 6 | Hooks, Subagents 패턴, MCP, 팀 협업, 문제 해결 |
핵심 원칙#
- CLAUDE.md는 간결하게: 100줄 이내, 핵심만
- 상세 규칙은 Skills로: Progressive Disclosure로 토큰 절약
- 강제가 필요하면 Hooks: CLAUDE.md는 권고, Hooks는 강제
- 대규모 작업은 Subagents로: 컨텍스트 오염 방지
- 레이어링으로 조합: 커뮤니티 + 팀 규칙 + 프로젝트 규칙
다음 단계#
- Claude Code 공식 문서에서 최신 기능 확인
- Anthropic 블로그에서 베스트 프랙티스 업데이트 확인
- 커뮤니티 Marketplace에서 유용한 플러그인 탐색
- 자신만의 Skills와 Plugins 만들어 공유하기
📚 참고 자료#
공식 문서#
커뮤니티 리소스#
블로그 & 가이드#
이 가이드가 Claude Code 마스터링에 도움이 되었기를 바랍니다. Happy Coding! 🚀
이전: Part 5: 나만의 Plugin Marketplace 만들기 처음으로: Part 0: Overview