분석 대상: src/ 내 프롬프트 관련 파일 전체
분석 일자: 2026-03-31


목차

  1. 프롬프트 시스템 개요
  2. 시스템 프롬프트 아키텍처
  3. 핵심 시스템 프롬프트 구성
  4. 도구(Tool)별 프롬프트
  5. 메모리/컨텍스트 프롬프트
  6. Compact(요약) 프롬프트
  7. 코디네이터 모드 프롬프트
  8. 팀/스웜 프롬프트
  9. 컴패니언(Buddy) 프롬프트
  10. CLAUDE.md 메모리 파일 시스템
  11. 프롬프트 캐싱 전략
  12. 기타 보조 프롬프트




폴더 구조


1. 프롬프트 시스템 개요

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.tsCLI 접두사 상수 및 Attribution 헤더
constants/cyberRiskInstruction.ts보안/사이버 위험 지침
context.ts시스템/사용자 컨텍스트 (Git 상태, CLAUDE.md)
utils/queryContext.ts시스템 프롬프트 파츠 조합 헬퍼
utils/systemPromptType.tsSystemPrompt 브랜드 타입
utils/claudemd.tsCLAUDE.md 파일 로딩/파싱
memdir/memdir.ts메모리 디렉토리 프롬프트 빌더
memdir/memoryTypes.ts메모리 타입 분류 (user/feedback/project/reference)
services/compact/prompt.tsCompact 요약 프롬프트
coordinator/coordinatorMode.ts코디네이터 모드 시스템 프롬프트
tools/*/prompt.ts개별 도구 설명 프롬프트 (36개 파일)

2. 시스템 프롬프트 아키텍처

2.1 프롬프트 조합 흐름

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)

2.2 섹션 캐싱 메커니즘

systemPromptSections.ts에서 두 가지 캐싱 전략을 제공한다:

2.3 DYNAMIC_BOUNDARY

SYSTEM_PROMPT_DYNAMIC_BOUNDARY는 시스템 프롬프트 배열 내에서 정적/동적 콘텐츠 경계를 표시한다. 경계 이전은 scope: 'global'로 캐시 가능하고, 이후는 사용자/세션별이다.


3. 핵심 시스템 프롬프트 구성

3.1 CLI 접두사 (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."비대화형 단독 실행

3.2 역할 소개 (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에 따라 응답"하도록 변경된다.

3.3 보안 지침 (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 팀이 전담 관리. 변경 시 반드시 해당 팀 리뷰를 받아야 한다.

3.4 시스템 규칙 (getSimpleSystemSection)

핵심 동작 규칙:

3.5 작업 수행 가이드라인 (getSimpleDoingTasksSection)

Claude Code의 작업 철학을 정의하는 핵심 섹션:

코드 스타일 원칙:

작업 행동 원칙:

3.6 행동 주의사항 (getActionsSection)

가역성 & 폭발 반경 기반 행동 판단 프레임워크:

확인 필요 작업 예시:

3.7 도구 사용법 (getUsingYourToolsSection)

3.8 출력 효율성 (getOutputEfficiencySection)

두 가지 변형:

외부 사용자 — 간결: "Go straight to the point. Be extra concise. Lead with the answer, not the reasoning."

내부 사용자 — 상세:

3.9 톤 & 스타일 (getSimpleToneAndStyleSection)


4. 도구(Tool)별 프롬프트

각 도구는 tools/<ToolName>/prompt.ts에 자체 프롬프트를 정의한다. 36개 도구가 개별 프롬프트 파일을 갖고 있다.

4.1 파일 작업 도구

Read (FileReadTool/prompt.ts):

Write (FileWriteTool/prompt.ts):

Glob (GlobTool/prompt.ts):

Grep (GrepTool/prompt.ts):

4.2 셸 도구

Bash (BashTool/prompt.ts) — 가장 복잡한 프롬프트:

4.3 에이전트 도구

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):

4.4 웹 도구

WebSearch (WebSearchTool/prompt.ts):

WebFetch (WebFetchTool/prompt.ts):

4.5 계획 모드 도구

ExitPlanMode (ExitPlanModeTool/prompt.ts):


5. 메모리/컨텍스트 프롬프트

5.1 Auto Memory 시스템 (memdir/)

메모리 4가지 유형 (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.

5.2 CLAUDE.md 파일 시스템 (utils/claudemd.ts)

우선순위유형경로
1 (낮음)Managed/etc/claude-code/CLAUDE.md
2User~/.claude/CLAUDE.md
3ProjectCLAUDE.md, .claude/CLAUDE.md, .claude/rules/*.md
4 (높음)LocalCLAUDE.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.

6. Compact(요약) 프롬프트

(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개 섹션):

  1. Primary Request and Intent — 사용자의 명시적 요청 의도
  2. Key Technical Concepts — 기술 개념, 프레임워크
  3. Files and Code Sections — 파일명, 코드 스니펫, 변경 이유
  4. Errors and fixes — 에러와 해결법
  5. Problem Solving — 해결된 문제, 진행 중 트러블슈팅
  6. All user messages — 도구 결과 아닌 사용자 메시지 전문
  7. Pending Tasks — 남은 작업
  8. Current Work — 요약 시점에 진행 중이던 작업 상세
  9. Optional Next Step — 최근 요청과 직접 관련된 다음 단계

<analysis> 블록은 연습장으로, 최종 컨텍스트에서 제거된다.


7. 코디네이터 모드 프롬프트

(coordinator/coordinatorMode.ts)

다중 작업자 오케스트레이션 프롬프트:

You are Claude Code, an AI assistant that orchestrates software
engineering tasks across multiple workers.

4단계 워크플로우:

단계수행자목적
Research작업자 (병렬)코드베이스 조사
Synthesis코디네이터발견 종합, 구현 명세
Implementation작업자코드 변경
Verification작업자변경 검증

작업자 프롬프트 5원칙:

  1. 자기 완결적 (작업자는 코디네이터 대화를 못 봄)
  2. 종합(Synthesize) 필수 — "your findings에 따라" 금지
  3. 목적 서술 포함
  4. Continue vs. Spawn을 컨텍스트 겹침으로 판단
  5. "Done" 정의 명시

검증(Verification) 원칙:

Verification means proving the code works, not confirming it exists.


8. 팀/스웜 프롬프트

(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):


9. 컴패니언(Buddy) 프롬프트

(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.

10. CLAUDE.md 메모리 파일 시스템

/init 명령어 (commands/init.ts)

인터뷰 기반 5단계:

단계내용
Phase 1설정 범위 확인 (Project/Personal/Both, Skills+Hooks 여부)
Phase 2코드베이스 탐색 (매니페스트, README, CI, 기존 규칙)
Phase 3빈 정보 인터뷰
Phase 4CLAUDE.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 — 높은 우선순위)

11. 프롬프트 캐싱 전략

services/api/claude.ts에서 관리:


12. 기타 보조 프롬프트

12.1 도구 사용 요약 (services/toolUseSummary/toolUseSummaryGenerator.ts)

Haiku 모델로 도구 결과를 30자 내외 라벨로 요약:

Write a short summary label. Keep verb in past tense.
Examples: "Searched in auth/", "Fixed NPE in UserService"

12.2 환경 정보 (computeSimpleEnvInfo)

모든 프롬프트에 포함: CWD, Git 여부, 플랫폼, 셸, OS, 모델명/ID, 지식 컷오프, 최신 모델 패밀리

12.3 MCP 서버 지시사항

MCP 서버의 instructions 필드가 시스템 프롬프트에 자동 주입

12.4 Git 상태 컨텍스트 (context.ts)

세션 시작 시 스냅샷: 현재 브랜치, 메인 브랜치, Git 사용자, 파일 상태, 최근 커밋 5개

12.5 토큰 예산 (Feature flag: TOKEN_BUDGET)

When the user specifies a token target, your output token count will be
shown each turn. Keep working until you approach the target.