Skip to content

Latest commit

 

History

History
337 lines (238 loc) · 7.01 KB

File metadata and controls

337 lines (238 loc) · 7.01 KB

Context Management

Effective context management is crucial for agent performance and cost efficiency. Learn how to scope context, use MDC files, track state, and manage dynamic context.

Context Scope

Define what information the agent needs access to.

Principles

  1. Include Only What's Necessary: More context = higher cost + slower responses
  2. Prioritize Recent Changes: Focus on files currently being modified
  3. Exclude Dependencies: Don't include node_modules, vendor files, etc.
  4. Use Abstractions: Include high-level docs instead of entire codebases

Scoping Strategies

File-Level Scoping

Include only relevant files:

# Good: Specific files
cursor-agent "@src/auth/user-service.ts @src/auth/auth-service.ts refactor authentication"

# Bad: Entire directory
cursor-agent "@src/ refactor authentication"

Directory-Level Scoping

When working on a module:

# Include module directory and related tests
cursor-agent "@src/auth/ @tests/auth/ improve authentication module"

Exclude Patterns

Use .cursorignore to exclude files:

# .cursorignore
node_modules/
dist/
build/
*.log
.env
coverage/

Context Size Guidelines

  • Small (< 10 files): Fast, cheap, focused
  • Medium (10-50 files): Balanced, good for module work
  • Large (50+ files): Slow, expensive, use sparingly

MDC Files (Markdown Context Files)

MDC files are markdown documents that serve as context sources for agents.

Creating MDC Files

Create .mdc files to provide structured context:

# Project Architecture

## Overview
This project is a REST API built with Node.js and Express.

## Key Components
- Authentication: JWT-based auth in src/auth/
- Database: PostgreSQL with Prisma ORM
- API Routes: RESTful routes in src/routes/

## Conventions
- Use async/await for all async operations
- Follow RESTful naming conventions
- All routes require authentication except /auth/login

Using MDC Files

Reference MDC files in agent prompts:

cursor-agent "@architecture.mdc implement new feature following project architecture"

MDC File Organization

Organize MDC files by purpose:

docs/
  architecture.mdc
  api-spec.mdc
  database-schema.mdc
  coding-standards.mdc

State Tracking

Track what has been completed vs. what remains.

State File Structure

{
  "task": "refactor-authentication",
  "started": "2024-01-15T10:00:00Z",
  "completedSteps": [
    {
      "step": "analyze-current-code",
      "completed": "2024-01-15T10:05:00Z",
      "result": "Identified 3 files to refactor"
    },
    {
      "step": "write-tests",
      "completed": "2024-01-15T10:15:00Z",
      "result": "15 tests written"
    }
  ],
  "currentStep": "refactor-user-service",
  "remainingSteps": [
    "refactor-auth-service",
    "refactor-token-service",
    "verify-all-tests"
  ],
  "filesModified": [
    "src/auth/user-service.ts",
    "tests/auth/user-service.test.ts"
  ]
}

Updating State

Update state after each agent action:

#!/bin/bash
STATE_FILE=".agent-state.json"

# Load state
STATE=$(cat $STATE_FILE)

# Agent completes step
cursor-agent "complete current step: $(echo $STATE | jq -r '.currentStep')"

# Update state
echo $STATE | jq '.completedSteps += [{"step": "refactor-user-service", "completed": "'$(date -Iseconds)'"}]' > $STATE_FILE

Dynamic Context Injection

Inject results from previous iterations into subsequent agent prompts.

Feedback Loop Pattern

#!/bin/bash

# Initial attempt
RESULT=$(cursor-agent "implement UserService.getUser(id)")

# Run tests
TEST_OUTPUT=$(npm test 2>&1)

# Inject test results into next iteration
cursor-agent "previous implementation failed tests: $TEST_OUTPUT. Fix the implementation."

Incremental Context Building

Build context incrementally:

# Step 1: Analysis
ANALYSIS=$(cursor-agent "analyze authentication code structure")

# Step 2: Use analysis for refactoring
cursor-agent "based on this analysis: $ANALYSIS, refactor the code"

# Step 3: Use refactoring results for testing
REFACTOR_RESULT=$(cursor-agent "based on refactoring, write comprehensive tests")

Context Compression

Compress context when it grows too large:

# Original context (too large)
LARGE_CONTEXT=$(cat large-file.txt)

# Compress to summary
SUMMARY=$(cursor-agent "summarize this context in 100 words: $LARGE_CONTEXT")

# Use summary for next iteration
cursor-agent "based on summary: $SUMMARY, implement feature"

Context Decay

Refresh context for long-running tasks to prevent staleness.

When Context Decays

  • Files modified outside agent control
  • Dependencies updated
  • External APIs changed
  • Team members made changes

Refreshing Context

#!/bin/bash

# Check if context needs refresh
LAST_REFRESH=$(cat .context-refresh)
CURRENT_TIME=$(date +%s)
REFRESH_INTERVAL=3600  # 1 hour

if [ $(($CURRENT_TIME - $LAST_REFRESH)) -gt $REFRESH_INTERVAL ]; then
  echo "Refreshing context..."
  
  # Re-read relevant files
  CONTEXT=$(cat src/**/*.ts | head -10000)
  
  # Update refresh time
  echo $CURRENT_TIME > .context-refresh
fi

Context Best Practices

1. Start Small, Expand as Needed

# Start with minimal context
cursor-agent "@specific-file.ts implement feature"

# Expand if needed
cursor-agent "@specific-file.ts @related-file.ts implement feature with integration"

2. Use Abstractions

Instead of entire codebase, use:

  • Architecture diagrams
  • API specifications
  • Design documents
  • High-level summaries

3. Cache Frequently Used Context

# Cache common context
echo "$(cursor-agent 'analyze project structure')" > .cached-context.txt

# Reuse cached context
cursor-agent "@.cached-context.txt implement new feature"

4. Prune Unnecessary Context

Remove completed items from context:

# Before: Includes completed steps
CONTEXT="completed: step1, step2, step3 | current: step4"

# After: Only current and remaining
CONTEXT="current: step4 | remaining: step5, step6"

5. Version Context

Track context versions for reproducibility:

# Save context version
echo "context-v1-$(date +%Y%m%d)" > .context-version

# Reference version in prompts
cursor-agent "@.context-version implement feature"

Tools and Techniques

Context Size Estimation

Estimate context size before sending:

# Count tokens (approximate)
CONTEXT_SIZE=$(wc -w context.txt | awk '{print $1}')
echo "Context size: ~$CONTEXT_SIZE tokens"

Context Validation

Validate context before use:

# Check for required files
for file in $REQUIRED_FILES; do
  if [ ! -f "$file" ]; then
    echo "Missing required file: $file"
    exit 1
  fi
done

Context Templates

Create reusable context templates:

# template-context.sh
cat << EOF
Project: $PROJECT_NAME
Language: $LANGUAGE
Framework: $FRAMEWORK
Key Files: $KEY_FILES
Conventions: $CONVENTIONS
EOF

Next Steps