クロードコードによる高度なエンジニアリングプロンプト
Claude Code の出力の品質は、プロンプトの品質に直接依存します。 の 迅速なエンジニアリング 単にリクエストを書くだけではありません。それは組み合わせの技術です コミュニケーションの明瞭さ、技術的な理解、構造化された思考。この記事では 予測可能な高品質の結果を達成するための高度なテクニックを探求します。
クロード・コードは特に以下の点で優れています。 長くて詳細なプロンプト:違う 他のツールよりも、提供するコンテキストが多いほど、応答が向上します。作成方法を学びます 一貫性を維持するための複数ステップのプロンプト、再利用可能なテンプレート、およびシミュレートされたエージェント 開発セッションを通じて。
シリーズ概要
| # | アイテム | 集中 |
|---|---|---|
| 1 | クロードコードの紹介 | セットアップと最初のステップ |
| 2 | コンセプトと要件 | アイデアから仕様まで |
| 3 | コードベースのアーキテクチャ | プロジェクトの構造 |
| 4 | コンテキストとCLAUDE.md | 高度な構成 |
| 5 | コードの構造 | ガイド付き実装 |
| 6 | あなたはここにいます - プロンプトエンジニアリング | 高度なプロンプト |
| 7 | テストと品質 | テストとデバッグ |
| 8 | ドキュメント | README と API ドキュメント |
| 9 | デプロイとDevOps | CI/CD と Docker |
| 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. 背景 - プロジェクトの背景
提供するコンテキストが多いほど、出力がプロジェクトとより一致するようになります。 これは、他のツールと比較して 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. タスク - 具体的な目的
「どのように」ではなく、「何をする必要があるか」を説明します。クロードに実装を提案してもらいましょう。
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 にしてください」
- 無関係な文脈が多すぎる
- スタイルの例はありません
- 1 つのプロンプトですべてを質問する
- 間違いを無視して繰り返す
- 制約を指定しないでください
- 彼が慣例を推測することを期待する
- 生成されたコードをテストしないでください
ベストプラクティス
- 何を、どのように、なぜ、について具体的にする
- 関連するコンテキストのみを提供する
- あなたのスタイルの例を含めてください
- 複雑なタスクには増分プロンプトを使用する
- エラーを分析し、プロンプトを修正する
- 明確な制約を定義する
- 既存の慣例を紹介する
- 使用前に必ず確認してください
プロンプト前のチェックリスト
プロンプトを送信する前に
- 特定の役割を定義しましたか?
- プロジェクトのコンテキストを十分に提供しましたか?
- タスクは具体的で測定可能ですか?
- 機能以外の制約を列挙しましたか?
- 出力形式を指定しましたか?
- 必要に応じて例を含めましたか?
- プロンプトは明確に理解できるほど短いですか?
- してはいけないことを指定しましたか?
結論と次のステップ
迅速なエンジニアリングは、Claude Code を最大限に活用するための基本的なスキルです。 単にリクエストを書くだけではなく、 構造思考 AI が効果的に理解し、対応できるようにします。
Gli 模擬エージェント このコンセプトを次のレベルに引き上げ、 プロジェクトを「知っている」永続的な人物を定義できるようにする そして、それらは自動的に規則に従います。
Nel 次の記事 クロードコードの使用方法を見ていきます。 テストとコードの品質: 単体テストの生成から ガイド付きリファクタリングからデバッグ支援まで、エッジケースのカバーまで。
覚えておくべき重要なポイント
- 構造: 役割 + コンテキスト + タスク + 制約 + 出力
- 増分: 複雑なタスクをステップに分割する
- 例: スタイルを定義するための数ショットのプロンプト
- ネガティブ: してはいけないことを指定する
- エージェント: 継続的なコンテキストのための永続的なパーソナリティ
- テンプレート: 再利用可能なライブラリを作成する
- 確認する: 生成された出力を常に検証する







