Przejdź do głównej zawartości

Context Patterns

Ta treść nie jest jeszcze dostępna w Twoim języku.

Context is the secret sauce of AI-powered development. Master these patterns to transform vague AI responses into precise, production-ready code. Learn to provide just enough context - not too little, not too much.

  • Token Limit: Models process ~128k tokens (≈10,000 lines of code)
  • Quality vs Quantity: More context ≠ better responses
  • Cost Factor: Larger context = higher API costs
  • Response Time: More context = slower responses
Context QualityAI ResponseDeveloper Time
Too LittleGeneric, wrong assumptionsHigh rework
Just RightPrecise, aligned with codebaseMinimal edits
Too MuchConfused, slow, expensiveDebugging AI

Surgical Context

Precise, focused context for specific tasks

Layered Context

Build context progressively for complex tasks

Semantic Context

Use AI to find relevant context automatically

Compressed Context

Reduce token usage while maintaining meaning

  • Quick fixes and small changes
  • Performance-critical operations
  • Clear, isolated problems
# Bad: Kitchen Sink Approach
@folder src/ # 50,000 lines included
Fix the login bug
# Good: Surgical Precision
@file src/auth/login.ts
@file src/auth/validation.ts
@code validateEmail # specific function
Fix the email validation rejecting valid addresses with + symbols
// Context: Only these specific items
@file utils/validation.js
@code EMAIL_REGEX
@code validateEmail
// Prompt
Update email validation to accept plus addressing (user+tag@domain.com)
Keep existing validation for other rules

Start narrow, expand as needed:

  1. Core Layer: The exact code/file with the issue
  2. Integration Layer: Directly connected code
  3. System Layer: Architecture and patterns
  4. Domain Layer: Business rules and requirements
## Layer 1: Core Focus
@file models/Order.ts
@file models/Payment.ts
Task: Add payment processing to orders
## Layer 2: Add Integration Context
@file services/PaymentService.ts
@file api/payments/webhook.ts
## Layer 3: Add System Context
@folder lib/payments/
@code PaymentProvider interface
## Layer 4: Add Domain Context
@file docs/payment-requirements.md
@docs Stripe integration guide

Let AI help you find relevant context:

# Step 1: Ask AI to find context
"What files and functions handle user authentication in this codebase?"
# Step 2: Review AI findings
# AI responds with: auth/, middleware/auth.ts, utils/jwt.ts
# Step 3: Use findings as context
@file auth/login.ts
@file middleware/auth.ts
@code generateJWT
"Add two-factor authentication to the login flow"
Query TypeExampleUse Case
Architecture”Show me all Redux actions”Understanding patterns
Dependencies”What calls UserService?”Impact analysis
Similar Code”Find pagination implementations”Consistency
Error Patterns”Where do we handle API errors?”Error handling
  1. Summary Files
.cursor/summaries/auth-system.md
## Authentication System Overview
- JWT-based auth with refresh tokens
- Roles: admin, user, guest
- Session timeout: 24h
- Password requirements: 8+ chars, 1 special
Key files:
- auth/login.ts - Main login flow
- auth/jwt.ts - Token generation
- middleware/auth.ts - Route protection
  1. Interface Extraction
// Instead of including entire implementation files
@file types/auth.d.ts // Just interfaces
@file api/auth/routes.ts // Just route definitions
  1. Selective Inclusion
# Include only public methods
@code "class UserService" "public"
@code "export function" auth/utils.ts
# Working across multiple repos
@folder ../shared-components/Button
@file ../api-server/src/endpoints/user.ts
@web https://api-docs.company.com/users
Ensure Button component matches API response structure
# Include relevant history
@git PR #1234 # Previous implementation
@git commit abc123 # When feature was added
@docs decisions/adr-auth.md # Architecture decision
Refactor auth to address issues from PR #1234
# Context that changes based on task
{{if FEATURE_FLAGS}}
@file config/features.ts
@code getFeatureFlag
{{/if}}
{{if DATABASE_CHANGE}}
@file prisma/schema.prisma
@folder migrations/
{{/if}}
MetricGood ContextPoor Context
Token Usage5-15k tokens50k+ tokens
Response Time2-5 seconds20+ seconds
Accuracy90%+ correctunder 70% correct
Iterations Needed1-25+
  • Relevance: Every file/symbol directly relates to task
  • Completeness: All necessary context included
  • Clarity: Clear relationship between context items
  • Efficiency: Minimal tokens for maximum understanding
  • Currency: Using latest versions of files
# Minimal context for new component
@file components/ui/Button.tsx # Pattern reference
@file styles/theme.ts # Design system
@code useTheme hook # Theme integration
Create Card component following Button patterns
# Redux/Zustand context pattern
@folder store/slices/ # See patterns
@file store/types.ts # Type definitions
@code specific slice only
1. Start with error context
@error "TypeError: Cannot read property 'name'"
@file src/components/UserCard.tsx
2. Expand to data flow
@code getUserData
@file api/users.ts
3. Add type context if needed
@file types/User.ts
1. Requirements context
@file specs/feature-x.md
@figma design-link
2. Pattern context
@file similar-feature.ts
@folder patterns/
3. Integration context
@file routes/index.ts
@file types/index.ts
1. Current implementation
@file old-service.ts
@code specific methods
2. Target pattern
@file patterns/service-template.ts
@docs architecture/services.md
3. Test context
@file tests/old-service.test.ts
  1. Build Context Templates

    • Create reusable context patterns for common tasks
    • Store in .cursor/contexts/
  2. Use Context Aliases

    # Define once, reuse
    AUTH_CONTEXT = @file auth/* @code JWT*
    Using AUTH_CONTEXT, add refresh token rotation
  3. Progressive Enhancement

    • Start minimal
    • Add context based on AI questions
    • Remove irrelevant context
  4. Context Comments

    @file api/user.ts # Current implementation
    @file api/user.v2.ts # Target pattern
    @docs api-standards.md # Must follow these

Master these context patterns to:

  • Reduce development time by 40-60%
  • Improve AI response accuracy to 90%+
  • Cut API costs by optimizing token usage
  • Handle complex multi-file changes confidently

Continue with:

Remember: Context is about signal, not noise. Every piece of context should earn its place by directly contributing to better AI understanding.