Antigravity プロンプトエンジニアリング上級ガイド
Antigravity の AI エージェントから最高の出力を引き出すには、単にコマンドを入力するだけでなく、戦略的にプロンプトを設計する必要があります。ここでAGENTS.md、コンテキスト最適化、チェーンオブソート、自己検証パターンを通じて、エージェント制御を完全にマスターします。
Antigravity がプロンプトを解釈する仕組み
Antigravity エディタが AI エージェントにリクエストを送る際、以下の情報が自動的に含まれます:
自動提供されるコンテキスト:
- 現在開いているファイルの内容
- プロジェクトのディレクトリ構造
- 関連する設定ファイル(
tsconfig.json、package.jsonなど) - 最近編集したファイル
- AGENTS.md に定義されたルール
あなたが提供する情報:
- インラインプロンプト(エディタに入力したテキスト)
- コンテキストウィンドウに追加されたファイル参照
- AI との会話履歴
この二層構造を理解することが、効果的なプロンプト設計の鍵です。
AGENTS.md の構造と設計
AGENTS.md は、Antigravity プロジェクトのルートに配置される特別なファイルで、AI エージェントの挙動をプロジェクト全体で定義します。
基本構造
# Project Agent Rules
## 🎯 Project Context
- **Technology Stack**: TypeScript, Next.js, React
- **Code Style**: ESLint + Prettier
- **Main Language**: English (comments and documentation)
## 📋 Core Principles
1. Always maintain type safety
2. Write tests before implementation
3. Prefer composition over inheritance
## 🛠️ Tools & Services
- Database: PostgreSQL with Prisma ORM
- API: REST (no GraphQL)
- Authentication: JWT tokens
- Deployment: Vercel
## ❌ Strict Rules
- Never use `any` type in TypeScript
- No console.log() in production code
- All public functions must have JSDoc comments
- Database migrations must be reversible
## ✅ Good Practices
- Use React hooks (useState, useEffect, useContext)
- Keep components under 200 lines
- Implement error boundaries for async operations
- Use environment variables for config
## 📁 Directory Rules
### /src/components
- UI components only
- No business logic
- Always export as named exports
- Add TypeScript interfaces for all props
### /src/api
- API routes and handlers
- Input validation with Zod or io-ts
- Consistent error response format
- Rate limiting for public endpoints
### /src/utils
- Pure utility functions
- No side effects
- Comprehensive unit tests required
## 🧪 Testing Standards
- Minimum 80% code coverage
- Unit tests for utils
- Integration tests for API routes
- E2E tests for critical user flows
## 📝 Code Review Checklist
- [ ] Code follows style guide
- [ ] TypeScript types are complete
- [ ] Tests are included
- [ ] Documentation is updated
- [ ] No console.log() or debug code
- [ ] Performance implications consideredディレクトリ別ルールの定義
複数のディレクトリに異なるルールを適用する場合、サブディレクトリに .agents ファイルを作成できます:
# /src/components/.agents
## Component-Specific Rules
### Naming Convention
- Components: PascalCase (e.g., UserProfile.tsx)
- Props interfaces: {ComponentName}Props
- Example: `UserProfileProps`
### Structure Template
```tsx
import React from 'react';
import styles from './ComponentName.module.css';
interface ComponentNameProps {
title: string;
onAction?: (data: unknown) => void;
}
export const ComponentName: React.FC<ComponentNameProps> = ({
title,
onAction,
}) => {
return <div className={styles.root}>{title}</div>;
};Do's
- Use TypeScript strict mode
- Separate styles into module.css files
- Accept children as prop when needed
- Use React.memo for performance-critical components
Don'ts
- No inline styles
- No deprecated lifecycle methods
- No direct DOM manipulation (use useRef)
- No CSS-in-JS (use CSS modules)
## コンテキストウィンドウの最適化
Antigravity はコンテキストウィンドウに制限があるため、効率的なコンテキスト利用が重要です。
### 優先度付けルール
**高優先度(常に含める):**
- AGENTS.md
- 現在編集中のファイル
- エラーメッセージやログ出力
- 関連する型定義や interface
**中優先度(必要に応じて):**
- 関連するテストファイル
- API ドキュメント
- 設定ファイル
**低優先度(明示的に参照しない限り):**
- ノード_modules
- ビルド出力
- キャッシュファイル
### コンテキストを明示的に追加
//@context src/types/api.ts //@context src/api/handlers/user.ts
このコンポーネントのエラーハンドリングを改善してください
`//@context` コメントにより、Antigravity はそのファイルをコンテキストに含めます。
## ロールプレイ技法による出力改善
AI エージェントに特定の専門家ペルソナを割り当てることで、より質の高い出力が得られます。
### 例 1: セキュリティ監査人ロール
```markdown
You are an experienced security auditor.
Your role is to identify vulnerabilities in code.
When reviewing code:
1. Look for authentication/authorization issues
2. Check for SQL injection or injection attacks
3. Identify sensitive data exposure
4. Verify encryption usage
5. Flag unsafe dependencies
Be specific about severity levels:
- CRITICAL: Immediate action required
- HIGH: Address before production
- MEDIUM: Should fix in next sprint
- LOW: Nice to have improvement
Provide concrete fixes, not just warnings.
例 2: パフォーマンス最適化エキスパート
You are a performance optimization expert.
Your task is to identify and fix performance bottlenecks.
When analyzing code:
1. Check for N+1 query problems
2. Identify unnecessary re-renders
3. Look for memory leaks
4. Verify bundle size impact
5. Suggest caching strategies
Provide metrics:
- Estimated improvement (% faster)
- Trade-offs and considerations
- Implementation difficulty (Low/Medium/High)ロールプレイの実装パターン
// good-reviewer.agents
# Code Review Expert Rules
You are a senior code reviewer with 15+ years experience.
Your goal is to provide constructive, specific feedback.
## Review Focus Areas
- **Readability**: Code should be self-documenting
- **Maintainability**: Future developers understand intent
- **Performance**: No unnecessary loops or allocations
- **Security**: Input validation, error handling
- **Testing**: Adequate coverage, edge cases
## Feedback Format
For each issue, provide:
1. Location: File and line number
2. Severity: Critical/High/Medium/Low
3. Problem: What's wrong and why
4. Suggestion: Concrete code example
5. Impact: Effect on readability/performance/security
## Positive Reinforcement
Also highlight well-written code sections.チェーンオブソート パターン
複雑なタスクを複数のステップに分解し、各ステップで AI に明示的に考えさせます。
Multi-Step Refactoring 例
You are refactoring a React component. Work through these steps:
### Step 1: Analyze Current Implementation
- List all props and their types
- Identify state management needs
- Note performance bottlenecks
### Step 2: Design New Architecture
- Propose component hierarchy
- Suggest state management approach
- Plan hook structure
### Step 3: Implementation Plan
- Break into smaller functions
- Identify potential issues
- Plan testing strategy
### Step 4: Code Generation
Generate the refactored component with:
- Full TypeScript types
- Error boundaries
- Performance optimizations
- JSDoc comments
Show your reasoning at each step before proceeding.実装例:API エンドポイント設計
You are designing a new API endpoint. Follow this process:
## Step 1: Understand Requirements
- What data needs to be accessed?
- Who will use this endpoint?
- What are the success criteria?
## Step 2: Define the Contract
- HTTP method (GET/POST/PUT/DELETE)
- Request schema (with Zod)
- Response schema (with Zod)
- Error responses
## Step 3: Security Review
- Authentication requirements
- Authorization logic
- Input validation rules
- Rate limiting
## Step 4: Implementation
- Generate full handler code
- Include error handling
- Add request/response logging
- Write unit tests
Show your complete analysis before writing code.
自己検証ループの構築
AI エージェントに自分の出力を検証させることで、エラーを減らせます。
検証パターン 1: 実装後のレビュー
After writing the code, verify:
1. **Type Safety Check**
- Are all variables properly typed?
- Does TypeScript strict mode pass?
- Are any 'any' types used? (Should not be)
2. **Logic Verification**
- Does the code match the requirements?
- Are edge cases handled?
- Is error handling complete?
3. **Code Quality Check**
- Does it follow our style guide?
- Is it readable and maintainable?
- Are there comments for complex sections?
4. **Testing Readiness**
- What tests should cover this code?
- What edge cases need tests?
- Is the code testable?
Before finalizing, address any failures in steps 1-3.検証パターン 2: チェックリスト駆動
## Code Implementation Checklist
Generate code that satisfies ALL items:
- [ ] All TypeScript types are explicit (no 'any')
- [ ] Functions have JSDoc comments
- [ ] Error handling covers all paths
- [ ] No console.log in production code
- [ ] Follows project naming conventions
- [ ] No hardcoded values (use config/env)
- [ ] Handles null/undefined safely
- [ ] Performance optimized for scale
- [ ] Security best practices applied
- [ ] Unit testable without mocks
Mark each item complete as you implement.
If any item fails, stop and fix it.マルチファイル調整ロール
複数ファイルにまたがる変更を一貫性を保ちながら実装させます。
# Multi-File Consistency Rules
When making changes across multiple files:
## Global Type Definitions
- All shared types go in /src/types
- Import from types, never duplicate definitions
- Update types.ts before implementing features
## Naming Consistency
- Use the same term across all files
(e.g., if user.id is "userId", use it everywhere)
- Keep naming consistent in:
- Variable names
- Function parameters
- API response fields
## Import/Export Structure
- All exports from /src/index.ts
- No circular imports
- Group related exports together
## Testing Alignment
- If a function in util.ts changes, update util.test.ts
- API changes require API test updates
- Component prop changes need test snapshots updated
## Documentation Sync
- Update JSDoc when signatures change
- Update API docs for endpoint changes
- Keep README examples in sync実用的なプロンプトテンプレートライブラリ
テンプレート 1: コードレビュー
//@context src/features/auth
Review this authentication implementation:
ASPECTS TO REVIEW:
1. Security: Are tokens properly secured?
2. Type Safety: All types explicit?
3. Error Handling: All edge cases covered?
4. Performance: Any N+1 queries?
5. Testability: Easy to unit test?
PROVIDE:
- Numbered list of issues found
- Severity level for each
- Concrete code suggestions
- Overall assessment
Format each finding as:
[SEVERITY] Issue Description
Location: file.ts:line-number
Fix: code exampleテンプレート 2: リファクタリング
//@context src/components/DataTable.tsx
Refactor this component to:
- Improve readability
- Reduce complexity
- Improve performance
- Make it more testable
PROCESS:
1. Analyze current implementation
2. Identify issues
3. Propose new structure
4. Generate refactored code
5. Explain improvements
6. Identify potential breaking changes
Keep same props interface for backward compatibility.テンプレート 3: テスト作成
//@context src/utils/validation.ts
Write comprehensive tests for this validation utility.
TEST STRATEGY:
1. List all exported functions
2. Define test cases per function
3. Include happy path tests
4. Include error/edge case tests
5. Aim for 100% code coverage
REQUIREMENTS:
- Use vitest + React Testing Library
- Follow AAA pattern (Arrange-Act-Assert)
- Group related tests with describe blocks
- Clear test descriptions
- No hardcoded magic numbers
Generate complete test file ready to run.テンプレート 4: ドキュメンテーション
//@context src/api/handlers/createUser.ts
Generate comprehensive documentation for this API endpoint.
INCLUDE:
1. Endpoint summary (1 sentence)
2. Purpose and use cases
3. Request schema (with examples)
4. Response schema (with examples)
5. Error responses (with examples)
6. Authentication requirements
7. Rate limiting details
8. Example cURL request
9. Example JavaScript fetch
10. Performance considerations
Format as Markdown suitable for API docs.テンプレート 5: バグ修正提案
//@context [file with bug]
I'm seeing this bug: [describe behavior]
Expected behavior: [what should happen]
ANALYSIS REQUIRED:
1. Root cause analysis
2. Why the bug occurs
3. Affected code paths
4. Impact assessment
SOLUTION:
1. Proposed fix with code
2. Why this fixes it
3. Any side effects?
4. Tests needed to verify fix
5. Similar bugs to watch for
Provide complete fixed code ready to test.デバッグとトラブルシューティング
悪い出力への対応
AI が期待と異なる出力をした場合:
1. 具体性を増す
❌ 悪い: "このコンポーネントをリファクタリングして"
✅ 良い: "UserProfile コンポーネント を、
- 子コンポーネントに分割
- hooks を使用した状態管理に変更
- TypeScript strict 対応
してください"
2. コンテキストを追加
❌ 不足: "API エラーハンドリングを追加して"
✅ 十分: "API レスポンスが以下の場合に対応:
- 401 Unauthorized
- 403 Forbidden
- 500 Internal Server Error
- Network timeout (3秒以上)
各ケースで適切なユーザーメッセージを表示"
3. 出力形式を指定
❌ 不明確: "最適化案を出して"
✅ 明確: "最適化案を以下の形式で提供:
[Issue] 問題説明
[Impact] パフォーマンス影響
[Solution] コード例
[Effort] 実装難度(Low/Med/High)"
プロンプトエンジニアリングチェックリスト
本ガイドで習得した内容を確認するチェックリスト:
## 基本要素
- [ ] AGENTS.md を作成し、プロジェクト全体ルールを定義
- [ ] ディレクトリ別ルールを実装 (.agents ファイル)
- [ ] コンテキスト優先度を理解している
## 高度なテクニック
- [ ] ロールプレイ技法でペルソナを割り当てられる
- [ ] チェーンオブソートで複雑なタスクを分解できる
- [ ] 自己検証ループでエラーを削減できる
## 実装スキル
- [ ] マルチファイル変更を一貫性保つ
- [ ] 用途別のプロンプトテンプレートを活用
- [ ] デバッグとトラブルシューティング対応
## アドバンス
- [ ] 独自のプロンプトテンプレートを作成している
- [ ] チーム用のプロンプト標準化ガイド作成
- [ ] AGENTS.md を継続的に改善している全体を振り返って
Antigravity のプロンプトエンジニアリングは、単なるコマンド入力ではなく、AI エージェントと効果的に協働するための戦略です。
最重要ポイント:
- AGENTS.md で一貫性のあるルールベースを構築
- ロールプレイで専門家ペルソナを活用
- チェーンオブソートで複雑さを管理
- 自己検証で品質を確保
- テンプレートで再利用性を向上
次は、カスタム MCP サーバーを構築して、Antigravity の能力をさらに拡張しましょう。