- Claude Code 2.1.87에는 문서화되지 않은 설정이 많고, 개인·프로젝트별 .claude/ 파일로 Hooks, Skills, Agents를 나눠 적용 가능함
- Hook은 stdin JSON과 exit code뿐 아니라 stdout의 이벤트별 JSON 필드로 명령 수정, 권한 결정, 컨텍스트 주입, 파일 감시까지 수행함
- 문서에 없는 Hook 필드 once, async, asyncRewake로 1회 실행, 백그라운드 감사 로그, 비동기 보안 차단 흐름을 만들 수 있음
- Skills와 Agents는 숨겨진 frontmatter로 모델·effort·스코프 Hook·Agent 위임·지속 메모리·CLAUDE.md 생략·MCP 의존성을 제어함
- Auto Mode, 자동 메모리, Dream, Magic Docs, 권한 glob, context: fork는 Claude Code를 학습형 개발 환경에 가깝게 구성해 줌
기준 버전과 파일 위치
- 내용은 @anthropic-ai/claude-code@2.1.87 기준이며, 문서화되지 않은 기능은 릴리스 사이에서 바뀔 수 있음
- 이름에 EXPERIMENTAL 이 들어간 필드는 Anthropic 엔지니어가 불안정하다고 표시한 것으로, 제거되거나 이름이 바뀔 수 있음
- 설정 파일 위치
- 개인 설정: ~/.claude/settings.json
- 프로젝트 설정: .claude/settings.json
- Skills 위치
- 개인: ~/.claude/skills/<name>/SKILL.md
- 프로젝트: .claude/skills/<name>/SKILL.md
- Agents 위치
- 개인: ~/.claude/agents/<name>.md
- 프로젝트: .claude/agents/<name>.md
- Hook 스크립트는 ~/.claude/hooks/에 두는 관례가 적합하며, 실행하려면 chmod +x가 필요함
- 프로젝트 수준의 .claude/ 파일은 Git에 커밋해 팀과 공유할 수 있고, ~/.claude/ 아래 개인 파일은 사용자에게만 적용됨
Hook은 stdout JSON으로 Claude Code 동작을 바꿀 수 있음
- 공식 문서는 Hook이 stdin으로 JSON을 받고 exit code 2로 작업을 막는 흐름만 다루지만, 실제로는 stdout의 이벤트별 JSON 필드로 Claude Code 동작을 실시간 변경할 수 있음
-
PreToolUse에서 반환 가능한 필드
- updatedInput: 도구 실행 전 입력을 다시 작성해 명령을 바꿀 수 있음
- permissionDecision: 사용자에게 묻지 않고 allow 또는 deny를 강제할 수 있음
- permissionDecisionReason: 결정 이유를 UI에 표시 가능함
- additionalContext: 대화 컨텍스트에 텍스트를 주입할 수 있음
-
SessionStart에서 반환 가능한 필드
- watchPaths: 자동 파일 감시를 설정해 FileChanged 이벤트를 트리거할 수 있음
- initialUserMessage: 세션의 첫 사용자 메시지 앞에 내용을 덧붙일 수 있음
- additionalContext: 전체 세션 동안 유지되는 컨텍스트를 주입 가능함
-
PostToolUse에서 반환 가능한 필드
- updatedMCPToolOutput: Claude가 보는 MCP 도구 응답을 수정할 수 있음
- additionalContext: 도구 실행 후 컨텍스트를 주입할 수 있음
-
PermissionRequest에서 반환 가능한 필드
- decision: updatedInput 또는 updatedPermissions와 함께 프로그래밍 방식으로 허용하거나 거부할 수 있음
-
git push를 자동으로 --dry-run으로 바꾸는 Hook
- PreToolUse Hook에서 Bash 명령을 검사해 git push가 포함되면 updatedInput 으로 명령 끝에 --dry-run을 붙일 수 있음
- Claude는 git push origin main을 실행한다고 보지만, Hook이 실제 실행 전 git push origin main --dry-run으로 바꿈
{
"hooks": {
"PreToolUse": [{
"matcher": "Bash",
"hooks": [{
"type": "command",
"command": "~/.claude/hooks/dry-run-pushes.sh"
}]
}]
}
}
#!/bin/bash
INPUT=$(jq -r '.tool_input.command' < /dev/stdin)
if echo "$INPUT" | grep -q 'git push'; then
jq -n --arg cmd "$INPUT --dry-run" '{"updatedInput": {"command": $cmd}}'
fi
-
세션 시작 시 파일 감시와 Git 컨텍스트를 주입하는 Hook
- SessionStart Hook은 package.json, .env, tsconfig.json을 감시 대상으로 지정하고, 현재 브랜치와 커밋되지 않은 파일 수를 세션 컨텍스트로 넣을 수 있음
{
"hooks": {
"SessionStart": [{
"hooks": [{
"type": "command",
"command": "~/.claude/hooks/session-context.sh",
"statusMessage": "Loading project context..."
}]
}]
}
}
#!/bin/bash
BRANCH=$(git branch --show-current 2>/dev/null)
CHANGES=$(git status --porcelain 2>/dev/null | wc -l | tr -d ' ')
jq -n \
--arg branch "$BRANCH" \
--arg changes "$CHANGES" \
'{
"watchPaths": ["package.json", ".env", "tsconfig.json"],
"additionalContext": "Current branch: \($branch). Uncommitted changes: \($changes) files."
}'
-
읽기 전용 Bash 명령을 자동 승인하는 Hook
- ls, cat, echo, pwd, whoami, date, git status, git log, git diff 같은 명령은 permissionDecision: "allow" 로 사용자 확인 없이 통과 가능함
{
"hooks": {
"PreToolUse": [{
"matcher": "Bash",
"hooks": [{
"type": "command",
"command": "~/.claude/hooks/auto-approve-readonly.sh"
}]
}]
}
}
#!/bin/bash
CMD=$(jq -r '.tool_input.command' < /dev/stdin)
if echo "$CMD" | grep -qE '^(ls|cat|echo|pwd|whoami|date|git status|git log|git diff)'; then
echo '{"permissionDecision": "allow", "permissionDecisionReason": "Safe read-only command"}'
fi
문서에 없는 Hook 설정 필드 3개
- 문서화된 Hook 필드는 type, command, matcher, timeout, if, statusMessage지만, 소스 코드 파서는 once, async, asyncRewake 도 받음
-
once: true
- Hook을 정확히 한 번만 실행한 뒤 자동 제거하므로 첫 세션 설정에 적합함
- .env가 없으면 .env.example을 복사하고 이후에는 다시 실행하지 않는 흐름을 만들 수 있음
{
"hooks": {
"SessionStart": [{
"hooks": [{
"type": "command",
"command": "[ -f .env ] || cp .env.example .env && echo 'Created .env from template'",
"once": true,
"statusMessage": "First-time setup..."
}]
}]
}
}
-
async: true
- Hook을 백그라운드에서 실행해 Claude의 진행을 막지 않음
- 모든 Bash 명령을 ~/.claude/audit.jsonl에 기록하면서 세션 지연을 추가하지 않는 데 쓸 수 있음
{
"hooks": {
"PostToolUse": [{
"matcher": "Bash",
"hooks": [{
"type": "command",
"command": "jq '{timestamp: now, command: .tool_input.command, session: .session_id}' < /dev/stdin >> ~/.claude/audit.jsonl",
"async": true
}]
}]
}
}
-
asyncRewake: true
- 정상 경로에서는 async처럼 백그라운드로 실행하지만, exit code 2로 종료되면 모델을 다시 깨워 작업을 차단함
- Claude가 작성한 파일마다 하드코딩된 password, secret, api_key 패턴을 검사하고, 발견 시 차단 가능함
{
"hooks": {
"PostToolUse": [{
"matcher": "Write|Edit",
"hooks": [{
"type": "command",
"command": "~/.claude/hooks/scan-secrets.sh",
"asyncRewake": true,
"statusMessage": "Scanning for secrets..."
}]
}]
}
}
#!/bin/bash
FILE=$(jq -r '.tool_input.file_path // .tool_response.filePath' < /dev/stdin)
if grep -qE '(password|secret|api_key)\s*=' "$FILE" 2>/dev/null; then
exit 2
fi
exit 0
Skill frontmatter의 숨겨진 필드
- 문서에는 name, description, allowed-tools, argument-hint, when_to_use, context가 다뤄지지만, 실제 파서는 추가 필드 6가지를 받음
-
model
- Skill 실행 모델을 바꿀 수 있으며, 빠르고 저렴한 작업에는 haiku, 복잡한 분석에는 opus를 쓸 수 있음
---
name: quick-lint
description: Fast lint check using the cheapest model
model: haiku
effort: low
allowed-tools: Bash, Read
argument-hint: "[file]"
---
Run the project linter on: $ARGUMENTS
Detect the linter from config (eslint, ruff, clippy) and run it. Report only errors, not warnings.
-
effort
- 모델이 얼마나 깊게 생각할지를 조절하며, 값은 low, medium, high, max임
- 내부적으로 응답별 추론 깊이를 제어하는 effort 시스템에 매핑됨
-
hooks
- Skill이 활성화될 때만 등록되고 완료되면 해제되는 스코프 지정 Hook을 정의할 수 있음
- TypeScript 파일을 쓸 때마다 동기적으로 타입 체크하고, 백그라운드에서 lint를 실행하는 식으로 쓸 수 있음
---
name: strict-typescript
description: Write TypeScript with type checking on every save
allowed-tools: Bash, Read, Write, Edit, Grep, Glob
hooks:
PostToolUse:
- matcher: "Write|Edit"
hooks:
- type: command
command: "~/.claude/hooks/typecheck-on-save.sh"
statusMessage: "Type checking..."
- type: command
command: "~/.claude/hooks/lint-on-save.sh"
async: true
---
Write TypeScript with strict enforcement. Every file you touch gets type-checked and linted automatically.
$ARGUMENTS
-
agent
- Skill 실행을 사용자 정의 Agent에 위임할 수 있음
---
name: deep-review
description: Thorough security review delegated to the review agent
agent: security-review
---
Review the following: $ARGUMENTS
-
disable-model-invocation: true
- 자동 호출을 막고 명시적인 /skill-name 호출로만 실행되게 하므로, 파괴적 Skill에 적합함
-
shell: bash
Agent frontmatter의 숨겨진 필드
- .claude/agents/의 사용자 정의 Agent도 문서에 없는 frontmatter 필드를 지원함
-
color
- UI 색상을 red, orange, yellow, green, blue, purple, pink, gray 중 하나로 설정할 수 있음
- 여러 Agent가 실행될 때 시각적으로 구분하는 데 도움이 됨
-
memory
- Agent에 호출 간 지속 메모리를 부여함
- user: 모든 프로젝트에 걸쳐 전역으로 유지됨
- project: 프로젝트별로 유지됨
- local: Git에서 제외되는 비공개 프로젝트별 메모리임
- 보안 리뷰어는 과거 발견 사항을 추적할 수 있고, 코드 리뷰어는 세션을 넘어 사용자의 패턴을 기억할 수 있음
---
name: codebase-guide
description: Answer questions about the codebase, learning more with each session
tools: [Read, Grep, Glob, Bash]
color: green
memory: project
---
You are a codebase guide with persistent memory. Check your memory first before exploring the code.
-
omitClaudeMd: true
- CLAUDE.md 지시 계층 로딩을 건너뛰며, 프로젝트 관습 대신 업계 기준으로 보는 “fresh eyes” 리뷰어에 적합함
---
name: fresh-eyes
description: Review code without project-specific biases
tools: [Read, Grep, Glob]
omitClaudeMd: true
effort: high
color: blue
---
Review this code purely from first principles. You have no project context. Focus on correctness, security, performance, and readability by industry standards.
-
criticalSystemReminder_EXPERIMENTAL
- 짧은 메시지를 매 턴마다 시스템 리마인더로 다시 주입하며, 대화 압축 이후에도 컨텍스트에 남음
- 필드 이름 자체에 EXPERIMENTAL 이 포함되어 있어 불안정하며, 핵심 인프라가 아니라 보조 안전 리마인더 용도로만 쓰는 편이 적합함
---
name: prod-deployer
description: Manages production deployments with strict safety checks
tools: [Bash, Read, Grep]
color: red
criticalSystemReminder_EXPERIMENTAL: "Always run migrations with --dry-run first. Never skip the staging verification step."
---
-
requiredMcpServers
- 필요한 MCP 서버 이름 패턴을 나열하며, 해당 서버가 없으면 Agent가 나타나지 않음
- 의존성이 준비되지 않은 Agent가 로드되는 일을 막을 수 있음
Auto Mode 분류기는 자연어 환경 설명을 받음
- settings.json의 autoMode 필드는 Anthropic 내부에서 “YOLO Classifier”라고 부르는 자동 승인 분류기를 설정함
- allow 패턴은 자동 승인되고, soft_deny 패턴은 항상 확인을 요구함
- environment 배열은 패턴이 아니라 분류기가 읽는 자연어 컨텍스트이며, 프로젝트 환경을 설명해 애매한 명령의 안전성 판단에 반영할 수 있음
{
"autoMode": {
"allow": [
"Bash(npm test)",
"Bash(npm run *)",
"Bash(git status)",
"Bash(git diff *)",
"Bash(git log *)",
"Read",
"Grep",
"Glob"
],
"soft_deny": [
"Bash(git push *)",
"Bash(rm *)",
"Write(.env*)"
],
"environment": [
"NODE_ENV=development",
"This is a local dev machine with no production database access",
"All Docker containers use isolated networks",
"The test suite is safe to run repeatedly, it uses a dedicated test database"
]
}
}
- This project uses Docker, all commands run in containers 같은 문장은 분류기가 환경을 이해하는 데 쓰임
- No production access는 파괴적 작업에 덜 보수적으로 대응하게 하고, Test database is isolated는 테스트 실행이 항상 안전하다는 신호로 작동함
자동 메모리와 Dream 통합 루프
- settings.json에서 autoMemoryEnabled 와 autoDreamEnabled 를 켜면 Claude Code의 자기개선 시스템이 활성화됨
{
"autoMemoryEnabled": true,
"autoDreamEnabled": true
}
-
autoMemoryEnabled
- 각 대화 후 백그라운드 Agent가 세션에서 오래 유지할 가치가 있는 정보를 추출함
- 사용자 선호, 코드베이스 패턴, 결정 사항을 표준 memory frontmatter 형식으로 ~/.claude/projects/<path>/memory/에 기록함
-
autoDreamEnabled
- 24시간마다, 누적 세션이 5개 이상이면 백그라운드 Agent가 과거 세션 transcript를 검토해 메모리를 통합함
- 중복 병합, 모순 해결, 상대 날짜의 절대 날짜 변환, 오래된 항목 제거를 수행함
- 두 설정을 함께 켜면 세션이 메모리를 만들고, Dream이 메모리를 통합하며, 통합된 메모리가 이후 세션에 반영되는 학습 루프가 만들어짐
- 몇 주 후에는 모델 재학습 없이 Claude Code가 사용자 선호, 관습, 공통 패턴을 기억하는 효과가 나타날 수 있음
Magic Docs 형식
- Magic Docs는 정규식 /^#\s*MAGIC\s+DOC:\s*(.+)$/im 으로 감지됨
- 반드시 H1 제목이어야 하고, 대소문자를 구분하지 않음
- 다음 줄에는 _underscores_ 또는 *asterisks*로 감싼 이탤릭 지시문을 둘 수 있으며, 업데이트 Agent가 집중할 범위를 제한함
# MAGIC DOC: API Endpoint Reference
_Only document public REST endpoints. Include method, path, request body, response schema, and auth requirements._
## Endpoints
(content auto-maintained by Claude Code)
- 지시문이 없으면 Agent는 모든 내용을 업데이트하려고 함
- 지시문이 있으면 only track public endpoints나 focus on breaking changes 같은 범위를 따름
- 업데이트 Agent는 백그라운드에서 실행되며, 해당 파일 하나만 편집하도록 제한됨
- 헤더를 삭제하면 추적이 자동으로 중단됨
전체 권한 규칙 문법
- 문서에는 Bash(git *) 같은 기본 예시가 있지만, 실제 패턴 언어는 Bash, 파일 경로, MCP 도구를 폭넓게 다룸
Bash(npm *) # wildcard after "npm "
Bash(git commit *) # specific subcommand
Read(*.ts) # file extension
Read(src/**/*.ts) # recursive directory with extension
Write(src/**) # recursive, all files
mcp__slack # all tools on slack server
mcp__slack__* # explicit wildcard (same effect)
mcp__slack__post_message # specific tool
Bash(npm:*) # legacy colon prefix (word boundary)
- *는 셸 glob처럼 경계 안에서 매칭되고, **는 디렉터리를 재귀적으로 매칭함
- MCP 도구 권한은 이중 밑줄 형식인 mcp__<server>__<tool>을 사용함
- Hook의 if 필드도 같은 문법을 사용하며, 정규식이 아니라 glob임
{
"permissions": {
"allow": [
"Bash(npm *)", "Bash(git status)", "Bash(git diff *)",
"Read(src/**)", "Read(tests/**)", "Grep", "Glob",
"mcp__database__query"
],
"deny": [
"Bash(rm -rf *)", "Write(/etc/**)", "Write(.env*)",
"mcp__slack__delete_*"
],
"ask": [
"Bash(git push *)", "Write(*.json)", "Write(*.lock)",
"mcp__slack__post_message"
]
}
}
context: fork와 모델 선택의 캐시 영향
- Skill에 context: fork 를 설정하면 백그라운드 forked subagent로 실행됨
- Fork는 CacheSafeParams라는 typed contract를 통해 부모의 prompt cache를 공유하며, 캐시 적중률을 높이기 위해 byte-identical API request prefix를 생성함
- Forked Skill에 다른 모델을 지정하면 prefix가 달라져 캐시가 깨질 수 있음
- 부모 대화가 Opus이고 fork가 Haiku이면 prefix가 달라져 cache miss가 발생하고 전체 비용을 내게 됨
- Forked Skill에서는 model 필드를 생략하거나 model: inherit 을 사용해야 캐시가 유지됨
- context: fork는 보안 스캔, 의존성 분석, 문서 생성, 테스트 스위트 실행 같은 무거운 작업에 적합하며, 메인 대화는 반응성을 유지함
---
name: full-audit
description: Comprehensive codebase audit running in the background
context: fork
allowed-tools: Bash, Read, Grep, Glob, WebSearch
effort: high
---
Run a comprehensive audit:
- Security scan (grep for dangerous patterns, check dependencies for CVEs)
- Code quality (duplicated logic, dead code, missing error handling)
- Test coverage (untested critical paths)
- Dependency health (outdated packages, unused deps, license issues)
Write a detailed report to /tmp/audit-report.md when complete.
기능 조합 예시
-
지속 메모리와 스코프 Hook을 가진 코드 리뷰어
- Agent가 코드베이스별 메모리를 읽고, 과거 발견 패턴과 새 문제를 함께 리뷰하며, 이후 발견 사항을 다시 메모리에 저장함
- 여러 리뷰를 거치면 일반 리뷰어가 놓칠 수 있는 프로젝트별 반복 문제를 잡는 데 도움이 됨
---
name: reviewer
description: Code reviewer that learns your codebase patterns over time
tools: [Read, Grep, Glob, Bash]
effort: high
color: yellow
memory: project
hooks:
PostToolUse:
- matcher: "Bash"
hooks:
- type: command
command: "~/.claude/hooks/log-review.sh"
async: true
---
Before reviewing, read your memory for past findings on this codebase.
Review git diff HEAD~1 for:
- Patterns you've flagged before (check memory)
- New issues worth flagging
- Resolved issues from past reviews
After review, save to memory:
- New patterns found (type: feedback)
- Recurring issues (type: project)
End with VERDICT: PASS, FAIL, or NEEDS_REVIEW.
-
파일 감시와 asyncRewake 안전망을 결합한 세션 설정
- 세션 시작 시 프로젝트 컨텍스트를 로드하고, 읽기 전용 Bash 명령은 즉시 자동 승인하며, 위험한 명령은 비동기 안전 검사로 차단함
- 읽기 전용 명령은 빠르게 통과하고, 위험 명령은 막히며, 나머지는 일반 권한 흐름을 따름
{
"hooks": {
"SessionStart": [{
"hooks": [{
"type": "command",
"command": "~/.claude/hooks/session-context.sh",
"statusMessage": "Loading project context..."
}]
}],
"PreToolUse": [{
"matcher": "Bash",
"hooks": [{
"type": "command",
"command": "~/.claude/hooks/auto-approve-readonly.sh"
}, {
"type": "command",
"command": "~/.claude/hooks/block-dangerous.sh",
"asyncRewake": true,
"statusMessage": "Safety check..."
}]
}]
}
}
#!/bin/bash
CMD=$(jq -r '.tool_input.command' < /dev/stdin)
echo "$CMD" | grep -qE '(rm -rf /|sudo rm|chmod 777|> /dev/)' && exit 2 || exit 0
-
모델 override, effort 제어, Agent 위임을 조합한 아키텍처 리뷰
- effort: max로 깊은 분석을 지정하고, 특정 Agent에 위임하며, 해당 Agent의 omitClaudeMd: true로 기존 프로젝트 관습의 영향을 줄임
---
name: architecture-review
description: Deep architecture review using max effort, delegated to fresh-eyes agent
agent: fresh-eyes
effort: max
---
Review the architecture of this project. Ignore existing conventions (the agent has omitClaudeMd: true).
Focus on: $ARGUMENTS
Evaluate structural decisions, dependency graph health, separation of concerns, and scalability characteristics.
의미와 한계
- 이벤트별 응답 필드를 가진 Hook 시스템은 AI 도구 사용을 위한 프로그래밍 가능한 미들웨어 계층으로 작동함
- 지속 Agent 메모리는 세션을 넘어 경험을 축적하는 AI 전문가를 만들 수 있게 함
- Dream 통합 시스템은 모델 재학습 없이 세션 경험에서 학습하는 구조를 제공함
- Auto Mode 분류기는 자연어 환경 설명을 받아 안전 판단에 반영함
- 이 기능들은 숨겨진 설정이나 이스터에그라기보다 지속적이고 학습하며 자율적인 AI 개발 환경을 위한 기반 기능으로, 현재 npm 패키지에 이미 들어 있음