Mastering Context Control in Antigravity Editor — Maximize AI Accuracy with @Mentions, Knowledge Items, and File References
Learn advanced techniques for strategically controlling Antigravity Editor's context window to dramatically improve AI code completions and agent accuracy. Covers @mentions, Knowledge Items, file references, and optimization patterns for large codebases.
The quality of code that Antigravity's AI agents produce depends heavily on the quality of context you provide. The same prompt can yield drastically different results depending on whether the right information is included in the context window.
Many developers experience a significant productivity boost when they first start using Antigravity. But as projects grow larger, they sometimes feel that "the AI's responses are becoming less accurate." In most cases, this happens because context window management isn't keeping pace with project complexity.
This guide provides a systematic deep dive into Antigravity Editor's context control mechanisms and practical techniques for maximizing AI accuracy. It's designed for intermediate to advanced developers who use Antigravity daily and want to push their productivity even further.
Understanding How Context Windows Work
Tokens and Context
The LLMs powering Antigravity (such as Gemini) have a maximum number of tokens they can process at once. Gemini 2.5 Pro supports up to 1 million tokens in its context window, but not all tokens carry equal weight.
LLM attention mechanisms exhibit what researchers call the "Lost in the Middle" effect. Information placed at the beginning and end of the context receives stronger attention, while information in the middle is more likely to be overlooked. This means that blindly stuffing files into the context can actually reduce accuracy.
// ❌ Bad: Including every file regardless of relevance// → Wastes tokens, important info gets buried in the middle// ✅ Good: Strategically referencing only what's needed// @file:src/lib/auth.ts — Current auth implementation// @file:src/types/user.ts — User type definitions// @file:tests/auth.test.ts — Existing test patterns// Using these 3 files as reference, add OAuth 2.0 refresh token handling.
Antigravity's Context Hierarchy
The context that Antigravity feeds to the AI is structured in layers.
Level 1 (Always Active): AGENTS.md, Knowledge Items, and files defined as always-loaded in user settings.
Level 2 (Session Context): Currently open files, chat history, and recently edited files.
Level 3 (Explicit References): Files, folders, symbols, and URLs specified via @mentions.
Level 4 (Auto-collected): Information the agent autonomously gathers from the file tree and symbol tables.
Understanding this hierarchy clarifies which information belongs at which level for optimal results.
✦
Thank you for reading this far.
Continue Reading
What follows includes implementation code, benchmarks, and practical content we hope you'll find useful. This site runs without ads — server and development costs are supported entirely by members like you. If it's been helpful, we'd be truly grateful for your support.
WHAT YOU'LL LEARN
✦Understand how context windows work and develop strategies that dramatically improve AI accuracy
In Antigravity's chat panel, you can reference various elements using the @ prefix.
@file:src/components/Button.tsx — Reference a specific file
@folder:src/lib/ — Reference an entire folder
@symbol:handleSubmit — Reference a specific function/class
@url:https://docs.example.com — Reference a web page
@git:HEAD~3 — Reference git commit diffs
@terminal — Reference terminal output
Optimized File Reference Patterns
In large projects, the order and combination of file references significantly impacts AI output quality. Here are proven patterns to follow.
Pattern 1: Interface → Implementation → Tests
Start with type definitions and interfaces, then reference the implementation, and finally the tests. This helps the AI understand the flow from specification to implementation to verification.
@file:src/types/payment.ts
@file:src/services/payment.service.ts
@file:tests/payment.service.test.ts
Add Stripe Webhook event verification logic to the payment service above.
Follow existing error handling patterns and add corresponding tests.
Pattern 2: Configuration → Middleware → Routes
For backend changes, starting from configuration files helps the AI correctly understand architectural constraints.
@file:wrangler.toml
@file:src/middleware.ts
@file:src/app/api/checkout/route.ts
Add rate limiting to the checkout endpoint, keeping Cloudflare Workers constraints in mind.
Pattern 3: Reference Similar Implementations
When adding new features, referencing existing similar features produces code that aligns with your project's conventions.
@file:src/app/api/auth/route.ts — Existing auth API (reference pattern)
@file:src/app/api/webhook/route.ts — Existing webhook API (reference pattern)
Following the patterns in the two API routes above, create a new /api/notifications endpoint.
Match the error handling, logging, and type definition patterns from the existing code.
Folder Reference Guidelines
@folder: is convenient but can consume large numbers of tokens with big directories. Follow these guidelines.
Folders with 10 or fewer files: @folder: works fine
Folders with 10–30 files: Reference individual files with @file:
Folders with 30+ files: Reference only the folder structure and let the AI select specific files
// Recommended approach for large folders
Search the src/components/ folder for form-related components and create
a new form following the same pattern as @file:src/components/FormField.tsx.
Knowledge Items for Persistent Context
The Role of Knowledge Items
Knowledge Items store information you want the AI to remember across sessions. While the Knowledge Items Complete Guide covers the basics, here we focus on advanced usage within the editor.
Information that belongs in Knowledge Items includes:
Domain knowledge: Business logic constraints, industry terminology definitions.
Past decisions: Records of "why we chose this design," technical decision logs.
Frequently used prompt templates: Standard code generation instructions.
Knowledge Items Design Patterns
Effective Knowledge Items follow a structured format.
# Project: E-Commerce Platform## Architecture Constraints- Runtime: Cloudflare Workers (some Node.js APIs unavailable)- DB: Cloudflare D1 (SQLite-compatible, limited transactions)- KV: Cloudflare KV (eventual consistency; use D1 when strong consistency needed)## Coding Conventions- State management: Zustand (no Redux)- Styling: Tailwind CSS only (no CSS Modules)- Testing: Vitest + Testing Library (no Jest)- Import order: external → internal → types → styles## API Design Conventions- Response format: { success: boolean, data?: T, error?: string }- Error codes: Follow HTTP status code standards- Auth: Bearer token (JWT) in Authorization header
With these Knowledge Items in place, you no longer need to tell the AI "we're using Cloudflare Workers" in every single prompt.
Choosing Between Knowledge Items and File Context
Use this decision framework.
Low change frequency + needed in all sessions → Save in Knowledge Items
High change frequency + needed for specific tasks → Reference with @file: as needed
Low change frequency + needed for specific tasks → Document in AGENTS.md
// Good candidate for Knowledge Items// → Project-wide conventions (rarely change)const CODING_STANDARDS = { formatter: "Biome", testRunner: "Vitest", stateManagement: "Zustand",};// Good candidate for @file: reference// → Current schema definitions (may change frequently)// @file:prisma/schema.prisma
Structuring Context with AGENTS.md
AGENTS.md Placement Strategy
AGENTS.md files can be placed not just at the repository root but also in subdirectories. Antigravity traverses the file tree and automatically includes relevant AGENTS.md files in the context.
This hierarchy ensures that the AI references the right rules based on which directory you're working in. When editing files under src/api/, the root AGENTS.md plus src/AGENTS.md and src/api/AGENTS.md are automatically included.
AGENTS.md Scope and Inheritance
Understanding how AGENTS.md inheritance works is crucial for effective context architecture. When the AI reads AGENTS.md files, it follows a bottom-up resolution strategy: rules in more specific (deeper) AGENTS.md files take precedence over rules in parent directories when there's a conflict.
For example, if the root AGENTS.md says "use camelCase for all variable names" but src/api/AGENTS.md says "use snake_case for database column mappings," the AI will correctly apply snake_case when working in the API layer while using camelCase everywhere else.
This inheritance model is particularly powerful for teams that work across different technology stacks within the same monorepo. The frontend team might have completely different conventions from the backend team, and subdirectory-level AGENTS.md files let each team maintain their own standards without conflicts.
One important consideration is keeping AGENTS.md files concise and focused. A common mistake is duplicating rules across multiple AGENTS.md files. Instead, place shared rules at the root level and only add overrides or additions in subdirectory files. This reduces maintenance overhead and prevents contradictions between different levels.
# Root AGENTS.md — shared rules
- TypeScript strict mode enabled
- All exports must have JSDoc comments
- Prefer async/await over .then() chains
# src/api/AGENTS.md — API-specific additions
- All routes must validate input with Zod schemas
- Use snake_case for database column mappings
- Response times must be logged for monitoring
Best Practices for Writing AGENTS.md
Effective AGENTS.md files anticipate situations where the AI might hesitate.
# API Route Design Guide## Required Patterns- Use try-catch in all API routes- Error responses must follow { success: false, error: string } format- Access env variables via getCloudflareContext() (never use process.env)## Prohibited Patterns- Importing fs module (not available in Cloudflare Workers)- Storing state in global variables (Workers are stateless)- Leaving console.log in production code (debug only via wrangler tail)## Decision Criteria- KV vs D1: High read frequency + eventual consistency OK → KV; consistency required → D1- Middleware vs in-route: Shared across 3+ routes → extract to middleware
While individual @mentions are powerful, the real productivity gains come from combining them strategically for complex, multi-step tasks. Here's how experienced developers structure their context for demanding scenarios.
Database Migration with Full Context:
When performing database schema changes that ripple through the entire stack, you need the AI to understand the complete picture. Start with the schema, then layer in the affected services and their tests.
@file:prisma/schema.prisma
@file:src/services/user.service.ts
@file:src/services/auth.service.ts
@file:src/app/api/users/route.ts
@file:tests/user.service.test.ts
I'm adding a `preferences` JSON field to the User model.
Update the schema, then propagate changes through the service layer and API routes.
Generate a migration file and update all affected tests.
Cross-cutting Concern Implementation:
When implementing features that touch many parts of the codebase (logging, error tracking, analytics), reference the entry points rather than every file.
@file:src/middleware.ts
@file:src/lib/logger.ts
@symbol:handleError
@git:HEAD~5
Looking at the last 5 commits for context on recent changes,
add structured logging to all API routes using the pattern in logger.ts.
The middleware should capture request/response metadata automatically.
Using @git for Historical Context
The @git: mention is one of the most underutilized features. It lets the AI understand not just the current state of the code but its recent evolution. This is particularly valuable when you need to understand why code was written a certain way or when debugging regressions.
// Understanding recent changes
@git:HEAD~10
What significant architectural changes were made in the last 10 commits?
Are there any patterns I should be aware of before modifying the auth module?
// Debugging a regression
@git:abc1234..HEAD
@file:src/services/payment.service.ts
The payment processing started failing after commit abc1234.
Compare the changes and identify what broke.
The @symbol Deep Dive
The @symbol: mention references specific functions, classes, interfaces, or type definitions by name. This is more precise than file-level references and helps the AI focus on exactly the code constructs that matter.
// Reference a specific function and its call graph
@symbol:processPayment
@symbol:validateWebhookSignature
@symbol:PaymentResult
Refactor processPayment to handle partial refunds.
The function should still satisfy the PaymentResult type
and maintain compatibility with validateWebhookSignature.
The key advantage of @symbol: over @file: is that it automatically includes the symbol's dependencies and type information without loading the entire file. For files with hundreds of lines, this can save significant context budget.
Context Optimization for Large Codebases
The Context Budget Approach
For large projects, think of your context window as a "budget" to be allocated strategically.
With this allocation in mind, the upper limit for @file: references becomes clear. Generally, 5 to 8 files per prompt is the sweet spot for optimal results.
Context Pruning
Long chat sessions accumulate history that compresses available context. Here's how to manage this.
Start a new chat session: When switching tasks, start a fresh chat to reset the context. In Antigravity, press Cmd+L (Mac) or Ctrl+L (Windows/Linux) to begin a new chat.
Insert summary prompts: During long sessions, ask the AI to "summarize all changes so far in 3 lines," then use that summary as the starting point for a new session.
Remove stale file references: As your task progresses, actively remove file references that are no longer needed.
// Mid-session context reset example
Summary of changes so far:
1. Added Webhook verification logic to PaymentService
2. Added 5 corresponding tests
3. Configured new KV namespace in wrangler.toml
Moving on to the next task.
@file:src/services/notification.service.ts
@file:src/types/notification.ts
Starting notification service implementation.
Context Management in Monorepos
In monorepos, it's critical to make package boundaries explicit to the AI.
# AGENTS.md (monorepo root)## Package Structure- packages/web — Next.js frontend- packages/api — Hono backend- packages/shared — Shared types & utilities- packages/db — Drizzle ORM schemas## Dependency Rules- web → shared, api (direct imports OK)- api → shared, db (direct imports OK)- shared → external deps only (no cross-package deps)- db → external deps only## Change Impact- Changes to shared require testing both web and api- Changes to db require api tests and migration verification
Measuring Context Quality with Response Accuracy
One practical approach to optimizing your context is to track how often the AI's first response is accurate enough to use without modification. Experienced developers aim for a "first-response accuracy" rate of 80% or higher. If you find yourself constantly correcting the AI or re-prompting, your context setup likely needs adjustment.
Here's a simple mental framework for diagnosing context issues based on the type of errors you observe.
Syntax or convention errors (wrong import style, incorrect naming): Your AGENTS.md or Knowledge Items are missing key conventions. Add the specific rules the AI keeps violating.
Architectural misunderstandings (wrong patterns, ignored constraints): Critical context about your stack or deployment target is absent. Add it to Knowledge Items for persistent availability.
Stale or outdated references (referencing deleted files, old APIs): Your chat session is too long, or cached Knowledge Items need updating. Start a fresh session and review your stored context.
Partially correct but incomplete: The AI has the right idea but misses edge cases. You likely need to reference additional files that cover those edge cases, such as test files or error handling utilities.
The .antigravityignore File
Just as .gitignore tells Git which files to exclude from version control, .antigravityignore tells Antigravity which files to exclude from automatic context collection. This is essential for large projects where the AI might waste tokens on irrelevant files.
By carefully tuning this file, you ensure that Antigravity's automatic context collection focuses on source code and configuration files that actually matter for code generation quality.
Practical Workflows: Context Control in Action
Context Design Templates for Daily Development
Here are optimized context design templates for common development tasks.
Bug Fix Context Design:
1. Error log / stack trace (@terminal)
2. File where the error occurs (@file:)
3. Related type definitions (@file:)
4. Existing tests (@file:)
5. "Identify the root cause of this error and fix it. Verify existing tests
still pass and add a regression test."
New Feature Context Design:
1. Similar feature implementation (@file:) — pattern reference
2. Related type definitions (@file:)
3. Routing configuration (@file:)
4. "Following the pattern in @file:src/app/api/auth/route.ts,
create a new /api/billing endpoint."
Refactoring Context Design:
1. Refactoring targets (@file: × multiple)
2. AGENTS.md coding conventions
3. Test files (@file:)
4. "Split these files according to the Single Responsibility Principle.
Confirm all tests pass before marking this complete."
Context Quality Self-Diagnosis
If AI responses feel off-target, run through this checklist.
Check 1: Is the AI working from incorrect assumptions?
→ Verify that the right config files and type definitions are in the context.
Check 2: Is the AI referencing stale information?
→ Check whether chat history has grown too long. Try starting a new session.
Check 3: Is the AI missing related files?
→ Add explicit @file: references for missing dependencies.
Check 4: Is there information overload?
→ Replace broad @folder: references with targeted @file: references.
// Context quality check prompt technique// Verify what the AI currently understands// Ask first:`List all files currently in your context and brieflydescribe each file's role.`// Review the response — add @file: for anything missing,// remove references for anything irrelevant
Team Context Strategies
When working on a team, context control becomes even more important because different team members have different mental models of the codebase. Here are strategies for maintaining consistent AI output quality across a team.
Shared AGENTS.md as the single source of truth: The team should collectively maintain AGENTS.md files that encode architectural decisions, coding standards, and common patterns. When a new convention is adopted, it should be added to AGENTS.md immediately — not just communicated in Slack.
Context setup documentation: For complex features that span multiple sessions, create a brief document listing the key files and context setup needed to work on that feature. This helps team members (and future-you) quickly establish productive AI sessions.
# Feature: Payment Processing# Context setup for AI sessions## Essential files to reference- src/services/payment.service.ts (core logic)- src/types/payment.ts (type definitions)- src/app/api/checkout/route.ts (API endpoint)- src/app/api/webhook/route.ts (Stripe webhook handler)- wrangler.toml (Worker config, KV bindings)## Key constraints to mention- Cloudflare Workers runtime (no Node.js fs, limited crypto)- Stripe API v2024-11-20- All amounts in cents (integer, never float)
Code review with context awareness: When reviewing AI-generated code, check whether the context was appropriate. If a PR contains code that doesn't follow project conventions, the root cause is often missing context rather than a bad prompt.
Building a Personal Context Playbook
Over time, you'll develop a personal library of context setups that work well for your specific projects and workflows. Consider maintaining a simple document — a context playbook — that records your most effective configurations.
Your playbook might include entries like "when adding a new API route, always reference middleware.ts and the most similar existing route" or "for CSS-heavy tasks, include the design tokens file and one example component." These accumulated insights compound over time and make you increasingly efficient at directing AI output.
The key is to treat context control not as an overhead cost but as an investment in output quality. The few seconds spent curating your @mentions and verifying your Knowledge Items will save minutes of back-and-forth corrections and re-prompting.
Summary
Context control in Antigravity Editor is one of the most important skills for achieving high-quality AI-assisted coding. By applying the techniques in this guide, you can maintain strong AI response quality even in large-scale projects.
The key takeaways are that context windows have a hierarchical structure, and placing the right information at each level is fundamental to accuracy. @mentions should be ordered and combined strategically. Knowledge Items and AGENTS.md serve different purposes based on change frequency and sharing scope. For large codebases, adopting a context budget mindset and regularly checking for information overload or gaps will keep your AI collaboration productive.
As a practical next step, try auditing your current context setup on the project you're actively working on. Review your AGENTS.md files, check whether your Knowledge Items are up to date, and experiment with the @mention patterns described in this guide. Pay attention to how these changes affect the AI's first-response accuracy, and iterate on your context configuration as you discover what works best for your specific codebase and workflow.
Share
Thank You for Reading
Antigravity Lab is ad-free, supported entirely by members like you. We publish practical guides daily with implementation code, benchmarks, and production-ready patterns. If you've found it useful, we'd love to have you on board.