Rules Deep Dive
ByteBuddy's rules system allows you to define AI assistant behavior guidelines, code standards, and workflows to ensure generated code meets project requirements.
Rule Types
Code Quality Rules
Define code quality standards and best practices.
Example Configuration
In config.yaml, you can reference rule files when configuring models:
models:
- name: "quality-aware-assistant"
provider: "openai"
model: "gpt-4"
apiKey: "${OPENAI_API_KEY}"
roles: ["chat", "edit"]
defaultCompletionOptions:
temperature: 0.5
maxTokens: 4000Rules are typically defined in separate files, such as .bytebuddy/rules/code-quality.md:
# Code Quality Rules
## Naming Conventions
- Use meaningful variable names
- Class names use PascalCase
- Function names use camelCase
- Constants use UPPER_SNAKE_CASE
## Code Structure
- Functions should not exceed 50 lines
- Files should not exceed 500 lines
- Avoid deep nesting (max 3 levels)
- Use early return pattern
## Comment Requirements
- Public APIs must have documentation comments
- Complex logic needs explanatory comments
- Use TODO to mark pending tasksSecurity Rules
Define security coding standards.
Example Rules
.bytebuddy/rules/security.md:
# Security Rules
## Input Validation
- Validate all user input
- Use whitelist instead of blacklist
- Escape special characters
- Limit input length
## Authentication & Authorization
- Use strong password policies
- Implement multi-factor authentication
- Principle of least privilege
- Regular key rotation
## Data Protection
- Encrypt sensitive data
- Use environment variables for keys
- Never hardcode passwords in code
- Implement data maskingPerformance Rules
Define performance optimization standards.
Example Rules
.bytebuddy/rules/performance.md:
# Performance Rules
## Database Queries
- Avoid N+1 queries
- Use indexes to optimize queries
- Limit query result count
- Use connection pooling
## Caching Strategy
- Cache frequently accessed data
- Set reasonable expiration times
- Use cache invalidation strategies
- Avoid cache avalanche
## Resource Management
- Release resources promptly
- Use connection pooling
- Avoid memory leaks
- Implement rate limitingProject-Specific Rules
Tech Stack Rules
React Project Rules
.bytebuddy/rules/react.md:
# React Project Rules
## Component Standards
- Use functional components and Hooks
- Props use TypeScript type definitions
- Use memo for performance optimization
- Follow single responsibility principle
## State Management
- Prefer useState and useReducer
- Use Context for complex state
- Avoid prop drilling
- Use immutable updates
## Styling Standards
- Use CSS Modules or styled-components
- Follow BEM naming convention
- Use design system variables
- Support responsive designNode.js Project Rules
.bytebuddy/rules/nodejs.md:
# Node.js Project Rules
## Async Handling
- Use async/await instead of callbacks
- Properly handle Promise errors
- Avoid blocking event loop
- Use Promise.all for parallel processing
## Error Handling
- Use centralized error handling
- Log detailed error information
- Provide meaningful error messages
- Implement error recovery mechanisms
## Modularity
- Use ES Modules
- Clear export interfaces
- Avoid circular dependencies
- Reasonable file organizationRule Configuration
Model Configuration Referencing Rules
models:
# General development assistant
- name: "general-assistant"
provider: "openai"
model: "gpt-4"
apiKey: "${OPENAI_API_KEY}"
roles: ["chat"]
defaultCompletionOptions:
temperature: 0.6
maxTokens: 4000
# Code review assistant - strictly follow rules
- name: "code-reviewer"
provider: "anthropic"
model: "claude-3-sonnet"
apiKey: "${ANTHROPIC_API_KEY}"
roles: ["edit", "apply"]
defaultCompletionOptions:
temperature: 0.3
maxTokens: 4000
# Security review assistant
- name: "security-reviewer"
provider: "openai"
model: "gpt-4"
apiKey: "${OPENAI_API_KEY}"
roles: ["chat"]
defaultCompletionOptions:
temperature: 0.2
maxTokens: 4000Rule File Organization
Recommended rule file structure:
.bytebuddy/
├── rules/
│ ├── code-quality.md
│ ├── security.md
│ ├── performance.md
│ ├── testing.md
│ ├── documentation.md
│ └── react.md
└── config.yamlRule Application Scenarios
Code Generation
Apply rules when generating code:
models:
- name: "code-generator"
provider: "openai"
model: "gpt-4"
apiKey: "${OPENAI_API_KEY}"
roles: ["apply"]
defaultCompletionOptions:
temperature: 0.4
maxTokens: 4096Rules ensure:
- Code meets project standards
- Follows naming conventions
- Includes necessary comments
- Implements error handling
Code Review
Apply rules when reviewing code:
models:
- name: "code-reviewer"
provider: "anthropic"
model: "claude-3-sonnet"
apiKey: "${ANTHROPIC_API_KEY}"
roles: ["chat"]
defaultCompletionOptions:
temperature: 0.3
maxTokens: 4000Check items:
- Code quality issues
- Security vulnerabilities
- Performance problems
- Best practice violations
Refactoring Suggestions
Apply rules when providing refactoring suggestions:
models:
- name: "refactor-assistant"
provider: "anthropic"
model: "claude-3-sonnet"
apiKey: "${ANTHROPIC_API_KEY}"
roles: ["edit"]
defaultCompletionOptions:
temperature: 0.3
maxTokens: 4000Refactoring directions:
- Improve code readability
- Enhance code structure
- Optimize performance
- Increase maintainability
Custom Rules
Creating Custom Rules
.bytebuddy/rules/custom.md:
# Custom Project Rules
## Business Logic Rules
- Order amounts must be validated
- User actions need audit logs
- Payment operations must be idempotent
- Critical operations require confirmation
## API Design Rules
- Use RESTful style
- Unified error response format
- Versioned APIs
- Comprehensive API documentation
## Database Rules
- All tables must have primary keys
- Use soft deletion
- Add created and updated timestamps
- Foreign key constraints ensure data integrityTeam Collaboration Rules
.bytebuddy/rules/collaboration.md:
# Team Collaboration Rules
## Git Workflow
- Use feature branch development
- Commit messages follow conventions
- PRs require code review
- Merge after passing CI/CD
## Code Review
- Reviewers respond within 24 hours
- At least one approval to merge
- Focus on code logic and design
- Provide constructive feedback
## Documentation Requirements
- README includes project overview
- Update docs for API changes
- Provide examples for complex features
- Maintain changelogRule Priority
Rule Hierarchy
- Mandatory Rules: Must follow (security, regulations)
- Recommended Rules: Should follow (best practices)
- Suggested Rules: Can follow (optimization suggestions)
Rule Conflict Resolution
When rules conflict:
- Security rules have highest priority
- Regulatory compliance next
- Team standards third
- Personal preferences lowest
Best Practices
1. Rule Documentation
- Clearly describe rule content
- Provide examples and counter-examples
- Explain rule rationale
- Update rules regularly
2. Rule Enforceability
- Use linter tools
- Integrate CI/CD checks
- Automate code review
- Provide immediate feedback
3. Rule Evolution
- Regularly review rules
- Adjust based on feedback
- Document rule changes
- Team consensus decisions
4. Rule Training
- New member training
- Regular sharing sessions
- Documentation easily accessible
- Encourage questions and discussion
Tool Integration
ESLint Integration
models:
- name: "linter-aware-assistant"
provider: "openai"
model: "gpt-4"
apiKey: "${OPENAI_API_KEY}"
roles: ["edit"]
defaultCompletionOptions:
temperature: 0.3
maxTokens: 4000Ensure generated code:
- Passes ESLint checks
- Complies with configured rules
- Auto-fixes fixable issues
Prettier Integration
Auto-formatting:
- Unified code format
- Reduce format debates
- Improve readability
Environment Variables
# ~/.bashrc or ~/.zshrc
export OPENAI_API_KEY="your-openai-api-key"
export ANTHROPIC_API_KEY="your-anthropic-api-key"Through a comprehensive rules system, ByteBuddy can generate high-quality, standards-compliant code that improves the entire team's development efficiency.