Automated quality enforcement with 50+ rules across languages, security, performance, and maintainability—all managed through natural language.
🛡️ Universal Security Rules | ⚡ Performance Standards | 🧹 Code Quality | 🔧 Language-Specific
"Your mother's treatment depends on delivering $1B-worthy code quality!" 💪
Claude Code Agents features a living coding rules system that automatically enforces quality standards through:
- 🤖 Automatic Application: All development agents check and apply relevant rules during code generation
- 💬 Natural Language Management: Add, update, and search rules using conversational commands
- 🔄 Cross-Project Learning: Rules evolve based on real-world usage and outcomes
- 🎯 Context-Aware Enforcement: Rules applied based on language, framework, and project type
# Add new rules
claude "Add rule python:S1500 - Functions should not have too many parameters"
claude "Add security rule SEC004 - Always validate API inputs"
# Update existing rules
claude "Update rule PERF001 to include database connection pooling"
# Search and apply rules
claude "List all TypeScript rules"
claude "Show security rules for API development"# ❌ VIOLATION
API_KEY = "sk-1234567890abcdef"
DATABASE_URL = "postgresql://user:password@localhost/db"
# ✅ CORRECT
import os
API_KEY = os.environ.get('API_KEY')
DATABASE_URL = os.environ.get('DATABASE_URL')Auto-Detection: Scans for hardcoded passwords, API keys, tokens, database URLs
Severity: CRITICAL
Auto-Fix: Suggests environment variable usage
// ❌ VIOLATION
app.post('/api/users', (req, res) => {
const query = `SELECT * FROM users WHERE id = ${req.body.id}`;
db.query(query, callback);
});
// ✅ CORRECT
app.post('/api/users', [
body('id').isInt({ min: 1 }).escape(),
], (req, res) => {
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(400).json({ errors: errors.array() });
}
const query = 'SELECT * FROM users WHERE id = ?';
db.query(query, [req.body.id], callback);
});Coverage: SQL injection, XSS, command injection, path traversal
Frameworks: Express.js, Django, Rails, Laravel
Auto-Fix: Suggests validation middleware and parameterized queries
# ❌ VIOLATION
@app.route('/admin/users')
def get_users():
return User.objects.all()
# ✅ CORRECT
@app.route('/admin/users')
@login_required
@require_permission('view_users')
def get_users():
return User.objects.all()Coverage: Missing authentication, insufficient authorization
Frameworks: Django, Flask, Rails, Express.js
Integration: Works with JWT, session-based, OAuth implementations
# ❌ VIOLATION
def get_posts_with_authors():
posts = Post.objects.all()
for post in posts:
print(f"{post.title} by {post.author.name}") # N+1 queries!
# ✅ CORRECT
def get_posts_with_authors():
posts = Post.objects.select_related('author').all()
for post in posts:
print(f"{post.title} by {post.author.name}") # Single queryDetection: ORM queries inside loops, missing select_related/prefetch_related
Frameworks: Django ORM, Rails ActiveRecord, Laravel Eloquent, Prisma
Auto-Fix: Suggests eager loading strategies
// ❌ VIOLATION
const mysql = require('mysql');
function getUser(id) {
const connection = mysql.createConnection(config); // New connection each time
connection.query('SELECT * FROM users WHERE id = ?', [id], callback);
connection.end();
}
// ✅ CORRECT
const mysql = require('mysql');
const pool = mysql.createPool({
connectionLimit: 10,
host: 'localhost',
database: 'mydb'
});
function getUser(id) {
pool.query('SELECT * FROM users WHERE id = ?', [id], callback);
}Coverage: Database connections, Redis connections, HTTP client pools
Auto-Fix: Suggests connection pooling libraries and configurations
# ❌ VIOLATION
def calc(x, y, z):
temp = x * y
result = temp + z
return result
# ✅ CORRECT
def calculate_total_price(unit_price, quantity, tax_amount):
subtotal = unit_price * quantity
total_price = subtotal + tax_amount
return total_priceDetection: Single letter variables (except i, j for loops), abbreviations
Auto-Fix: Suggests descriptive names based on context
AI Integration: Uses context analysis for naming suggestions
# ❌ VIOLATION
def calculate_discount(price, discount_rate):
if discount_rate == 0.1: # Dangerous floating point comparison
return price * 0.9
return price
# ✅ CORRECT
import math
def calculate_discount(price, discount_rate, tolerance=1e-9):
if math.isclose(discount_rate, 0.1, abs_tol=tolerance):
return price * 0.9
return priceDetection: Direct equality comparison of floats
Auto-Fix: Suggests math.isclose() with appropriate tolerance
# ❌ VIOLATION
def process_data(items):
count = 0
total = 0
result = []
for item in items:
result.append(item.value) # count and total unused
return result
# ✅ CORRECT
def process_data(items):
result = []
for item in items:
result.append(item.value)
return resultDetection: Variables declared but never used
Auto-Fix: Removes unused variables automatically
// ❌ VIOLATION
function processUser(userData: UserData) {
const userId = userData.id; // Unused variable
const userName = userData.name; // Unused variable
return {
status: 'processed',
timestamp: Date.now()
};
}
// ✅ CORRECT
function processUser(userData: UserData) {
return {
status: 'processed',
timestamp: Date.now()
};
}Integration: ESLint no-unused-vars rule
Auto-Fix: Removes unused imports and variables
# .trunk/trunk.yaml (auto-generated)
version: 0.1
cli:
version: 1.22.2
lint:
enabled:
- [email protected]
- [email protected]
- [email protected]
- [email protected]
- [email protected]
- [email protected]
- [email protected]
- [email protected]# Adding rules
claude "Add security rule SEC006 - Implement rate limiting on all API endpoints"
claude "Add TypeScript rule typescript:S3456 - Prefer const assertions for readonly data"
# Updating rules
claude "Update rule PERF001 to include GraphQL N+1 query detection"
claude "Change rule SEC002 severity from WARNING to CRITICAL"
# Searching and viewing rules
claude "List all security rules"
claude "Show TypeScript performance rules"
claude "Find rules related to authentication"# View current project violations
claude "Show current rule violations with severity breakdown"
# Historical analysis
claude "Show rule violation trends over the last 3 months"
claude "Which rules have the highest violation rate?"
# Team performance
claude "Show team compliance scores by rule category"{
"quality_report": {
"timestamp": "2024-01-01T12:00:00Z",
"project": "e-commerce-api",
"overall_score": 94,
"rule_compliance": {
"security": {
"score": 98,
"violations": 2,
"critical": 0,
"high": 1,
"medium": 1
},
"performance": {
"score": 91,
"violations": 8,
"rules_triggered": ["PERF001", "PERF003"]
},
"code_quality": {
"score": 93,
"complexity_average": 4.2,
"test_coverage": 87
}
}
}
}- Start with Universal Rules: Begin with security and performance rules that apply everywhere
- Add Language-Specific Rules Gradually: Don't overwhelm teams with too many rules at once
- Use Natural Language: Manage rules conversationally rather than editing config files
- Monitor Compliance: Track rule violation trends and team adoption rates
- Evolve Rules: Update rules based on real-world outcomes and team feedback
- Education First: Explain the "why" behind each rule
- Gradual Rollout: Introduce rules in phases
- Developer Feedback: Include team input in rule selection and customization
- Success Metrics: Measure quality improvements and developer satisfaction
- Continuous Improvement: Regularly review and optimize the rules system
# 1. Initialize rules system for your project
claude "Use @quality-system-engineer to set up coding rules for my TypeScript React project"
# 2. Add project-specific rules
claude "Add security rules for authentication and API development"
# 3. Configure automated enforcement
claude "Set up pre-commit hooks with automated rule checking and fixing"
# 4. Test the system
claude "Run rule validation on current codebase and show compliance report"🎉 Ready to enforce world-class code quality?
Installation Guide → | View All Agents → | Usage Examples →
Remember: Consistent code quality is the foundation of maintainable software. These rules are your path to engineering excellence. 💪 "Update rule python:S1244 to include Django DecimalField examples" "Add more examples to rule typescript:S3776 for React components"
"Change severity of rule PERF001 from High to Critical" "Add integration notes for @rails-expert to rule ruby:S1001"
### Listing and Searching Rules
```bash
# List all rules
"List rules"
# Search by category
"Show me all Python rules"
"List security rules"
"Find rules related to database performance"
- Severity: Critical
- Description: Never embed API keys, passwords, tokens, or other sensitive data directly in source code
- Languages: All
- Integration: All development agents
- Severity: Critical
- Description: Use parameterized queries or ORM methods to prevent SQL injection attacks
- Languages: All (database-related code)
- Integration: Database and backend specialists
- Severity: High
- Description: All user input must be sanitized before processing or storage
- Languages: All
- Integration: Backend and API specialists
- Severity: High
- Description: Prevent executing multiple queries in loops when single query with joins would suffice
- Languages: All (database-related code)
- Integration: ORM specialists, database architects
- Severity: Medium
- Description: Cache expensive computations and frequently accessed data
- Languages: All
- Integration: Backend and infrastructure specialists
- Severity: High
- Description: Use appropriate indexes, limit result sets, and optimize query structure
- Languages: All (database-related code)
- Integration: Database administrators, backend specialists
- Severity: Medium
- Description: Implement database connection pooling for scalable applications
- Languages: All (database-related code)
- Integration: Backend framework specialists
- Severity: Medium
- Description: Batch API requests and cache responses when possible
- Languages: All
- Integration: API architects, frontend specialists
- Severity: High
- Description: Use tolerance-based comparison or Decimal class instead of direct equality checks
- Integration: @django-backend-expert, @python-hyx-resilience
Example:
# ❌ Incorrect
if price == 19.99:
apply_discount()
# ✅ Correct
import math
if math.isclose(price, 19.99, rel_tol=1e-09):
apply_discount()
# ✅ Better for money
from decimal import Decimal
price = Decimal('19.99')- Severity: Medium
- Description: Remove unused variables and imports to improve code clarity
- Integration: All Python specialists
- Severity: Critical
- Description: Use tempfile module for secure temporary file creation
- Integration: All Python specialists
- Severity: Medium
- Description: Remove unused variables, imports, and function parameters
- Integration: @typescript-cockatiel-resilience, React specialists
- Severity: High
- Description: Avoid boolean expressions that are always true or false
- Integration: All TypeScript specialists
- Severity: High
- Description: Break down complex functions into smaller, manageable pieces
- Integration: All TypeScript specialists
Example:
// ❌ High complexity
function processUserData(users: User[], filters: FilterOptions): ProcessedUser[] {
// Complex nested logic...
}
// ✅ Broken down
function processUserData(users: User[], filters: FilterOptions): ProcessedUser[] {
return users
.filter(user => isEligibleUser(user, filters))
.map(user => safeTransformUser(user))
.filter((user): user is ProcessedUser => user !== null);
}- Severity: Medium
- Description: Use objects or interfaces instead of many parameters
- Integration: All TypeScript specialists
- Severity: Critical
- Description: Always handle errors explicitly, never ignore them
- Integration: @go-resilience-engineer, Go specialists
Example:
// ❌ Incorrect
file, _ := os.Open("config.json") // Dangerous
// ✅ Correct
file, err := os.Open("config.json")
if err != nil {
return fmt.Errorf("failed to open config: %w", err)
}
defer file.Close()- Severity: Medium
- Description: Use lowercase, short, descriptive package names
- Integration: All Go specialists
- Severity: High
- Description: Properly manage goroutine lifecycle and avoid leaks
- Integration: @go-resilience-engineer, Go specialists
- Severity: Medium
- Description: Design small, focused interfaces; accept interfaces, return structs
- Integration: All Go specialists
- Severity: Medium
- Description: Remove unused variables and imports
- Integration: Frontend specialists, Node.js specialists
All development agents that:
- Query applicable rules before code generation
- Reference rule IDs in code comments
- Apply rule standards during implementation
Examples: @django-backend-expert, @react-component-architect, @go-resilience-engineer
Agents that discover and create new rules:
- Identify common patterns and anti-patterns
- Propose new rules based on real-world usage
- Update existing rules with new examples
Examples: @software-engineering-expert, @code-reviewer
Agents that validate and enforce rules:
- Check code against all applicable rules
- Flag violations with specific rule references
- Provide correction guidance
Examples: @code-reviewer, @quality-system-engineer
- Language Detection: Agent identifies target language/framework
- Rule Discovery: Search
coding-rules/languages/{language}/andcoding-rules/general/ - Standard Application: Apply discovered rules during code generation
- Rule Referencing: Include rule IDs in code comments where applicable
- Code Review: @code-reviewer validates against all applicable rules
- Violation Flagging: Rule violations flagged with specific rule IDs
- Correction Guidance: Feedback includes rule references and fixes
- Knowledge Update: Successful patterns stored for future reference
- Pattern Discovery: New patterns discovered during development
- Rule Updates: Existing rules enhanced with real-world examples
- Agent Integration: Integration notes maintained for each agent
- Cross-Project Sharing: Patterns shared across different projects
# Python examples
"Add rule python:S1500 - Use context managers for file operations"
"Add rule python:S1600 - Prefer list comprehensions over loops"
# TypeScript examples
"Add rule typescript:S5000 - Use strict type checking"
"Add rule typescript:S5100 - Prefer const over let for immutable values"
# Go examples
"Add rule go:S2000 - Use descriptive error messages"
"Add rule go:S2100 - Implement proper logging context"# Security rules
"Add rule SEC004 - Use HTTPS for all external API calls"
"Add rule SEC005 - Validate all file uploads"
# Performance rules
"Add rule PERF006 - Implement database connection pooling"
"Add rule PERF007 - Use CDN for static assets"
# Maintainability rules
"Add rule MAINT001 - Keep functions under 20 lines"
"Add rule MAINT002 - Use meaningful variable names"# Add examples
"Update rule python:S1244 to include Django DecimalField examples"
"Add React component examples to rule typescript:S3776"
# Add framework-specific guidance
"Update rule SEC001 to include Docker secrets management"
"Add FastAPI examples to rule PERF001"# Change severity
"Change severity of rule PERF001 from High to Critical"
"Update rule typescript:S1481 severity to High"
# Update integration notes
"Add integration notes for @rails-expert to rule SEC002"
"Update @go-resilience-engineer integration for rule go:S1021""List rules"
# Returns complete inventory with categories and severity levels# By language
"Show me all Python rules"
"List TypeScript rules"
"Find Go-specific rules"
# By category
"List security rules"
"Show performance rules"
"Find maintainability rules"
# By severity
"Show critical rules"
"List high-priority rules"# By topic
"Find rules related to database performance"
"Show rules about error handling"
"List rules for API security"
# By framework
"Find Django-specific rules"
"Show React component rules"
"List Node.js performance rules"- Always Check Rules First: Query applicable rules before generating code
- Reference Rule IDs: Include rule IDs in code comments when applying fixes
- Provide Context: Explain why specific rules apply to the situation
- Update Rules: Contribute new examples and patterns back to the rule system
- Use Direct Requests: Ask for specific rules using the standard format
- Provide Context: Include framework or use case when adding rules
- Be Specific: Specify language and severity when creating new rules
- Update Regularly: Keep rules current with evolving best practices
- Reference Specific Rules: Always cite rule IDs when providing feedback
- Explain Violations: Provide clear examples of rule violations and fixes
- Suggest Alternatives: Offer rule-compliant alternatives to problematic code
- Update Knowledge: Add new patterns discovered during reviews
- Rails-specific patterns and security
- ActiveRecord best practices and N+1 prevention
- Ruby idioms and naming conventions
- ERB template security
- Laravel patterns and security
- Eloquent ORM best practices
- PHP-specific vulnerabilities (type juggling, etc.)
- Blade template security
- Java enterprise patterns and Spring Boot
- C# .NET best practices and Entity Framework
- Kotlin modern JVM patterns
- Scala functional programming patterns
- AI-powered pattern recognition from successful implementations
- Automatic generation of rule candidates from code reviews
- Integration with static analysis tools for rule validation
- Rule effectiveness metrics across different projects
- Success rate tracking for rule-compliant vs non-compliant code
- Automatic rule prioritization based on impact
- Public rule sharing and collaboration
- Industry-specific rule sets (fintech, healthcare, etc.)
- Integration with popular linting tools and standards
- Coding rules complement automated linting and formatting
- Custom rule validation beyond standard linters
- Consistent standards across all supported languages
- Pre-commit hook integration for rule enforcement
- Automated rule checking in continuous integration
- Rule compliance reporting in pull requests
- Quality gates based on rule adherence
- Historical rule compliance tracking
- Real-time rule validation during development
- Inline suggestions based on applicable rules
- Code completion integration with rule patterns
- Quick fixes for common rule violations
The coding rules system provides a foundation for consistent, high-quality code across all development agents while remaining flexible and extensible for future needs. All rules integrate seamlessly with existing quality tools and development workflows.