Antigravity Advanced Prompt Engineering
Extracting maximum performance from Antigravity's AI agents goes beyond typing commands. It requires strategic prompt design, context optimization, and clear role definition. This guide covers AGENTS.md mastery, chain-of-thought reasoning, self-verification loops, and battle-tested templates.
How Antigravity Interprets Your Prompts
When you send a request to Antigravity's AI agent, several layers of context are automatically assembled:
Automatically Included Context:
- Current open file contents
- Project directory structure
- Configuration files (tsconfig.json, package.json, etc.)
- Recently edited files
- AGENTS.md rules for the project
User-Provided Context:
- Inline prompts typed in the editor
- Explicitly referenced files
- Conversation history
Understanding this two-layer model is critical for effective prompt design. Your inline prompts augment—not replace—the automatic context.
AGENTS.md Mastery
AGENTS.md is a special file placed in your Antigravity project root that defines AI agent behavior at the project level.
Complete Project Structure
# Project Agent Rules
## 🎯 Project Context
- **Technology Stack**: TypeScript, Next.js, React
- **Code Style**: ESLint + Prettier
- **Primary Language**: English (code and comments)
## 📋 Core Principles
1. Always maintain type safety with strict TypeScript
2. Test before implementation (TDD philosophy)
3. Prefer composition over inheritance
4. Keep functions small and focused
## 🛠️ Tools & Services
- Database: PostgreSQL with Prisma ORM
- API Style: REST endpoints only
- Authentication: JWT Bearer tokens
- Deployment: Vercel with edge functions
## ❌ Strict Rules
- Never use `any` type in TypeScript
- No console.log() in production code
- All public functions require JSDoc comments
- Database migrations must be reversible
- No hardcoded secrets or credentials
## ✅ Best Practices
- Use React hooks (useState, useEffect, useContext)
- Keep components under 200 lines of code
- Implement error boundaries for async operations
- Use environment variables for all configuration
- Add loading and error states for all async operations
## 📁 Directory-Specific Rules
### /src/components
- UI components only (no business logic)
- Named exports exclusively
- TypeScript interfaces for all props
- CSS modules for styling
- No inline styles
### /src/api
- Validated input with Zod schemas
- Consistent error response format
- Rate limiting for public routes
- Proper HTTP status codes
- Comprehensive error messages
### /src/utils
- Pure functions only (no side effects)
- Full TypeScript typing
- Unit tests required (minimum 80% coverage)
- Clear function documentation
## 🧪 Testing Standards
- Minimum 80% code coverage across codebase
- Unit tests for all utils (vitest)
- Integration tests for API routes
- E2E tests for critical user flows (Cypress)
- Test naming: describe("what it does", () => {})
## 📝 Code Review Checklist
- [ ] Code follows style guidelines
- [ ] TypeScript types are complete
- [ ] Tests included and passing
- [ ] Documentation updated
- [ ] No debug code or console.log
- [ ] Performance implications reviewedDirectory-Level Rule Files
For different behavior in specific directories, create .agents files in subdirectories:
# /src/components/.agents
## Component-Specific Rules
### File Naming
- All files: PascalCase.tsx
- Props interfaces: {ComponentName}Props
- Styles: {ComponentName}.module.css
### Component 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>;
};Requirements
- Use TypeScript strict mode
- Prop types always explicit (no 'any')
- CSS modules for isolation
- Memoization for expensive renders
- Storybook stories for all components
Forbidden
- Inline styles (use CSS modules)
- Direct DOM manipulation (use useRef)
- Deprecated lifecycle methods
- Console.log statements
## Context Window Optimization
Antigravity has a finite context window. Strategic context use is critical for consistent, high-quality output.
### Context Priority Matrix
**Always Include (High Priority):**
- AGENTS.md
- Currently edited file
- Error messages and stack traces
- Related type definitions and interfaces
- Recent conversation history
**Include When Needed (Medium Priority):**
- Related test files
- API documentation
- Configuration files
- Schema definitions
**Exclude Unless Referenced (Low Priority):**
- node_modules
- Build artifacts
- Cache files
- Third-party library code
### Explicitly Add Context with Comments
//@context src/types/api.ts //@context src/hooks/useAuth.ts
Implement a user profile form that validates email before submission.
The `//@context` directive tells Antigravity to include those files in the message context.
## Role-Playing and Persona Techniques
Assigning expert personas to the AI agent produces significantly higher-quality output.
### Expert Security Auditor
```markdown
You are a seasoned security auditor with 12+ years experience.
Your task: identify vulnerabilities and propose fixes.
## Review Methodology
1. Scan for auth/authz flaws
2. Check for injection vulnerabilities
3. Identify sensitive data exposure
4. Verify encryption implementation
5. Flag unsafe dependencies
## Severity Classification
- **CRITICAL**: Immediate risk, must fix before production
- **HIGH**: Serious flaw, fix in current sprint
- **MEDIUM**: Should address, plan for next sprint
- **LOW**: Nice-to-have improvement
## Feedback Format
For each issue:
- Severity level and title
- Why it's a problem
- Concrete exploitation scenario
- Recommended fix with code example
- Testing verification step
Performance Optimization Specialist
You are a performance engineer specializing in web applications.
Your expertise: identifying and eliminating bottlenecks.
## Analysis Focus
1. Database query patterns (N+1 detection)
2. React rendering efficiency
3. Bundle size optimization
4. Memory leak detection
5. Cache strategy effectiveness
## Measurement Metrics
Provide for each optimization:
- Baseline performance metric
- Expected improvement percentage
- Implementation complexity (Low/Medium/High)
- Trade-offs and considerations
## Deliverables
1. Identified bottleneck
2. Root cause explanation
3. Optimization code
4. Measurement approach
5. Monitoring recommendationsImplementation: Senior Code Reviewer
# /src/.agents
## Code Review Expert
You are a senior engineer with 15+ years experience.
### Review Standards
- **Readability**: Self-documenting code
- **Maintainability**: Clear intent for future developers
- **Performance**: No wasteful algorithms
- **Security**: Input validation, error handling
- **Testing**: Adequate coverage, edge cases
### Feedback Structure
For each issue:
1. **Location**: File and exact line number
2. **Category**: Readability/Security/Performance/Test
3. **Severity**: Critical/High/Medium/Low
4. **Explanation**: Why this is an issue
5. **Solution**: Working code example
6. **Impact**: Effect on codebase quality
### Positive Feedback
Also highlight well-written sections and good decisions.Chain-of-Thought Reasoning
Break complex tasks into explicit steps, having the AI reason through each one.
Multi-Step Component Refactoring
You are refactoring a React component. Work through each step explicitly:
### Step 1: Analyze Current State
- List all props and their types
- Identify state management approach
- Note performance bottlenecks
- Highlight code duplication
### Step 2: Design New Architecture
- Propose improved component hierarchy
- Suggest optimal state management
- Design hook structure
- Plan integration approach
### Step 3: Implementation Strategy
- Break into smaller sub-components
- Identify potential edge cases
- Plan testing approach
- Consider migration from old component
### Step 4: Generate Code
- Implement refactored component
- Add full TypeScript types
- Include error boundaries
- Add comprehensive comments
Show your reasoning explicitly at each step before proceeding to the next.API Endpoint Design Process
Design a new API endpoint following this exact process:
## Step 1: Requirements Analysis
- What data must be accessed?
- Who is the consumer?
- What are success criteria?
- What are failure modes?
## Step 2: API Contract Definition
- HTTP method (GET/POST/PATCH/DELETE)
- Request schema (with Zod)
- Response schema (with Zod)
- Error response formats
## Step 3: Security & Validation
- Authentication requirement
- Authorization rules
- Input validation strategy
- Rate limiting approach
## Step 4: Implementation
- Complete handler code
- Request validation
- Response transformation
- Error handling
- Logging strategy
## Step 5: Testing
- Unit test cases
- Edge case testing
- Error scenario tests
- Integration test outline
Explain your decisions before coding.Self-Verification Loops
Have the AI verify its own output to catch errors before delivery.
Post-Implementation Verification
After generating code, verify ALL of the following:
### Type Safety Verification
- [ ] All variables have explicit types (no 'any')
- [ ] TypeScript strict mode passes
- [ ] Interfaces are properly imported
- [ ] Generic types are properly constrained
### Logic Correctness
- [ ] Does code satisfy requirements?
- [ ] All edge cases handled?
- [ ] Error paths complete?
- [ ] Return values match types?
### Code Quality Review
- [ ] Follows project style guide?
- [ ] Readable for other developers?
- [ ] Comments on complex sections?
- [ ] No console.log or debug code?
### Performance Check
- [ ] No unnecessary loops?
- [ ] No N+1 query patterns?
- [ ] Proper memoization used?
- [ ] Inefficient algorithms avoided?
### Testing Readiness
- [ ] Code is testable?
- [ ] What tests should exist?
- [ ] Edge cases testable?
- [ ] Mocks/fixtures needed?
If any item fails, stop and fix it before finalizing.Checklist-Driven Implementation
## Code Implementation Requirements
Generate code satisfying ALL items:
- [ ] All TypeScript types explicit (strict: true)
- [ ] Every function has JSDoc documentation
- [ ] All error paths handled (try/catch, null checks)
- [ ] No console.log in production code
- [ ] Follows directory-specific naming rules
- [ ] No hardcoded values (uses config/env)
- [ ] Safe null/undefined handling everywhere
- [ ] Optimized for scale (no wasteful iterations)
- [ ] Security best practices applied
- [ ] Unit testable without complex mocks
Check each item as implemented.
If any item incomplete, stop and fix before proceeding.Multi-File Consistency Patterns
Manage changes across multiple files while maintaining coherence.
# Multi-File Change Rules
When modifying code across multiple files:
## Global Type Definitions
- Shared types live in /src/types/index.ts
- No duplicate type definitions
- Update types.ts before feature implementation
- Import all types from central source
## Naming Consistency
- Use same terminology throughout codebase
- If userId, never use user_id in other files
- Consistent naming in:
- Variables and parameters
- API request/response fields
- Database columns
## Import/Export Patterns
- Central exports from /src/index.ts
- Never allow circular imports
- Group related exports logically
## Test File Alignment
- When util.ts changes → update util.test.ts
- API changes require route test updates
- Component prop changes need snapshot updates
- Keep tests synchronized with implementation
## Documentation Sync
- Update JSDoc when function signatures change
- Keep API documentation current
- Update README code examples
- Refresh integration guidesProduction-Ready Prompt Templates
Template 1: Comprehensive Code Review
//@context src/features/payment/checkout.ts
Perform a detailed code review of this checkout implementation.
REVIEW ASPECTS:
1. **Security**: Token handling, data validation
2. **Type Safety**: TypeScript compliance
3. **Error Handling**: All paths covered
4. **Performance**: Query efficiency, rendering
5. **Testability**: Easy to unit test?
6. **Maintainability**: Clear intent?
REQUIRED FORMAT FOR EACH FINDING:
[SEVERITY] Issue Title
File: path.ts:lineNumber
Description: What's wrong
Impact: How it affects code
Fix: Working code solution
Prioritize CRITICAL and HIGH severity issues.Template 2: Refactoring with Impact Analysis
//@context src/components/UserDashboard.tsx
Refactor this component for:
1. Improved readability
2. Reduced cyclomatic complexity
3. Better performance
4. Enhanced testability
ANALYSIS PHASE:
- Current responsibilities
- Identified issues
- Proposed architecture
- Impact on dependent code
CODE PHASE:
- Refactored component code
- Any new utility functions
- Updated props interface
- Backward compatibility notes
TESTING PHASE:
- Test cases to add
- Snapshot changes required
- Integration test updates
Keep component API unchanged for backwards compatibility.Template 3: Comprehensive Test Suite
//@context src/utils/dateFormatter.ts
Write comprehensive tests for this date utility.
TEST STRATEGY:
- List all exported functions
- Define test cases per function
- Happy path + error cases
- Target 100% code coverage
IMPLEMENTATION REQUIREMENTS:
- Use vitest test framework
- Follow AAA pattern (Arrange-Act-Assert)
- Group with describe blocks
- Clear, specific test names
- No magic numbers (use named constants)
- Mock external dependencies appropriately
EDGE CASES TO TEST:
- Leap years
- Timezone changes
- DST transitions
- Invalid input (null, undefined, bad format)
- Boundary dates (1970, 2038)
Generate production-ready test file.Template 4: API Documentation
//@context src/api/handlers/updateUser.ts
Generate comprehensive API documentation.
DOCUMENTATION STRUCTURE:
1. Summary (one sentence)
2. Description (purpose and use cases)
3. Authentication (if required)
4. Request schema (with example)
5. Response schema (success + errors)
6. HTTP status codes
7. Rate limiting info
8. Example requests (cURL, JavaScript)
9. Validation rules
10. Known limitations
FORMAT:
- Use Markdown (suitable for API docs)
- Include real, valid examples
- Document error responses with examples
- Show typical usage patterns
Suitable for OpenAPI/Swagger documentation.Template 5: Bug Fix with Root Cause Analysis
//@context [file containing bug]
Observed Behavior: [what users see]
Expected Behavior: [what should happen]
ROOT CAUSE ANALYSIS:
1. Reproduce the bug
2. Identify affected code paths
3. Explain why it happens
4. Assess scope of impact
5. Find similar potential bugs
SOLUTION PHASE:
1. Proposed fix with code
2. Why this fixes it
3. Possible side effects
4. Tests to verify fix
5. Similar bugs to check for
TESTING STRATEGY:
- Unit tests for fix
- Regression test cases
- Integration test updates
Provide complete, tested fix ready to merge.Debugging Poor Output
When output doesn't meet expectations, diagnosis and iteration are key.
Failure Mode 1: Vague Output
❌ Bad: "Refactor this component"
✅ Good: "Refactor UserProfile component to:
- Split into smaller sub-components
- Convert to hooks-based state management
- Add complete TypeScript typing
- Improve accessibility (ARIA labels)
"
Failure Mode 2: Missing Context
❌ Insufficient: "Add error handling"
✅ Complete: "Add error handling for API responses:
- 401: Redirect to login
- 403: Show permission denied message
- 500: Log error, show generic message
- Network timeout (>3s): Retry with exponential backoff
Use consistent error UI component
"
Failure Mode 3: Unclear Output Format
❌ Ambiguous: "Suggest optimizations"
✅ Specific: "Suggest optimizations in format:
[Issue] Problem description
[Impact] Performance improvement estimate
[Solution] Code example
[Effort] Complexity (Low/Medium/High)
"
Advanced Prompt Engineering Checklist
Verify you've mastered all advanced techniques:
## Foundation Elements
- [ ] AGENTS.md defines project-wide rules
- [ ] Directory-specific .agents files created
- [ ] Context priorities understood and applied
- [ ] Explicit context referencing used (//@context)
## Expert Techniques
- [ ] Role-playing personas assigned appropriately
- [ ] Chain-of-thought for complex tasks
- [ ] Self-verification loops reduce errors
- [ ] Multi-file changes keep consistency
## Implementation Skills
- [ ] Use correct prompt templates for task type
- [ ] Iterate when output is unclear
- [ ] Diagnose and refine problem prompts
- [ ] Team prompts standardized and documented
## Advanced Mastery
- [ ] Custom prompt templates for your workflow
- [ ] Team prompt engineering guidelines created
- [ ] AGENTS.md continuously improved
- [ ] Template library grows with experienceLooking back
Antigravity prompt engineering is a skill that compounds over time. Start with clear AGENTS.md rules, progress to role-playing and chain-of-thought, then master verification loops for consistently excellent output.
Core Takeaways:
- AGENTS.md is your foundation—build it well
- Personas shape output quality dramatically
- Chain-of-thought makes reasoning transparent
- Self-verification catches mistakes early
- Templates scale prompt engineering across teams
With these techniques mastered, you're ready to build custom MCP servers that extend Antigravity's capabilities to your entire organization.