agent rules
Concise directives you can add to your CLAUDE.md or agent config files. Each rule shapes how your AI agent writes and reviews code.
Code Quality 20
Keep Files Short
Limit file length to maintain readability and focus
Single Responsibility Functions
Each function should do exactly one thing
Meaningful Names
Use descriptive variable and function names that reveal intent
No Magic Numbers
Replace magic numbers and strings with named constants
No Dead Code
Remove unused code instead of commenting it out
Don't Repeat Yourself
Extract shared logic when you see the same pattern three times
Early Returns
Use early returns to reduce nesting depth
Consistent Code Style
Follow the existing code style and patterns in the project
No Abbreviations
Avoid abbreviations in identifiers unless they are universally understood
Small Functions
Keep functions under 25 lines to maintain readability
No Nested Ternaries
Avoid nested ternary expressions for readability
Explicit Over Implicit
Prefer explicit code over clever implicit behavior
No Premature Abstraction
Don't create abstractions until you have three concrete use cases
Guard Clauses
Use guard clauses instead of deeply nested conditionals
Immutable by Default
Prefer const and readonly; mutate only when necessary
No Side Effects
Keep functions pure when possible
Limit Parameters
Functions should take no more than 3 parameters
Boolean Naming
Name booleans as questions using is, has, can, or should prefixes
No Commented-Out Code
Delete commented-out code; git preserves history
Consistent Return Types
Functions should consistently return the same type
Architecture 15
Separation of Concerns
Separate business logic from I/O and presentation
Dependency Injection
Inject dependencies instead of importing them directly
Interface Boundaries
Define clear interfaces between modules
Feature Folders
Organize code by feature, not by file type
No Circular Dependencies
Avoid circular dependencies between modules
Thin Controllers
Keep route handlers thin; delegate to service functions
Config from Environment
Read configuration from environment variables, never hardcode
API Versioning
Version APIs from the start to enable non-breaking changes
Clear Layers
Maintain clear architectural layers: routes, services, data
No God Objects
Break large classes or modules into focused, smaller units
Encapsulate Implementation
Keep implementation details private; expose minimal interfaces
Colocate Related Code
Keep related code close together in the file system
Domain Modeling
Model the domain with explicit types rather than primitive values
Stateless Services
Keep service functions stateless when possible
Limit Module Exports
Only export what consumers actually need
Testing 15
Test Behavior, Not Implementation
Test outcomes and behavior, not internal implementation details
Arrange-Act-Assert
Structure tests with clear arrange, act, and assert sections
Descriptive Test Names
Name tests to describe the expected behavior
Independent Tests
Each test must pass when run in isolation
Test Edge Cases
Always test boundary conditions, empty inputs, and error paths
Integration Over Mocks
Prefer integration tests over mocking internal modules
One Concept Per Test
Each test should verify one logical concept
Test Public API
Test through public interfaces, not private internals
No Flaky Tests
Fix or remove flaky tests immediately
Test Error Paths
Test failure scenarios as thoroughly as success paths
Realistic Test Data
Use realistic data in tests, not placeholder values
Snapshot Tests Sparingly
Use snapshot tests sparingly; prefer explicit assertions
Test Before Refactoring
Add tests before refactoring code that lacks coverage
Fast Unit Tests
Unit tests should run in under 100ms each
Test File Convention
Follow a consistent test file naming and location convention
Security 12
Validate All Input
Validate and sanitize all user input at system boundaries
No Hardcoded Secrets
Never hardcode API keys, passwords, or tokens in source code
Parameterized Queries
Use parameterized queries to prevent SQL injection
Escape Output
Escape all dynamic output to prevent XSS attacks
Least Privilege
Grant minimum necessary permissions to users and services
Auth Every Endpoint
Verify authentication and authorization on every endpoint
No Sensitive Data in Logs
Never log passwords, tokens, PII, or other sensitive data
Secure Defaults
Default to the most secure configuration option
CSRF Protection
Include CSRF protection on all state-changing endpoints
Audit Dependencies
Regularly audit dependencies for known vulnerabilities
Rate Limiting
Apply rate limiting to all public-facing endpoints
HTTPS Only
Enforce HTTPS everywhere; reject plain HTTP
Git & Version Control 12
Conventional Commits
Use conventional commit messages with type prefixes
Atomic Commits
Each commit should be a single, complete logical change
No Force Push
Never force-push to shared branches
Branch Naming Convention
Use descriptive branch names with type prefixes
Small Pull Requests
Keep pull requests small and focused on one change
Commit the Why
Commit messages should explain why the change was made
Linear History
Rebase instead of merge to keep a linear commit history
Tag Releases
Tag every release with a semantic version
Sign Commits
Sign commits with GPG or SSH keys for verification
PR Descriptions
Every pull request must have a description explaining the change
Clean Commit History
Squash work-in-progress commits before merging
Branch Protection
Never commit directly to main; always use pull requests
Communication Style 15
Be Concise
Keep responses short and direct without unnecessary preamble
No Trailing Summaries
Don't summarize what you just did at the end of responses
Explain Why
When suggesting changes, explain the reasoning behind them
Ask Before Refactoring
Ask before making changes beyond the requested scope
No Unsolicited Improvements
Only change what was specifically requested
Match Communication Tone
Match the formality level of the user's messages
Code Over Prose
Show code examples instead of describing changes in words
Flag Tradeoffs
When making a design choice, mention the tradeoffs involved
Admit Uncertainty
Say 'I'm not sure' instead of guessing confidently
No Filler Phrases
Avoid filler phrases like 'Great question!' or 'Absolutely!'
Actionable Suggestions
Every suggestion should include a clear, concrete next step
Reference File Locations
Reference file paths and line numbers when discussing code
Prefer Examples
Use short code examples rather than long explanations
One Approach
Suggest one recommended approach, not a menu of options
No Apologies
Don't apologize; just fix the issue and move on
Error Handling 10
Fail Fast
Detect and report errors as early as possible
Specific Error Types
Throw specific error types, not generic Error objects
No Silent Catch
Never swallow exceptions with empty catch blocks
Error Boundaries
Use error boundaries to prevent cascading failures
Retry with Backoff
Use exponential backoff for retryable operations
User-Friendly Error Messages
Show friendly messages to users; log technical details separately
Structured Errors
Return structured error objects with code, message, and details
Validate at Boundaries
Validate data at system boundaries; trust internal code
Graceful Degradation
Degrade functionality gracefully rather than crash entirely
Log Errors Once
Log errors at the point of handling, not at every level
Performance 10
Lazy Loading
Load resources and modules only when they are needed
Paginate Everything
Always paginate list endpoints and large data sets
Debounce Rapid Events
Debounce rapid-fire events like scroll, resize, and input
Avoid N+1 Queries
Batch or join database queries to avoid the N+1 pattern
Cache Expensive Operations
Cache results of expensive computations and external API calls
Index Query Columns
Add database indexes for columns used in WHERE and JOIN clauses
Minimize Bundle Size
Minimize JavaScript bundle size with tree-shaking and code splitting
Stream Large Data
Stream large files and data sets instead of loading into memory
Async I/O
Use async I/O for file, network, and database operations
Measure Before Optimizing
Profile and measure before optimizing; don't guess at bottlenecks
Documentation 10
No Obvious Comments
Don't comment code that is already self-explanatory
Document Why, Not What
Comments should explain reasoning and context, not describe code
Keep Docs Current
Update documentation when changing the code it describes
API Documentation
Document all public API endpoints with examples
README Quickstart
README must contain setup, install, and run instructions
Comment Complex Logic
Add inline comments only for genuinely complex or non-obvious code
Changelog Entries
Add changelog entries for user-facing changes
Deprecation Notices
Mark deprecated APIs with migration instructions and timeline
Types as Documentation
Use types and interfaces as self-documenting contracts
Example-Driven Docs
Include usage examples in documentation, not just descriptions
Dependencies 8
Pin Dependency Versions
Pin versions and use lockfiles for reproducible builds
Minimize Dependencies
Add dependencies only when they provide substantial value
Audit Before Installing
Check maintenance status and license before adding a package
No Duplicate Dependencies
Don't add packages that duplicate functionality you already have
Update Dependencies Regularly
Keep dependencies up to date; don't let them go stale
Remove Unused Dependencies
Remove packages that are no longer used from your manifest
Check Bundle Impact
Evaluate bundle size impact before adding frontend dependencies
Prefer Standard Library
Use standard library functions before reaching for external packages
Agent Behavior 20
Read Before Edit
Always read a file completely before modifying it
Verify Assumptions
Check code and docs to verify assumptions instead of guessing
One Change at a Time
Make one logical change and verify before moving to the next
Run Tests After Changes
Run the test suite after making changes to catch regressions
Minimal Changes
Make the minimum change needed to accomplish the task
Preserve Existing Style
Match the codebase's existing style; don't impose new patterns
No Placeholder Code
Never leave TODO comments or placeholder implementations
Check Existing Patterns
Look for established patterns before introducing new ones
Confirm Destructive Actions
Ask before running destructive or irreversible operations
Explain Errors Clearly
When something fails, explain what went wrong and why
No Hallucinated APIs
Never invent API methods or library functions; verify they exist
Incremental Progress
Work incrementally; don't try to change everything at once
Read Surrounding Context
Read surrounding code and related files before making changes
Respect .gitignore
Never commit files that should be gitignored
Test After Implementation
Verify the feature works end-to-end after implementing it
Don't Create Unnecessary Files
Prefer editing existing files over creating new ones
Fix Root Cause
Fix the underlying cause of problems, not just symptoms
No Backwards Compatibility Hacks
Change the code directly; don't add shims or wrappers
Rollback on Failure
If a change breaks things, revert and try a different approach
Scope Discipline
Stay within the requested scope; don't add unrequested features
Frontend 12
Semantic HTML
Use semantic HTML elements for structure and accessibility
Accessible Forms
All form inputs must have associated labels
Keyboard Navigation
All interactive elements must be keyboard accessible
Responsive Design
Design mobile-first with relative units and breakpoints
Image Alt Text
All images must have descriptive alt text or be marked decorative
No Inline Styles
Use CSS classes or modules instead of inline style attributes
Progressive Enhancement
Build core functionality that works without JavaScript
ARIA Labels
Add ARIA labels to interactive elements that lack visible text
Color Contrast
Maintain WCAG AA contrast ratio for all text
Focus Indicators
Always show visible focus indicators on interactive elements
Loading States
Show loading indicators for all asynchronous operations
Error States in UI
Display clear error states with recovery actions
Backend 12
Idempotent Endpoints
Make API endpoints idempotent where possible
Consistent Response Shape
Use a consistent response structure across all API endpoints
Request Validation
Validate request bodies with a schema validator
Health Endpoint
Expose a /health endpoint for monitoring and load balancers
Structured Logging
Use structured JSON logging instead of console.log
Graceful Shutdown
Handle SIGTERM signals and shut down cleanly
Database Migrations
Use versioned migrations; never modify the schema manually
Connection Pooling
Use connection pools for database and external service connections
Timeout All Requests
Set timeouts on all outgoing HTTP and database requests
Correlation IDs
Include correlation IDs in logs and responses for request tracing
No Business Logic in Routes
Keep route handlers free of business logic
Environment-Specific Config
Use configuration objects, not if/else blocks for environments
TypeScript 10
Strict Mode
Enable strict mode in tsconfig.json for maximum type safety
No Any Type
Avoid the any type; use unknown or proper types instead
Explicit Return Types
Add return types to exported and public functions
Discriminated Unions
Use discriminated unions for variant types instead of optional fields
Readonly Properties
Mark object properties as readonly when they shouldn't be mutated
No Type Assertions
Avoid type assertions (as); narrow types with guards instead
Use Generics
Write reusable, type-safe functions with generics
Infer Internal Types
Let TypeScript infer types for local variables and private code
No Enums
Use const objects or union types instead of TypeScript enums
Runtime Schema Validation
Use Zod or similar for runtime validation that generates types
React 10
Functional Components
Use functional components with hooks instead of class components
Custom Hooks
Extract reusable stateful logic into custom hooks
Stable Key Props
Use stable, unique keys in list rendering; never use array index
Controlled Inputs
Use controlled components for form inputs with React state
Memoize Sparingly
Only use React.memo, useMemo, and useCallback for measured issues
Effect Cleanup
Always return cleanup functions from useEffect for subscriptions
Lift State Minimally
Lift state only as high as the nearest common ancestor needs
Composition Over Props
Prefer component composition over deeply nested prop drilling
React Error Boundaries
Wrap feature areas with error boundaries to isolate failures
Server Components by Default
Use server components by default; add 'use client' only when needed
Python 10
Type Hints
Add type hints to all function signatures and class attributes
Virtual Environments
Always use virtual environments for Python project isolation
F-Strings
Use f-strings for readable string formatting
Dataclasses
Use dataclasses or Pydantic models for structured data
Context Managers
Use with statements for resource management
List Comprehensions
Prefer list comprehensions for simple transformations
Use pathlib
Use pathlib instead of os.path for file system operations
Use Logging Module
Use the logging module instead of print for application output
Docstrings
Add docstrings to all public modules, classes, and functions
No Mutable Defaults
Never use mutable default arguments in function signatures
DevOps 8
Infrastructure as Code
Define infrastructure in code with Terraform, Pulumi, or similar
Environment Parity
Keep dev, staging, and production environments as similar as possible
CI Runs Tests
CI must run the full test suite on every push
Containerize Applications
Package applications in containers for consistent deployment
Secrets Management
Use a secrets manager; never store secrets in env files or code
Rollback Plan
Every deployment must have a tested rollback procedure
Monitoring and Alerts
Set up monitoring and alerting before shipping to production
Zero-Downtime Deploys
Use blue/green or canary deployments to minimize downtime
Swift 10
Weak Self in Closures
Use [weak self] in closures that outlive the current scope
Value Types First
Prefer structs and enums over classes unless reference semantics are needed
Guard Early Return
Use guard for preconditions and early exits to reduce nesting
Protocol Extensions
Use protocol extensions for default implementations instead of base classes
Main Thread UI
All UI updates must happen on the main thread
Keychain for Secrets
Store sensitive data in Keychain, never in UserDefaults or plain files
Codable Models
Use Codable with explicit CodingKeys for JSON serialization
NSView Layer Setup
Always set wantsLayer before configuring layer properties
Optional Chaining
Use optional chaining and nil coalescing instead of force unwrapping
SPM Dependencies
Pin Swift Package Manager dependencies to exact versions or ranges
No rules match your search.