| name | agent-context-optimization |
| description | This skill should be used when preparing context for agent delegation to maximize output quality - teaches what information agents need, how to structure context efficiently, when to @mention files, and how to provide background without overwhelming agents with unnecessary details. |
Agent Context Optimization
Overview
Agents produce dramatically better outputs when given optimal context. This skill teaches how to prepare and structure context for maximum agent effectiveness while avoiding context bloat.
Core principle: More context ≠ better context. The right context at the right time produces the best results.
When to Use
Use this skill when:
- Agent outputs consistently miss the mark
- Unsure what context to provide
- Agent seems confused or asks for clarification
- Want to improve first-try output quality
- Delegating complex or novel tasks
- Agent needs to understand existing patterns
Symptoms of poor context:
- Agents make wrong assumptions
- Outputs don't match project style
- Multiple clarification rounds needed
- Agent reinvents existing patterns
- Outputs don't integrate with existing code
The Context Hierarchy
Essential Context (Always Provide)
1. Clear Objective What exactly needs to be done
✅ "Create a responsive UserCard component showing avatar, name, email, and join date"
❌ "Make a user thing"
2. Success Criteria How to know it's done
✅ "Success: Component renders all user data, works on mobile (320px+), uses shadcn/ui Card"
❌ "Make it work"
3. Relevant Files Where to work or what to reference
✅ "File: Create src/components/UserCard.tsx
Reference: src/components/ProductCard.tsx for our card pattern"
❌ No file paths mentioned
Important Context (Provide When Relevant)
4. Background/Why Context on why this matters
✅ "Users complained about slow profile loads (3s). Need to reduce to <1s by lazy loading images"
❌ "Optimize the profile page"
5. Constraints Technical or business limitations
✅ "Must use Postgres (our existing DB), budget $100/mo max, maintain API compatibility"
❌ No constraints mentioned
6. Existing Patterns How we do things in this project
✅ "@mention src/components/LoginForm.tsx - follow this form pattern"
❌ "Make a form somehow"
Optional Context (Provide Sparingly)
7. Implementation Hints Suggestions on approach (but don't over-specify)
✅ "Consider using WebSockets or Supabase Realtime for this"
✅ "react-virtual might help with the large list performance"
❌ "Use exactly this library with these exact settings..." (too prescriptive)
8. Historical Context Previous attempts or decisions (only if relevant)
✅ "We tried Redis caching but it didn't help - the bottleneck is database queries"
❌ "Three months ago we considered MongoDB..." (not relevant)
@-Mention Strategies
When to @-Mention Files
Always @-mention when:
- Agent needs to modify specific files
- Showing examples of patterns to follow
- Referencing related code for understanding
- Large files (>500 lines) that agent must understand
Example:
@frontend-developer refactor the Dashboard component
Files to modify:
@src/components/Dashboard.tsx (the component)
@src/hooks/useDashboardData.ts (data fetching)
Pattern to follow:
@src/components/AnalyticsPage.tsx (similar layout structure)
When NOT to @-Mention
Skip @-mentioning when:
- Tiny files (<50 lines) that agent can read quickly
- Common configuration files (agent knows to check)
- Files in standard locations (package.json, etc.)
- Too many files (>5) - let agent explore instead
Example:
✅ Good: "@frontend-developer add React Hook Form to the signup form"
(Agent can find signup form via Explore)
❌ Overkill: "@package.json @tsconfig.json @next.config.js @src/app/signup/page.tsx..."
(Too many files, most aren't relevant)
@-Mention Pattern Library
Pattern 1: Show, don't tell
"@backend-architect add user authentication
Follow our existing auth pattern:
@src/api/auth/session.ts
@src/middleware/requireAuth.ts"
Pattern 2: Reference + Delta
"@frontend-developer create ProductCard component
Base structure from: @src/components/UserCard.tsx
Changes: Replace user data with product data (image, title, price, rating)"
Pattern 3: Multiple examples
"@test-writer-fixer add tests for PaymentForm
Test patterns we use:
@src/components/LoginForm.test.tsx (form testing pattern)
@src/components/Checkout.test.tsx (payment mocking pattern)"
Context Structuring Templates
For Implementation Tasks
@[agent] [action] [target]
**Objective:** [Clear, specific goal]
**Files:**
- Modify: @path/to/main/file.ts
- Reference: @path/to/example.ts (for pattern)
**Requirements:**
- [Requirement 1]
- [Requirement 2]
**Constraints:**
- [Constraint 1]
- [Constraint 2]
**Success:** [Specific completion criteria]
For Research Tasks
@[agent] research [topic]
**Background:** [Why we need this]
**Questions:**
1. [Specific question]
2. [Specific question]
**Focus areas:**
- [Area 1]
- [Area 2]
**Deliverable:** [What format you want the answer in]
For Design Tasks
@ui-designer design [component/page]
**Purpose:** [User need this serves]
**User flow:**
1. [Step 1]
2. [Step 2]
**Must include:**
- [Element 1]
- [Element 2]
**Style reference:**
@path/to/similar/component.tsx (follow this visual style)
**Platform:** [Desktop, mobile, both]
**Success:** [What good output looks like]
Context Efficiency Techniques
Technique 1: Layered Context
Start minimal, add layers as needed:
Layer 1 (Initial request):
"@backend-architect optimize /api/users endpoint - currently 2.3s, need <200ms"
[If agent needs more]
Layer 2 (Follow-up):
"Current implementation: @src/api/users/route.ts
Database: Postgres, 50k users
Known issue: N+1 query on user posts"
[If agent needs more]
Layer 3 (Deep details):
"Schema: @prisma/schema.prisma
Current query: @src/db/queries/getUsers.ts
Performance profile: @docs/performance-analysis.md"
Technique 2: Context by Reference
Point to context, don't inline everything:
✅ Good:
"@frontend-developer implement checkout flow
Payment integration: See our Stripe docs at @docs/stripe-integration.md
Error handling: Follow pattern in @src/utils/errorHandler.ts
Form validation: Use Zod schemas like @src/schemas/userSchema.ts"
❌ Bad:
"@frontend-developer implement checkout
[Paste 500 lines of Stripe docs]
[Paste 200 lines of error handling code]
[Paste 100 lines of validation examples]"
Technique 3: Progressive Disclosure
Provide context as agent progresses:
Phase 1:
"@ai-engineer add document summarization feature"
[Agent explores, asks questions]
Phase 2:
"Use Claude API, budget $50/month max
Current doc processing: @src/utils/documentProcessor.ts"
[Agent designs solution]
Phase 3:
"Implement your design. Additional context:
Rate limits: @docs/api-limits.md
Error handling: @src/utils/retryHandler.ts"
Context Anti-Patterns
| Anti-Pattern | Problem | Better Approach |
|---|---|---|
| The Info Dump | @-mention 20 files | @-mention 2-3 most relevant |
| The Assumption | "You know what I mean" | Be explicit about everything |
| The Novel | Write essay of background | 2-3 sentences max |
| The Vague Reference | "Like the other thing" | @-mention the actual thing |
| The Empty Brief | No context at all | Minimum: objective + success criteria |
| The Over-Specifier | Prescribe exact implementation | State requirements, not implementation |
| The Context Hoarder | Withhold relevant information | Share upfront, avoid clarification rounds |
Context Preparation Checklists
For Frontend Agents
Essential:
- What component/page to build
- Required functionality
- Design specs or reference component
- Responsive requirements
If applicable:
- State management approach
- API endpoints to call
- Existing components to use
- Performance requirements
For Backend Agents
Essential:
- What endpoint/function to create
- Input/output specifications
- Database schema involvement
- Authentication requirements
If applicable:
- Performance targets
- Existing patterns to follow
- Third-party integrations
- Error handling requirements
For Testing Agents
Essential:
- What to test (file/component/feature)
- Coverage expectations
- Test framework being used
If applicable:
- Specific edge cases to cover
- Mocking requirements
- Integration test needs
- Performance test targets
For Design Agents
Essential:
- What to design (component/page/flow)
- User needs / purpose
- Platform (web/mobile/both)
- Existing design system
If applicable:
- Brand guidelines
- Similar designs to reference
- Accessibility requirements
- Target audience
For Product/Strategy Agents
Essential:
- What question to answer
- Why it matters
- Scope of research
If applicable:
- Timeline/urgency
- Existing data to consider
- Specific hypotheses to validate
- Format for deliverable
Context Quality Indicators
Green Flags (Good Context)
- Agent produces 80%+ correct output on first try
- Minimal clarification questions
- Output matches project patterns
- Fast turnaround time
- Agent references your provided context in output
Red Flags (Poor Context)
- Agent asks basic questions you could have answered
- Output ignores existing patterns
- Multiple false starts
- Generic output (doesn't leverage your specific context)
- Agent apologizes for misunderstanding
If you see red flags: Review this skill and provide better context next time
Example Context Transformations
Before Optimization
Request:
"@frontend-developer add dark mode"
Result:
- Agent implements custom dark mode solution
- Doesn't use existing theme system
- Hardcodes colors
- Doesn't persist preference
- Requires major refactoring
After Optimization
Request:
"@frontend-developer add dark mode toggle to Settings page
Context:
- Theme system already set up with CSS variables (@src/app/globals.css)
- Need toggle component (use shadcn/ui Switch)
- Store preference in localStorage as 'theme' key
- Apply by adding/removing 'dark' class on document.documentElement
- Reference existing theme toggle in docs: @docs/theming.md
Files:
- Modify: @src/app/settings/page.tsx
- Reference: @src/app/globals.css (see CSS variables)
Success: Toggle switches theme, persists across sessions, all components adapt correctly"
Result:
- Agent uses existing theme system perfectly
- Clean implementation
- Works first try
- No refactoring needed
Context Budget Management
When Context is Limited
Prioritize:
- Core objective (what to build)
- Critical constraints (what can't change)
- One reference file (pattern to follow)
- Success criteria (how to verify)
Defer:
- Background information
- Historical decisions
- Alternative approaches considered
- Nice-to-have features
When to Provide More Context
Add context when:
- Novel problem (no existing patterns)
- High-stakes task (production, security)
- Complex domain knowledge needed
- Agent must understand trade-offs
- Multiple valid approaches exist
Example:
High-stakes security task:
"@backend-architect implement API authentication
Background:
We're handling financial data, SOC 2 compliance required.
Previous JWT implementation had security audit findings.
Requirements:
- Secure token storage (HttpOnly cookies)
- CSRF protection
- Rate limiting on auth endpoints
- Session timeout after 30 min inactivity
- Audit logging for all auth events
Compliance docs: @docs/soc2-requirements.md
Previous issues: @docs/security-audit-findings.md
Our auth spec: @docs/auth-specification.md
Success: Passes security review, meets SOC 2 requirements"
Quick Reference
Context Checklist for Every Delegation
Minimum (always):
□ Clear objective
□ Success criteria
□ Relevant file paths
Standard (most tasks):
□ Why it matters (1-2 sentences)
□ Key constraints
□ Pattern to follow (@-mention example)
Maximum (complex/novel tasks):
□ Background context
□ Multiple reference files
□ Trade-off considerations
□ Domain knowledge docs
The 80/20 Rule
80% of context value comes from:
- Clear objective (what to build)
- Explicit constraints (limitations)
- One good reference (pattern to follow)
The remaining 20%:
- Background information
- Historical context
- Alternative approaches
- Implementation hints
Start with the 80%, add the 20% only when needed.
Context Optimization Formula
Effective Context = Clarity × Relevance / Volume
Maximize: Clarity (be specific) and Relevance (pertinent info)
Minimize: Volume (concise, essential only)
Examples:
High Score (Effective):
Clear: ✅ Specific component with requirements
Relevant: ✅ @-mentions pattern file to follow
Volume: ✅ 3 sentences + 1 file
"@frontend-developer create UserBadge component
Props: name, role, avatar URL
Style: Follow @src/components/TeamMember.tsx
File: src/components/UserBadge.tsx"
Low Score (Ineffective):
Clear: ❌ "Improve the user stuff"
Relevant: ❌ No references or examples
Volume: ❌ Either too sparse or walls of text
"@frontend-developer work on users"
OR
"@frontend-developer [paste 50 files with vague instructions]"
Best Practices
Do:
- ✅ Be specific about objectives
- ✅ @-mention 2-3 most relevant files
- ✅ State constraints upfront
- ✅ Provide one clear example/pattern
- ✅ Define success criteria
- ✅ Use concise background (2-3 sentences)
Don't:
- ❌ @-mention everything "just in case"
- ❌ Paste large code blocks inline
- ❌ Assume agent has unstated context
- ❌ Withhold critical information
- ❌ Over-explain obvious things
- ❌ Provide outdated or irrelevant context
The Bottom Line
Formula for agent success:
Clear Objective
+ Right Amount of Context
+ Specific Examples
+ Defined Boundaries
= High-Quality First-Try Output
Master context optimization and agents will consistently deliver exactly what you need, faster, with fewer revisions.