-
Notifications
You must be signed in to change notification settings - Fork 59
Pattern Categories
geoffrey fernald edited this page Jan 28, 2026
·
2 revisions
Drift detects patterns across 15 categories covering all aspects of modern software development.
| Category | Description | Example Patterns |
|---|---|---|
api |
REST endpoints, GraphQL | Route handlers, response format |
auth |
Authentication/authorization | Middleware, guards, RBAC |
security |
Security patterns | Validation, sanitization, CSRF |
errors |
Error handling | Try/catch, Result types |
logging |
Observability | Structured logging, correlation |
data-access |
Database queries | ORM patterns, repositories |
config |
Configuration | Environment vars, feature flags |
testing |
Test patterns | Mocks, fixtures, setup |
performance |
Optimization | Caching, memoization |
components |
UI components | React, Vue, Angular |
styling |
CSS patterns | Tailwind, CSS-in-JS |
structural |
Code organization | Modules, exports, naming |
types |
Type definitions | Interfaces, schemas |
accessibility |
A11y patterns | ARIA, semantic HTML |
documentation |
Doc patterns | JSDoc, docstrings |
Patterns for HTTP endpoints and API design.
- HTTP Methods β GET, POST, PUT, DELETE usage
- Route Structure β Path patterns, parameters
- Response Envelopes β Consistent response format
- Pagination β Cursor vs offset, page size
- Retry Patterns β Exponential backoff, circuit breaker
- Error Formats β Error response structure
- Client Patterns β Fetch, Axios, custom clients
// Detected pattern: REST controller with consistent structure
@Controller('/api/v1/users')
export class UsersController {
@Get('/:id')
async getUser(@Param('id') id: string) {
return { data: user, meta: { timestamp: Date.now() } };
}
}- POST for read operations
- GET for mutations
- Inconsistent response format
- Missing pagination on list endpoints
Patterns for authentication and authorization.
- Middleware Usage β Auth middleware placement
- Permission Checks β Role-based access control
- Token Handling β JWT, session tokens
- Audit Logging β Auth event tracking
- Resource Ownership β User-scoped data access
// Detected pattern: Auth middleware before handlers
@Controller('/api/admin')
@UseGuards(AuthGuard, RoleGuard('admin'))
export class AdminController {
// All routes require auth + admin role
}- Unprotected sensitive endpoints
- Missing role checks
- Inconsistent auth middleware
Patterns for application security.
- Input Sanitization β XSS prevention
- CSRF Protection β Token validation
- SQL Injection Prevention β Parameterized queries
- Rate Limiting β Request throttling
- Secret Management β Environment variables
- CSP Headers β Content Security Policy
// Detected pattern: Input validation before processing
@Post('/users')
@UsePipes(ValidationPipe)
async createUser(@Body() dto: CreateUserDto) {
// dto is validated and sanitized
}- Raw SQL with string concatenation
- Missing input validation
- Hardcoded secrets
Patterns for error handling.
- Try-Catch Placement β Error boundary locations
- Error Propagation β How errors flow up
- Exception Hierarchy β Custom error classes
- Error Logging β What gets logged
- Circuit Breaker β Failure isolation
- Async Errors β Promise rejection handling
// Detected pattern: Consistent error handling
try {
const result = await service.process();
return result;
} catch (error) {
logger.error('Processing failed', { error, context });
throw new AppError('PROCESSING_FAILED', error);
}- Empty catch blocks
- Swallowed errors
- Inconsistent error types
Patterns for observability.
- Log Levels β DEBUG, INFO, WARN, ERROR usage
- Structured Format β JSON logging
- Correlation IDs β Request tracing
- Context Fields β What's included in logs
- PII Redaction β Sensitive data masking
- Health Checks β Liveness/readiness probes
- Metrics β Custom metrics collection
// Detected pattern: Structured logging with context
logger.info('User created', {
userId: user.id,
email: '[REDACTED]',
correlationId: req.correlationId,
});- Console.log in production code
- Missing correlation IDs
- PII in logs
Patterns for database operations.
- Repository Pattern β Data access abstraction
- Query Patterns β ORM usage
- N+1 Detection β Inefficient queries
- DTO Patterns β Data transfer objects
- Transaction Patterns β ACID compliance
- Connection Pooling β Database connections
| Language | ORMs |
|---|---|
| TypeScript | Prisma, TypeORM, Drizzle, Sequelize, Mongoose |
| Python | Django ORM, SQLAlchemy, Tortoise |
| Java | JPA, Hibernate, MyBatis |
| C# | Entity Framework, Dapper |
| PHP | Eloquent, Doctrine |
| Go | GORM, sqlx, Ent |
| Rust | SQLx, Diesel, SeaORM |
// Detected pattern: Repository with consistent methods
class UserRepository {
async findById(id: string): Promise<User | null> {
return this.prisma.user.findUnique({ where: { id } });
}
async create(data: CreateUserDto): Promise<User> {
return this.prisma.user.create({ data });
}
}- Raw SQL without parameterization
- N+1 query patterns
- Missing transactions for multi-step operations
Patterns for configuration management.
- Environment Detection β Dev/staging/prod
- Feature Flags β Toggle functionality
- Default Values β Fallback configuration
- Required vs Optional β Mandatory settings
- Validation β Config validation
- Naming Conventions β ENV_VAR naming
// Detected pattern: Validated config with defaults
const config = {
port: parseInt(process.env.PORT ?? '3000'),
database: {
url: requireEnv('DATABASE_URL'),
poolSize: parseInt(process.env.DB_POOL_SIZE ?? '10'),
},
};- Missing required environment variables
- Hardcoded configuration
- Inconsistent naming
Patterns for test code.
- File Naming β Test file conventions
- Describe Naming β Test suite structure
- Fixture Patterns β Test data setup
- Mock Patterns β Mocking strategies
- Setup/Teardown β Before/after hooks
- Test Structure β Arrange-Act-Assert
- Co-location β Tests near source
| Language | Frameworks |
|---|---|
| TypeScript | Jest, Vitest, Mocha |
| Python | pytest, unittest |
| Java | JUnit, TestNG |
| C# | xUnit, NUnit, MSTest |
| PHP | PHPUnit, Pest |
| Go | testing, testify |
| Rust | rust-test, tokio-test |
| C++ | Google Test, Catch2 |
// Detected pattern: Consistent test structure
describe('UserService', () => {
let service: UserService;
let mockRepo: MockUserRepository;
beforeEach(() => {
mockRepo = createMockUserRepository();
service = new UserService(mockRepo);
});
it('should create user', async () => {
const result = await service.create(userData);
expect(result).toMatchObject(expectedUser);
});
});- Tests without assertions
- Inconsistent naming
- Missing setup/teardown
Patterns for optimization.
- Caching Patterns β Cache usage and invalidation
- Code Splitting β Dynamic imports
- Lazy Loading β Deferred loading
- Memoization β Computed value caching
- Debounce/Throttle β Rate limiting
- Bundle Size β Import optimization
// Detected pattern: Memoized expensive computation
const expensiveResult = useMemo(() => {
return computeExpensiveValue(data);
}, [data]);- Missing memoization for expensive operations
- Unnecessary re-renders
- Large bundle imports
Patterns for UI components.
- Props Patterns β Prop types and defaults
- State Patterns β State management
- Composition β Component composition
- Ref Forwarding β Ref handling
- Near-Duplicates β Similar components
- Modal Patterns β Dialog handling
// Detected pattern: Consistent component structure
interface ButtonProps {
variant: 'primary' | 'secondary';
size?: 'sm' | 'md' | 'lg';
children: React.ReactNode;
onClick?: () => void;
}
export const Button: React.FC<ButtonProps> = ({
variant,
size = 'md',
children,
onClick,
}) => {
return (
<button className={cn(styles[variant], styles[size])} onClick={onClick}>
{children}
</button>
);
};- Missing prop types
- Inconsistent component structure
- Duplicate components
Patterns for CSS and styling.
- Class Naming β BEM, utility-first
- Design Tokens β Color, spacing, typography
- Responsive Patterns β Breakpoints, media queries
- Spacing Scale β Consistent spacing
- Typography β Font usage
- Color Usage β Color palette
- Z-Index Scale β Layering
- Tailwind Patterns β Utility class usage
// Detected pattern: Tailwind with consistent spacing
<div className="p-4 md:p-6 lg:p-8 space-y-4">
<h1 className="text-2xl font-bold text-gray-900">Title</h1>
<p className="text-gray-600">Description</p>
</div>- Hardcoded colors
- Inconsistent spacing
- Missing responsive styles
Patterns for code organization.
- File Naming β Naming conventions
- Directory Structure β Folder organization
- Barrel Exports β Index files
- Circular Dependencies β Import cycles
- Co-location β Related files together
- Import Ordering β Import organization
- Module Boundaries β Package structure
// Detected pattern: Feature-based structure
src/
βββ features/
β βββ users/
β β βββ components/
β β βββ hooks/
β β βββ services/
β β βββ index.ts
β βββ orders/
β βββ components/
β βββ hooks/
β βββ services/
β βββ index.ts
βββ shared/
βββ components/
βββ utils/
- Inconsistent naming
- Circular imports
- Deep nesting
Patterns for type definitions.
- Any Usage β Type safety violations
- Interface vs Type β Declaration style
- Generic Patterns β Generic usage
- Naming Conventions β Type naming
- Type Assertions β Cast usage
- Utility Types β Built-in type usage
// Detected pattern: Consistent interface naming
interface User {
id: string;
email: string;
createdAt: Date;
}
interface CreateUserDto {
email: string;
password: string;
}
type UserWithPosts = User & { posts: Post[] };-
anytype usage - Inconsistent naming
- Missing type annotations
Patterns for accessibility.
- Alt Text β Image descriptions
- ARIA Roles β Semantic roles
- Keyboard Navigation β Focus handling
- Focus Management β Focus trapping
- Heading Hierarchy β H1-H6 structure
- Semantic HTML β Proper elements
// Detected pattern: Accessible button
<button
aria-label="Close dialog"
onClick={onClose}
onKeyDown={(e) => e.key === 'Escape' && onClose()}
>
<CloseIcon aria-hidden="true" />
</button>- Missing alt text
- Incorrect heading hierarchy
- Missing ARIA labels
Patterns for code documentation.
- JSDoc Patterns β Function documentation
- README Structure β Project documentation
- Deprecation β Deprecated code marking
- Example Code β Usage examples
- TODO Patterns β Task tracking
// Detected pattern: Consistent JSDoc
/**
* Creates a new user in the system.
*
* @param data - User creation data
* @returns The created user
* @throws {ValidationError} If data is invalid
* @example
* const user = await createUser({ email: 'test@example.com' });
*/
async function createUser(data: CreateUserDto): Promise<User> {
// ...
}- Missing documentation on public APIs
- Outdated documentation
- Missing examples
Each pattern has a confidence score (0.0-1.0):
| Score | Level | Meaning |
|---|---|---|
| 0.9-1.0 | High | Strongly established, consistent |
| 0.7-0.9 | Medium | Well-established, some variation |
| 0.5-0.7 | Low | Emerging, review recommended |
| <0.5 | Uncertain | Insufficient data, may be noise |
Confidence is calculated from:
- Frequency β How often the pattern appears
- Consistency β How uniform the pattern is
- Spread β How many files contain it
- Age β How long it's existed
Discovery β Discovered β Approved/Ignored β Enforcement
- Discovered β Auto-detected during scan
- Approved β User confirms as "how we do things"
- Ignored β User marks as not relevant
- Enforcement β Approved patterns flag violations
See Architecture for more details on the pattern system.
- Cortex V2 Overview
- Memory Setup Wizard
- Memory CLI
- Universal Memory Types
- Learning System
- Token Efficiency
- Causal Graphs
- Code Generation
- Predictive Retrieval
- Architecture
- Call Graph Analysis
- Impact Analysis
- Security Analysis
- Data Boundaries
- Test Topology
- Coupling Analysis
- Error Handling Analysis
- Wrappers Detection
- Environment Variables
- Constants Analysis
- Styling DNA
- Constraints
- Contracts
- Decision Mining
- Speculative Execution
- Watch Mode
- Trends Analysis
- Projects Management
- Package Context
- Monorepo Support
- Reports & Export
- Dashboard
- 10 Languages
- 21 Frameworks
- 16 ORMs
- 400+ Detectors
- 50+ MCP Tools
- 60+ CLI Commands
- 23 Memory Types