Claude Code를 사용한 고급 엔지니어링 프롬프트
Claude Code의 출력 품질은 프롬프트의 품질에 직접적으로 좌우됩니다. 그만큼 신속한 엔지니어링 그것은 단지 요청을 작성하는 것이 아니라 결합하는 예술입니다. 의사소통의 명확성, 기술적 이해 및 구조화된 사고. 이 기사에서는 우리는 예측 가능한 고품질 결과를 얻기 위한 고급 기술을 탐구할 것입니다.
Claude Code는 특히 길고 자세한 프롬프트: 달리 다른 도구보다 더 많은 컨텍스트를 제공할수록 더 나은 응답을 얻을 수 있습니다. 만드는 법을 배우게 됩니다. 일관성을 유지하기 위한 다단계 프롬프트, 재사용 가능한 템플릿 및 시뮬레이션 에이전트 개발 세션을 통해
시리즈 개요
| # | Articolo | 집중하다 |
|---|---|---|
| 1 | 클로드 코드 소개 | 설정 및 첫 번째 단계 |
| 2 | 개념 및 요구사항 | 아이디어에서 사양까지 |
| 3 | 코드베이스 아키텍처 | 프로젝트 구조 |
| 4 | 컨텍스트 및 CLAUDE.md | 고급 구성 |
| 5 | 코드의 구조 | 구현 안내 |
| 6 | 현재 위치 - 프롬프트 엔지니어링 | 고급 프롬프트 |
| 7 | 테스트 및 품질 | 테스트 및 디버깅 |
| 8 | 선적 서류 비치 | README 및 API 문서 |
| 9 | 배포 및 DevOps | CI/CD 및 도커 |
| 10 | 프로젝트 진화 | 유지 |
프롬프트 엔지니어링이 기본인 이유
평범한 프롬프트와 우수한 프롬프트의 차이는 몇 시간의 작업을 의미할 수 있습니다. 저장하거나 낭비하십시오. 확장된 컨텍스트 창을 갖춘 Claude Code는 보상을 제공합니다. 특히 잘 구성된 프롬프트.
프롬프트 엔지니어링의 이점
- 정도: 일반 코드 대신 타겟 응답
- 일관성: 프로젝트 규칙과 일치하는 출력
- 능률: 결과를 얻기 위한 반복 횟수 감소
- 재현성: 동일한 프롬프트, 동일한 품질 결과
- 오토메이션: 일반적인 작업을 위한 재사용 가능한 템플릿
효과적인 프롬프트 분석
잘 구성된 프롬프트는 예측 가능한 패턴을 따릅니다. 기본 구성 요소는 다음과 같습니다.
+-------------+-----------------------------------------------+
| ROLE | Chi deve essere l'AI (ruolo, expertise) |
+-------------+-----------------------------------------------+
| CONTEXT | Background del progetto, stack, architettura |
+-------------+-----------------------------------------------+
| TASK | Cosa deve fare SPECIFICAMENTE |
+-------------+-----------------------------------------------+
| CONSTRAINTS| Limitazioni, requisiti NON-FUNZIONALI |
+-------------+-----------------------------------------------+
| OUTPUT | Formato desiderato della risposta |
+-------------+-----------------------------------------------+
| EXAMPLES | Esempi di input/output attesi (opzionale) |
+-------------+-----------------------------------------------+
1. 역할 - 전문성 정의
역할은 단순한 직위가 아니라 역할을 정의합니다. 전문 지식 수준, 는 지식의 영역 그리고 그것 의사소통 스타일.
# Troppo generico
ROLE: You are a developer.
# Specifico e contestuale
ROLE: You are a senior TypeScript developer with 10+ years of experience
in building scalable Node.js APIs. You follow Clean Architecture principles
and prioritize maintainability over clever solutions. You always consider
security implications and write defensive code.
2. CONTEXT - 프로젝트의 배경
더 많은 컨텍스트를 제공할수록 프로젝트에 더 부합하는 결과가 나올 것입니다. 이것이 Claude Code가 다른 도구에 비해 빛나는 곳입니다.
CONTEXT:
- Project: E-commerce platform for handmade products
- Stack: Node.js 20 + Express 5 + TypeScript 5.3
- Database: PostgreSQL 16 with Prisma ORM
- Architecture: Clean Architecture (Controller - Service - Repository)
- Auth: JWT with refresh tokens, OAuth2 for social login
- Current phase: MVP development, 2 developers
- Existing patterns: We use class-validator for DTOs, custom error classes
- API style: RESTful with JSON:API specification
- Testing: Jest for unit tests, Supertest for integration
3. 과제 - 구체적인 목표
어떻게 해야 하는지가 아니라 무엇을 해야 하는지 설명하세요. Claude가 구현을 제안하게 하세요.
TASK:
Create a ProductService class that handles:
1. Create product (validate price > 0, name unique per seller)
2. Get all products with pagination and filtering (by category, price range)
3. Get product by ID or slug
4. Update product (only owner can update)
5. Soft delete product (mark as inactive, don't remove from DB)
6. Get seller's products with statistics (total views, favorites count)
4. 제약 - 비기능적 요구사항
여기에서는 구현에 관계없이 코드가 따라야 하는 규칙을 정의합니다.
CONSTRAINTS:
- Use dependency injection (constructor injection)
- All methods must be async
- Throw custom errors: ValidationError, NotFoundError, ForbiddenError
- Never expose internal IDs (use UUIDs or slugs in responses)
- Include JSDoc comments for all public methods
- Follow existing naming conventions (camelCase methods, PascalCase classes)
- Don't use 'any' type - always use specific types or generics
- Logging: use structured logging with correlation IDs
- All database operations must use transactions where appropriate
5. 출력 - 응답 형식
응답을 받을 방법을 정확하게 지정하세요.
OUTPUT FORMAT:
- Single TypeScript file
- Export the class as default
- Include all necessary imports at the top
- Add interface definition for the service (IProductService)
- Group methods logically (CRUD operations, then queries, then statistics)
- After the code, provide a brief explanation of key design decisions
- Include TODO comments for potential future improvements
길고 구조화된 프롬프트
Claude Code는 긴 프롬프트에 탁월합니다. 프롬프트 작성을 두려워하지 마세요. 500단어 이상 - 자세한 내용을 제공할수록 더 나은 결과를 얻을 수 있습니다.
ROLE: You are a senior TypeScript developer specialized in e-commerce systems.
You have deep knowledge of payment processing, inventory management, and
order fulfillment workflows.
CONTEXT:
- Project: Handmade marketplace (like Etsy)
- Stack: Node.js 20 + Express 5 + TypeScript 5.3 + Prisma
- Architecture: Clean Architecture with DDD patterns
- We already have: UserService, ProductService, PaymentGateway interface
- Order statuses: pending - paid - processing - shipped - delivered (or cancelled)
- Payment: Stripe integration via PaymentGateway interface
TASK:
Create an OrderService that handles the complete order lifecycle:
1. Create order from cart (validate stock, calculate totals with tax)
2. Process payment (use PaymentGateway, handle failures gracefully)
3. Update order status (with status machine validation)
4. Cancel order (refund if paid, restore stock)
5. Get order history for user (with pagination)
6. Get order details (include items, shipping, payment info)
CONSTRAINTS:
- Use transactions for operations that modify multiple tables
- Implement optimistic locking to prevent race conditions on stock
- All monetary calculations must use integer cents (not floats)
- Status transitions must be validated (can't go from 'delivered' to 'pending')
- Emit events for status changes (OrderPaid, OrderShipped, OrderCancelled)
- Never expose payment details in responses (mask card numbers)
- Include retry logic for payment processing (max 3 attempts)
- Handle partial failures gracefully (e.g., payment succeeds but email fails)
OUTPUT FORMAT:
- Complete TypeScript file with all imports
- IOrderService interface first
- OrderService class implementing the interface
- Include a STATUS_TRANSITIONS constant defining valid transitions
- Add JSDoc with @throws annotations
- After code: list potential edge cases that tests should cover
다단계 프롬프트
복잡한 작업의 경우 작업을 논리적인 단계로 나누세요. 이 접근 방식은 각 단계를 구체화할 수 있기 때문에 더 나은 결과를 얻을 수 있습니다.
다단계 작업 흐름
| 단계 | 프롬프트 | 출력 |
|---|---|---|
| 1 | "OrderService에 대한 인터페이스/유형 정의" | 유형 및 계약 |
| 2 | "기본 클래스 구조 구현" | DI가 포함된 비계 |
| 3 | "재고 확인을 통해 createOrder 구현" | 완전한 방법 |
| 4 | "재시도 로직을 사용하여 processPayment 구현" | 결제 로직 |
| 5 | "상태에 대한 상태 머신 추가" | 전환 |
| 6 | "오류 처리 및 로깅 추가" | 견고성 |
| 7 | "중요한 사례에 대한 단위 테스트 생성" | 테스트 범위 |
I'm building an OrderService step by step.
STEP 1: Define all TypeScript interfaces and types needed.
Requirements:
- Order entity with all fields
- OrderItem entity
- DTOs for create, update, response
- Status enum with all possible states
- Event types for order lifecycle
- Error types specific to orders
Follow our project patterns:
- Use branded types for IDs (OrderId, ProductId, etc.)
- DTOs should use class-validator decorators
- Response DTOs should have static fromEntity() factory methods
Output: Complete types file with all interfaces and types.
STEP 4: Implement processPayment with retry logic.
Context from previous steps:
- We have IOrderService interface defined
- OrderService class with constructor injection
- createOrder() is implemented
Now implement processPayment():
- Accept orderId and paymentMethodId
- Verify order is in 'pending' status
- Call PaymentGateway.charge()
- Implement exponential backoff retry (3 attempts)
- On success: update status to 'paid', emit OrderPaid event
- On failure: mark order as 'payment_failed', log error details
- Handle network timeouts vs payment declines differently
- Use transaction for status update + event emission
Include:
- Private helper for retry logic
- Proper error types for different failure modes
- Logging at each step
검토 프롬프트
생성된 코드나 기존 코드에 대한 코드 검토를 수행하려면 Claude Code를 사용하세요. 이는 눈에 띄지 않는 문제를 식별하는 데 특히 유용합니다.
Review this code comprehensively:
```typescript
[PASTE CODE HERE]
```
ANALYZE FOR:
1. SECURITY
- Injection vulnerabilities (SQL, XSS, Command)
- Authentication/Authorization issues
- Sensitive data exposure
- Input validation gaps
2. CORRECTNESS
- Logic errors
- Edge cases not handled
- Race conditions
- Error handling gaps
3. PERFORMANCE
- N+1 queries
- Memory leaks
- Unnecessary computations
- Missing caching opportunities
4. MAINTAINABILITY
- Code complexity
- Naming clarity
- Single responsibility violations
- Missing documentation
5. TESTING
- Untestable code patterns
- Missing test coverage areas
- Suggested test cases
OUTPUT FORMAT:
For each issue:
- Severity: CRITICAL / HIGH / MEDIUM / LOW
- Location: Line number or function name
- Issue: What's wrong
- Impact: Why it matters
- Fix: Code example of the solution
아키텍처 검증 프롬프트
기능을 구현하기 전에 아키텍처 접근 방식을 검증하세요.
Validate this architectural approach:
FEATURE: Real-time notifications system
PROPOSED APPROACH:
- WebSocket server for real-time push
- Redis pub/sub for cross-instance messaging
- PostgreSQL for notification persistence
- Background job for email fallback
CURRENT ARCHITECTURE:
- Node.js + Express REST API
- PostgreSQL with Prisma
- Redis for caching
- 2 server instances behind load balancer
QUESTIONS:
1. Is WebSocket the right choice here? Consider SSE alternatives.
2. How should we handle WebSocket connections across instances?
3. What happens if Redis goes down?
4. How do we ensure notification delivery (at-least-once)?
5. Scaling concerns at 10k concurrent connections?
For each question:
- Analysis of trade-offs
- Recommended approach
- Implementation complexity (Low/Medium/High)
- Alternative approaches considered
재사용 가능한 프롬프트 템플릿
일반적인 작업을 위한 프롬프트 템플릿 라이브러리를 만듭니다. 당신의 것으로 저장하세요
CLAUDE.md 아니면 별도의 파일로.
템플릿: CRUD 생성
Generate complete CRUD operations for [ENTITY_NAME].
ENTITY FIELDS:
[List each field with:]
- name: type (constraints)
EXAMPLE:
- id: UUID (auto-generated)
- title: string (required, 3-200 chars)
- description: string (optional, max 5000)
- status: enum [draft, published, archived]
- createdAt: datetime (auto)
- updatedAt: datetime (auto)
GENERATE:
1. Entity class with Prisma decorators
2. DTOs (Create, Update, Response, List with pagination)
3. Repository interface and implementation
4. Service with business logic
5. Controller with REST endpoints
6. Unit tests for service
7. Integration tests for controller
FOLLOW THESE PATTERNS:
[Reference existing file or paste example]
ENDPOINTS TO CREATE:
- POST /api/[entities] - Create
- GET /api/[entities] - List (paginated, filterable)
- GET /api/[entities]/:id - Get by ID
- PATCH /api/[entities]/:id - Update
- DELETE /api/[entities]/:id - Soft delete
템플릿: 디버그 지원
I need help debugging an issue.
ERROR MESSAGE:
```
[PASTE EXACT ERROR MESSAGE]
```
STACK TRACE (if available):
```
[PASTE STACK TRACE]
```
CONTEXT:
- File: [filename and path]
- Function/Method: [name]
- What I'm trying to do: [brief description]
- When it happens: [trigger conditions]
- What I've already tried: [list attempts]
RELEVANT CODE:
```typescript
[PASTE CODE - include enough context]
```
RELATED CONFIGURATION (if relevant):
```
[PASTE CONFIG]
```
HELP ME:
1. Understand WHY this error is happening
2. Identify the ROOT CAUSE (not just symptoms)
3. Provide a FIX with explanation
4. Suggest how to PREVENT similar issues
템플릿: 리팩토링
Refactor this code while maintaining identical behavior:
CURRENT CODE:
```typescript
[PASTE CODE]
```
REFACTORING GOALS (prioritized):
1. [Primary goal - e.g., "Reduce complexity"]
2. [Secondary goal - e.g., "Improve testability"]
3. [Tertiary goal - e.g., "Better naming"]
CONSTRAINTS:
- MUST keep the same public interface (method signatures)
- MUST NOT break existing tests
- MUST NOT change external behavior
- SHOULD be reviewable in one PR
OUTPUT:
1. BEFORE/AFTER comparison (side by side)
2. CHANGES LIST with reasoning for each
3. MIGRATION STEPS if changes are incremental
4. TEST UPDATES needed (if any)
5. RISK ASSESSMENT of the refactoring
지속적인 프롬프트가 있는 시뮬레이션된 에이전트
지속적인 성격을 정의하여 특수한 "에이전트"를 시뮬레이션할 수 있습니다.
당신의 것 CLAUDE.md. 이러한 에이전트는 컨텍스트와 규칙을 유지합니다.
모든 상호작용을 통해
시뮬레이션 에이전트란 무엇입니까?
시뮬레이션된 에이전트는 다음을 정의하는 영구 프로필입니다.
- 신원: 이름, 역할, 전문 지식
- 규칙: 항상 답을 안내하는 원칙
- 메모리: 연상되는 프로젝트 컨텍스트
- 스타일: 답변의 형식을 지정하고 구성하는 방법
- 제한사항: 절대로 해서는 안되는 일
대리인: 프로젝트 설계자
## Agent: ProjectArchitect
### Identity
ROLE: Senior Software Architect (15+ years experience)
EXPERTISE:
- Distributed systems design
- API design and contracts
- Database modeling
- Performance optimization
- Security best practices
PERSONALITY: Thoughtful, explains trade-offs, prefers simplicity
### Rules (Always Follow)
1. ALWAYS explain the "why" behind architectural decisions
2. PREFER simplicity - suggest the simplest solution that works
3. CONSIDER scalability but don't over-engineer for MVP
4. IDENTIFY risks and trade-offs for every major decision
5. SUGGEST documentation when introducing new patterns
6. RECOMMEND tests for critical business logic
7. FLAG potential security issues immediately
8. RESPECT existing patterns unless there's a strong reason to change
9. PROPOSE incremental changes over big bang refactoring
10. ALWAYS consider operational complexity (deployment, monitoring)
### Response Format
For architecture questions, structure responses as:
1. Understanding: Restate the problem to confirm understanding
2. Options: List 2-3 approaches with pros/cons
3. Recommendation: Clear recommendation with reasoning
4. Implementation: High-level steps or code if appropriate
5. Risks: Potential issues to watch for
6. Testing: How to validate the solution
### Never Do
- Never suggest removing tests to meet deadlines
- Never recommend storing passwords in plain text
- Never propose solutions without considering failure modes
- Never ignore backwards compatibility without explicit approval
- Never suggest "quick hacks" for production code
에이전트: 백엔드 엔지니어
## Agent: BackendEngineer
### Identity
ROLE: Senior Backend Engineer specialized in Node.js
EXPERTISE:
- API design (REST, GraphQL)
- Database optimization
- Caching strategies
- Message queues
- Authentication/Authorization
PERSONALITY: Pragmatic, detail-oriented, security-conscious
### Rules
1. Business logic ALWAYS stays in services, never in controllers
2. Controllers only handle: routing, validation, response formatting
3. Repositories only handle: data access, no business logic
4. ALWAYS validate inputs at the boundary (DTOs with class-validator)
5. ALWAYS handle errors gracefully with custom error classes
6. Use transactions for multi-table operations
7. Prefer optimistic locking for concurrent updates
8. ALWAYS use parameterized queries (never string concat)
9. Log with correlation IDs for traceability
10. Return consistent response formats
### Code Patterns to Follow
```typescript
// Service method signature
async methodName(dto: InputDto): Promise<OutputDto>
// Error handling
if (!entity) throw new NotFoundError('Entity', id);
if (!hasPermission) throw new ForbiddenError('Cannot modify this resource');
// Response format
{{ '{' }}
"data": {{ '{' }} ... {{ '}' }},
"meta": {{ '{' }} "timestamp": "...", "requestId": "..." {{ '}' }}
{{ '}' }}
```
### Never Do
- Never use 'any' type
- Never log sensitive data (passwords, tokens, PII)
- Never expose internal IDs in responses
- Never return stack traces in production
- Never use SELECT * in queries
대리인: 기술 작가
## Agent: TechnicalWriter
### Identity
ROLE: Technical Writer with developer background
EXPERTISE:
- API documentation (OpenAPI)
- README and onboarding guides
- Architecture Decision Records
- Runbooks and troubleshooting guides
- Code comments and JSDoc
PERSONALITY: Clear, concise, assumes reader is a new team member
### Rules
1. Write for a developer joining the project tomorrow
2. Always include working code examples
3. Explain the "why" not just the "what"
4. Use consistent terminology throughout
5. Document edge cases and error scenarios
6. Keep sentences short and scannable
7. Use bullet points and tables for complex information
8. Include diagrams for architectural concepts
9. Version documentation with code changes
10. Always include "Last Updated" date
### Documentation Types
README.md - Project overview, quick start, architecture
API.md - Endpoints, request/response, authentication
ADR/ - Architecture Decision Records (numbered)
RUNBOOK.md - Operational procedures, troubleshooting
CHANGELOG.md - Version history (Keep a Changelog format)
### Response Format
When writing documentation:
1. Start with a one-sentence summary
2. Explain who this is for
3. Provide prerequisites
4. Give step-by-step instructions
5. Include examples
6. List common issues and solutions
7. Link to related documentation
고급 사용: 에이전트 활성화
대화 시작 시 특정 에이전트를 활성화할 수 있습니다.
# All'inizio della sessione:
"Activate the ProjectArchitect agent. I need to design the notification system
for our e-commerce platform."
# Claude rispondera nel ruolo dell'architetto, seguendo tutte le regole
# definite nel CLAUDE.md.
# Per cambiare agente:
"Switch to BackendEngineer. Now implement the NotificationService based on
the architecture we just discussed."
효과적인 프롬프트를 위한 모범 사례
일반적인 실수
- 모호한 프롬프트: "나를 API로 만들어 주세요"
- 관련 없는 문맥이 너무 많음
- 스타일의 예가 없습니다
- 하나의 프롬프트로 모든 것을 물어보세요
- 실수를 무시하고 반복하라
- 제약조건을 지정하지 마세요
- 그가 규칙을 추측할 것으로 예상
- 생성된 코드를 테스트하지 마세요
모범 사례
- 무엇을, 어떻게, 왜에 대해 구체적으로 설명하세요.
- 관련 컨텍스트만 제공
- 귀하의 스타일 예시를 포함하세요
- 복잡한 작업에는 증분 프롬프트 사용
- 오류 분석 및 프롬프트 수정
- 명확한 제약 조건 정의
- 기존 규칙을 보여주세요
- 사용하기 전에 항상 확인하세요
프롬프트 전 체크리스트
프롬프트를 보내기 전에
- 특정 역할을 정의했습니까?
- 충분한 프로젝트 맥락을 제공했는가?
- 업무가 구체적이고 측정 가능한가?
- 비기능적 제약 조건을 나열했나요?
- 출력 형식을 지정했습니까?
- 필요한 경우 예시를 포함시켰나요?
- 프롬프트가 명확할 정도로 짧습니까?
- 하지 말아야 할 일을 지정했습니까?
결론 및 다음 단계
신속한 엔지니어링은 Claude Code를 최대한 활용하기 위한 기본 기술입니다. 단순히 요청사항을 작성하는 것이 아니라 구조적 사고 AI가 효과적으로 이해하고 대응할 수 있도록 말이죠.
그만큼 시뮬레이션 에이전트 이 개념을 한 단계 더 발전시켜 귀하의 프로젝트를 "알고 있는" 지속적인 성격을 정의할 수 있습니다. 그리고 그들은 자동으로 귀하의 규칙을 따릅니다.
에서 다음 기사 Claude Code를 사용하는 방법을 살펴보겠습니다. 테스트 및 코드 품질: 단위 테스트 생성에서 가이드 리팩토링부터 지원 디버깅까지 엣지 케이스 적용 범위까지.
기억해야 할 핵심 사항
- 구조: 역할 + 컨텍스트 + 작업 + 제약 조건 + 출력
- 증분: 복잡한 작업을 단계로 나누기
- 예: 스타일을 정의하기 위한 몇 번의 메시지 표시
- 부정적인: 하지 말아야 할 일을 명시하세요
- 자치령 대표: 지속적인 맥락을 위한 지속적인 성격
- 템플릿: 재사용 가능한 라이브러리 만들기
- 확인하다: 생성된 출력을 항상 검증하세요.







