Continue.dev uses a dual-system architecture that separates machine-readable configuration from human-readable instructions:
The Two-Layer System:
Configuration Layer (YAML/JSON)
├── Models and providers
├── API keys and endpoints
├── Context providers
├── Tool integrations
└── System settings
Rules Layer (Markdown)
├── Coding standards
├── Project conventions
├── Architectural patterns
├── Examples and templates
└── Natural language guidance
Why This Matters:
| Aspect | Configuration (YAML) | Rules (Markdown) |
|---|---|---|
| Purpose | Configure Continue.dev's behavior | Guide AI's coding decisions |
| Format | Structured key-value pairs | Natural language + code examples |
| Validation | JSON Schema enforced | Freeform, no validation |
| Change Frequency | Rarely (model switches, provider changes) | Often (evolving standards) |
| Version Control | Commit reference in settings | Commit all rule files |
| Audience | Continue.dev software | Language model |
1.2 File Locations and Precedence
Global Configuration:
~/.continue/
├── config.yaml # Global model and provider settings
├── rules/ # Global user rules (all projects)
│ ├── personal-style.md
│ └── preferred-patterns.md
└── index/ # Codebase embeddings cache
Project-Local Configuration:
my-project/
├── .continue/
│ ├── config.yaml # Project-specific overrides (optional)
│ └── rules/ # Project rules (team-shared)
│ ├── 01-typescript.md
│ ├── 02-react.md
│ └── 03-testing.md
├── .vscode/
│ └── settings.json # VS Code reference to Continue config
└── src/
Precedence Hierarchy (Higher Overrides Lower):
- Inline chat context (what you type in chat)
-
Project rules (
.continue/rules/) -
Global rules (
~/.continue/rules/) -
Model system message (
config.yaml→chatOptions.baseSystemMessage) - Continue defaults (built-in)
1.3 Configuration vs. Rules: Key Differences
Use config.yaml For:
# Model selection
models:
- name: Claude 3.5
provider: anthropic
model: claude-3-5-sonnet-20241022
# API authentication
apiKey: ${{ secrets.ANTHROPIC_API_KEY }}
# Role assignment
roles: [chat, edit, apply]
# Context providers
context:
- provider: codebase
params:
nRetrieve: 30
Use .md Rules For:
# TypeScript Standards
## Type Safety
All functions must have explicit return types:
typescript
// ✅ CORRECT
function calculateTotal(items: Item[]): number {
return items.reduce((sum, item) => sum + item.price, 0);
}
// ❌ WRONG
function calculateTotal(items: Item[]) {
return items.reduce((sum, item) => sum + item.price, 0);
}
II. Quick Start: First-Time Setup
2.1 Installation and Initial Configuration
Step 1: Install Continue.dev Extension
# VS Code
# Open Extensions (Ctrl+Shift+X / Cmd+Shift+X)
# Search: "Continue"
# Click Install
# Or via command line
code --install-extension continue.continue
Step 2: Initial Setup Wizard
On first launch, Continue.dev opens setup wizard:
-
Choose Provider:
- Anthropic (Claude)
- OpenAI (GPT-4)
- Ollama (Local)
- Custom
Enter API Key:
Option A: Paste directly (stored in config)
Option B: Use secrets (recommended)
- Select Default Model:
Recommended: claude-3-5-sonnet-20241022 (most capable)
Alternative: gpt-4o (fast, reliable)
Local: ollama/qwen2.5-coder (free, private)
Step 3: Verify Installation
# Check config file created
cat ~/.continue/config.yaml
# Should see:
# models:
# - name: [Your Model]
# provider: [Your Provider]
# model: [Model ID]
Step 4: Test Connection
Open Continue.dev panel in VS Code:
-
Shortcut:
Ctrl+L(Windows/Linux) orCmd+L(Mac) - Type:
"Hello, are you working?" - Expected: AI responds
2.2 Creating Your First Rules File
Option A: Simple Inline Rules (Quick Start)
Edit ~/.continue/config.yaml:
models:
- name: Claude 3.5 Sonnet
provider: anthropic
model: claude-3-5-sonnet-20241022
apiKey: ${{ secrets.ANTHROPIC_API_KEY }}
roles: [chat, edit, apply]
# Add inline rules here
rules:
- "Use TypeScript strict mode for all code"
- "Prefer functional components in React"
- "Always include error handling in async functions"
Option B: Markdown Rules File (Recommended)
Create directory structure:
mkdir -p ~/.continue/rules
touch ~/.continue/rules/personal-style.md
Edit personal-style.md:
# My Personal Coding Style
## Response Format
- Give concise answers with code examples
- Explain complex concepts simply
- Highlight breaking changes
## TypeScript Standards
- Strict mode enabled
- Explicit return types required
- No `any` types without justification
## React Patterns
- Functional components only
- Hooks over class lifecycle methods
- Server Components by default (Next.js)
## Error Handling
Always use Result<T> pattern:
typescript
type Result =
| { success: true; data: T }
| { success: false; error: string };
async function operation(): Promise> {
try {
const data = await fetch();
return { success: true, data };
} catch (error) {
logger.error('Operation failed', { error });
return { success: false, error: 'User-friendly message' };
}
}
2.3 Verifying Rules Are Loaded
Test 1: Ask AI About Rules
In Continue.dev chat:
User: "What coding standards should I follow in this project?"
Expected Response:
"Based on the project rules:
1. Use TypeScript strict mode
2. Prefer functional components
3. Include error handling in async functions
[...]"
Test 2: Generate Code
User: "Create a function to fetch user data from API"
Expected: AI generates code following your rules:
- TypeScript with explicit return type
- Result<T> error handling
- Functional pattern
Test 3: Check Loaded Rules (Debug)
Open Continue.dev console:
# VS Code: View → Output → Continue
# Look for:
# [Continue] Loaded rules from: /Users/you/.continue/rules/personal-style.md
2.4 Common First-Time Issues
Issue 1: Rules Not Loading
Symptom: AI ignores your rules
Causes & Solutions:
# ❌ WRONG: Rules in wrong location
/path/to/random/rules.md
# ✅ CORRECT: Rules in Continue directory
~/.continue/rules/your-rules.md
# OR: Reference explicitly in config.yaml
rules:
- uses: ./path/to/your-rules.md
Issue 2: YAML Syntax Errors
Symptom: Continue.dev won't start, shows error
Common Mistakes:
# ❌ WRONG: Inconsistent indentation (tabs vs spaces)
models:
- name: Claude
provider: anthropic # Tab character here!
# ✅ CORRECT: 2-space indentation throughout
models:
- name: Claude
provider: anthropic
Validation Tool:
# Install YAML validator
npm install -g yaml-lint
# Check config
yaml-lint ~/.continue/config.yaml
Issue 3: API Key Not Working
Symptom: "Authentication failed" errors
Solutions:
# ❌ WRONG: Hardcoded key (insecure)
apiKey: sk-ant-1234567890abcdef
# ✅ CORRECT: Use secrets
apiKey: ${{ secrets.ANTHROPIC_API_KEY }}
# Then set environment variable:
# export ANTHROPIC_API_KEY=sk-ant-1234567890abcdef
VS Code Settings Method:
// .vscode/settings.json
{
"continue.secrets": {
"ANTHROPIC_API_KEY": "sk-ant-1234567890abcdef"
}
}
III. Configuration Deep Dive: config.yaml
3.1 Complete Schema Reference
Root Structure:
name: my-configuration # Optional: Config name
version: 0.0.1 # Optional: Semantic versioning
schema: v1 # Required: Schema version
models: [] # Required: Model definitions
rules: [] # Optional: Inline rules
context: [] # Optional: Context providers
prompts: [] # Optional: Custom commands
Minimal Working Configuration:
name: minimal-config
version: 1.0.0
schema: v1
models:
- name: GPT-4
provider: openai
model: gpt-4o
apiKey: ${{ secrets.OPENAI_API_KEY }}
roles: [chat]
3.2 Model Configuration and Roles
Complete Model Schema:
models:
- name: string # Display name (required)
provider: string # Provider ID (required)
model: string # Model ID (required)
apiKey: string # API key (optional, use secrets)
apiBase: string # Custom endpoint (optional)
roles: array # Role assignments (required)
defaultCompletionOptions: object # Model parameters (optional)
chatOptions: object # Mode-specific prompts (optional)
requestOptions: object # HTTP request config (optional)
capabilities: array # Feature flags (optional)
embedOptions: object # Embedding config (optional)
Provider-Specific Configurations:
Anthropic (Claude):
models:
- name: Claude 3.5 Sonnet
provider: anthropic
model: claude-3-5-sonnet-20241022
apiKey: ${{ secrets.ANTHROPIC_API_KEY }}
roles: [chat, edit, apply]
defaultCompletionOptions:
temperature: 0.7
maxTokens: 4096
topP: 0.9
chatOptions:
baseSystemMessage: |
You are an expert TypeScript engineer.
Focus on type safety, performance, and maintainability.
baseAgentSystemMessage: |
Break complex problems into clear, actionable steps.
Verify preconditions before proceeding.
basePlanSystemMessage: |
Create concrete plans with specific file changes.
Consider dependencies and execution order.
capabilities:
- tool_use
- image_input
OpenAI (GPT-4):
models:
- name: GPT-4o
provider: openai
model: gpt-4o
apiKey: ${{ secrets.OPENAI_API_KEY }}
roles: [chat, edit, apply]
defaultCompletionOptions:
temperature: 0.7
maxTokens: 4000
presencePenalty: 0.0
frequencyPenalty: 0.0
requestOptions:
headers:
X-Custom-Header: "value"
Ollama (Local Models):
models:
- name: Qwen Coder Local
provider: ollama
model: qwen2.5-coder:7b
apiBase: http://localhost:11434
roles: [autocomplete, summarize]
defaultCompletionOptions:
temperature: 0.2
maxTokens: 1000
Role Definitions:
| Role | Purpose | Model Requirements | Typical Usage |
|---|---|---|---|
chat |
Main conversational coding | High capability (GPT-4, Claude) | Primary development assistant |
edit |
Code transformations | High capability | Refactoring, code changes |
apply |
Targeted modifications | Medium capability | Applying suggestions |
autocomplete |
Real-time suggestions | Fast, lightweight (GPT-4o-mini, local) | While typing |
embed |
Semantic search | Embedding model (text-embedding) | Codebase search |
rerank |
Search result ordering | Reranking model (Cohere) | Refining search |
summarize |
Content summarization | Cheap, fast (GPT-4o-mini) | File summaries |
Multi-Model Strategy:
models:
# Primary: Powerful, expensive
- name: Claude 3.5 Sonnet
provider: anthropic
model: claude-3-5-sonnet-20241022
roles: [chat, edit, apply]
defaultCompletionOptions:
temperature: 0.7
maxTokens: 4096
# Secondary: Fast, cheap
- name: GPT-4o Mini
provider: openai
model: gpt-4o-mini
roles: [autocomplete, summarize]
defaultCompletionOptions:
temperature: 0.3
maxTokens: 1000
# Specialized: Embeddings
- name: OpenAI Embeddings
provider: openai
model: text-embedding-3-small
roles: [embed]
embedOptions:
maxChunkSize: 512
maxBatchSize: 10
# Local: Free, private
- name: Local Qwen
provider: ollama
model: qwen2.5-coder:7b
roles: [autocomplete]
3.3 Context Providers Setup
Available Providers:
context:
# Currently open files
- provider: code
# Semantic codebase search
- provider: codebase
params:
nRetrieve: 30 # Retrieve 30 chunks from embeddings
nFinal: 5 # Show top 5 in final context
useReranking: true # Use reranking model to refine
# Fetch documentation
- provider: docs
params:
sites:
- https://nextjs.org/docs
- https://react.dev
# Git diff (unstaged changes)
- provider: diff
# Recent terminal output
- provider: terminal
params:
lines: 50 # Last 50 lines
# IDE problems (errors/warnings)
- provider: problems
# Directory tree
- provider: folder
params:
folders:
- src
- tests
maxDepth: 3
# GitHub issues/PRs
- provider: github
params:
repos:
- owner/repo
includeIssues: true
includePRs: true
# Search providers
- provider: search
params:
engine: google # or bing, duckduckgo
# Database schema
- provider: database
params:
connectionString: ${{ secrets.DB_URL }}
# Jira tickets
- provider: jira
params:
domain: company.atlassian.net
project: PROJ
Context Provider Best Practices:
# ✅ RECOMMENDED: Balanced context
context:
- provider: code # Always include
- provider: codebase # Essential for large repos
params:
nRetrieve: 30
nFinal: 5
- provider: diff # Show current changes
- provider: problems # Include errors
- provider: terminal # Recent command output
# ❌ AVOID: Too many providers (slows down, token overflow)
context:
- provider: code
- provider: codebase
params:
nRetrieve: 100 # Too many! Wastes tokens
nFinal: 20
- provider: docs
- provider: github
- provider: jira
- provider: search
# Too much context = confusion
3.4 Custom Prompts and Commands
Prompt Structure:
prompts:
- name: string # Command name (required)
description: string # Help text (required)
prompt: string # Prompt template (required)
Practical Examples:
prompts:
# Code review
- name: review
description: Comprehensive code review
prompt: |
Review this code for:
**Security**:
- Exposed secrets or credentials
- SQL injection vulnerabilities
- XSS prevention
- Input validation
**Quality**:
- Code duplication (DRY violations)
- Overly complex logic (high cyclomatic complexity)
- Missing error handling
- Type safety issues
**Performance**:
- Inefficient algorithms (O(n²) or worse)
- Unnecessary re-renders (React)
- Database N+1 queries
- Memory leaks
**Testing**:
- Missing test coverage
- Edge cases not covered
- Mock dependencies appropriately
Provide:
1. Issue description with severity (Critical/High/Medium/Low)
2. File location and line numbers
3. Specific code example
4. Suggested fix with code
# Generate tests
- name: test
description: Generate comprehensive tests
prompt: |
Generate tests for the selected code using our testing stack:
- Unit tests: Vitest
- Component tests: Testing Library
- E2E tests: Playwright
Follow AAA pattern (Arrange, Act, Assert).
Include:
1. Happy path test
2. Error handling test
3. Edge case tests (null, undefined, empty, boundary values)
4. Mock external dependencies (API calls, database)
Aim for >90% code coverage.
Test file location: Same directory as source, `.test.ts` extension.
# Optimize performance
- name: optimize
description: Performance optimization analysis
prompt: |
Analyze this code for performance bottlenecks:
**Algorithm Complexity**:
- Identify O(n²) or worse algorithms
- Suggest optimized approaches
**React Performance**:
- Unnecessary re-renders
- Missing memoization (useMemo, useCallback)
- Inefficient list rendering (keys, virtualization)
**Bundle Size**:
- Large imports (tree-shaking opportunities)
- Unused dependencies
**Database**:
- N+1 query problems
- Missing indexes
- Inefficient queries
For each issue:
1. Explain the bottleneck
2. Measure impact (time complexity, bundle size, etc.)
3. Provide optimized code
4. Include benchmarks or measurements
# Documentation generator
- name: docs
description: Generate comprehensive documentation
prompt: |
Generate documentation for this code following JSDoc standard:
**For Functions**:
```
{% endraw %}
typescript
/**
* Brief one-line description
*
* Detailed explanation of what the function does,
* including any important implementation details.
*
* @param paramName - Parameter description
* @returns Return value description
* @throws ErrorType - When and why this error is thrown
* @example
*
{% raw %}
```typescript
* const result = myFunction('example');
* console.log(result); // Output: ...
* ```
{% endraw %}
*/
{% raw %}
```
**For Components** (React):
Include props table, usage examples, accessibility notes.
**For APIs**:
Include endpoint, method, params, response format, error codes.
# Refactor legacy code
- name: refactor
description: Refactor to modern patterns
prompt: |
Refactor this code to modern best practices:
**TypeScript**:
- Add explicit types
- Remove `any` types
- Use strict null checks
**React**:
- Convert class components to functional
- Use hooks instead of lifecycle methods
- Server Components if applicable (Next.js)
**Async**:
- Replace `.then()` with async/await
- Add proper error handling
**Patterns**:
- Extract reusable logic
- Reduce complexity (split large functions)
- Apply SOLID principles
Provide:
1. Before/after code comparison
2. Explanation of improvements
3. Any breaking changes
4. Migration notes
# Explain complex code
- name: explain
description: Explain code in simple terms
prompt: |
Explain this code as if teaching a junior developer:
**Overview**: What does this code do? (1-2 sentences)
**Step-by-Step**: Walk through the logic line by line.
**Key Concepts**: Explain any advanced patterns or algorithms used.
**Gotchas**: Point out tricky parts or common mistakes.
**Related Code**: Mention where this is called from and what it calls.
Use analogies and simple language. Include diagrams if helpful.
Using Custom Prompts:
# In Continue.dev chat
/review # Runs review prompt on selected code
/test # Generates tests
/optimize # Performance analysis
/docs # Generates documentation
3.5 Advanced Model Settings
Temperature and Creativity:
models:
- name: Creative Writer
provider: anthropic
model: claude-3-5-sonnet-20241022
defaultCompletionOptions:
temperature: 0.9 # High: Creative, varied outputs
maxTokens: 4096
- name: Deterministic Coder
provider: openai
model: gpt-4o
defaultCompletionOptions:
temperature: 0.0 # Low: Consistent, predictable outputs
maxTokens: 4000
Token Management:
models:
- name: Claude 3.5
provider: anthropic
model: claude-3-5-sonnet-20241022
defaultCompletionOptions:
maxTokens: 4096 # Response limit
# Context window management
contextLength: 200000 # Claude's full context (200k tokens)
Response Quality Tuning:
models:
- name: GPT-4o Tuned
provider: openai
model: gpt-4o
defaultCompletionOptions:
temperature: 0.7
topP: 0.9 # Nucleus sampling (higher = more diverse)
presencePenalty: 0.1 # Encourage new topics
frequencyPenalty: 0.1 # Reduce repetition
maxTokens: 4000
Request Timeouts and Retries:
models:
- name: Claude 3.5
provider: anthropic
model: claude-3-5-sonnet-20241022
requestOptions:
timeout: 60000 # 60 second timeout
retries: 3 # Retry 3 times on failure
headers:
X-Request-ID: "continue-${timestamp}"
IV. Rules System Mastery
4.1 The Three Approaches to Rules
Continue.dev offers three distinct methods for providing instructions to AI:
Comparison Matrix:
| Approach | Complexity | Flexibility | Best For | Token Efficiency |
|---|---|---|---|---|
| YAML Inline Rules | Low | Low | 3-5 universal rules | Always loaded (low) |
| Markdown Rules Files | Medium | High | Project-specific, conditional | Conditional loading (high) |
| chatOptions Override | Low | Medium | Model-specific behavior | Always loaded (low) |
Decision Tree:
Do you need file-specific or language-specific rules?
├─ YES → Use Markdown Rules Files (.continue/rules/*.md)
└─ NO → Do you need model-specific behavior?
├─ YES → Use chatOptions.baseSystemMessage
└─ NO → Use YAML inline rules array
4.2 Markdown Rules Files (Recommended)
Directory Structure:
.continue/
└── rules/
├── 01-project-overview.md # Always apply
├── 02-typescript-standards.md # Apply to *.ts, *.tsx
├── 03-react-patterns.md # Apply to *.tsx, *.jsx
├── 04-backend-api.md # Apply to api/**/*
├── 05-testing-guide.md # Manual invocation
└── 06-security-checklist.md # Always apply
File Naming Conventions:
# ✅ RECOMMENDED: Numeric prefixes for ordering
01-core.md
02-frontend.md
03-backend.md
# ✅ ACCEPTABLE: Descriptive names
typescript-standards.md
react-component-patterns.md
# ❌ AVOID: Generic names
rules.md
standards.md
guidelines.md
Basic Markdown Rules File:
<!-- .continue/rules/02-typescript-standards.md -->
# TypeScript Coding Standards
## Type Safety Requirements
### Explicit Return Types
All functions MUST have explicit return types:
typescript
// ✅ CORRECT
export function calculateTotal(items: Item[]): number {
return items.reduce((sum, item) => sum + item.price, 0);
}
// ❌ WRONG - Implicit return type
export function calculateTotal(items: Item[]) {
return items.reduce((sum, item) => sum + item.price, 0);
}
### Avoid `any` Type
typescript
// ✅ CORRECT - Use unknown + type guards
function processData(data: unknown): ProcessedData {
if (!isValidData(data)) {
throw new ValidationError('Invalid data shape');
}
return transformData(data);
}
// Helper type guard
function isValidData(data: unknown): data is RawData {
return (
typeof data === 'object' &&
data !== null &&
'id' in data &&
'name' in data
);
}
// ❌ WRONG - Using any
function processData(data: any) {
return data.someProperty; // No type safety!
}
## Error Handling Pattern
ALL async operations use Result<T> type:
typescript
type Result =
| { success: true; data: T }
| { success: false; error: string };
async function fetchUser(id: string): Promise> {
try {
const user = await db.query.users.findFirst({
where: eq(users.id, id)
});
if (!user) {
return { success: false, error: 'User not found' };
}
return { success: true, data: user };
} catch (error) {
logger.error('fetchUser failed', { id, error });
return { success: false, error: 'Database error occurred' };
}
}
## Import Organization
typescript
// 1. External dependencies
import { useState, useEffect } from 'react';
import { z } from 'zod';
// 2. Internal packages
import { Button } from '@/components/ui/button';
import { trpc } from '@/lib/trpc/client';
// 3. Relative imports
import { UserCard } from './UserCard';
import type { UserCardProps } from './types';
// 4. Styles
import './styles.css';
4.3 YAML Frontmatter Specifications
Complete Frontmatter Schema:
---
name: string # Rule name (required)
description: string # When to apply this rule (optional)
globs: string | array # File patterns (optional)
alwaysApply: boolean # Force inclusion (optional, default: false)
tags: array , Categorization (optional)
regex: string # Advanced pattern matching (optional)
priority: number # Loading order (optional)
---
# Rule content starts here
Frontmatter Field Details:
name: Human-readable identifier
---
name: TypeScript Strict Mode Standards
---
description: Explains when AI should use this rule
---
name: React Component Patterns
description: Apply when creating or modifying React components (*.tsx, *.jsx files)
---
globs: File pattern matching (gitignore syntax)
---
name: TypeScript Rules
globs: "**/*.{ts,tsx}"
---
# OR: Array format
---
name: TypeScript Rules
globs:
- "**/*.ts"
- "**/*.tsx"
- "!**/*.test.ts" # Exclude test files
---
Glob Pattern Examples:
| Pattern | Matches | Doesn't Match |
|---|---|---|
**/*.ts |
src/app.ts, lib/utils.ts
|
src/app.tsx, app.js
|
**/*.{ts,tsx} |
app.ts, Button.tsx
|
app.js, style.css
|
src/** |
src/app.ts, src/lib/utils.ts
|
tests/app.test.ts |
!**/*.test.ts |
Excludes all test files | - |
api/**/*.ts |
api/users.ts, api/routes/auth.ts
|
src/utils.ts |
alwaysApply: Force rule inclusion regardless of context
---
name: Security Checklist
alwaysApply: true
---
# This rule is ALWAYS included in every AI request
tags: Organize rules by category
---
name: React Hooks Patterns
tags: [frontend, react, hooks, patterns]
---
regex: Advanced pattern matching
---
name: Controller File Standards
regex: ".*Controller\\.ts$"
---
# Applies to any file ending with "Controller.ts"
4.4 Rule Activation Patterns
Pattern 1: Always-On Rules
---
name: Project Core Standards
alwaysApply: true
---
# Core Standards
These rules apply to EVERY request:
1. Never commit secrets or API keys
2. Always validate user input
3. Use TypeScript strict mode
4. Include error handling
5. Write tests for new features
Pattern 2: File-Type-Specific Rules
---
name: React Component Standards
globs: "**/*.{tsx,jsx}"
alwaysApply: false
---
# React Component Rules
These rules apply ONLY when working with React component files.
## Component Structure
- Functional components only
- Named exports (not default)
- Props interface above component
[...]
Pattern 3: Directory-Specific Rules
---
name: API Endpoint Standards
globs: "src/api/**/*.ts"
---
# API Development Rules
These apply to files in `src/api/` directory.
## tRPC Procedures
[...]
Pattern 4: Manual Invocation Rules
---
name: Comprehensive Testing Guide
# No globs, no alwaysApply = Manual only
---
# Testing Guide
Invoke this rule when writing tests: @testing-guide
## Test Structure
[...]
Pattern 5: Multi-Condition Rules
---
name: Frontend TypeScript Standards
globs:
- "src/components/**/*.tsx"
- "src/pages/**/*.tsx"
- "app/**/*.tsx"
tags: [frontend, typescript, react]
---
# Frontend TypeScript Rules
Applies to TypeScript files in component, page, or app directories.
4.5 Rule Loading Order and Precedence
Loading Sequence:
1. Hub Assistant Rules (if using Hub config)
↓
2. Referenced Hub Rules (via uses: in config)
↓
3. Local Workspace Rules (.continue/rules/)
├─ Files loaded alphabetically
├─ 01-core.md
├─ 02-frontend.md
└─ 03-backend.md
↓
4. Global User Rules (~/.continue/rules/)
├─ personal-style.md
└─ preferred-patterns.md
↓
5. Model System Message (config.yaml chatOptions)
↓
6. Continue.dev Defaults
Priority Resolution:
When multiple rules conflict:
# Scenario: Two rules about state management
# Rule A (01-core.md, alwaysApply: true):
"Use Redux Toolkit for global state"
# Rule B (02-frontend.md, globs: "**/*.tsx"):
"Use Zustand for global state (NOT Redux)"
# Result: Both are loaded, AI sees contradiction
# Resolution: More specific rule (B) should take precedence
Best Practice: Explicit Override
---
name: Frontend State Management
globs: "src/**/*.tsx"
---
# State Management (OVERRIDES General Rules)
**IMPORTANT**: This rule OVERRIDES any general state management guidance.
For this project's frontend:
- ✅ USE: Zustand for global client state
- ❌ AVOID: Redux (legacy, being phased out)
- ✅ USE: TanStack Query for server state
Rationale: Migrating from Redux to Zustand (see ADR-015)
File Naming for Priority:
# Lower numbers load first (act as defaults)
01-core-standards.md # Loads first
02-typescript.md # Loads second
03-frontend-overrides.md # Loads third (can override earlier rules)
# Alternative: Use descriptive names + explicit override markers
core-standards.md
typescript-standards.md
frontend-standards-OVERRIDES.md
Testing Rule Precedence:
Ask AI in Continue.dev chat:
User: "What state management solution should I use for global client state?"
Expected Response (with proper precedence):
"Use Zustand for global client state (from frontend-standards).
Note: General rules mentioned Redux, but frontend-specific rules override this."
V. Production-Ready Examples
5.1 TypeScript/React Full-Stack Project
Project Structure:
my-fullstack-app/
├── .continue/
│ ├── config.yaml
│ └── rules/
│ ├── 01-project-overview.md
│ ├── 02-typescript-standards.md
│ ├── 03-react-patterns.md
│ ├── 04-backend-api.md
│ └── 05-testing-strategy.md
├── app/ # Next.js App Router
├── components/
├── lib/
│ ├── api/ # tRPC routers
│ └── db/ # Drizzle ORM
└── tests/
config.yaml:
name: fullstack-typescript-config
version: 1.0.0
schema: v1
models:
# Primary: Claude for complex reasoning
- name: Claude 3.5 Sonnet
provider: anthropic
model: claude-3-5-sonnet-20241022
apiKey: ${{ secrets.ANTHROPIC_API_KEY }}
roles: [chat, edit, apply]
defaultCompletionOptions:
temperature: 0.7
maxTokens: 4096
chatOptions:
baseSystemMessage: |
You are an expert full-stack TypeScript engineer.
Focus on type safety, performance, and maintainability.
# Fast: GPT-4o Mini for autocomplete
- name: GPT-4o Mini
provider: openai
model: gpt-4o-mini
apiKey: ${{ secrets.OPENAI_API_KEY }}
roles: [autocomplete, summarize]
defaultCompletionOptions:
temperature: 0.3
maxTokens: 1000
context:
- provider: code
- provider: codebase
params:
nRetrieve: 30
nFinal: 5
- provider: diff
- provider: problems
- provider: terminal
prompts:
- name: test
description: Generate comprehensive tests
prompt: |
Generate tests using Vitest and Testing Library.
Include: happy path, error cases, edge cases.
Aim for >90% coverage.
- name: review
description: Code review for standards compliance
prompt: |
Review for:
- Type safety (no any, explicit returns)
- Error handling (Result<T> pattern)
- Security (input validation, SQL injection)
- Performance (algorithm complexity, re-renders)
01-project-overview.md:
---
name: Project Overview
alwaysApply: true
---
# Full-Stack E-Commerce Project
## Tech Stack
- **Frontend**: Next.js 15 (App Router), React 19, TypeScript 5.4
- **Styling**: Tailwind CSS 4.0, shadcn/ui
- **Backend**: tRPC 11, Drizzle ORM, PostgreSQL 16
- **Auth**: NextAuth.js v5
- **State**: TanStack Query, Zustand
- **Testing**: Vitest, Playwright
- **Monorepo**: Turborepo
## Project Structure
app/ # Next.js App Router pages
components/ui/ # shadcn/ui primitives
components/features/ # Feature-specific components
lib/api/ # tRPC routers
lib/db/ # Drizzle schema
## Key Principles
1. Server Components by default
2. Type-safe APIs via tRPC
3. Result<T> for error handling
4. 80% test coverage minimum
5. Functional programming patterns
02-typescript-standards.md:
---
name: TypeScript Standards
globs: "**/*.{ts,tsx}"
tags: [typescript, type-safety]
---
# TypeScript Standards
## Type Annotations
typescript
// ✅ REQUIRED: Explicit return types
export function calculateTotal(items: Item[]): number {
return items.reduce((sum, item) => sum + item.price, 0);
}
// ❌ FORBIDDEN: Implicit types
export function calculateTotal(items: Item[]) {
return items.reduce((sum, item) => sum + item.price, 0);
}
## Error Handling
typescript
type Result =
| { success: true; data: T }
| { success: false; error: string };
async function fetchUser(id: string): Promise> {
try {
const user = await db.query.users.findFirst({
where: eq(users.id, id)
});
if (!user) {
return { success: false, error: 'User not found' };
}
return { success: true, data: user };
} catch (error) {
logger.error('fetchUser failed', { id, error });
return { success: false, error: 'Database error' };
}
}
## Zod Validation
typescript
import { z } from 'zod';
// Define schema
const UserSchema = z.object({
email: z.string().email(),
name: z.string().min(2),
age: z.number().min(18).optional(),
});
// Infer type
type User = z.infer;
// Validate
const user = UserSchema.parse(untrustedData);
03-react-patterns.md:
---
name: React Patterns
globs: "**/*.{tsx,jsx}"
tags: [react, frontend, components]
---
# React Patterns
## Server vs Client Components
### Server Component (Default)
tsx
// No directive needed for Server Components
async function UserProfilePage({ params }: { params: { id: string } }) {
// Can fetch data directly
const user = await db.query.users.findFirst({
where: eq(users.id, params.id)
});
return ;
}
### Client Component (Only When Needed)
tsx
'use client';
import { useState } from 'react';
// Add 'use client' ONLY when using:
// - Hooks (useState, useEffect, useContext)
// - Event handlers (onClick, onChange)
// - Browser APIs (window, localStorage)
export function InteractiveCounter() {
const [count, setCount] = useState(0);
return (
setCount(count + 1)}>
Count: {count}
);
}
## State Management
| Use Case | Solution | Example |
|----------|----------|---------|
| Server data | TanStack Query | `useQuery('users', fetchUsers)` |
| Form state | React Hook Form | `useForm()` |
| Local UI state | useState | `const [open, setOpen] = useState(false)` |
| Global client | Zustand | `const user = useUserStore(s => s.user)` |
| URL params | useSearchParams | `const [search] = useSearchParams()` |
## Component Size
- Maximum 200 lines per component
- Extract sub-components when exceeded
- Use composition over props drilling
04-backend-api.md:
---
name: Backend API Standards
globs: "lib/api/**/*.ts"
tags: [backend, trpc, api]
---
# Backend API Standards
## tRPC Procedure Structure
typescript
import { z } from 'zod';
import { createTRPCRouter, protectedProcedure, publicProcedure } from '@/lib/api/trpc';
export const userRouter = createTRPCRouter({
// Public procedure
getById: publicProcedure
.input(z.object({ id: z.string().uuid() }))
.query(async ({ input, ctx }) => {
const user = await ctx.db.query.users.findFirst({
where: eq(users.id, input.id)
});
if (!user) {
throw new TRPCError({
code: 'NOT_FOUND',
message: 'User not found',
});
}
return user;
}),
// Protected procedure (requires auth)
update: protectedProcedure
.input(z.object({
id: z.string().uuid(),
name: z.string().min(2).optional(),
email: z.string().email().optional(),
}))
.mutation(async ({ input, ctx }) => {
// ctx.user available from protectedProcedure
if (ctx.user.id !== input.id) {
throw new TRPCError({
code: 'FORBIDDEN',
message: 'Cannot update other users',
});
}
const updated = await ctx.db
.update(users)
.set(input)
.where(eq(users.id, input.id))
.returning();
return updated[0];
}),
});
## Database Patterns (Drizzle)
### Eager Loading
typescript
// ✅ CORRECT: Fetch relations in one query
const user = await db.query.users.findFirst({
where: eq(users.id, id),
with: {
posts: true,
profile: true,
},
});
// ❌ WRONG: N+1 queries
const user = await db.query.users.findFirst({ where: eq(users.id, id) });
const posts = await db.query.posts.findMany({ where: eq(posts.userId, id) });
### Transactions
typescript
// ✅ Atomic operations
await db.transaction(async (tx) => {
const user = await tx.insert(users).values(userData).returning();
await tx.insert(profiles).values({ userId: user[0].id, ...profileData });
});
5.2 Python FastAPI Backend
config.yaml:
models:
- name: Claude 3.5 Sonnet
provider: anthropic
model: claude-3-5-sonnet-20241022
chatOptions:
baseSystemMessage: |
You are an expert Python developer specializing in FastAPI.
Focus on type hints, async patterns, and Pydantic validation.
prompts:
- name: test
description: Generate Pytest cases
prompt: |
Generate tests using Pytest and AsyncIO.
Use fixtures for database sessions.
Mock external services.
01-python-standards.md:
---
name: Python Standards
globs: "**/*.py"
---
# Python Coding Standards
## Type Hints
All functions must be fully typed:
python
✅ CORRECT
async def get_user(user_id: str) -> Optional[User]:
...
❌ WRONG
async def get_user(user_id):
...
## Pydantic Models
Use Pydantic for data validation:
python
from pydantic import BaseModel, EmailStr
class UserCreate(BaseModel):
email: EmailStr
username: str
age: int | None = None
## Async Database (SQLAlchemy)
python
✅ Async session context manager
async with AsyncSession(engine) as session:
stmt = select(User).where(User.id == user_id)
result = await session.execute(stmt)
user = result.scalar_one_or_none()
## Dependency Injection
python
✅ FastAPI Dependencies
async def get_db() -> AsyncGenerator[AsyncSession, None]:
async with AsyncSessionLocal() as session:
yield session
@router.get("/users/{id}")
async def read_user(id: int, db: AsyncSession = Depends(get_db)):
...
5.3 Monorepo Configuration
For monorepos (Turborepo, Nx, Lerna), structure rules by package:
my-monorepo/
├── .continue/
│ └── rules/
│ ├── 00-monorepo.md # Global monorepo rules
│ ├── 01-frontend-app.md # apps/web rules
│ ├── 02-backend-api.md # apps/api rules
│ └── 03-shared-packages.md # packages/* rules
00-monorepo.md:
---
name: Monorepo Structure
alwaysApply: true
---
# Monorepo Guidelines
## Package Management
- Use **pnpm** workspaces
- Run commands from root: `pnpm --filter <package> <command>`
- Shared dependencies in root `package.json`
## Structure
- `apps/`: Deployable applications
- `packages/`: Shared libraries (ui, database, config)
- `tooling/`: Build tools and configs
## Imports
Use workspace protocol:
json
"dependencies": {
"@repo/ui": "workspace:",
"@repo/database": "workspace:"
}
01-frontend-app.md:
---
name: Frontend App Rules
globs: "apps/web/**/*.{ts,tsx}"
---
# Frontend App Rules
- Import shared UI from `@repo/ui`
- Import types from `@repo/types`
- Use Next.js App Router
5.4 Multi-Language Projects
Strategy: Separate Rule Files by Extension
<!-- .continue/rules/rust.md -->
---
name: Rust Standards
globs: "**/*.rs"
---
# Rust Guidelines
- Use `Result<T, E>` for errors (no panics)
- Prefer `impl Trait` over generics where possible
- Use `clippy` lints
<!-- .continue/rules/python.md -->
---
name: Python Standards
globs: "**/*.py"
---
# Python Guidelines
- Use `poetry` for dependency management
- Type hints mandatory (`mypy --strict`)
- `ruff` for linting/formatting
<!-- .continue/rules/typescript.md -->
---
name: TypeScript Standards
globs: "**/*.{ts,tsx}"
---
# TypeScript Guidelines
- Strict mode
- `zod` for runtime validation
VI. Advanced Techniques
6.1 Hub vs. Local Configuration
Local Config (Recommended for Individuals):
-
File:
~/.continue/config.yaml - Pros: Private, offline-capable, full control
- Cons: Harder to sync across devices
Hub Config (Recommended for Teams):
- Platform: Continue Hub (cloud)
- Pros: Centralized management, team sharing, pre-built assistants
- Cons: Requires login, dependency on cloud
Hybrid Strategy:
Use Local Config that references Hub Rules:
# config.yaml
name: Hybrid Config
models:
- name: Claude 3.5
provider: anthropic
model: claude-3-5-sonnet-20241022
rules:
# Reference team rules hosted on Hub
- uses: continuedev/team-security-standards
- uses: continuedev/react-best-practices
# Local overrides
- uses: ./rules/local-overrides.md
6.2 Conditional Rule Loading
Use sophisticated glob patterns for context-aware rules:
<!-- Test Files Only -->
---
name: Testing Standards
globs: ["**/*.test.ts", "**/*.spec.ts", "**/tests/**"]
---
<!-- API Routes Only -->
---
name: API Standards
globs: ["app/api/**", "lib/api/**", "server/routes/**"]
---
<!-- Configuration Files Only -->
---
name: Config Standards
globs: ["*.config.js", "*.json", ".env*"]
---
6.3 Multi-Model Optimization
Route tasks to the best model:
| Task | Model | Why | Config Role |
|---|---|---|---|
| Complex Refactoring | Claude 3.5 Sonnet | Huge context, strong logic |
edit, chat
|
| Quick Questions | GPT-4o | Fast, reliable | chat |
| Autocomplete | GPT-4o Mini / Local | Ultra-low latency | autocomplete |
| Summarization | GPT-4o Mini | Cheap, sufficient | summarize |
Config Implementation:
models:
- name: Claude 3.5 (Primary)
provider: anthropic
model: claude-3-5-sonnet-20241022
roles: [chat, edit, apply]
- name: GPT-4o Mini (Background)
provider: openai
model: gpt-4o-mini
roles: [autocomplete, summarize]
6.4 Team Collaboration Strategies
1. Commit the Rules Directory
Ensure .continue/rules/ is tracked in git. Add to .gitignore:
# Track shared rules
! .continue/rules/
# Ignore local config (API keys)
.continue/config.yaml
.continue/config.json
2. Use a Config Template
Create config.yaml.example for new team members:
# .continue/config.yaml.example
models:
- name: Claude 3.5
provider: anthropic
model: claude-3-5-sonnet-20241022
apiKey: YOUR_KEY_HERE # Replace this
3. Shared Prompts Library
Standardize team workflows (e.g., code review format, testing standards) via shared prompts in a committed config or rules file.
VII. Troubleshooting and Optimization
7.1 Common Configuration Issues
| Symptom | Cause | Solution |
|---|---|---|
| "Model not found" | Typo in model string | Check provider docs for exact model ID |
| "Authentication failed" | Invalid API key | Verify key, check environment variable loading |
| YAML parsing error | Tab indentation | Convert tabs to spaces (2 or 4) |
| Settings ignored | Config location | Ensure editing correct file (~/.continue vs project .continue) |
7.2 Rules Not Being Applied
Diagnostic Checklist:
-
Check File Location: Is rule in
.continue/rules/? -
Check Frontmatter: Is YAML syntax valid? (
---separators) -
Check Globs: Does glob pattern match current file?
- Try
alwaysApply: trueto test
- Try
-
Reload Window: VS Code command
Developer: Reload Window - Check Logs: Output panel → "Continue" channel
7.3 Performance Optimization
1. Reduce alwaysApply Rules
Too many always-on rules consume context window and slow down responses. Use globs to scope rules.
2. Optimize Context Providers
- Limit
codebaseretrieval (nRetrieve: 20) - Disable unused providers
- Use
rerankingfor better relevance
3. Use Faster Models for Autocomplete
Switch autocomplete role to a smaller model (e.g., qwen2.5-coder:1.5b via Ollama) for <50ms latency.
7.4 Debugging Tools and Techniques
Verbose Logging:
Enable in VS Code settings to see raw prompts and context:
"continue.loggingLevel": "verbose"
Inspect Prompt:
In chat, use command:
/config -> Shows currently loaded configuration and rules
Test Rule Injection:
Ask AI: "Repeat the system message instructions starting with 'TypeScript Standards'" to verify injection.
This guide covers everything needed to deploy Continue.dev effectively, from single-user setups to enterprise team configurations. By separating structure (config.yaml) from instruction (rules/*.md), you create a maintainable, scalable AI coding environment.
Top comments (0)