상위: 08_00_MOC
Claude Code — 서브에이전트 컨텍스트 격리
서브에이전트란
“Use one when a side task would flood your main conversation with search results, logs, or file contents you won’t reference again: the subagent does that work in its own context and returns only the summary.” — Create custom subagents, Anthropic
각 서브에이전트는:
- 자체 컨텍스트 창(context window)을 가짐
- 커스텀 시스템 프롬프트를 받음
- 특정 도구 접근만 허용됨
- 독립적인 권한으로 실행됨
06 해결전략의 이론을 실제 Claude Code 기능으로 구현한 것이다.
격리 수준: 무엇이 공유되고 무엇이 격리되는가
공식 문서를 기준으로 정리하면 다음과 같다.
| 항목 | 서브에이전트 |
|---|---|
| CLAUDE.md (프로젝트 루트) | ✅ 로드됨 (자체 컨텍스트에) |
| MCP 도구 목록 | ✅ 접근 가능 (부모와 동일) |
| Skill 설정 | ✅ 접근 가능 |
| 부모의 대화 히스토리 | ❌ 공유 안 됨 |
| 부모의 Auto Memory | ❌ 공유 안 됨 |
| 부모의 git status | ⚠️ 기본은 로드, Explore·Plan은 스킵 |
“The subagent gets its own system prompt, shorter than the main session’s. The main session’s auto memory is not included.” — Explore the context window, Anthropic
예외는 Explore·Plan 빌트인 에이전트다. 이 둘은 CLAUDE.md와 부모 git status를 건너뛰어 더 가볍고 빠르게 실행된다.
“Explore and Plan skip your CLAUDE.md files and the parent session’s git status to keep research fast and inexpensive.” — Create custom subagents, Anthropic
빌트인 서브에이전트
Claude Code에 내장된 서브에이전트:
| 에이전트 | 모델 | 도구 | 용도 |
|---|---|---|---|
| Explore | Haiku | 읽기 전용 | 코드베이스 탐색, 파일 검색 |
| Plan | 부모 상속 | 읽기 전용 | plan mode 시 컨텍스트 수집 |
| General-purpose | 부모 상속 | 전체 | 복합 탐색 + 수정 작업 |
| statusline-setup | Sonnet | - | /statusline 설정 |
| claude-code-guide | Haiku | - | Claude Code 기능 질문 답변 |
Explore는 thoroughness level을 지정할 수 있다. quick(목표형 조회), medium(균형 탐색), very thorough(종합 분석) 세 단계다.
커스텀 서브에이전트 설정
서브에이전트는 YAML 프론트매터 + 마크다운 시스템 프롬프트로 정의:
---
name: code-reviewer
description: Reviews code for quality and best practices. Use proactively after code changes.
tools: Read, Glob, Grep
model: sonnet
memory: project
---
You are a code reviewer. When invoked, analyze the code and provide
specific, actionable feedback on quality, security, and best practices.저장 위치 (우선순위 높은 순):
- Managed settings
.claude/agents/(조직 전체) --agentsCLI 플래그 (현재 세션).claude/agents/(현재 프로젝트)~/.claude/agents/(모든 프로젝트)- Plugin
agents/디렉토리
지속 메모리 (memory 필드)
서브에이전트에 memory 프론트매터를 설정하면 세션을 넘어 지식을 축적할 수 있다:
| 스코프 | 경로 | 공유 범위 |
|---|---|---|
user | ~/.claude/agent-memory/<name>/ | 모든 프로젝트 공유 |
project | .claude/agent-memory/<name>/ | 현재 프로젝트, 버전관리 공유 가능 |
local | .claude/agent-memory-local/<name>/ | 현재 프로젝트, 비공개 |
“The memory field gives the subagent a persistent directory that survives across conversations. The subagent uses this directory to build up knowledge over time, such as codebase patterns, debugging insights, and architectural decisions.” — Create custom subagents, Anthropic
지원 프론트매터 필드
핵심 필드 요약:
| 필드 | 설명 |
|---|---|
name | 고유 식별자 (소문자+하이픈) — 필수 |
description | Claude가 위임 시점 판단에 사용 — 필수 |
tools | 사용 가능한 도구 목록 (생략 시 전체 상속) |
disallowedTools | 명시적으로 거부할 도구 |
model | sonnet/opus/haiku/fable/풀 모델 ID/inherit |
permissionMode | default/acceptEdits/auto/dontAsk/bypassPermissions/plan |
maxTurns | 최대 에이전틱 턴 수 |
skills | 시작 시 미리 로드할 스킬 목록 |
memory | user/project/local |
isolation | worktree — 독립된 git worktree에서 실행 |
effort | low/medium/high/xhigh/max |
background | true — 항상 백그라운드 태스크로 실행 |
worktree 격리
isolation: worktree레포의 임시 git worktree에서 실행. 변경 없으면 자동 정리됨. 부모 세션 HEAD가 아닌 기본 브랜치 기준으로 분기.
비용: 7배 토큰 주의
“Agent teams use approximately 7x more tokens than standard sessions when teammates run in plan mode, because each teammate maintains its own context window and runs as a separate Claude instance.” — Manage costs effectively, Anthropic
비용 관리 전략:
- 단순 서브에이전트는
model: haiku로 라우팅 - 팀 규모 최소화
- 스폰 프롬프트를 간결하게 (CLAUDE.md·MCP·Skills는 자동 로드)
- 작업 완료 후 즉시 종료
- 에이전트 팀은
CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS=1로 활성화해야 함 (기본 비활성)
실패모드 매핑
- 01 오염 완화: 대용량 로그·검색·파일 탐색을 서브에이전트에 위임하면 메인 컨텍스트에 잔재가 남지 않는다.
- 02 산만 완화: 탐색 작업을 격리해 메인 대화의 핵심 지시를 지킨다.
- 비용 트레이드오프: 격리는 공짜가 아니다. 서브에이전트마다 별도의 컨텍스트 비용이 든다.
참고문헌
- Create custom subagents — Anthropic, 공식 문서
- Explore the context window — Anthropic, 공식 문서
- Manage costs effectively — Anthropic, 공식 문서
관련 노트
- 08_02-compact와-자동컴팩션 — 서브에이전트와 /compact의 관계
- 08_05-Hooks-컨텍스트전처리 — SubagentStart 훅
- 08_06-프롬프트캐싱-비용레버 — 서브에이전트 캐시는 5분 TTL
- 08_08-실패모드-공식기능-매핑표 — 오염·산만 실패모드 대응