Setup and context: Why Context Engineering Is an Advanced Skill
If there's one skill that separates Antigravity power users from casual users, it's context engineering. Learning to write prompts is easy. Designing the environment in which AI operates — so that it consistently makes accurate, project-aware decisions across a codebase of tens of thousands of lines — is an entirely different discipline.
This guide goes well beyond the basics of "how to write AGENTS.md" or "how to add Knowledge Items." We'll explore production-grade techniques for maintaining AI accuracy at scale.
This guide is for:
- Developers who use Antigravity daily and have mastered the fundamentals
- Tech leads evaluating or rolling out Antigravity across a team or organization
- Engineers frustrated by AI accuracy degradation in large, complex codebases
- Anyone hitting Antigravity's context limits and looking for smarter architectural solutions
When context engineering is done right, Antigravity stops feeling like a new hire who needs everything explained from scratch. It starts feeling like a senior engineer who knows your project's entire history.
For foundational concepts, see Context Engineering Introduction: Growing AI into Your Personal Development Partner before diving into this guide.
Chapter 1: The Three-Layer Context Architecture
1-1. Why Three Layers?
Most developers write AGENTS.md as a flat list of rules and call it a day. That works at small scale, but breaks down quickly. Advanced context engineering organizes information into three distinct layers, each serving a different purpose.
Layer 1 — Project Intelligence Layer
The "DNA" of your project — information that rarely changes. This includes architectural philosophy, technology stack rationale, domain vocabulary definitions, and non-negotiable constraints with their reasons.
Layer 2 — Dynamic Context Layer
Information that shifts by sprint, feature, or module. Current sprint goals, active module dependencies, temporary workarounds, and in-progress flags belong here.
Layer 3 — Session Intelligence Layer
Context that's valid only for the current working session. Recent changes, conversation conclusions, error root causes discovered in the last hour — this layer is ephemeral but critical for in-session accuracy.
Designing with these three layers in mind lets you give AI the right information at the right granularity at the right time.
1-2. Layer 1: Advanced AGENTS.md Design Patterns
AGENTS.md shouldn't be a rule book — it should be a transmission of your project's reasoning style. Here's a structure that has proven effective in real production environments:
# Project Intelligence — [Project Name]
## Architecture Philosophy
This project uses Hexagonal Architecture (Ports & Adapters).
**Why**: To isolate business logic from infrastructure, maximizing testability and portability.
### Decision Priority Order
1. Follow existing patterns (prefer consistency over invention)
2. Never compromise TypeScript type safety (no `as unknown as` without explicit approval)
3. Always return errors as `Result<T, E>` types (exceptions only in UI layer)
## Domain Vocabulary
- **Listing**: A single property record. Never call it `Property` — Property refers to legal ownership.
- **Offer**: A buyer's purchase intent. Different from `Bid`, which is auction-only.
- **Escrow**: Third-party holding state. Always requires legal-approved workflow.
## What NOT to Do
- [ ] Business logic does not go in `src/infrastructure/`
- [ ] No `console.log` in production code — use `logger.info()` instead
- [ ] No hardcoded Stripe price IDs — always use `config/pricing.ts`
- [ ] No direct DB access from UI components
## Uncertainty Protocol
When uncertain about an implementation decision:
1. Check `src/docs/decisions/` for relevant ADRs
2. Follow the closest existing pattern in the codebase
3. If still unclear, ask before implementing — don't guessThe key insight here: rules without reasons are followed mechanically. Reasons are what allow AI to generalize correctly to novel situations.
1-3. Layer 2: Dynamic Context Injection Patterns
In large projects, the context of "what we're working on" changes constantly. Rewriting AGENTS.md every sprint is impractical. Instead, set up dynamic context injection:
# scripts/inject-context.sh
#!/bin/bash
# Injects current working context at session start
SPRINT_FILE=".antigravity/current-sprint.md"
MODULE_FILE=".antigravity/current-module.md"
if [ -f "$SPRINT_FILE" ]; then
echo "## 📍 Current Sprint Context"
cat "$SPRINT_FILE"
echo ""
fi
if [ -f "$MODULE_FILE" ]; then
echo "## 🔧 Active Module Context"
cat "$MODULE_FILE"
echo ""
fi
echo "## ⚠️ Active Workarounds"
cat ".antigravity/workarounds.md" 2>/dev/null || echo "(none currently active)"Run this script at the start of each session and paste the output as your first message. AI immediately understands what work is in progress without needing to explore the codebase blindly.
Chapter 2: Optimizing Knowledge Items at Scale
2-1. Three Principles for Knowledge Item Design
Simply adding files to Knowledge Items often yields disappointing results. Effective Knowledge Items design requires optimizing for information density and retrievability.
Principle 1: One topic per Knowledge Item
"A combined doc covering API specs, DB schema, and auth flow" is an anti-pattern. Split it into api-spec.md, db-schema.md, and auth-flow.md. Focused documents yield significantly better retrieval accuracy.
Principle 2: Include the "Why" in every Knowledge Item
# Authentication Flow — Why This Design
## Current Implementation
JWT + Refresh Token rotation pattern.
## Why not Session Cookies?
- SameSite constraints in Cloudflare Workers environments
- High session synchronization costs at CDN edge nodes
- This decision was made after Incident #143 in Nov 2025
## Planned Changes
Passkey support planned for Q3 2026 (see design-doc/passkey-migration.md)Principle 3: Regular garbage collection
Stale Knowledge Items actively harm AI accuracy by injecting false context. Schedule a quarterly review of all Knowledge Items. Mark deprecated content explicitly, or delete it.
2-2. Knowledge Items Priority Framework
For codebases over 100,000 lines, you can't add everything. Use this prioritization framework:
Highest priority (always include):
- System interface definitions (API contracts, event schemas)
- Core data models with broad ripple effects
- Business rules that are easy to misunderstand
- Context around areas that have caused critical bugs
Medium priority (add for key modules):
- Complex state management flow diagrams
- External service integration specifications
- Test strategy and boundary condition explanations
Low priority (typically skip):
- Self-explanatory utility functions
- Standard CRUD implementations
- Third-party library usage (link to official docs instead)
2-3. Context Compression Techniques
Antigravity's context window has a limit. In large projects, context compression becomes a critical skill:
# ❌ Verbose (wastes context window)
When a user adds an item to the cart, the system first checks the inventory database.
If inventory is available, the item is added to the cart table. If inventory is
unavailable, an error is returned. Premium members can add up to 10 items, while
standard members are limited to 5. During sale periods, limits may change...
# ✅ Compressed (same information, higher density)
Cart add logic:
- Inventory check → add to cart or StockError
- Quantity limits: Premium=10 / Standard=5 / Sale: see config/sale-limits.ts
- Implementation: `CartService.addItem()` in src/domain/cart/CartService.tsThe goal isn't to reduce information — it's to increase information density.
Chapter 3: Scope Control and Accuracy Optimization
3-1. Intentional Scope Control
Counterintuitively, giving AI access to too many files can reduce accuracy. When AI must consider hundreds of files, critical information gets diluted — what's called Context Overload.
Use scope control prompts to focus AI attention deliberately:
Please reference only these files for this task:
- src/features/checkout/CheckoutFlow.tsx
- src/domain/order/OrderService.ts
- src/api/payment/route.ts
Do not explore other files. If something is needed that isn't in these files,
reference only the interface/type definitions — do not dig into implementations.
This technique alone can dramatically improve output quality on targeted changes.
3-2. Task Decomposition for Higher Accuracy
Complex, multi-goal requests lead to lower-quality outputs. Advanced context engineering means deliberately decomposing tasks before presenting them to AI:
# ❌ Low accuracy request
"Refactor the entire payment flow, improve error handling, add tests,
and increase type safety"
# ✅ High accuracy (decomposed)
Phase 1 — Type audit:
"Review CheckoutService.ts only. List all locations where `any` type is used.
Do not make changes yet — just report."
Phase 2 — Refactoring:
"Convert the locations you identified to use Result<T, E> types.
Minimize impact on other files."
Phase 3 — Testing:
"Add unit tests for the functions you modified.
Handle edge cases according to the Uncertainty Protocol in AGENTS.md."
Each phase has a clear scope, a clear success criterion, and builds on verified output from the previous phase.
3-3. Building a Feedback Loop
Long-term accuracy improvement requires embedding a feedback loop into AGENTS.md itself:
## AI Interaction Patterns — What Works
### Effective Prompt Patterns
1. "Modify only X — leave everything else untouched"
→ Reduces unintended side effects significantly
2. "Before making changes, summarize what you plan to do"
→ Catches misunderstandings before they become commits
3. "Verify existing tests still pass before showing me the output"
→ Prevents regression bugs from slipping through
### Patterns to Avoid
- "Implement using best practices" (ambiguous judgment criteria)
- "Improve the performance" (no measurement baseline)
- "Clean this up generally" (undefined scope)Maintaining this document collaboratively as a team creates a living guide that progressively improves your AI interaction quality.
Chapter 4: Preventing Context Pollution in Team Development
4-1. What Is Context Pollution?
In team environments, context pollution is among the most dangerous failure modes for Antigravity adoption. It occurs when incorrect assumptions, temporary workarounds, or session-specific context from one developer's session contaminate the shared context design.
Symptoms include:
- Two developers implementing the same feature with completely different architectures
- AGENTS.md accumulating contradictory rules over time
- Temporary workarounds becoming permanent "rules"
4-2. A Team Context Consistency Framework
Maintaining context quality across a team requires a structured approach:
Weekly Context Review Agenda:
## Weekly Context Review Agenda
1. Review AGENTS.md changes from the past week (git diff main -- AGENTS.md)
2. Review Knowledge Items added during the sprint
3. Share "AI-suggested temporary workarounds" from this week
4. Classify: What should be formalized vs. deleted?
5. Pre-design context for upcoming sprint workContext Ownership Model:
AGENTS.md editing permissions:
- Layer 1 (Architecture Philosophy): Tech lead only
- Layer 2 (Dynamic Context): Module owners
- Layer 3 (Temporary Notes): All team members (reviewed in PR)
4-3. AGENTS.md Version Control Strategy
Beyond basic git tracking, mature teams apply more deliberate version management:
# .git/hooks/pre-commit
#!/bin/bash
if git diff --cached --name-only | grep -q "AGENTS-md"; then
echo "⚠️ AGENTS.md has changes"
echo "Before committing, confirm:"
echo " 1. Has this change been agreed upon by the team?"
echo " 2. Does it conflict with any existing rules?"
echo " 3. Did you include the reason (Why)?"
read -p "Type 'yes' to proceed: " confirm
if [ "$confirm" != "yes" ]; then
exit 1
fi
fiThis hook creates a small but meaningful friction point that prevents accidental or unreviewed context changes.
Chapter 5: Advanced Planning Mode Integration
Antigravity's Planning Mode reaches its full potential when combined with intentional context engineering. See Antigravity Planning Mode — AI-Driven Design Strategy for Large Projects for the full foundation. Here, we cover advanced integration patterns.
5-1. The Context Pre-Load Pattern
Before entering Planning Mode, deliberately load related context:
[Context Pre-Load Before Planning Mode]
I'm about to design [feature name]. Before switching to Planning Mode, please review:
1. The "Architecture Philosophy" section of AGENTS.md
2. src/domain/[relevant domain]/README.md
3. Past related decisions: docs/decisions/ADR-[number].md
With those in mind, enter Planning Mode.
Goal: prioritize designs that integrate naturally with the existing architecture.
5-2. Contextualizing Design Decisions
Transform Planning Mode outputs directly into context artifacts:
# ADR-042: Real-Time Search Implementation
## Decision
Server-Sent Events (SSE) over WebSocket
## Rationale (determined during Antigravity Planning Mode)
- WebSocket: Limited support in Cloudflare Workers environment
- SSE: Unidirectional streaming meets requirements at significantly lower infra cost
## Guidance for Antigravity
When referencing this file:
- All "real-time" search implementations must use SSE
- WebSocket proposals were evaluated and rejected — treat this as settledChapter 6: Implementation Patterns and Code Examples
6-1. Context Validation Script
Automate context quality checks with this validation script:
#!/usr/bin/env python3
"""
scripts/validate-context.py
Validates quality of AGENTS.md and Knowledge Items
"""
import re
import sys
from pathlib import Path
def validate_agents_md(filepath: Path) -> list[str]:
errors = []
content = filepath.read_text(encoding='utf-8')
required_sections = [
"## Architecture Philosophy",
"## What NOT to Do",
"## Uncertainty Protocol",
]
for section in required_sections:
if section not in content:
errors.append(f"Missing required section: {section}")
rules = re.findall(r'- \[ \] (.+)', content)
for rule in rules:
if len(rule) < 20:
errors.append(f"Rule may be missing context: '{rule}'")
old_dates = re.findall(r'202[34]-\d{2}', content)
if old_dates:
errors.append(f"Old date references found (consider updating): {old_dates}")
return errors
def validate_knowledge_items(directory: Path) -> list[str]:
errors = []
md_files = list(directory.glob("**/*.md"))
for filepath in md_files:
content = filepath.read_text(encoding='utf-8')
word_count = len(content.split())
if word_count > 2000:
errors.append(
f"{filepath.name}: {word_count} words — consider splitting"
)
if "## Why" not in content and word_count > 300:
errors.append(f"{filepath.name}: Missing 'Why' section")
return errors
if __name__ == "__main__":
errors = []
agents_path = Path("AGENTS-md")
if agents_path.exists():
errors.extend(validate_agents_md(agents_path))
knowledge_dir = Path(".antigravity/knowledge")
if knowledge_dir.exists():
errors.extend(validate_knowledge_items(knowledge_dir))
if errors:
print("❌ Context validation failed:")
for error in errors:
print(f" - {error}")
sys.exit(1)
else:
print("✅ Context validation passed")Sample output:
$ python3 scripts/validate-context.py
✅ Context validation passed
# or
❌ Context validation failed:
- Missing required section: ## Uncertainty Protocol
- auth-flow.md: 3247 words — consider splitting into smaller files
6-2. Context Quality Dashboard
Visualize context health across your team with this shell dashboard:
#!/bin/bash
# scripts/context-dashboard.sh
echo "=== Antigravity Context Quality Dashboard ==="
echo ""
echo "📋 AGENTS.md Stats:"
AGENTS_WORDS=$(wc -w < AGENTS.md)
AGENTS_RULES=$(grep -c "- \[ \]" AGENTS.md || echo 0)
echo " - Word count: $AGENTS_WORDS"
echo " - Defined rules: $AGENTS_RULES"
echo ""
echo "📚 Knowledge Items:"
TOTAL_FILES=$(find .antigravity/knowledge -name "*.md" 2>/dev/null | wc -l)
echo " - Total files: $TOTAL_FILES"
echo ""
echo "🕐 Context Changes (last 7 days):"
git log --oneline --since="7 days ago" -- AGENTS.md .antigravity/ 2>/dev/null | head -5
echo ""
echo "=== Dashboard Complete ==="Summary
Context engineering in Antigravity at an advanced level comes down to a few foundational principles.
Design context as a three-layer architecture — Project Intelligence, Dynamic Context, and Session Intelligence — so that information is managed and updated cleanly at each level. Write AGENTS.md not as a rule list but as a transmission of your project's reasoning style, including the "why" behind every constraint. Keep Knowledge Items focused and dense, with regular garbage collection to maintain freshness.
In team environments, actively prevent context pollution through structured weekly reviews, clear ownership models, and git-enforced change governance. And always counter Context Overload with intentional scope control and task decomposition.
When these techniques are applied together, Antigravity transforms from "an AI that needs constant hand-holding" into "a senior engineer who understands your project deeply." Context engineering is not a one-time setup — it's a continuous practice that grows with your project.
For a solid foundation in project knowledge design, also see Antigravity Project Context Mastery: Building AI-Understandable Projects with AGENTS.md and Knowledge Items.
Chapter 7: Measuring and Iterating on Context Quality
7-1. Defining Context Quality Metrics
Context engineering without measurement is guesswork. To continuously improve, you need clear metrics that tell you whether your context design is actually working. Here are four metrics that experienced teams track:
Acceptance Rate: The percentage of AI-generated code that is accepted without modification. A well-tuned context system should yield 50–70% acceptance on targeted tasks. If you're below 30%, your context is likely underspecified in key areas.
Clarification Frequency: How often AI asks clarifying questions before starting work. Some clarification is healthy — it means AI is using your Uncertainty Protocol correctly. But if AI asks for clarification more than once per task, your AGENTS.md may be too ambiguous.
Scope Violation Rate: How often AI touches files or areas outside the explicitly requested scope. This should be near zero with proper scope control prompts. Track it in weekly retrospectives.
Rework Cycles: How many revision rounds are needed before an AI-generated output is production-ready. Track this per category of task (refactoring vs. new feature vs. bug fix) to identify where your context design has gaps.
7-2. Running Controlled Context Experiments
Improving context quality requires treating it like any other engineering problem: form a hypothesis, run an experiment, measure the result.
A practical format for context experiments:
# Context Experiment: Reducing Scope Violations
## Hypothesis
Adding explicit "Files NOT to touch" sections to task prompts will reduce
scope violations from ~3/week to <1/week.
## Change
Added to AGENTS.md under "Uncertainty Protocol":
"Before making any change outside the explicitly requested scope,
STOP and ask — do not proceed with assumptions."
## Measurement Period
2 weeks (sprint 24 + sprint 25)
## Results
- Scope violations: 3/week → 0.5/week (83% reduction)
- Acceptance rate: unchanged
- Clarification frequency: +0.5/task (acceptable tradeoff)
## Decision
Formalize this addition. Update Layer 1 of AGENTS.md permanently.Running these experiments systematically transforms context engineering from an art into a discipline.
7-3. Context Debt: Recognizing and Paying It Down
Just as codebases accumulate technical debt, context systems accumulate context debt — the gap between what your AGENTS.md says and what your codebase actually does. Context debt manifests as:
- Rules that reference refactored-away patterns
- Domain vocabulary that no longer matches how the team talks
- Knowledge Items that describe deprecated APIs
- AGENTS.md sections nobody reads because they've become irrelevant
Paying down context debt has compounding returns. A single stale rule that causes one AI mistake per week costs 52 hours of developer time per year. Removing it takes 5 minutes.
A practical context debt audit process runs as follows. Once per quarter, export a diff of all AGENTS.md and Knowledge Items changes over the period. For each section that was never referenced in any AI session during the quarter, flag it for review. For each rule that was violated by AI more than twice, rewrite it with more specificity. For each section that contains dates more than 6 months in the past, update or archive it.
This quarterly ritual, combined with weekly reviews, keeps your context system lean and accurate over the long term.
7-4. Context Portability: Scaling Across Projects
Once you've developed effective context patterns in one project, the most efficient organizations extract context templates that can be adapted quickly for new projects.
A minimal portable context template looks like this:
# [Project Name] — AGENTS.md Template
## Architecture Philosophy
[Fill in: primary architectural pattern and the reason it was chosen]
[Fill in: non-negotiable quality constraints with their justifications]
## Domain Vocabulary
[Fill in: 5–10 domain terms that are commonly misunderstood or have project-specific meanings]
## What NOT to Do
- [ ] [Constraint]: [Reason this constraint exists]
- [ ] [Constraint]: [Reason this constraint exists]
- [ ] [Constraint]: [Reason this constraint exists]
## Uncertainty Protocol
When uncertain:
1. Check [project-specific documentation location]
2. Follow [project-specific fallback pattern]
3. Ask before implementing if still unclear
## AI Interaction History
[This section starts empty and fills over time with effective patterns discovered]Starting every new project with this template means your team never starts from zero. The institutional knowledge of what makes AI interaction effective transfers automatically.
Teams that maintain a context template library — versioned and shared across projects — report significantly faster AI adoption on new codebases, because engineers can focus on filling in project-specific content rather than rediscovering universal principles from scratch.
7-5. When to Rebuild vs. Refine
One final consideration: knowing when your context system needs a fundamental rebuild rather than incremental refinement. Signs that a rebuild is warranted include:
- Your AGENTS.md has grown beyond 500 lines and nobody can summarize what it says
- AI routinely contradicts itself because rules have accumulated without coherence
- New team members require more than a week to understand the context system
- The context system was designed for an earlier version of the codebase and no longer reflects current reality
When a rebuild is needed, the most effective approach is to start with a blank AGENTS.md, then add rules back only as they become necessary — guided by actual AI mistakes, not anticipatory rule-writing. This produces a leaner, more coherent context system than one built top-down from imagination.
The core principle that holds across every stage of context engineering maturity is this: context design is an investment in AI accuracy, not a configuration exercise. Every hour spent thoughtfully designing context saves multiples of that in AI-related rework. Treat it as a first-class engineering discipline, and Antigravity will perform as a first-class engineering partner.