JetBrains AI Assistant operates through three distinct layers:
Layer 1: IDE Integration
-
AI Chat Panel (
Alt+Shift+A/β₯β§A): Conversational interface - Inline Suggestions: Context-aware code completion
- Quick Actions: Right-click menu AI operations
- Code Review: AI-powered PR analysis
Layer 2: Context System
- Open Files Context: Currently active editor tabs
- Project Structure: Module dependencies, build files
- VCS State: Git history, uncommitted changes
- Attached Artifacts: Manually added context files
Layer 3: Rules System β Focus of this guide
-
Project Rules:
.aiassistant/rules/*.mdfiles - Global Rules: User-level defaults
- Rule Metadata: Activation logic stored in IDE settings
- Dynamic Loading: Context-aware rule application
1.2 How Rules Influence AI Behavior
User Query
β
IDE Context Collection
β
Rule Selection (based on file patterns, manual tags)
β
Context Assembly: [Open Files + Project Structure + Selected Rules]
β
LLM API Call (Claude/GPT/Gemini)
β
Response Processing
β
Presentation in Chat/Editor
Key Insight: Rules are always-included system prompts, not optional suggestions. They fundamentally shape AI responses.
1.3 Differences from Other AI Tools
| Aspect | JetBrains AI | Cursor | Windsurf | Claude Code |
|---|---|---|---|---|
| Configuration Format | Markdown files |
.mdc with YAML frontmatter |
YAML + Markdown | Plain Markdown |
| Storage Location | .aiassistant/rules/ |
.cursor/rules/ |
.windsurf/rules/ |
Root CLAUDE.md
|
| Metadata Storage | IDE settings (XML) | YAML frontmatter | GUI + YAML | None (filename only) |
| Rule Activation | UI-configured + file patterns | Frontmatter-driven | GUI modes | Auto-load all |
| Version Control | Rules: Yes, Settings: Partial | Full | Full | Full |
Unique Advantage: JetBrains deeply integrates with existing project structure (module system, build tools, test frameworks).
2. The .aiassistant/ Directory System
2.1 Official Directory Structure
my-project/
βββ .aiassistant/
β βββ rules/
β β βββ general-standards.md
β β βββ kotlin-conventions.md
β β βββ spring-patterns.md
β β βββ testing-requirements.md
β βββ .aiignore # Optional: exclude files from context
βββ .idea/
β βββ ai-assistant.xml # Rule metadata (auto-generated)
β βββ workspace.xml # User-specific settings
β βββ ...
βββ src/
2.2 File Naming Conventions
Rules Files (.aiassistant/rules/*.md):
β
RECOMMENDED:
- general-standards.md # Project-wide conventions
- kotlin-style-guide.md # Language-specific
- spring-boot-patterns.md # Framework-specific
- api-design-rules.md # Domain-specific
- testing-checklist.md # Activity-specific
β
ACCEPTABLE:
- 01-general.md # Numeric prefix for ordering
- 02-kotlin.md
- 03-spring.md
β AVOID:
- rules.md # Too generic
- MyRules.md # Inconsistent casing
- kotlin rules.md # Spaces in filename
- .hidden-rules.md # Hidden files not reliably loaded
Character Restrictions:
- Use lowercase with hyphens:
kotlin-conventions.md - Avoid spaces, special characters, Unicode
- Maximum length: 255 characters
- Extension: Must be
.md(Markdown)
2.3 .aiignore File Format
Purpose: Exclude files/directories from AI context (similar to .gitignore).
Location: .aiassistant/.aiignore
Syntax:
# .aiassistant/.aiignore
# Build artifacts
build/
target/
out/
*.class
*.jar
# Generated code
generated/
src/generated/
# Dependencies
node_modules/
.mvn/
.gradle/
# IDE files
.idea/workspace.xml
.idea/tasks.xml
*.iws
# Large data files
*.sql
*.csv
data/
# Sensitive files
*.key
*.pem
secrets/
Inheritance: .aiignore is additive with .gitignore. Files in .gitignore are automatically excluded unless explicitly added with add-gitignore-files setting.
2.4 Creating the Directory Structure
Method 1: Via IDE UI
- Open Settings/Preferences (
Ctrl+Alt+S/β,) - Navigate to Tools β AI Assistant β Rules
- Click "New Project Rules File"
- IDE automatically creates
.aiassistant/rules/and opens editor - Directory structure appears in Project view
Method 2: Manual Creation
# From project root
mkdir -p .aiassistant/rules
touch .aiassistant/rules/general-standards.md
touch .aiassistant/.aiignore
Method 3: Git Clone Template
# Use pre-made template
git clone https://github.com/your-org/ai-rules-template .aiassistant
cd .aiassistant
rm -rf .git # Remove template git history
2.5 Version Control Recommendations
What to Commit:
# .gitignore
# β
COMMIT these (shared team rules)
.aiassistant/rules/
.aiassistant/.aiignore
# β DON'T commit (user-specific)
.idea/workspace.xml
.idea/tasks.xml
*.iws
# β οΈ MAYBE commit (team decision)
.idea/ai-assistant.xml # Rule metadata (optional)
.idea/codeStyles/ # If standardizing
Rationale:
- Rules: Team-shared coding standards
-
.aiignore: Consistent context boundaries - Workspace files: User preferences (open tabs, window layout)
-
ai-assistant.xml: Contains rule activation settings (some teams commit for consistency)
3. Creating Project Rules
3.1 Your First Rule File
Step 1: Create File
touch .aiassistant/rules/kotlin-standards.md
Step 2: Add Basic Content
# Kotlin Coding Standards
## Naming Conventions
- **Classes**: PascalCase (`UserRepository`)
- **Functions**: camelCase (`getUserById`)
- **Constants**: UPPER_SNAKE_CASE (`MAX_RETRY_COUNT`)
- **Properties**: camelCase (`isActive`)
## Preferred Patterns
### Use Data Classes for DTOs
kotlin
// β
CORRECT
data class UserDto(
val id: String,
val name: String,
val email: String
)
// β AVOID
class UserDto {
var id: String = ""
var name: String = ""
var email: String = ""
}
### Null Safety
kotlin
// β
CORRECT: Safe call operator
val length = user?.name?.length ?: 0
// β AVOID: Force unwrap
val length = user!!.name!!.length
## Testing Requirements
- All public functions require unit tests
- Use JUnit 5 and MockK for mocking
- Minimum 80% code coverage
Step 3: Register Rule in IDE
- Settings β Tools β AI Assistant β Rules
- Click "+" or "Add Rule"
- Browse to
.aiassistant/rules/kotlin-standards.md - Configure Rule Type (see Section 4)
- Click OK
Step 4: Verify Loading
Open AI Chat (Alt+Shift+A) and ask:
What are the naming conventions for Kotlin classes in this project?
Expected response should reference PascalCase and your specific rules.
3.2 Rule File Template
Comprehensive Template:
# [Rule Category] - [Technology/Pattern]
**Purpose**: [One-sentence description of what this rule covers]
**Applies To**: [File patterns, modules, or languages]
**Last Updated**: 2025-11-29
**Owner**: @team-name or @username
---
## Quick Reference
[5-10 bullet points summarizing key rules]
- Rule 1
- Rule 2
- Rule 3
---
## 1. Context and Scope
[Explain when these rules apply, project background, architectural decisions]
---
## 2. Standards and Conventions
### 2.1 [Category Name]
[Detailed explanation with code examples]
language
// β
CORRECT
[Good example]
// β WRONG
[Bad example]
**Why**: [Explanation of reasoning]
### 2.2 [Another Category]
[More examples]
---
## 3. Common Patterns
### Pattern 1: [Name]
**Use Case**: [When to apply this pattern]
**Implementation**:
language
[Complete working example]
**Benefits**:
- [Benefit 1]
- [Benefit 2]
---
## 4. Anti-Patterns to Avoid
### β Anti-Pattern 1: [Name]
**Problem**: [What's wrong]
**Example**:
language
[Bad code example]
**Solution**:
language
[Corrected code]
---
## 5. Testing Guidelines
[Testing requirements specific to this rule category]
---
## 6. Additional Resources
- Internal docs: [link to Confluence/wiki]
- External reference: [link to framework docs]
- Examples: `src/main/kotlin/com/example/GoodExample.kt`
3.3 Multi-File Organization Strategy
Scenario: Large Spring Boot + Kotlin project
.aiassistant/rules/
βββ 01-project-overview.md # Always apply
βββ 02-kotlin-style.md # Language rules
βββ 03-spring-boot-patterns.md # Framework rules
βββ 04-jpa-database.md # Persistence layer
βββ 05-rest-api-design.md # API conventions
βββ 06-security-requirements.md # Security standards
βββ 07-testing-standards.md # Testing approach
βββ 08-deployment-checklist.md # Release procedures
Numbering Rationale:
-
01-09: Critical rules (always load) -
10-19: Domain-specific rules (conditional) -
20+: Reference documentation (manual)
3.4 Importing External Standards
Pattern: Reference Existing Documentation
# Spring Boot Best Practices
## Official Standards
This project follows Spring Boot official best practices:
https://docs.spring.io/spring-boot/reference/
## Project-Specific Adaptations
### Configuration Management
We use YAML (not properties):
yaml
spring:
datasource:
url: ${DATABASE_URL}
username: ${DATABASE_USER}
### Exception Handling
Standard approach (see `GlobalExceptionHandler.kt`):
kotlin
@RestControllerAdvice
class GlobalExceptionHandler {
@ExceptionHandler(EntityNotFoundException::class)
fun handleNotFound(e: EntityNotFoundException): ResponseEntity {
return ResponseEntity.status(404).body(
ErrorResponse("Entity not found", e.message)
)
}
}
4. Rule Types and Activation Modes
4.1 Four Rule Activation Types
JetBrains AI Assistant supports four activation patterns:
Type 1: Always Apply
Behavior: Rule included in every AI interaction regardless of context.
Use Case: Universal project standards (code style, security requirements, testing mandates).
Configuration:
- Settings β AI Assistant β Rules
- Select rule file
- Set Rule Type β "Always"
- No additional configuration needed
Example:
# Security Requirements (Always Apply)
## Critical Security Rules
1. **NEVER commit secrets**: Use environment variables
2. **ALWAYS validate inputs**: Use Bean Validation annotations
3. **ALWAYS use parameterized queries**: Prevent SQL injection
4. **NEVER log sensitive data**: PII, passwords, tokens
These rules apply to ALL code in this project.
When to Use:
- Security policies
- Code quality standards
- Legal/compliance requirements
- Universal testing requirements
Type 2: By File Pattern
Behavior: Rule activates when working with files matching glob patterns.
Use Case: Language-specific, framework-specific, or directory-specific rules.
Configuration:
- Settings β AI Assistant β Rules
- Select rule file
- Set Rule Type β "By file patterns"
- Add File Patterns (one per line):
**/*.kt
src/main/kotlin/**/*.kt
src/test/kotlin/**/*Test.kt
Glob Pattern Syntax:
| Pattern | Matches | Example |
|---|---|---|
**/*.kt |
All Kotlin files recursively | src/main/kotlin/User.kt |
src/main/**/*.java |
Java files in main source | src/main/java/com/App.java |
**/test/**/*Test.kt |
Test files | src/test/kotlin/UserTest.kt |
*.gradle.kts |
Gradle build files | build.gradle.kts |
frontend/**/*.{ts,tsx} |
TypeScript files in frontend | frontend/App.tsx |
Example Rule:
# Kotlin Coroutines Patterns (File Pattern: **/*.kt)
## Coroutine Best Practices
### Always Use Structured Concurrency
kotlin
// β
CORRECT
suspend fun fetchUserData(): User = coroutineScope {
val profile = async { fetchProfile() }
val posts = async { fetchPosts() }
User(profile.await(), posts.await())
}
// β WRONG: GlobalScope escapes structured concurrency
fun fetchUserData(): User {
GlobalScope.launch { // Bad!
fetchProfile()
}
}
### Exception Handling in Coroutines
kotlin
// β
CORRECT
try {
withContext(Dispatchers.IO) {
performNetworkCall()
}
} catch (e: IOException) {
logger.error("Network call failed", e)
throw ServiceException("Operation failed", e)
}
When to Use:
- Language-specific patterns (Kotlin, Java, TypeScript)
- Framework patterns (Spring in
*Controller.kt, React in*.tsx) - Test files (
*Test.kt,*.spec.ts) - Build files (
*.gradle.kts,pom.xml)
Type 3: By Model Decision
Behavior: AI decides whether to apply rule based on natural language description.
Use Case: Context-dependent guidelines (performance optimization, accessibility, security audits).
Configuration:
- Settings β AI Assistant β Rules
- Select rule file
- Set Rule Type β "By model decision"
- Add Description (natural language):
Apply when the user is asking about database optimization,
query performance, or experiencing slow database operations.
Description Writing Guidelines:
- Use natural language (no code or patterns)
- Describe when to apply (not what the rule contains)
- Include synonyms and related concepts
- Be specific but not overly narrow
Good Descriptions:
β
"Apply when working with Spring Data JPA repositories,
database queries, or experiencing N+1 query problems."
β
"Use for questions about authentication, authorization,
JWT tokens, OAuth2, or security vulnerabilities."
β
"Apply when discussing React component performance,
re-renders, memoization, or optimization."
Bad Descriptions:
β "Database stuff" (Too vague)
β "Use for JPA" (Too brief, missing context)
β "Performance" (Too broad, applies to everything)
Example Rule:
# Database Performance Optimization
**Description for Model**: Apply when discussing database
performance, slow queries, N+1 problems, or JPA optimization.
---
## N+1 Query Problem
### Identify the Issue
kotlin
// β PROBLEM: N+1 queries (1 query for users + N queries for posts)
val users = userRepository.findAll()
users.forEach { user ->
println(user.posts) // Lazy loading triggers separate query
}
### Solution: Eager Loading
kotlin
// β
SOLUTION: Single query with JOIN FETCH
@Query("SELECT u FROM User u LEFT JOIN FETCH u.posts")
fun findAllWithPosts(): List
### Solution: Entity Graphs
kotlin
@EntityGraph(attributePaths = ["posts", "profile"])
fun findAll(): List
## Query Optimization Checklist
- [ ] Add database indexes on foreign keys
- [ ] Use `@BatchSize` for collections
- [ ] Enable query logging: `spring.jpa.show-sql=true`
- [ ] Monitor with Hibernate statistics
- [ ] Use projections for large entities (only fetch needed fields)
When to Use:
- Performance optimization scenarios
- Security review contexts
- Debugging specific issues
- Architecture decision guidance
- Accessibility requirements
Type 4: Manual
Behavior: Rule never auto-applies; must be explicitly referenced.
Use Case: Reference documentation, specialized workflows, migration guides.
Configuration:
- Settings β AI Assistant β Rules
- Select rule file
- Set Rule Type β "Manual"
How to Invoke:
In AI Chat, mention the rule explicitly:
@kotlin-migration-guide How do I migrate from Java to Kotlin?
Or attach via UI:
- AI Chat panel
- Click paperclip icon (Attach context)
- Select rule file from list
Example Rule:
# Java to Kotlin Migration Guide (Manual Reference)
## Migration Process
### Step 1: Convert Syntax
Use IntelliJ's built-in converter:
- Code β Convert Java File to Kotlin File
### Step 2: Address Nullability
kotlin
// Java (implicit nullability)
String getName() { return name; }
// Kotlin (explicit)
fun getName(): String? = name // Nullable
fun getName(): String = name ?: "" // Non-null with default
### Step 3: Replace Getters/Setters
kotlin
// Before (Java style)
class User {
private String name;
public String getName() { return name; }
public void setName(String name) { this.name = name; }
}
// After (Kotlin property)
class User {
var name: String = ""
}
### Step 4: Use Data Classes
kotlin
// Before
class UserDto {
String id;
String name;
// + equals, hashCode, toString
}
// After
data class UserDto(val id: String, val name: String)
## Common Pitfalls
[Detailed migration gotchas]
When to Use:
- Migration guides (language, framework)
- Specialized workflows (deployment, rollback)
- Reference architectures
- Historical context (legacy system documentation)
- Training materials
4.2 Rule Priority and Conflicts
Resolution Order:
When multiple rules apply:
- Always rules load first (all of them)
- File Pattern rules load next (all matching patterns)
- Model Decision rules load if AI deems relevant
- Manual rules load only if explicitly referenced
Conflict Handling:
JetBrains AI doesn't automatically resolve conflicts. If rules contradict:
Example Conflict:
-
kotlin-style.md: "Usevarfor mutable properties" -
immutability-guide.md: "Always useval, nevervar"
Resolution Strategy 1: Explicit Overrides
# Immutability Guide (Higher Priority)
## Mutable Properties
β οΈ **OVERRIDES kotlin-style.md**
Always prefer `val` (immutable) over `var` (mutable):
kotlin
// β
CORRECT
val user = User(name = "John") // Immutable reference
// β WRONG
var user = User(name = "John") // Mutable reference
Exception: Use `var` only for:
- Local loop counters
- Builder pattern internal state
Resolution Strategy 2: Consolidate Rules
Merge conflicting rules into single authoritative file, remove outdated version.
5. File Structure and Organization
5.1 Small Projects (1-5 Files)
Structure:
.aiassistant/rules/
βββ project-overview.md # Tech stack, architecture
βββ coding-standards.md # Language conventions
βββ testing-requirements.md # Test patterns
βββ deployment-guide.md # Release procedures
Example: project-overview.md
# Project Overview
## Technology Stack
- **Language**: Kotlin 1.9
- **Framework**: Spring Boot 3.2
- **Database**: PostgreSQL 15 with JPA
- **Build**: Gradle 8.5 with Kotlin DSL
- **Testing**: JUnit 5, MockK, Testcontainers
## Architecture
Hexagonal architecture (Ports & Adapters):
src/main/kotlin/
βββ domain/ # Business logic (pure Kotlin)
βββ application/ # Use cases
βββ infrastructure/ # JPA, REST controllers
βββ config/ # Spring configuration
## Project Goals
- Clean architecture with clear boundaries
- 80% test coverage minimum
- Sub-100ms API response times
- PostgreSQL-specific optimizations allowed
5.2 Medium Projects (5-15 Files)
Structure:
.aiassistant/rules/
βββ 01-overview.md
βββ 02-kotlin-standards.md
βββ 03-spring-patterns.md
βββ 04-jpa-database.md
βββ 05-rest-api.md
βββ 06-security.md
βββ 07-testing.md
βββ 08-error-handling.md
βββ 09-logging.md
βββ 10-performance.md
βββ 11-deployment.md
Activation Configuration:
| File | Type | Pattern/Description |
|---|---|---|
01-overview.md |
Always | β |
02-kotlin-standards.md |
File Pattern | **/*.kt |
03-spring-patterns.md |
File Pattern | **/*{Controller,Service,Repository}.kt |
04-jpa-database.md |
Model Decision | "Database, JPA, queries, persistence" |
05-rest-api.md |
File Pattern | **/*Controller.kt |
06-security.md |
Always | β |
07-testing.md |
File Pattern | **/*Test.kt |
10-performance.md |
Model Decision | "Performance, optimization, slow" |
5.3 Large Projects / Monorepos (15+ Files)
Structure:
.aiassistant/
βββ rules/
β βββ shared/ # Cross-module standards
β β βββ overview.md
β β βββ kotlin-core.md
β β βββ testing-universal.md
β βββ backend/ # Backend module rules
β β βββ spring-boot.md
β β βββ jpa-patterns.md
β β βββ rest-api.md
β βββ frontend/ # Frontend module rules
β β βββ react-patterns.md
β β βββ typescript-style.md
β β βββ component-library.md
β βββ devops/ # Infrastructure rules
β βββ kubernetes.md
β βββ github-actions.md
β βββ monitoring.md
βββ .aiignore
Multi-Module Rule Configuration:
Root Module Rules (shared/*.md):
- Type: Always
- Applies to entire project
Backend Rules (backend/*.md):
- Type: File Pattern
- Pattern:
backend/**/*.kt
Frontend Rules (frontend/*.md):
- Type: File Pattern
- Pattern:
frontend/**/*.{ts,tsx}
DevOps Rules (devops/*.md):
- Type: Manual
- Invoked during deployment tasks
6. Rules Syntax and Formatting
6.1 Markdown Basics for Rules
Headers (Hierarchy):
# H1: Rule File Title (top of file only)
## H2: Major Section (primary categories)
### H3: Subsection (specific patterns)
#### H4: Detail Level (use sparingly)
Lists:
## Unordered Lists
- Item 1
- Item 2
- Nested item
- Another nested
## Ordered Lists
1. First step
2. Second step
3. Third step
## Checklist
- [ ] TODO item
- [x] Completed item
Code Blocks:
```
kotlin
// Syntax-highlighted code
data class User(val id: String, val name: String)
```
```
json
{
"key": "value"
}
```
```
`
**Emphasis**:
```markdown
**Bold text** for requirements
*Italic text* for emphasis
`Code inline` for keywords
```
**Links**:
```markdown
[Internal docs](https://company.atlassian.net/wiki/page)
[External reference](https://kotlinlang.org/docs/coding-conventions.html)
```
**Tables**:
```markdown
| Column 1 | Column 2 | Column 3 |
|----------|----------|----------|
| Value A | Value B | Value C |
| Value D | Value E | Value F |
```
### 6.2 Effective Code Examples
**Pattern: Bad β Good Comparison**
`
```markdown
### Null Safety
```
kotlin
// β WRONG: Force unwrap
val name = user!!.profile!!.name
// β WRONG: Silently ignore nulls
val name = user?.profile?.name ?: ""
// β
CORRECT: Explicit handling
val name = user?.profile?.name ?: run {
logger.warn("User profile missing")
"Unknown"
}
```
```
`
**Pattern: Progressive Complexity**
`
```markdown
### Coroutine Patterns
#### Basic: Single Suspend Function
```
kotlin
suspend fun fetchUser(id: String): User {
return api.getUser(id)
}
```
#### Intermediate: Parallel Operations
```
kotlin
suspend fun fetchUserData(id: String): UserData = coroutineScope {
val user = async { api.getUser(id) }
val posts = async { api.getPosts(id) }
UserData(user.await(), posts.await())
}
```
#### Advanced: Error Handling + Timeout
```
kotlin
suspend fun fetchUserData(id: String): Result<UserData> = try {
withTimeout(5000) {
coroutineScope {
val user = async { api.getUser(id) }
val posts = async { api.getPosts(id) }
Result.success(UserData(user.await(), posts.await()))
}
}
} catch (e: TimeoutCancellationException) {
Result.failure(Exception("Request timeout"))
} catch (e: Exception) {
logger.error("Failed to fetch user data", e)
Result.failure(e)
}
```
```
`
### 6.3 Visual Indicators and Icons
**Emoji Strategy**:
```markdown
## Status Indicators
β
**CORRECT**: Recommended approach
β **WRONG**: Anti-pattern to avoid
β οΈ **WARNING**: Deprecated but still in codebase
π **MIGRATION**: Transitioning from old to new
π **NOTE**: Important context
π‘ **TIP**: Helpful suggestion
π **BEST PRACTICE**: Optimal solution
## Priority Levels
π΄ **CRITICAL**: Must fix immediately
π‘ **IMPORTANT**: Address in current sprint
π’ **NICE-TO-HAVE**: Future improvement
```
### 6.4 Structured Documentation Patterns
**Pattern: ADR (Architecture Decision Record)**
```markdown
# Spring Boot Migration (ADR-003)
## Status
β
**Accepted** (2025-11-15)
## Context
- Legacy Java EE application with 200k LOC
- Maintenance burden increasing
- Team expertise shifting to Kotlin + Spring
## Decision
Migrate to Spring Boot 3.2 + Kotlin incrementally.
## Consequences
### Positive
- Modern framework with active ecosystem
- Kotlin coroutines for async operations
- Simplified configuration
### Negative
- 6-month migration timeline
- Temporary dual-stack complexity
- Learning curve for junior developers
## Implementation
See `docs/migration/spring-boot-plan.md`
```
**Pattern: Checklist Template**
```markdown
## API Endpoint Checklist
Before merging any new REST endpoint:
- [ ] Request DTO validated with `@Valid`
- [ ] Response DTO documented with OpenAPI annotations
- [ ] Error handling with `@ExceptionHandler`
- [ ] Unit tests with MockMvc
- [ ] Integration tests with Testcontainers
- [ ] API documented in Swagger
- [ ] Rate limiting configured
- [ ] Authentication/authorization checked
- [ ] Logging added (request/response)
- [ ] Metrics recorded (latency, errors)
```
---
## 7. Global vs Project Rules
### 7.1 Global Rules System
**Location**: Stored in IDE user configuration directory
**Platform Paths**:
```
Windows: %APPDATA%\JetBrains\[IDE][Version]\ai-assistant\rules\
macOS: ~/Library/Application Support/JetBrains/[IDE][Version]/ai-assistant/rules/
Linux: ~/.config/JetBrains/[IDE][Version]/ai-assistant/rules/
```
**Example**:
```
~/.config/JetBrains/IntelliJIdea2024.3/ai-assistant/rules/
βββ personal-preferences.md
βββ kotlin-personal-style.md
βββ general-workflow.md
```
**Access via IDE**:
1. Settings β Tools β AI Assistant β Rules
2. Click **"Global Rules"** tab
3. Create/edit global rules
**Use Cases**:
- Personal coding preferences
- Organization-wide standards (if using centralized config)
- Language conventions you follow across all projects
**Example Global Rule**:
```markdown
# Personal Kotlin Preferences
## Response Style
- Give concise answers
- Show code first, explain after
- Highlight breaking changes or gotchas
## My Coding Style
- Prefer `when` expressions over `if-else` chains
- Use extension functions liberally
- Prefer sealed classes for state modeling
- Always use trailing commas in multiline structures
## Git Commits
- I follow Conventional Commits
- Format: `type(scope): description`
- Types: feat, fix, refactor, docs, test, chore
```
### 7.2 Precedence and Overrides
**Rule Priority Order** (highest to lowest):
1. **Project rules** (`.aiassistant/rules/`)
2. **Global rules** (`~/.config/.../ai-assistant/rules/`)
3. **IDE defaults** (built-in AI behavior)
**Override Example**:
**Global Rule** (`~/.../kotlin-style.md`):
```markdown
## String Concatenation
Prefer string templates over concatenation.
```
**Project Rule** (`.aiassistant/rules/kotlin-style.md`):
```markdown
## String Concatenation
β οΈ **OVERRIDES GLOBAL RULE**
For this project: Use `StringBuilder` for performance-critical paths.
```kotlin
// β
CORRECT (performance-critical)
val result = StringBuilder()
.append(prefix)
.append(value)
.append(suffix)
.toString()
// β
ACCEPTABLE (readability-focused)
val result = "$prefix$value$suffix"
```
Choose based on context: StringBuilder for loops/heavy concatenation.
```
**Result**: Project rule takes precedence; AI uses `StringBuilder` in this project but string templates globally.
### 7.3 Sharing Global Rules Across Team
**Method 1: Centralized Settings Repository**
```bash
# Team shared settings repo
git clone git@github.com:company/jetbrains-settings.git
cd jetbrains-settings
./install.sh # Symlinks to user config directory
```
**Method 2: IDE Settings Sync**
1. Settings β Tools β Settings Repository
2. Add upstream URL: `https://github.com/company/jetbrains-settings`
3. **Merge**: Combines with local settings
4. **Auto-sync**: Pulls updates on IDE start
**Method 3: Manual Distribution**
```bash
# Package global rules
tar -czf team-ai-rules.tar.gz -C ~/.config/JetBrains/IntelliJIdea2024.3/ai-assistant/rules .
# Team members extract
mkdir -p ~/.config/JetBrains/IntelliJIdea2024.3/ai-assistant/rules
tar -xzf team-ai-rules.tar.gz -C ~/.config/JetBrains/IntelliJIdea2024.3/ai-assistant/rules
```
---
## 8. Advanced Configuration Patterns
### 8.1 Hierarchical Rules in Monorepos
**Scenario**: Monorepo with multiple sub-projects
```
company-monorepo/
βββ .aiassistant/
β βββ rules/
β βββ 01-company-standards.md # Root level (all projects)
βββ backend-api/
β βββ .aiassistant/
β β βββ rules/
β β βββ 02-kotlin-backend.md
β β βββ 03-spring-boot.md
β βββ src/
βββ frontend-app/
β βββ .aiassistant/
β β βββ rules/
β β βββ 02-typescript.md
β β βββ 03-react.md
β βββ src/
βββ shared-lib/
βββ .aiassistant/
β βββ rules/
β βββ 02-library-standards.md
βββ src/
```
**Loading Behavior**:
When working in `backend-api/`:
1. Load `company-monorepo/.aiassistant/rules/01-company-standards.md` (root)
2. Load `backend-api/.aiassistant/rules/*.md` (local)
3. Combined context for AI
**Best Practice**: Root rules = universal, sub-project rules = specific.
### 8.2 Dynamic Rule Selection
**Pattern: Environment-Specific Rules**
```markdown
# Database Rules
## Development Environment
Use H2 in-memory database:
```kotlin
// application-dev.yml
spring:
datasource:
url: jdbc:h2:mem:testdb
```
## Production Environment
β οΈ **PRODUCTION ONLY**
Use PostgreSQL with connection pooling:
```kotlin
// application-prod.yml
spring:
datasource:
url: ${DATABASE_URL}
hikari:
maximum-pool-size: 20
minimum-idle: 5
```
## Rules
When user mentions "development" β suggest H2
When user mentions "production" β suggest PostgreSQL with pooling
```
### 8.3 Language-Specific Rules
**Pattern: Per-Language Files**
```
.aiassistant/rules/
βββ kotlin-style.md # Pattern: **/*.kt
βββ java-legacy.md # Pattern: **/*.java
βββ typescript-frontend.md # Pattern: frontend/**/*.ts
βββ python-scripts.md # Pattern: scripts/**/*.py
βββ sql-migrations.md # Pattern: **/*.sql
```
**Rule Configuration**:
- Each file has **File Pattern** type
- Patterns ensure only relevant language rules load
**Example: `kotlin-style.md`**
```markdown
# Kotlin Style Guide
**File Pattern**: `**/*.kt`
---
## Extension Functions
Prefer extension functions for utility operations:
```kotlin
// β
CORRECT
fun String.toSlug(): String {
return this.lowercase()
.replace(Regex("[^a-z0-9]+"), "-")
.trim('-')
}
// Usage
val slug = "Hello World!".toSlug() // "hello-world"
// β AVOID: Utility class
object StringUtils {
fun toSlug(input: String): String { ... }
}
```
```
### 8.4 Framework-Specific Rules
**Pattern: Layered Architecture Rules**
```
.aiassistant/rules/
βββ spring-boot-general.md
βββ spring-controllers.md # Pattern: **/*Controller.kt
βββ spring-services.md # Pattern: **/*Service.kt
βββ spring-repositories.md # Pattern: **/*Repository.kt
βββ spring-config.md # Pattern: **/config/*.kt
```
**Example: `spring-repositories.md`**
```markdown
# Spring Data JPA Repositories
**File Pattern**: `**/*Repository.kt`
---
## Interface-Only Repositories
Repositories should be interfaces:
```kotlin
// β
CORRECT
interface UserRepository : JpaRepository<User, String> {
fun findByEmail(email: String): User?
@Query("SELECT u FROM User u WHERE u.createdAt > :since")
fun findRecentUsers(@Param("since") since: Instant): List<User>
}
// β WRONG: Concrete class
class UserRepository : JpaRepository<User, String> {
// No implementation needed!
}
```
## Query Methods Naming
Follow Spring Data naming conventions:
- `findBy...`: Single or multiple results
- `existsBy...`: Boolean check
- `countBy...`: Count results
- `deleteBy...`: Delete operation
Examples:
```kotlin
fun findByEmailAndActive(email: String, active: Boolean): User?
fun existsByEmail(email: String): Boolean
fun countByRole(role: Role): Long
fun deleteByCreatedAtBefore(cutoff: Instant): Long
```
```
### 8.5 Testing-Specific Rules
**Pattern: Test Type Segregation**
```
.aiassistant/rules/
βββ testing-unit.md # Pattern: **/test/**/unit/**/*Test.kt
βββ testing-integration.md # Pattern: **/test/**/integration/**/*Test.kt
βββ testing-e2e.md # Pattern: **/test/**/e2e/**/*Test.kt
βββ testing-general.md # Always apply
```
**Example: `testing-integration.md`**
```markdown
# Integration Testing Standards
**File Pattern**: `**/test/**/integration/**/*Test.kt`
---
## Testcontainers Setup
All integration tests use Testcontainers:
```kotlin
@SpringBootTest
@Testcontainers
class UserRepositoryIntegrationTest {
companion object {
@Container
val postgres = PostgreSQLContainer<Nothing>("postgres:15-alpine").apply {
withDatabaseName("testdb")
withUsername("test")
withPassword("test")
}
@JvmStatic
@DynamicPropertySource
fun properties(registry: DynamicPropertyRegistry) {
registry.add("spring.datasource.url", postgres::getJdbcUrl)
registry.add("spring.datasource.username", postgres::getUsername)
registry.add("spring.datasource.password", postgres::getPassword)
}
}
@Test
fun `should persist and retrieve user`() {
val user = User(id = UUID.randomUUID(), email = "test@example.com")
userRepository.save(user)
val found = userRepository.findByEmail("test@example.com")
assertThat(found).isEqualTo(user)
}
}
```
## Transaction Rollback
Use `@Transactional` with rollback:
```kotlin
@SpringBootTest
@Transactional // Rolls back after each test
class ServiceIntegrationTest {
// Tests here
}
```
```
---
## 9. Integration with `.idea/` Settings
### 9.1 Understanding `.idea/` Directory
**Purpose**: IntelliJ project configuration (modules, libraries, code styles, run configurations).
**Key Files**:
```
.idea/
βββ ai-assistant.xml # AI rule metadata (auto-generated)
βββ workspace.xml # User-specific (open files, layout)
βββ modules.xml # Project modules
βββ vcs.xml # VCS configuration
βββ codeStyles/
β βββ Project.xml # Code formatting rules
βββ inspectionProfiles/
β βββ Project_Default.xml # Code inspections
βββ runConfigurations/ # Run/debug configs
```
### 9.2 `ai-assistant.xml` Structure
**File**: `.idea/ai-assistant.xml`
**Content** (example):
```xml
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="AIAssistantSettings">
<option name="projectRules">
<list>
<ProjectRule>
<option name="path" value="$PROJECT_DIR$/.aiassistant/rules/kotlin-standards.md" />
<option name="type" value="ALWAYS" />
</ProjectRule>
<ProjectRule>
<option name="path" value="$PROJECT_DIR$/.aiassistant/rules/spring-patterns.md" />
<option name="type" value="FILE_PATTERN" />
<option name="patterns">
<list>
<option value="**/*Controller.kt" />
<option value="**/*Service.kt" />
</list>
</option>
</ProjectRule>
<ProjectRule>
<option name="path" value="$PROJECT_DIR$/.aiassistant/rules/performance.md" />
<option name="type" value="MODEL_DECISION" />
<option name="description" value="Apply when discussing performance optimization or slow operations" />
</ProjectRule>
</list>
</option>
</component>
</project>
```
**Should You Edit Manually?**
β **Not Recommended**: Use IDE UI instead (Settings β AI Assistant β Rules)
**Should You Commit?**
β οΈ **Team Decision**:
- **Pros**: Consistent rule activation across team
- **Cons**: May conflict with personal preferences
**Typical Approach**: Commit `.idea/ai-assistant.xml` but document that team members can override locally.
### 9.3 Code Styles Integration
**Synergy**: AI rules + IDE code styles
**Code Style** (`.idea/codeStyles/Project.xml`):
- Defines formatting (indentation, braces, spacing)
- Applied automatically on **Reformat Code** (`Ctrl+Alt+L`)
**AI Rules** (`.aiassistant/rules/*.md`):
- Guide AI-generated code structure and patterns
- AI respects code style implicitly (IDE reformats after generation)
**Example Workflow**:
1. AI generates code following rules
2. IDE automatically reformats using Project code style
3. Result: Consistent formatting + correct patterns
**Best Practice**: Define detailed formatting in Code Styles, high-level patterns in AI rules.
### 9.4 Inspection Profiles Integration
**Inspection Profile** (`.idea/inspectionProfiles/Project_Default.xml`):
- Defines code warnings/errors (unused variables, potential NPE, etc.)
- IDE highlights issues in editor
**AI Rules Reference Inspections**:
```markdown
# Kotlin Code Quality
## Unused Code
IDE inspection "Unused declaration" is enabled.
When generating code:
- No unused imports
- No unused parameters (prefix with `_` if unavoidable)
- No dead code or commented-out blocks
## Null Safety
IDE inspection "Unsafe call on nullable receiver" is FATAL.
Always use safe calls:
```kotlin
// β
CORRECT
val length = user?.name?.length ?: 0
// β WRONG: IDE error
val length = user!!.name.length // Force unwrap triggers inspection
```
```
**Alignment Strategy**:
1. Enable strict inspections in IDE
2. Document them in AI rules
3. AI generates inspection-compliant code
4. Manual verification easier (fewer yellow/red highlights)
---
## 10. Multi-Module and Monorepo Setup
### 10.1 Gradle Multi-Module Projects
**Project Structure**:
```
my-app/
βββ .aiassistant/
β βββ rules/
β βββ root-standards.md # Root-level rules
βββ app/ # Application module
β βββ .aiassistant/
β β βββ rules/
β β βββ app-specific.md
β βββ build.gradle.kts
βββ domain/ # Domain module
β βββ .aiassistant/
β β βββ rules/
β β βββ domain-rules.md
β βββ build.gradle.kts
βββ infrastructure/ # Infrastructure module
β βββ .aiassistant/
β β βββ rules/
β β βββ infra-rules.md
β βββ build.gradle.kts
βββ settings.gradle.kts
βββ build.gradle.kts
```
**Rule Loading Behavior**:
Working in `domain/src/main/kotlin/User.kt`:
1. **Root rules** load: `my-app/.aiassistant/rules/root-standards.md`
2. **Module rules** load: `domain/.aiassistant/rules/domain-rules.md`
3. **Combined context** guides AI
**Root Standards Example**:
```markdown
# Root Standards (All Modules)
## Universal Requirements
1. **Kotlin 1.9+** across all modules
2. **JUnit 5** for testing
3. **SLF4J** for logging
4. **Arrow** for functional patterns
## Dependency Rules
- Core domain: ZERO external dependencies
- Infrastructure: Can depend on Spring, database drivers
- App: Orchestrates domain + infrastructure
## Testing
- Unit tests: `src/test/kotlin`
- Integration tests: `src/integration/kotlin`
- All tests must be deterministic (no random values without seeds)
```
**Module-Specific Example** (`domain/.aiassistant/rules/domain-rules.md`):
```markdown
# Domain Module Rules
## Pure Business Logic
Domain module is **framework-agnostic**:
```kotlin
// β
CORRECT: Pure Kotlin
data class User(
val id: UserId,
val email: Email,
val profile: UserProfile
) {
fun updateProfile(newProfile: UserProfile): User {
return copy(profile = newProfile)
}
}
// β WRONG: Spring annotations in domain
@Entity
@Table(name = "users")
data class User(...) { // NO! This is infrastructure concern
@Id val id: String
}
```
## Value Objects
Wrap primitives:
```kotlin
// β
CORRECT
@JvmInline
value class Email(val value: String) {
init {
require(value.contains("@")) { "Invalid email" }
}
}
// β WRONG: Primitive obsession
typealias Email = String // No validation!
```
```
### 10.2 Maven Multi-Module Projects
**Project Structure**:
```
parent-project/
βββ .aiassistant/
β βββ rules/
β βββ parent-pom-standards.md
βββ module-a/
β βββ .aiassistant/
β β βββ rules/
β β βββ module-a-rules.md
β βββ pom.xml
βββ module-b/
β βββ .aiassistant/
β β βββ rules/
β β βββ module-b-rules.md
β βββ pom.xml
βββ pom.xml
```
**Parent POM Rules**:
```markdown
# Maven Parent POM Standards
## Dependency Management
All versions declared in parent `<dependencyManagement>`:
```xml
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-dependencies</artifactId>
<version>3.2.0</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
```
Child modules inherit versions (no version tags):
```xml
<!-- Child pom.xml -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<!-- No <version> tag! -->
</dependency>
```
## Module Naming
- `module-a`: Lowercase, hyphenated
- `artifactId`: Matches directory name
- `groupId`: `com.company.project`
```
### 10.3 Cross-Module Dependencies
**Pattern: Document Module Boundaries**
```markdown
# Module Dependency Rules
## Allowed Dependencies
```mermaid
graph TD
A[app] --> D[domain]
A --> I[infrastructure]
I --> D
```
- **app** β domain, infrastructure
- **infrastructure** β domain
- **domain** β NOTHING (pure)
## Forbidden Dependencies
β **domain** β infrastructure (violates clean architecture)
β **domain** β app (violates layering)
## Enforcement
Add to parent `pom.xml`:
```xml
<plugin>
<groupId>com.github.ferstl</groupId>
<artifactId>depgraph-maven-plugin</artifactId>
<configuration>
<failOn>
<forbidden>true</forbidden>
</failOn>
</configuration>
</plugin>
```
```
### 10.4 Shared Rules Across Modules
**Pattern: Symlinks to Shared Rules**
```bash
# Create shared rules at root
mkdir -p .aiassistant/rules/shared
touch .aiassistant/rules/shared/kotlin-common.md
# Symlink from modules
cd module-a/.aiassistant/rules
ln -s ../../../.aiassistant/rules/shared/kotlin-common.md .
cd ../../module-b/.aiassistant/rules
ln -s ../../../.aiassistant/rules/shared/kotlin-common.md .
```
**Result**: Update shared rules once, applies to all modules.
---
## 11. Cross-IDE Compatibility
### 11.1 Multi-Tool Team Scenarios
**Scenario**: Team uses JetBrains IDEs + Cursor + Windsurf
**Strategy: Universal `AGENTS.md` + IDE-Specific Wrappers**
```
my-project/
βββ AGENTS.md # Universal standard (master)
βββ .aiassistant/
β βββ rules/
β βββ jetbrains-wrapper.md # References AGENTS.md
βββ .cursor/
β βββ rules/
β βββ index.mdc # References AGENTS.md
βββ .windsurfrules -> AGENTS.md # Symlink
```
**`jetbrains-wrapper.md`**:
```markdown
# JetBrains AI Assistant Rules
## Shared Standards
See `AGENTS.md` at project root for complete coding standards.
---
## JetBrains-Specific Notes
### Code Generation Shortcuts
- **Alt+Enter** β Quick fix actions
- **Ctrl+Shift+A** β "Generate code with AI"
- **Alt+Shift+A** β AI Chat panel
### Module Context
JetBrains AI automatically includes:
- Current module structure
- Build file context (build.gradle.kts, pom.xml)
- Test framework configuration
No need to repeat in rulesβAI already sees it.
### Inspection Integration
AI respects enabled inspections. If code triggers warnings:
1. AI will avoid patterns causing warnings
2. Check **Settings β Editor β Inspections** for active checks
```
### 11.2 Portable Rule Patterns
**Pattern: Tool-Agnostic Markdown**
```markdown
# React Component Standards
**Compatible With**: JetBrains WebStorm, Cursor, Windsurf, VS Code
---
## Functional Components Only
```tsx
// β
CORRECT
export function UserProfile({ user }: Props) {
return <div>{user.name}</div>;
}
// β WRONG
export class UserProfile extends React.Component {
render() {
return <div>{this.props.user.name}</div>;
}
}
```
## Hooks Over Lifecycle
```tsx
// β
CORRECT
function DataFetcher() {
useEffect(() => {
fetchData();
}, []);
}
// β WRONG
class DataFetcher extends Component {
componentDidMount() {
this.fetchData();
}
}
```
```
**Avoidance List** (don't include in portable rules):
- Tool-specific shortcuts (`Cmd+K in Cursor`)
- File path references specific to tool structure
- Tool-specific features (`@cursorrules` syntax)
### 11.3 Syncing Rules with External Tools
**Sync Script Example**:
```bash
#!/bin/bash
# sync-ai-rules.sh
MASTER="AGENTS.md"
JETBRAINS=".aiassistant/rules/shared-standards.md"
CURSOR=".cursor/rules/00-shared.mdc"
WINDSURF=".windsurfrules"
echo "π Syncing AI rules from $MASTER..."
# Copy to JetBrains
cp "$MASTER" "$JETBRAINS"
# Copy to Cursor (strip if has frontmatter)
cp "$MASTER" "$CURSOR"
# Symlink to Windsurf
ln -sf "$MASTER" "$WINDSURF"
echo "β
Rules synced to all tools"
```
**Git Hook** (`.git/hooks/post-commit`):
```bash
#!/bin/bash
# Auto-sync rules after commit
if git diff HEAD~1 --name-only | grep -q "AGENTS.md"; then
./sync-ai-rules.sh
echo "π AI rules auto-synced"
fi
```
---
## 12. Migration from Other Tools
### 12.1 Migrating from Cursor
**Source**: `.cursor/rules/*.mdc` files with YAML frontmatter
**Process**:
**Step 1: Extract Content**
```bash
# Remove YAML frontmatter from Cursor files
for file in .cursor/rules/*.mdc; do
basename=$(basename "$file" .mdc)
# Skip lines between first --- and second ---
sed '1{/^---$/!q;};/^---$/,/^---$/d' "$file" > ".aiassistant/rules/${basename}.md"
done
```
**Step 2: Configure in JetBrains**
1. Settings β AI Assistant β Rules
2. Add each file
3. Map `globs` from Cursor frontmatter to JetBrains "File Pattern" setting
### 12.2 Migrating from GitHub Copilot
**Source**: `.github/copilot-instructions.md`
**Process**:
**Step 1: Copy File**
```bash
mkdir -p .aiassistant/rules
cp .github/copilot-instructions.md .aiassistant/rules/github-copilot-import.md
```
**Step 2: Split (Optional but Recommended)**
Copilot instructions are often monolithic. Split into:
- `general-standards.md`
- `language-specific.md`
- `testing-guide.md`
**Step 3: Configure**
1. Settings β AI Assistant β Rules
2. Add files
3. Set Rule Type:
- General β **Always**
- Language-specific β **File Pattern**
### 12.3 Migrating from Continue.dev
**Source**: `.continue/rules/*.md`
**Process**:
**Step 1: Copy Rules**
```bash
cp -r .continue/rules/ .aiassistant/rules/
```
**Step 2: Clean Up**
Remove Continue.dev frontmatter if present (though JetBrains will just ignore it as text).
**Step 3: Configure**
Map Continue frontmatter `globs` to JetBrains File Patterns.
### 12.4 Migrating from Claude Code
**Source**: `CLAUDE.md`
**Process**:
**Step 1: Copy File**
```bash
cp CLAUDE.md .aiassistant/rules/claude-code-import.md
```
**Step 2: Configure**
Set Rule Type β **Always**.
**Note**: `CLAUDE.md` is usually well-structured for JetBrains as-is.
---
## 13. Troubleshooting and Common Issues
### 13.1 Rules Not Applying
**Symptom**: AI ignores instructions in generated code.
**Diagnostic Steps**:
1. **Check Rule Activation**:
- Open AI Chat
- Type `/rules` (if supported) or ask "What rules are active?"
- Verify your rule file is listed
2. **Check File Pattern**:
- Verify glob syntax: `**/*.kt` vs `*.kt`
- `*.kt` only matches files in root!
- Always use `**` prefix for recursive match: `src/**/*.kt`
3. **Check Context Window**:
- If rule file is huge (>50KB), it might be truncated
- Split large rules into smaller, focused files
4. **Check Conflicts**:
- Do multiple rules contradict each other?
- Does a global rule override project rule?
### 13.2 "Rule Not Found" Error
**Symptom**: IDE settings show broken link to rule file.
**Causes**:
- File deleted or renamed externally
- File moved to different directory
- Git branch switch removed file
**Fix**:
1. Open Settings β AI Assistant β Rules
2. Remove invalid entry (red text)
3. Re-add correct file path
### 13.3 AI Hallucinating Non-Existent Rules
**Symptom**: AI claims to follow a rule that doesn't exist.
**Cause**: Over-generalization from training data or confusion with standard practices.
**Fix**:
- Add **explicit** rule clarifying the behavior
- Use "NEVER" constraints:
```markdown
β NEVER assume we use Lombok (we use standard getters/setters)
```
### 13.4 Metadata Sync Issues
**Symptom**: Team members don't see rules despite files being in repo.
**Cause**: Rule *files* are committed (`.aiassistant/rules/*.md`), but *metadata* (`.idea/ai-assistant.xml`) is not.
**Fix**:
1. **Option A**: Commit `.idea/ai-assistant.xml`
2. **Option B**: Document setup steps for new devs ("Go to Settings -> Add these files...")
3. **Option C**: Use "Always" rules in `project-overview.md` which tends to be auto-discovered (version dependent)
---
## 14. Production Examples
### 14.1 Enterprise Java/Spring Boot
**File**: `.aiassistant/rules/spring-enterprise.md`
```markdown
# Enterprise Spring Boot Standards
**Rule Type**: Always Apply
---
## Logging Standards
All logs must be structured JSON for Splunk ingestion.
```java
// β
CORRECT
log.info("Order processed", Map.of(
"orderId", order.getId(),
"amount", order.getAmount(),
"status", "SUCCESS"
));
// β WRONG
log.info("Order processed: " + order.getId());
```
## Transaction Management
- Service layer methods: `@Transactional(readOnly = true)`
- Write methods: `@Transactional`
- Never call transactional methods from within same class (proxy bypass)
## API Versioning
All controllers must use header versioning:
```java
@GetMapping(value = "/users", headers = "X-API-VERSION=1")
```
```
### 14.2 React + TypeScript Frontend
**File**: `.aiassistant/rules/react-standards.md`
```markdown
# React Component Standards
**Rule Type**: File Pattern (`src/**/*.tsx`)
---
## Component Definition
Functional components with named exports:
```tsx
// β
CORRECT
interface Props {
title: string;
}
export const PageHeader = ({ title }: Props) => (
<h1>{title}</h1>
);
// β WRONG
export default function PageHeader(props: any) { ... }
```
## Styling
Use Tailwind CSS via `className`:
```tsx
// β
CORRECT
<div className="flex items-center justify-between p-4">
// β WRONG
<div style={{ display: 'flex', padding: '1rem' }}>
```
```
### 14.3 Python Data Science
**File**: `.aiassistant/rules/pandas-polars.md`
```markdown
# Data Processing Rules
**Rule Type**: Model Decision ("Pandas, Polars, dataframes, ETL")
---
## Library Choice
Prefer **Polars** over Pandas for large datasets (>1GB):
```python
# β
CORRECT (Large data)
import polars as pl
df = pl.read_csv("large_file.csv")
# β
ACCEPTABLE (Small data)
import pandas as pd
df = pd.read_csv("small_config.csv")
```
## Type Hinting
Always type hint DataFrames:
```python
def process_data(df: pl.DataFrame) -> pl.DataFrame:
...
```
```
---
## 15. Best Practices
### 15.1 Maintenance
- **Audit Quarterly**: Check for outdated rules (e.g., Java 17 β 21 updates)
- **Verify Links**: Ensure links to internal docs work
- **Prune**: Remove rules that AI has "learned" natively in newer models
### 15.2 Team Alignment
- **PR Reviews**: If AI generates bad code, **update the rules**, don't just fix the code
- **Onboarding**: New devs read rules to understand project standards
- **Feedback Loop**: Create `#ai-rules` Slack channel for suggestions
### 15.3 Performance
- **Keep Files Small**: < 500 lines per file
- **Use Patterns**: Don't load Python rules for Kotlin files
- **Avoid Noise**: Don't document basic language syntax (AI knows `if/else`)
### 15.4 Security
- **Zero Trust**: Don't put secrets in rule files
- **Sanitization**: Explicitly tell AI to sanitize logs
- **Compliance**: Add rules for GDPR/PII handling
Top comments (0)