# Cursor AI Rules for AIWF Projects

## Project Context
This project uses the AI Workflow Framework (AIWF) for structured development with AI assistance. Follow these rules to ensure Cursor provides AIWF-aware suggestions.

## Core Principles

### 1. Feature-Driven Development
- Always check Feature Ledger before implementing new features
- Reference Feature IDs (FL###) in all related code
- Maintain feature traceability throughout the codebase

### 2. Sprint-Aligned Coding
- Reference current sprint tasks in implementations
- Update task status as work progresses
- Follow sprint acceptance criteria strictly

### 3. Persona-Based Development
- Apply appropriate coding style based on active persona
- Switch personas for different types of work
- Document persona usage in code comments

## AIWF Integration Rules

### Feature References
```javascript
/**
 * @feature FL001 - User Authentication System
 * @task TX01_S01 - Implement login functionality
 * @persona developer
 */
```

### Sprint Context
```javascript
// Sprint: S01_M02 - Authentication Foundation
// Task: TX01_S01
// Status: in_progress
// Acceptance Criteria:
// - [ ] User can log in with email/password
// - [ ] Sessions are managed securely
// - [ ] Rate limiting is implemented
```

### Error Handling with Context
```javascript
class FeatureError extends Error {
  constructor(message, context) {
    super(`[${context.featureId}/${context.taskId}] ${message}`);
    this.feature = context.featureId;
    this.task = context.taskId;
    this.timestamp = new Date().toISOString();
  }
}
```

## Code Generation Guidelines

### 1. Documentation Standards
Every function/class must include:
- Feature ID reference
- Task ID (if applicable)
- Active persona
- Brief description
- Example usage

### 2. Naming Conventions
- Features: `FL###_FeatureName`
- Tasks: `TX##_S##_TaskName`
- Sprints: `S##_M##_SprintName`
- Files: `feature-id_component-name.ext`

### 3. Import Organization
```javascript
// External dependencies
import express from 'express';
import jwt from 'jsonwebtoken';

// AIWF core imports
import { FeatureLedger } from '@aiwf/core';
import { TaskManager } from '@aiwf/tasks';

// Project imports
import { AuthService } from './services/auth.service';

// Feature-specific imports
import { FL001_UserAuth } from './features/FL001_user_auth';
```

## Persona-Specific Patterns

### Architect Persona
Focus on:
- System design patterns
- Architecture documentation
- Technology decisions
- Scalability considerations

```javascript
// Architect persona active
interface IAuthenticationStrategy {
  authenticate(credentials: ICredentials): Promise<IAuthResult>;
  refresh(token: string): Promise<IAuthResult>;
  revoke(token: string): Promise<void>;
}

// Suggest factory patterns, dependency injection, etc.
```

### Security Persona
Focus on:
- Input validation
- Security best practices
- Vulnerability prevention
- Audit logging

```javascript
// Security persona active
class SecureAuthService {
  async authenticate(credentials) {
    // Input sanitization
    this.validator.sanitize(credentials);
    
    // Rate limiting check
    await this.rateLimiter.check(credentials.email);
    
    // Secure password comparison
    const isValid = await bcrypt.compare(
      credentials.password,
      hashedPassword
    );
    
    // Audit log
    this.auditLogger.log('auth_attempt', {
      email: credentials.email,
      success: isValid,
      ip: request.ip,
      timestamp: new Date()
    });
  }
}
```

### Developer Persona
Focus on:
- Clean implementation
- Error handling
- Testing
- Performance

```javascript
// Developer persona active
class UserController {
  constructor(
    private authService: AuthService,
    private logger: Logger
  ) {}

  async login(req: Request, res: Response) {
    try {
      const result = await this.authService.authenticate(req.body);
      
      res.json({
        success: true,
        data: result
      });
      
      this.logger.info('User logged in', { userId: result.user.id });
    } catch (error) {
      this.logger.error('Login failed', error);
      
      res.status(401).json({
        success: false,
        error: 'Authentication failed'
      });
    }
  }
}
```

## Testing Guidelines

### Test Structure
```javascript
describe('Feature FL001: User Authentication', () => {
  describe('Task TX01_S01: Login Implementation', () => {
    describe('Acceptance Criteria', () => {
      it('should authenticate valid credentials', async () => {
        // Test implementation
      });
      
      it('should reject invalid credentials', async () => {
        // Test implementation
      });
      
      it('should enforce rate limiting', async () => {
        // Test implementation
      });
    });
  });
});
```

### Test Documentation
```javascript
/**
 * Test Suite: User Authentication
 * @feature FL001
 * @sprint S01_M02
 * @coverage Unit, Integration
 */
```

## Git Integration

### Commit Message Format
```
<type>(<feature-id>): <description>

<body>

Task: <task-id>
Sprint: <sprint-id>
Persona: <active-persona>
```

Example:
```
feat(FL001): implement JWT authentication

- Add token generation service
- Implement refresh token logic
- Add token validation middleware

Task: TX01_S01
Sprint: S01_M02
Persona: developer
```

### Branch Naming
```
feature/FL###-short-description
task/TX##-S##-task-name
bugfix/FL###-issue-description
```

## Code Review Checklist

When reviewing code, ensure:
- [ ] Feature ID is referenced
- [ ] Task requirements are met
- [ ] Appropriate persona patterns are used
- [ ] AIWF conventions are followed
- [ ] Documentation is complete
- [ ] Tests cover acceptance criteria
- [ ] Security considerations are addressed
- [ ] Performance impact is acceptable

## Quick Commands

Include these in comments for quick actions:
```javascript
// @aiwf-check-feature - Verify feature exists in ledger
// @aiwf-update-task - Update task progress
// @aiwf-switch-persona - Change active persona
// @aiwf-link-sprint - Link to current sprint
```

## AI Behavior Modifiers

### Context-Aware Suggestions
- Prioritize AIWF patterns
- Include feature/task references
- Apply persona-specific styles
- Maintain project consistency

### Auto-Complete Preferences
1. AIWF-specific imports first
2. Feature-based function names
3. Task-aligned variable names
4. Persona-appropriate patterns

## Integration Points

### Feature Ledger
```javascript
// Always validate against Feature Ledger
const ledger = new FeatureLedger();
const feature = await ledger.getFeature('FL001');

if (feature.status !== 'active') {
  throw new FeatureError('Feature not active', {
    featureId: 'FL001',
    status: feature.status
  });
}
```

### Task Management
```javascript
// Update task progress
const taskManager = new TaskManager();
await taskManager.updateProgress('TX01_S01', {
  percentage: 75,
  notes: 'Authentication implemented, testing remaining'
});
```

### Sprint Tracking
```javascript
// Get current sprint context
const sprint = await aiwf.getCurrentSprint();
console.log(`Working on: ${sprint.name} (${sprint.id})`);
```

## Performance Considerations

### Feature-Specific Optimization
```javascript
// Include performance metrics per feature
/**
 * @feature FL001
 * @performance Target: <100ms response time
 * @performance Current: 85ms average
 */
```

### Caching Strategy
```javascript
// Feature-aware caching
const cacheKey = `feature:${featureId}:${userId}`;
const cached = await cache.get(cacheKey);
```

## Security Patterns

### Feature-Level Security
```javascript
// Apply security based on feature requirements
@FeatureSecurity('FL001', ['auth:read', 'auth:write'])
class AuthenticationEndpoint {
  // Implementation
}
```

### Audit Logging
```javascript
// Include feature context in audit logs
auditLogger.log({
  action: 'user.login',
  feature: 'FL001',
  task: 'TX01_S01',
  user: userId,
  timestamp: new Date(),
  result: 'success'
});
```

---

*Cursor AI Rules for AIWF Integration v1.0.0*
*These rules ensure Cursor provides AIWF-aware code suggestions and maintains project consistency*