Setup and context — Why Does Antigravity Still Feel Slow?
The first days with Antigravity feel like magic. Code appears instantly, bugs vanish, and features that once took hours get done before lunch. But a few weeks in, something shifts. You notice you're repeating instructions. Context gets confused. The same fix takes three exchanges instead of one.
This isn't Antigravity failing you — it's a workflow design problem. Your process isn't structured to draw out the AI's full capabilities.
Think of it this way: Antigravity is an extraordinarily skilled developer who joins your project fresh every single session. They have deep expertise, but they start with zero institutional knowledge. If you give that developer a confusing briefing, an unclear scope, and contradictory requirements, they'll produce confusing output — no matter how talented they are. The same is true of AI. The quality of Antigravity's output is a direct reflection of how well your workflow sets it up to succeed.
The developers who achieve sustained 5x or 10x speed improvements with AI tools all share a common trait: they treat workflow design as seriously as they treat code design. They have intentional session structures, explicit context management habits, purpose-built AGENTS.md configurations, and measurement systems that keep them improving over time.
This guide covers the advanced workflow strategies that professional developers use to keep that first-week feeling alive permanently. From context window theory to real-world AGENTS.md configurations, from measurement frameworks to parallel work patterns — everything you need to build a development workflow that compounds in speed over time.
Target reader: Developers and indie hackers who already use Antigravity regularly and are ready to push to the next level.
1. Managing the Context Window as a Strategic Asset
1-1. Understanding How Context Gets "Polluted"
Antigravity's context window is finite. When you keep many files open, run long conversations, and jump between unrelated topics, the AI loses track of what matters. This is context pollution — and it's the silent killer of AI development speed.
Signs your context is polluted:
- You find yourself repeating instructions you've already given
- The AI starts editing files it shouldn't be touching
- The quality of responses varies noticeably between questions
- Response times noticeably slow down
The core solution is simple: split sessions intentionally and frequently.
1-2. The Principle of One Session, One Goal
Effective session design follows a single rule: one session = one clearly scoped goal.
# Good: Sessions scoped to a single outcome
# Session 1: Implement user authentication API
# Session 2: Build frontend login UI
# Session 3: Add E2E tests for the auth flow
# Bad: Cramming everything into one session
# Session 1: Auth API + Login UI + Tests + Refactoring + Bug fixesMake it a habit to declare your session goal explicitly at the start:
This session is focused on implementing the user profile update API endpoint.
Relevant files: src/api/users.ts, src/types/user.ts, tests/api/users.test.ts
Let's work exclusively on this scope.
1-3. Strategic File Context Control
Consciously controlling which files Antigravity reads is one of the highest-leverage habits you can build. Every file you open is context budget spent.
Pinpoint referencing: When you only need part of a large file, extract just that section:
// Please only modify this specific function:
// processPayment() in src/services/payment.ts (lines 50-80)
async function processPayment(amount: number, currency: string): Promise<PaymentResult> {
// ... current implementation ...
}Structure-first, details-later: When adding new functionality, show the existing architecture without all the implementation details:
Current file structure (details omitted for brevity):
- getUserById(): Fetch user by ID
- updateUser(): Update user data
- deleteUser(): Soft-delete user
→ Please add createUserSession() following the same patterns
1-4. The "Context Handoff" Protocol Between Sessions
One of the highest-value habits you can build is a consistent session handoff format. When you close a session and prepare to start a new one on the same feature, write a compact handoff document before you stop:
## Session Handoff — [Feature Name] — [Date]
**What was accomplished:**
- Implemented UserProfile API endpoint with CRUD operations
- Added zod validation schemas for request/response
- Wrote unit tests for happy paths
**What's next (exact first task for next session):**
- Add error handling for 404 (user not found) case in getUserById()
- Then add rate limiting middleware
**Key decisions made:**
- Chose Server Actions over API routes for data mutations (Cloudflare Workers reason)
- Used optimistic updates pattern in the UI layer
**Gotchas to remember:**
- The user ID is a UUID, not a numeric ID — don't confuse with orderUserId
- Supabase RLS policies require auth.uid() check on every table queryPaste this handoff at the start of the next session and the AI will orient itself in seconds. This alone eliminates 80% of "wait, where were we?" friction.
2. Task Decomposition: Turning Elephants Into Bites
2-1. The Elephant Strategy
"How do you eat an elephant? One bite at a time." This applies directly to AI-assisted development. Telling Antigravity "build me an e-commerce platform" is the fastest path to wasted effort.
Effective decomposition follows a three-level hierarchy:
Level 1: Epics
Epic: Order management system
Level 2: Stories
Story 1: Display order list
Story 2: Show order details
Story 3: Update order status
Story 4: Handle order cancellation
Story 5: Send notification emails
Level 3: Tasks (the unit you give to Antigravity)
Task 1-1: Create OrderList component skeleton
Task 1-2: Implement API call logic
Task 1-3: Handle loading and error states
Task 1-4: Add pagination
Task 1-5: Write unit tests
2-2. Defining Acceptance Criteria Upfront
Stating acceptance criteria for each task dramatically improves output quality on the first try, eliminating the revision loop.
Task: Implement the OrderList component
Acceptance criteria:
✅ Type-safe TypeScript implementation
✅ Errors caught by error boundary component
✅ Skeleton UI displays during loading
✅ Shows "No orders found" message when empty
✅ 80%+ test coverage
✅ Storybook story included
2-3. Using Planning Mode for Automatic Task Decomposition
Before large implementations, let Antigravity do the breakdown work for you:
[Run in Planning Mode]
Project: Multi-tenant SaaS authentication system
Tech stack: Next.js 15 + Supabase + TypeScript
Please create a plan covering:
1. A full list of components and modules to implement
2. Dependencies (what must be built first)
3. Rough effort estimates for each task
4. High-risk areas and proposed alternatives
Review the plan it generates, refine it, then move to implementation. This two-phase approach — plan then build — is what separates senior AI developers from beginners.
2-4. The "One Change at a Time" Rule
A subtler but important principle: even when you have multiple things to fix in a session, address them sequentially — not simultaneously. This sounds obvious, but under deadline pressure it's easy to bundle requests:
# Tempting but problematic
"Fix the login bug, update the profile page styles, and add the missing
validation for the email field."
# Better approach
"Let's fix the login bug first. [After fix] Great, now let's move to
the profile page styles. [After fix] Now let's add the email validation."
Why does this matter? When multiple changes are bundled, you lose the ability to pinpoint which change caused any new issues. Each change should be a discrete, reversible unit. This is the software equivalent of the scientific method: change one variable, observe results, iterate.
3. Advanced AGENTS.md Configuration — Teaching the AI Your House Rules
3-1. AGENTS.md as an Onboarding Document
AGENTS.md works best when you think of it as "an onboarding doc so thorough that a new team member could contribute on day one without asking questions." Most developers only scratch the surface of what this file can do.
An effective AGENTS.md structure:
# Project Overview
[1-2 sentences describing what this is]
# Tech Stack (with rationale)
- Next.js 15 App Router: Required for Cloudflare Workers compatibility
- Supabase: Needed for real-time features; PostgreSQL basis is non-negotiable
- Stripe: Payment processing (webhook confirmed working on Edge Runtime)
# Architectural Constraints (non-negotiable rules)
- Never use the fs module in Server Components (Cloudflare Workers incompatible)
- Client components must use NEXT_PUBLIC_ prefix for environment variables
- All data fetching must go through Server Actions (no direct API route calls from client)
# Naming Conventions
- Components: PascalCase (e.g., UserProfileCard)
- File names: kebab-case (e.g., user-profile-card.tsx)
- Types: PascalCase without Type/Interface suffix (e.g., User, Order)
# Testing Policy
- Unit tests: Vitest + Testing Library
- E2E tests: Playwright (CI only)
- Mock policy: Never mock the database; only mock external APIs
# Anti-patterns to Avoid
- useEffect for data fetching: Always use Server Components or SWR
- Type any: Always validate with zod schemas
- Raw console.log: Use logger.ts for all logging3-2. Teaching Domain Knowledge
Technical constraints alone aren't enough. Business logic belongs in AGENTS.md too.
# Business Rules (Critical)
## Pricing
- All prices stored in smallest currency unit (¥100 = 10000 yen_cents)
- Consumption tax: 10% (8% reduced rate applies only to qualifying food items)
- Discounts applied to pre-tax price, then tax calculated
## User Permissions
- ROLE_ADMIN: All operations across all organizations
- ROLE_MANAGER: All operations within their organization
- ROLE_MEMBER: Read access + update own data only
## Order Status Transitions
pending → confirmed → shipped → delivered → completed
↓
cancelled (only valid from pending/confirmed)
refunded (only valid from delivered/completed)3-3. Keeping AGENTS.md Alive with a Session-End Ritual
AGENTS.md should evolve continuously. Build this into your workflow:
[End of every session]
Based on what we implemented today, what insights should we add to AGENTS.md
to improve future sessions?
This single habit compounds dramatically — your AGENTS.md becomes richer every day, and the AI's output quality rises with it.
3-4. AGENTS.md Anti-Patterns to Avoid
Just as important as what to include is what to leave out. Bloated AGENTS.md files that try to document everything create their own problems.
Don't include:
- Information already captured in code comments or JSDoc
- Obvious language/framework conventions (e.g., "TypeScript files use .ts extension")
- Long lists of acceptable library names without explaining the "why"
- Outdated constraints that no longer apply to the project
Do include:
- Decisions that surprised people when they first encountered them
- Non-obvious gotchas specific to your deployment environment
- Context that explains "why not" (why you chose A over B)
- Recurring mistakes that appear despite competent developers being aware
The test: if a senior developer who knows TypeScript and Next.js would already know it, skip it. Only document what's unique to your project's situation.
3-5. Project-Specific Custom Commands
Beyond AGENTS.md, building a library of custom prompt templates for recurring tasks can dramatically reduce the cognitive overhead of each session. Keep these in a /.antigravity/prompts/ directory:
/.antigravity/prompts/
├── new-api-endpoint.md # Template for adding new API endpoints
├── add-component.md # Template for new React components
├── debug-session.md # Template for structured debugging
└── refactor-module.md # Template for module-level refactoring
Example new-api-endpoint.md:
## New API Endpoint Request
**Endpoint**: [METHOD] /api/[path]
**Purpose**: [One sentence description]
**Authentication required**: [Yes/No] [Role: ADMIN/MANAGER/MEMBER]
**Request body**:
[Type definition or JSON example]
**Success response** (200):
[Type definition or JSON example]
**Error cases**:
- 400: [Validation failure conditions]
- 404: [Not found conditions]
- 403: [Forbidden conditions]
**Side effects** (emails, webhooks, cache invalidation):
[List any]
**Files to create/modify**:
- src/app/api/[path]/route.ts
- src/lib/[service].ts (if new service logic)
- tests/api/[path].test.ts
Follow the patterns in src/app/api/users/route.ts as reference.Copy, fill in, paste. Consistent structure, consistent output, every time.
4. Planning Mode and Fast Mode: A Hybrid Strategy
4-1. Decision Framework for Mode Selection
Receive a task
↓
Is the scope clearly defined?
├─ NO → Start with Planning Mode
└─ YES → Does it touch 3+ files?
├─ YES → Planning Mode to verify, then implement
└─ NO → Fast Mode directly
Use Planning Mode when:
- Implementing new features with ambiguous scope
- Refactoring (wide impact across the codebase)
- Debugging an issue where the root cause is unknown
- Making architectural changes
Use Fast Mode when:
- Fixing a bug with an identified cause
- Small UI adjustments (1-2 components)
- Adding tests to existing implementations
- Updating documentation
4-2. Asking Better Planning Mode Questions
The quality of your Planning Mode prompt determines the quality of the plan you receive.
# Weak prompt
"Implement user authentication"
# Strong prompt
"Please design a user authentication system with these requirements:
- Email + password authentication
- Google OAuth via Supabase
- JWT tokens stored in httpOnly cookies
- Refresh token support
- Session expiry: 24 hours
- Multi-device session management
Current auth-related files:
- src/lib/supabase/client.ts (client-side)
- src/lib/supabase/server.ts (server-side)
- middleware.ts (route protection)
Please provide: the full list of files that need changes, what changes each requires,
and a recommended implementation sequence with reasoning."
4-3. Recognizing When to Switch Modes Mid-Session
Learn to recognize the signals that tell you to shift into Planning Mode while implementing:
- "This change might break something else..." (mental uncertainty spike)
- You've fixed the same bug three times already
- You're over 5 minutes into debugging without progress
[Mid-session mode switch]
Let's pause implementation and diagnose the root cause properly.
Current situation: [error message or symptom]
What I've tried: [attempt 1], [attempt 2]
Please list possible root causes in priority order, with specific investigation
steps for each.
5. Parallel Processing and Multi-Window Patterns
5-1. Leveraging Antigravity's Multi-Agent Windows
Antigravity supports running multiple editor windows simultaneously. Used strategically, this enables true parallel development.
Frontend / Backend / Tests in parallel:
Window 1: API endpoint implementation (backend)
Window 2: UI component implementation (frontend)
Window 3: Test case design (testing)
The golden rule for parallel work: agree on interfaces (type definitions) before splitting. Starting parallel implementation before types are finalized causes expensive merge conflicts.
// Align on the interface first (types/order.ts)
export interface Order {
id: string;
userId: string;
items: OrderItem[];
totalAmount: number; // yen_cents unit
status: OrderStatus;
createdAt: Date;
updatedAt: Date;
}
export type OrderStatus =
| 'pending'
| 'confirmed'
| 'shipped'
| 'delivered'
| 'completed'
| 'cancelled'
| 'refunded';
// ↑ Commit this to all windows before parallel work begins5-2. Designing Parallel Work to Minimize Conflicts
The most common parallel work failure is two windows editing the same file. Prevent this with a clear territorial split:
Parallel work territory mapping:
- Window A: src/app/ (pages, layouts, routes)
- Window B: src/components/ (reusable components)
- Window C: src/lib/ (utilities, API clients)
- Window D: tests/ (test files)
This division keeps file-level conflicts near zero.
5-3. Merging Parallel Work Strategically
# One branch per window
git checkout -b feature/order-api # Window 1
git checkout -b feature/order-ui # Window 2
git checkout -b feature/order-tests # Window 3
# Merge in dependency order:
# 1. Merge API branch first (no dependencies)
# 2. Merge UI branch (depends on API)
# 3. Merge tests branch (depends on both)6. Measuring Development Speed with Metrics
6-1. Three Metrics Worth Tracking
Metric 1: Task Completion Rate
# Simple daily worklog structure
{
"date": "2026-04-04",
"planned_tasks": 8,
"completed_tasks": 6,
"rework_tasks": 1,
"completion_rate": 0.75,
"notes": "Auth session bug delayed 2 tasks"
}Metric 2: Context Reset Frequency
Track how many times in a day you needed to "start over" because the session lost track. High frequency signals a context management problem.
Metric 3: First-Pass Acceptance Rate
What percentage of Antigravity's outputs pass your review without needing revision? Low rates indicate task definition problems, not AI problems.
6-2. Building a Personal Baseline
Before you can improve, you need to know where you stand. Spend one week logging these three metrics without changing anything about your workflow. This gives you a baseline — the starting point against which future improvements are measured.
Many developers find that just the act of measurement improves performance. When you know you're tracking context resets, you naturally become more deliberate about session scoping. When you're tracking first-pass acceptance, you naturally write better acceptance criteria. Measurement and improvement are intertwined.
6-3. Weekly Review Template
## Weekly AI Workflow Review ([date])
### Quantitative
- Tasks completed: XX / XX (planned)
- Context resets: X times
- First-pass failures: X%
### What worked best this week
[Specific technique and result]
### Biggest time sink and its cause
[Root cause + next week's fix]
### AGENTS.md updates made
[New knowledge added this week]7. Common Slowdown Patterns and Their Solutions
7-1. Breaking the "Vague Instruction Loop"
Symptom: Every correction produces slightly wrong output, causing endless back-and-forth.
Root cause: Instructions are ambiguous — the AI is guessing what you want.
Fix: Specify exact Before/After:
# Weak instruction
"Make the button look better"
# Strong instruction
"Update the button styles as follows:
Current: bg-blue-500 text-white px-4 py-2 rounded
Target: bg-gradient-to-r from-blue-600 to-purple-600 text-white
px-6 py-3 rounded-xl shadow-lg hover:shadow-xl
transition-all duration-200 hover:scale-105
font-semibold tracking-wide
Apply this to both LoginButton.tsx and RegisterButton.tsx."
7-2. Breaking the "Regression Loop"
Symptom: Fixing A breaks B. Fixing B breaks A. Repeat indefinitely.
Root cause: No tests; side effects detected only by human observation.
Fix: Test-first repair.
[When caught in a regression loop]
Current problem: [symptom]
Concern: I'm worried about regressions spreading further.
Proposed approach:
1. First, write tests that lock down the current behavior
2. Then propose the smallest change that passes all tests
3. Confirm all tests pass after the change
7-3. The "Three-Strike Rule" for Stuck Situations
When you're stuck on the same problem for three consecutive exchanges without meaningful progress, that's a signal — not to try harder, but to change approach.
Strike 1: Clarify the problem more precisely. Include exact error messages, reproduction steps, and what you've already ruled out.
Strike 2: Simplify the problem. Create a minimal reproduction case. Strip away everything except the core issue.
Strike 3: Switch to diagnosis mode. Stop trying to fix and start trying to understand:
[Strike 3 prompt]
Let's stop trying to fix this and focus on understanding it.
Please help me map out:
1. What is the exact sequence of events that leads to this bug?
2. What assumptions am I making that might be wrong?
3. What would I need to verify to confirm or rule out each possible cause?
Most stuck situations resolve at Strike 1 or 2. But having the discipline to switch strategy rather than push harder is the difference between a 10-minute fix and a 2-hour spiral.
7-4. Diagnosing and Recovering from Context Overflow
Symptom: After a long session, response quality degrades noticeably.
Diagnostic prompt:
Based on our conversation, summarize in 3 bullet points what you understand
I'm trying to accomplish in this session.
If the answer doesn't match your actual goal, context overflow has occurred.
Recovery: Reset the session and start with a compact summary:
[New session — continuation]
Context summary from last session:
Goal: [one sentence]
Completed: [2-3 bullet points]
Next task: [one specific task]
Watch out for: [any gotchas, if applicable]
8. Practical: Running Large-Scale Refactors
8-1. The Phased Refactoring Strategy
Attempting to refactor everything at once is the highest-risk approach. Phase it instead:
Phase 1: Current state analysis (Planning Mode)
[Planning Mode]
Analyze the directory structure below and produce a refactoring priority map.
Evaluation criteria:
- Change frequency (inferred from git history)
- Dependency depth (how widely referenced)
- Test coverage
- Severity of technical debt
src/
├── components/ (28 files)
├── hooks/ (15 files)
├── lib/ (12 files)
└── pages/ (20 files)
Phase 2: Interface-first design — the contract before the code
// Current (problematic) type definitions
interface UserData {
id: any;
info: any;
settings: any;
}
// Target type definitions post-refactor
interface User {
id: UserId; // Branded type
profile: UserProfile;
preferences: UserPreferences;
subscription: SubscriptionPlan;
}
// Implement only this type definition first — migrate everything else incrementallyPhase 3: Strangler fig migration
[Fast Mode]
Migrating UserData → User type, one file at a time.
Today's target: src/components/UserProfileCard.tsx only.
Requirements:
- Replace all UserData usage with the User type
- Centralize required data transformations in src/lib/adapters/userAdapter.ts
- All existing tests must continue to pass
8-2. Tracking Refactoring Progress
Large refactors can take days or weeks. Without a clear progress tracker, it's easy to lose momentum or forget which files have been migrated.
A simple approach: maintain a REFACTOR_PROGRESS.md in the root of your project during the refactor period:
# UserData → User Type Migration Progress
## Status: In Progress
## Started: 2026-04-01
## Target completion: 2026-04-15
## Migrated (✅)
- src/components/UserProfileCard.tsx
- src/components/UserSettingsPanel.tsx
- src/hooks/useUser.ts
## In Progress (🔄)
- src/pages/profile.tsx
## Remaining (⏳)
- src/components/AdminUserList.tsx
- src/components/UserSearchModal.tsx
- src/lib/api/users.ts
- tests/components/UserProfileCard.test.tsx (update mocks)
## Notes
- userAdapter.ts is the central conversion layer — update it first in each file pair
- Some components use the id field as string elsewhere — careful with type narrowingReference this document in your session opener: "Check REFACTOR_PROGRESS.md and continue with the next file in the Remaining list."
Summary
To complement the techniques in this guide, check out our Antigravity Workspace Optimization Guide for environment-level improvements, and Planning Mode vs Fast Mode: A Deep Comparison for a deeper look at mode selection. For large-scale project context strategies, Antigravity Project Context Mastery is an excellent companion read.
This guide covered six core levers for compounding your development speed with Antigravity.
Context management means scoping sessions to single goals and controlling which files the AI sees at any given time. Task decomposition means breaking work into acceptance-criteria-backed units small enough to succeed on the first try. AGENTS.md configuration means teaching the AI your domain knowledge and architectural rules so it never has to guess. Planning/Fast Mode hybrid strategy means reading the situation and switching modes based on scope ambiguity, not habit. Parallel processing means agreeing on interfaces before splitting into concurrent streams. And measurement means making improvements data-driven, not gut-feel.
The underlying truth is this: the developers who get exponentially faster with AI aren't the ones using the most features. They're the ones who've designed their workflow to amplify what AI does well and minimize what it does poorly.