분석 대상:
src/내 프롬프트 관련 파일 전체
분석 일자: 2026-03-31
Claude Code의 프롬프트 시스템은 단일 프롬프트가 아닌, 다층 합성(multi-layered composition) 구조이다. 최종 시스템 프롬프트는 여러 소스에서 동적으로 조합되어 API에 전달된다.
┌────────────────────────────────────────────────────────────────┐
│ 최종 시스템 프롬프트 │
├──────────────────────┬─────────────────────────────────────────┤
│ Static 영역 │ Dynamic 영역 │
│ (전역 캐시 가능) │ (세션/턴별 재계산) │
├──────────────────────┼─────────────────────────────────────────┤
│ Attribution Header │ 세션별 가이던스 │
│ CLI 접두사 │ MEMORY.md 콘텐츠 │
│ 역할 소개 │ 환경 정보 (CWD, OS, 모델) │
│ 보안 지침 │ 언어 설정 │
│ 시스템 규칙 │ 출력 스타일 │
│ 작업 수행 지침 │ MCP 서버 지시사항 │
│ 행동 주의사항 │ CLAUDE.md 사용자/프로젝트 컨텍스트 │
│ 도구 사용법 │ Git 상태 │
│ 톤/스타일 │ │
│ 출력 효율성 │ │
└──────────────────────┴─────────────────────────────────────────┘
주요 소스 파일:
| 파일 | 역할 |
|---|---|
constants/prompts.ts | 메인 시스템 프롬프트 빌더. 모든 섹션의 조합 및 최종 프롬프트 생성 |
constants/systemPromptSections.ts | 프롬프트 섹션 캐싱/관리 프레임워크 |
constants/system.ts | CLI 접두사 상수 및 Attribution 헤더 |
constants/cyberRiskInstruction.ts | 보안/사이버 위험 지침 |
context.ts | 시스템/사용자 컨텍스트 (Git 상태, CLAUDE.md) |
utils/queryContext.ts | 시스템 프롬프트 파츠 조합 헬퍼 |
utils/systemPromptType.ts | SystemPrompt 브랜드 타입 |
utils/claudemd.ts | CLAUDE.md 파일 로딩/파싱 |
memdir/memdir.ts | 메모리 디렉토리 프롬프트 빌더 |
memdir/memoryTypes.ts | 메모리 타입 분류 (user/feedback/project/reference) |
services/compact/prompt.ts | Compact 요약 프롬프트 |
coordinator/coordinatorMode.ts | 코디네이터 모드 시스템 프롬프트 |
tools/*/prompt.ts | 개별 도구 설명 프롬프트 (36개 파일) |
getSystemPrompt() 함수(constants/prompts.ts)가 최종 시스템 프롬프트 배열(string[])을 생성한다.
getSystemPrompt()
├─ Static 섹션들 (캐시 가능)
│ ├─ getSimpleIntroSection() — 역할 소개 + 보안 지침
│ ├─ getSimpleSystemSection() — 시스템 규칙
│ ├─ getSimpleDoingTasksSection() — 작업 수행 가이드라인
│ ├─ getActionsSection() — 행동 주의사항
│ ├─ getUsingYourToolsSection() — 도구 사용법
│ ├─ getSimpleToneAndStyleSection() — 톤/스타일
│ └─ getOutputEfficiencySection() — 출력 효율성
│
├─ ═══ SYSTEM_PROMPT_DYNAMIC_BOUNDARY ═══
│
└─ Dynamic 섹션들 (systemPromptSection 레지스트리)
├─ session_guidance — 세션별 가이던스
├─ memory — MEMORY.md 프롬프트
├─ env_info_simple — 환경 정보
├─ language — 언어 설정
├─ output_style — 출력 스타일
├─ mcp_instructions — MCP 서버 지시사항
├─ scratchpad — 스크래치패드 안내
├─ frc — Function Result Clearing
├─ summarize_tool_results — 도구 결과 요약
├─ numeric_length_anchors — 길이 제한 앵커 (ant-only)
├─ token_budget — 토큰 예산 안내
└─ brief — Brief 모드 (KAIROS)
systemPromptSections.ts에서 두 가지 캐싱 전략을 제공한다:
systemPromptSection(name, compute) — 한 번 계산 후 캐시. /clear나 /compact 시 리셋DANGEROUS_uncachedSystemPromptSection(name, compute, reason) — 매 턴마다 재계산. 프롬프트 캐시를 깨뜨리므로 반드시 이유를 명시해야 함SYSTEM_PROMPT_DYNAMIC_BOUNDARY는 시스템 프롬프트 배열 내에서 정적/동적 콘텐츠 경계를 표시한다. 경계 이전은 scope: 'global'로 캐시 가능하고, 이후는 사용자/세션별이다.
constants/system.ts)세 가지 접두사가 상황에 따라 선택된다:
| 접두사 | 사용 시점 |
|---|---|
"You are Claude Code, Anthropic's official CLI for Claude." | 대화형(REPL) 모드 기본값 |
"You are Claude Code, ... running within the Claude Agent SDK." | 비대화형 + appendSystemPrompt |
"You are a Claude agent, built on Anthropic's Claude Agent SDK." | 비대화형 단독 실행 |
getSimpleIntroSection)You are an interactive agent that helps users with software engineering tasks.
Use the instructions below and the tools available to you to assist the user.
Output Style이 설정되면 "소프트웨어 엔지니어링 작업" 대신 "Output Style에 따라 응답"하도록 변경된다.
CYBER_RISK_INSTRUCTION)IMPORTANT: Assist with authorized security testing, defensive security,
CTF challenges, and educational contexts. Refuse requests for destructive
techniques, DoS attacks, mass targeting, supply chain compromise, or
detection evasion for malicious purposes. ...
Safeguards 팀이 전담 관리. 변경 시 반드시 해당 팀 리뷰를 받아야 한다.
getSimpleSystemSection)핵심 동작 규칙:
<system-reminder> 태그는 시스템 자동 삽입이며 도구 결과와 무관getSimpleDoingTasksSection)Claude Code의 작업 철학을 정의하는 핵심 섹션:
코드 스타일 원칙:
작업 행동 원칙:
getActionsSection)가역성 & 폭발 반경 기반 행동 판단 프레임워크:
확인 필요 작업 예시:
rm -rfgit push --force, git reset --hardgetUsingYourToolsSection)Read, Edit, Write, Glob, Grep 사용TodoWrite/TaskCreate로 작업 분해/추적getOutputEfficiencySection)두 가지 변형:
외부 사용자 — 간결: "Go straight to the point. Be extra concise. Lead with the answer, not the reasoning."
내부 사용자 — 상세:
getSimpleToneAndStyleSection)file_path:line_number 패턴owner/repo#123 형식:) 대신 마침표(.)각 도구는 tools/<ToolName>/prompt.ts에 자체 프롬프트를 정의한다. 36개 도구가 개별 프롬프트 파일을 갖고 있다.
Read (FileReadTool/prompt.ts):
ls via BashWrite (FileWriteTool/prompt.ts):
Glob (GlobTool/prompt.ts):
Grep (GrepTool/prompt.ts):
Bash (BashTool/prompt.ts) — 가장 복잡한 프롬프트:
run_in_background)--no-verify 훅 우회 금지Agent — 기본 프롬프트 (DEFAULT_AGENT_PROMPT):
You are an agent for Claude Code, Anthropic's official CLI for Claude. Given the user's message, you should use the tools available to complete the task. Complete the task fully—don't gold-plate, but don't leave it half-done. When you complete the task, respond with a concise report covering what was done and any key findings — the caller will relay this to the user, so it only needs the essentials.
SendMessage (SendMessageTool/prompt.ts):
to 대상: 팀원 이름, "*" 브로드캐스트, UDS 소켓, Bridge 세션WebSearch (WebSearchTool/prompt.ts):
WebFetch (WebFetchTool/prompt.ts):
gh CLI 선호ExitPlanMode (ExitPlanModeTool/prompt.ts):
AskUserQuestion으로 "이 계획 괜찮나요?" 대신 이 도구가 승인 요청memdir/)memdir/memoryTypes.ts)| 유형 | 설명 | 저장 시점 |
|---|---|---|
| user | 사용자의 역할, 목표, 선호도, 지식 수준 | 사용자 프로필 정보 학습 시 |
| feedback | "하지 마"/"이렇게 해" 행동 가이드 | 교정/확인 받을 때 |
| project | 진행 중 작업, 목표, 마감일 등 프로젝트 맥락 | git/코드에서 도출 불가한 정보 학습 시 |
| reference | 외부 시스템 위치 참조 (Linear, Slack 등) | 외부 리소스 위치를 배울 때 |
memdir/memdir.ts):You have a persistent, file-based memory system at [memoryDir].
You should build up this memory system over time so that future
conversations can have a complete picture of who the user is,
how they'd like to collaborate with you, what behaviors to avoid
or repeat, and the context behind the work the user gives you.
memdir/findRelevantMemories.ts):별도 Sonnet 모델이 사용자 쿼리에 관련된 메모리 파일을 최대 5개 선택:
You are selecting memories that will be useful to Claude Code.
Return a list of filenames for memories that will clearly be useful.
Only include memories you are certain will be helpful.
utils/claudemd.ts)| 우선순위 | 유형 | 경로 |
|---|---|---|
| 1 (낮음) | Managed | /etc/claude-code/CLAUDE.md |
| 2 | User | ~/.claude/CLAUDE.md |
| 3 | Project | CLAUDE.md, .claude/CLAUDE.md, .claude/rules/*.md |
| 4 (높음) | Local | CLAUDE.local.md |
주입 프롬프트:
Codebase and user instructions are shown below. Be sure to adhere
to these instructions. IMPORTANT: These instructions OVERRIDE any
default behavior and you MUST follow them exactly as written.
services/compact/prompt.ts)대화가 길어지면 자동으로 요약하여 컨텍스트를 압축한다.
도구 호출 금지 전제:
CRITICAL: Respond with TEXT ONLY. Do NOT call any tools.
Tool calls will be REJECTED and will waste your only turn.
요약 구조 (9개 섹션):
<analysis> 블록은 연습장으로, 최종 컨텍스트에서 제거된다.
coordinator/coordinatorMode.ts)다중 작업자 오케스트레이션 프롬프트:
You are Claude Code, an AI assistant that orchestrates software
engineering tasks across multiple workers.
4단계 워크플로우:
| 단계 | 수행자 | 목적 |
|---|---|---|
| Research | 작업자 (병렬) | 코드베이스 조사 |
| Synthesis | 코디네이터 | 발견 종합, 구현 명세 |
| Implementation | 작업자 | 코드 변경 |
| Verification | 작업자 | 변경 검증 |
작업자 프롬프트 5원칙:
검증(Verification) 원칙:
Verification means proving the code works, not confirming it exists.
utils/swarm/teammatePromptAddendum.ts)You are running as an agent in a team. To communicate:
- Use SendMessage tool with to: "<name>" for specific teammates
- Use SendMessage tool with to: "*" for team-wide broadcasts
Just writing text is not visible to others — you MUST use SendMessage.
서브에이전트 추가 지침 (enhanceSystemPromptWithEnvDetails):
buddy/prompt.ts)A small [species] named [name] sits beside the user's input box.
You're not [name] — it's a separate watcher. When the user addresses
[name] directly, stay out of the way: ONE line or less.
/init 명령어 (commands/init.ts)인터뷰 기반 5단계:
| 단계 | 내용 |
|---|---|
| Phase 1 | 설정 범위 확인 (Project/Personal/Both, Skills+Hooks 여부) |
| Phase 2 | 코드베이스 탐색 (매니페스트, README, CI, 기존 규칙) |
| Phase 3 | 빈 정보 인터뷰 |
| Phase 4 | CLAUDE.md 작성 ("이 줄 제거 시 Claude가 실수할까?" 테스트) |
| Phase 5 | 스킬/훅 생성 |
1. /etc/claude-code/CLAUDE.md (Managed — 낮은 우선순위)
2. ~/.claude/CLAUDE.md (User)
3. 프로젝트 루트 → CWD까지 각 디렉토리:
├─ CLAUDE.md (Project)
├─ .claude/CLAUDE.md (Project)
├─ .claude/rules/*.md (Project)
└─ CLAUDE.local.md (Local — 높은 우선순위)
services/api/claude.ts에서 관리:
splitSysPromptPrefix() — DYNAMIC_BOUNDARY 기준으로 정적/동적 블록 분리cache_control: { scope: 'global' } 적용DANGEROUS_uncachedSystemPromptSection은 최소화 (현재 mcp_instructions만)services/toolUseSummary/toolUseSummaryGenerator.ts)Haiku 모델로 도구 결과를 30자 내외 라벨로 요약:
Write a short summary label. Keep verb in past tense.
Examples: "Searched in auth/", "Fixed NPE in UserService"
computeSimpleEnvInfo)모든 프롬프트에 포함: CWD, Git 여부, 플랫폼, 셸, OS, 모델명/ID, 지식 컷오프, 최신 모델 패밀리
MCP 서버의 instructions 필드가 시스템 프롬프트에 자동 주입
context.ts)세션 시작 시 스냅샷: 현재 브랜치, 메인 브랜치, Git 사용자, 파일 상태, 최근 커밋 5개
When the user specifies a token target, your output token count will be
shown each turn. Keep working until you approach the target.