Skip to content

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:

yaml
models:
  - name: "quality-aware-assistant"
    provider: "openai"
    model: "gpt-4"
    apiKey: "${OPENAI_API_KEY}"
    roles: ["chat", "edit"]
    defaultCompletionOptions:
      temperature: 0.5
      maxTokens: 4000

Rules are typically defined in separate files, such as .bytebuddy/rules/code-quality.md:

markdown
# 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 tasks

Security Rules

Define security coding standards.

Example Rules

.bytebuddy/rules/security.md:

markdown
# 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 masking

Performance Rules

Define performance optimization standards.

Example Rules

.bytebuddy/rules/performance.md:

markdown
# 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 limiting

Project-Specific Rules

Tech Stack Rules

React Project Rules

.bytebuddy/rules/react.md:

markdown
# 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 design

Node.js Project Rules

.bytebuddy/rules/nodejs.md:

markdown
# 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 organization

Rule Configuration

Model Configuration Referencing Rules

yaml
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: 4000

Rule File Organization

Recommended rule file structure:

.bytebuddy/
├── rules/
│   ├── code-quality.md
│   ├── security.md
│   ├── performance.md
│   ├── testing.md
│   ├── documentation.md
│   └── react.md
└── config.yaml

Rule Application Scenarios

Code Generation

Apply rules when generating code:

yaml
models:
  - name: "code-generator"
    provider: "openai"
    model: "gpt-4"
    apiKey: "${OPENAI_API_KEY}"
    roles: ["apply"]
    defaultCompletionOptions:
      temperature: 0.4
      maxTokens: 4096

Rules ensure:

  • Code meets project standards
  • Follows naming conventions
  • Includes necessary comments
  • Implements error handling

Code Review

Apply rules when reviewing code:

yaml
models:
  - name: "code-reviewer"
    provider: "anthropic"
    model: "claude-3-sonnet"
    apiKey: "${ANTHROPIC_API_KEY}"
    roles: ["chat"]
    defaultCompletionOptions:
      temperature: 0.3
      maxTokens: 4000

Check items:

  • Code quality issues
  • Security vulnerabilities
  • Performance problems
  • Best practice violations

Refactoring Suggestions

Apply rules when providing refactoring suggestions:

yaml
models:
  - name: "refactor-assistant"
    provider: "anthropic"
    model: "claude-3-sonnet"
    apiKey: "${ANTHROPIC_API_KEY}"
    roles: ["edit"]
    defaultCompletionOptions:
      temperature: 0.3
      maxTokens: 4000

Refactoring directions:

  • Improve code readability
  • Enhance code structure
  • Optimize performance
  • Increase maintainability

Custom Rules

Creating Custom Rules

.bytebuddy/rules/custom.md:

markdown
# 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 integrity

Team Collaboration Rules

.bytebuddy/rules/collaboration.md:

markdown
# 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 changelog

Rule Priority

Rule Hierarchy

  1. Mandatory Rules: Must follow (security, regulations)
  2. Recommended Rules: Should follow (best practices)
  3. Suggested Rules: Can follow (optimization suggestions)

Rule Conflict Resolution

When rules conflict:

  1. Security rules have highest priority
  2. Regulatory compliance next
  3. Team standards third
  4. 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

yaml
models:
  - name: "linter-aware-assistant"
    provider: "openai"
    model: "gpt-4"
    apiKey: "${OPENAI_API_KEY}"
    roles: ["edit"]
    defaultCompletionOptions:
      temperature: 0.3
      maxTokens: 4000

Ensure 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

bash
# ~/.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.