상위: 08_00_MOC

실전 레시피 — 스니펫 모음

챕터 08에서 다룬 공식 기능을 바로 쓸 수 있는 스니펫과 체크리스트로 정리했다. 레시피마다 출처 노트를 링크해 두었다.


레시피 1: 프로젝트 CLAUDE.md 템플릿

출처: 08_01-CLAUDE.md-메모리계층

<!-- 유지보수 담당: [팀명], 최종 수정: YYYY-MM -->
 
# 프로젝트명 — Claude Code 지시
 
## 빌드 & 테스트
- 빌드: `pnpm run build`
- 테스트: `pnpm test`
- 린트: `pnpm run lint` (커밋 전 필수)
 
## 코드 컨벤션
- 들여쓰기: 2스페이스
- API 핸들러 위치: `src/api/handlers/`
- 컴포넌트 위치: `src/components/`
- 타입 정의: 파일과 동일 디렉토리, `.types.ts` 확장자
 
## 아키텍처
- 상태 관리: Zustand (Redux 사용 금지)
- API 클라이언트: `src/lib/api.ts` 싱글톤
 
## 절대 하지 말 것 (강제는 Hook으로 별도 설정)
- main 브랜치 직접 푸시
- `console.log` 프로덕션 코드에 남기기
 
# Compact instructions
When you are using compact, please focus on code changes and test results.

원칙은 셋이다. 200줄 이하로 유지하고, 검증할 수 있는 구체적 지시를 쓰고, 관리 메모는 블록 주석에 남긴다.


레시피 2: Path-scoped 규칙 설정

출처: 08_01-CLAUDE.md-메모리계층

프로젝트 구조:
.claude/
└── rules/
    ├── api-design.md       # src/api/**/*.ts 매칭 시
    ├── testing.md          # *.test.ts 매칭 시
    └── security.md         # 무조건 로드 (paths 없음)
---
paths:
  - "src/api/**/*.{ts,tsx}"
---
# API 개발 규칙
- 모든 엔드포인트에 입력 유효성 검사 필수
- 표준 오류 응답 형식 사용: `{ error: string, code: string }`
- OpenAPI 문서 주석 포함 (JSDoc 형식)

레시피 3: 테스트 출력 필터 Hook

출처: 08_05-Hooks-컨텍스트전처리

#!/bin/bash
# ~/.claude/hooks/filter-test-output.sh
input=$(cat)
cmd=$(echo "$input" | jq -r '.tool_input.command // empty')
 
if [[ "$cmd" =~ ^(npm test|pnpm test|pytest|go test|jest) ]]; then
  filtered_cmd="$cmd 2>&1 | grep -A 5 -E '(FAIL|ERROR|error:|✗|×)' | head -100"
  echo "{\"hookSpecificOutput\":{\"hookEventName\":\"PreToolUse\",\"permissionDecision\":\"allow\",\"updatedInput\":{\"command\":\"$filtered_cmd\"}}}"
else
  echo "{}"
fi
// .claude/settings.json
{
  "hooks": {
    "PreToolUse": [
      {
        "matcher": "Bash",
        "hooks": [{ "type": "command", "command": "~/.claude/hooks/filter-test-output.sh" }]
      }
    ]
  }
}

효과는 분명하다. 10,000줄짜리 테스트 로그에서 실패와 오류 100줄만 컨텍스트로 넘긴다.


레시피 4: 위험 명령 차단 Hook

출처: 08_05-Hooks-컨텍스트전처리

#!/bin/bash
# ~/.claude/hooks/block-destructive.sh
input=$(cat)
cmd=$(echo "$input" | jq -r '.tool_input.command // empty')
 
BLOCKED_PATTERNS=("rm -rf /" "DROP TABLE" "git push --force origin main" "kubectl delete namespace")
 
for pattern in "${BLOCKED_PATTERNS[@]}"; do
  if echo "$cmd" | grep -qF "$pattern"; then
    jq -n --arg reason "Blocked: '$pattern' pattern detected" '{
      hookSpecificOutput: {
        hookEventName: "PreToolUse",
        permissionDecision: "deny",
        permissionDecisionReason: $reason
      }
    }'
    exit 0
  fi
done
exit 0
{
  "hooks": {
    "PreToolUse": [
      {
        "matcher": "Bash",
        "hooks": [{ "type": "command", "command": "~/.claude/hooks/block-destructive.sh" }]
      }
    ]
  }
}

레시피 5: SessionStart 컨텍스트 주입 Hook

출처: 08_05-Hooks-컨텍스트전처리

#!/bin/bash
# ~/.claude/hooks/session-context.sh
BRANCH=$(git branch --show-current 2>/dev/null || echo "no-git")
CHANGES=$(git diff --name-only 2>/dev/null | head -5 | tr '\n' ', ')
LAST_COMMIT=$(git log -1 --oneline 2>/dev/null || echo "no commits")
 
jq -n \
  --arg ctx "Branch: $BRANCH\nUncommitted: ${CHANGES:-none}\nLast commit: $LAST_COMMIT" \
  '{
    hookSpecificOutput: {
      hookEventName: "SessionStart",
      additionalContext: $ctx
    }
  }'
{
  "hooks": {
    "SessionStart": [
      {
        "hooks": [{ "type": "command", "command": "~/.claude/hooks/session-context.sh" }]
      }
    ]
  }
}

레시피 6: 코드 리뷰 서브에이전트

출처: 08_04-서브에이전트-컨텍스트격리

---
name: code-reviewer
description: Reviews changed files for quality, security, and best practices. Use proactively after significant code changes.
tools: Read, Glob, Grep
model: sonnet
memory: project
---
 
You are a senior code reviewer specializing in TypeScript/Node.js.
 
When invoked:
1. Read the changed files (check git diff or what was just edited)
2. Analyze for: security issues, performance problems, code style violations, missing error handling
3. Report findings grouped by severity: CRITICAL > WARNING > SUGGESTION
4. Show specific file:line references for each finding
 
Keep your output concise. Lead with the most important issues.

저장 위치: .claude/agents/code-reviewer.md


레시피 7: AGENTS.md 기본 템플릿 (Codex)

출처: 08_07-Codex-AGENTS.md-설정

# 프로젝트명 — Codex 지시
 
## 프로젝트 개요
TypeScript 기반 REST API 서버. Node.js 20, PostgreSQL 15.
 
## 빌드 & 실행
- 의존성: `pnpm install`
- 개발: `pnpm dev`
- 테스트: `pnpm test`
- 타입 체크: `pnpm tsc --noEmit`
 
## 코드 컨벤션
- 모든 함수에 JSDoc 타입 주석
- async/await 사용 (Promise.then 금지)
- 에러는 커스텀 AppError 클래스로 래핑
 
## 디렉토리 구조
- `src/routes/` — Express 라우터
- `src/services/` — 비즈니스 로직
- `src/models/` — Prisma 모델
 
## 알려진 패턴 (피드백 루프)
- DB 쿼리는 반드시 트랜잭션 내부에서 실행
- 환경변수는 `src/config/env.ts`에서만 접근

레시피 8: claudeMdExcludes 설정

출처: 08_01-CLAUDE.md-메모리계층

// .claude/settings.local.json (gitignore에 추가)
{
  "claudeMdExcludes": [
    "**/other-team/.claude/rules/**",
    "**/legacy-service/CLAUDE.md"
  ]
}

모노레포에서 다른 팀의 CLAUDE.md가 자동으로 딸려 오는 것을 막는다.


레시피 9: 자동 컴팩션 안전망 CLAUDE.md 섹션

출처: 08_02-compact와-자동컴팩션

# Compact instructions
 
When compacting, preserve:
- Current task description and target files
- Any API design decisions made this session
- Test failures and their root causes
- Architecture decisions with rationale
 
Do not preserve:
- Exploratory searches and their raw output
- File contents that were read but not modified

컨텍스트 위생 체크리스트

세션 시작 전

  • /memory — 로드된 지시 파일 목록 확인
  • 이전 작업과 다른 도메인이면 /clear 또는 /compact
  • 모델·effort 레벨 확정 (세션 중 변경 = 캐시 무효화 + 비용 급증)
  • MCP 서버 연결 상태 확인 (/mcp)

작업 중

  • 대용량 파일 탐색·로그 분석 → 서브에이전트로 위임
  • 잘못된 방향 감지 시 즉시 Escape → /rewind (캐시 절약)
  • 작업 전환 시점에 수동 /compact Focus on [현재 작업]
  • Context window 사용률 모니터링 (/usage 또는 statusline)

CLAUDE.md 유지보수

  • 200줄 이하 유지
  • 아키텍처 변경 시 즉시 업데이트
  • 편집 후 /clear 또는 /compact 실행
  • “절대 금지” 규칙은 Hook/permissions.deny로 이전
  • 분기별 중복·모순 감사

Codex AGENTS.md 유지보수

  • 잘못된 가정 발견 시 즉시 AGENTS.md에 교정 추가 (다음 실행부터 반영)
  • 32KiB 한도 초과 방지
  • Memories 활성화 시 주기적 내용 검토

비용 기준점 참고

“Across enterprise deployments, the average cost is around $13 per developer per active day and $150-250 per developer per month.” — Manage costs effectively, Anthropic

모델 선택권장 용도
Haiku서브에이전트 단순 탐색, 코드 리뷰 보조
Sonnet일반 코딩 작업 (기본값)
Opus복잡한 아키텍처 결정, 멀티스텝 추론

에이전트 팀은 플랜 모드에서 표준 세션보다 토큰을 ~7배 소비한다. 팀 규모를 줄이고, Sonnet으로 라우팅하고, 작업이 끝나면 곧바로 종료하는 편이 좋다.


참고문헌

관련 노트