diff --git a/.ai/README.md b/.ai/README.md new file mode 100644 index 0000000000..33fbc124f2 --- /dev/null +++ b/.ai/README.md @@ -0,0 +1,124 @@ +# RedisInsight AI Development Rules + +This directory contains the **single source of truth** for AI-assisted development rules and workflows in RedisInsight. These rules are used by multiple AI coding assistants: + +- **Cursor** (via symlinks: `.cursor/rules/` and `.cursor/commands/`) +- **Augment** (via symlink: `.augment/`) +- **Windsurf** (via symlink: `.windsurfrules`) +- **GitHub Copilot** (via file: `.github/copilot-instructions.md`) + +## MCP (Model Context Protocol) Setup + +AI tools can access external services (JIRA, Confluence, GitHub) via MCP configuration. + +### Initial Setup + +1. **Copy the example configuration:** + + ```bash + cp env.mcp.example .env.mcp + ``` + +2. **Get your Atlassian API token:** + + - Go to: https://id.atlassian.com/manage-profile/security/api-tokens + - Create a classic token by pressing the first "Create Token" button + - Copy the token + +3. **Edit `.env.mcp` with your credentials:** + +4. **Verify your setup:** + + **For Cursor users:** + + - Restart Cursor to load the new MCP configuration + - Ask the AI: "Can you list all available MCP tools and test them?" + - The AI should be able to access JIRA, Confluence, GitHub, and other configured services + + **For Augment users:** + + ```bash + npx @augmentcode/auggie --mcp-config mcp.json "go over all my mcp tools and make sure they work as expected" + ``` + + **For GitHub Copilot users:** + + - Note: GitHub Copilot does not currently support MCP integration + - MCP services (JIRA, Confluence, etc.) will not be available in Copilot + +### Available MCP Services + +The `mcp.json` file configures these services: + +- **github** - GitHub integration (issues, PRs, repository operations) +- **memory** - Persistent context storage across sessions +- **sequential-thinking** - Enhanced reasoning for complex tasks +- **context-7** - Advanced context management +- **atlassian** - JIRA (RI-XXX tickets) and Confluence integration + +## Structure + +``` +.ai/ # 🎯 Single source of truth +├── README.md # Overview & quick reference +├── rules/ # Development standards (modular) +│ ├── code-quality.md # Linting, TypeScript standards +│ ├── frontend.md # React, Redux, UI patterns +│ ├── backend.md # NestJS, API patterns +│ ├── testing.md # Testing standards +│ ├── branches.md # Branch naming conventions +│ ├── commits.md # Commit message guidelines +│ └── pull-requests.md # Pull request process +└── commands/ # AI workflow commands + ├── commit-message.md # Commit message generation + └── pull-request-review.md # PR review workflow + +# Symlinks (all AI tools read from .ai/) +.cursor/ + ├── rules/ -> ../.ai/rules/ # Cursor AI (rules) + └── commands/ -> ../.ai/commands/ # Cursor AI (commands) +.augment/ -> .ai/ # Augment AI +.windsurfrules -> .ai/ # Windsurf AI +.github/copilot-instructions.md # GitHub Copilot +``` + +## Project Overview + +**RedisInsight** is a desktop application for Redis database management built with: + +- **Frontend**: React 18, TypeScript, Redux Toolkit, Elastic UI, Monaco Editor, Vite +- **Backend**: NestJS, TypeScript, Node.js +- **Desktop**: Electron for cross-platform distribution +- **Testing**: Jest, Testing Library, Playwright + +**Architecture**: + +``` +redisinsight/ +├── ui/ # React frontend (Vite + TypeScript) +├── api/ # NestJS backend (TypeScript) +├── desktop/ # Electron main process +└── tests/ # E2E tests (Playwright) +``` + +## Detailed Guidelines + +All detailed development standards, coding practices, and workflows are maintained in modular files: + +- **Code Quality Standards**: See `.ai/rules/code-quality.md` +- **Frontend Patterns**: See `.ai/rules/frontend.md` +- **Backend Patterns**: See `.ai/rules/backend.md` +- **Testing Standards**: See `.ai/rules/testing.md` +- **Branch Naming**: See `.ai/rules/branches.md` +- **Commit Messages**: See `.ai/rules/commits.md` +- **Pull Request Process**: See `.ai/rules/pull-requests.md` + +## Updating These Rules + +To update AI rules: + +1. **Edit files in `.ai/` only** (never edit symlinked files directly) +2. Changes automatically propagate to all AI tools +3. Commit changes to version control + +**Remember**: These rules exist to maintain code quality and consistency. Follow them, but also use good judgment. diff --git a/.ai/commands/commit-message.md b/.ai/commands/commit-message.md new file mode 100644 index 0000000000..18f9852a95 --- /dev/null +++ b/.ai/commands/commit-message.md @@ -0,0 +1,112 @@ +# Commit Message Generation + +Generate concise, meaningful commit messages following RedisInsight conventions. + +## Format + +``` +(): + +[optional body] + +References: #RI-XXX +``` + +## Types & Scopes + +**Types**: `feat`, `fix`, `refactor`, `test`, `docs`, `chore`, `perf`, `ci` + +**Scopes**: `api`, `ui`, `e2e`, `deps` + +## Rules + +**DO:** +- ✅ Always include scope: `feat(api):`, `fix(ui):` +- ✅ Use imperative mood: "add feature" not "added feature" +- ✅ Start with lowercase after scope +- ✅ Keep subject under 250 characters +- ✅ Inspect all uncommitted files before generating + +**DON'T:** +- ❌ Omit scope +- ❌ Use past tense +- ❌ Add period at end +- ❌ Use multiple scopes (split into separate commits) + +## Examples + +```bash +feat(ui): add user profile editing +fix(api): resolve memory leak in connection pool +refactor(api): extract validation logic +test(e2e): add authentication tests +chore(deps): upgrade React to 18.2 +``` + +## Issue References + +**JIRA**: `References: #RI-123` or `Fixes #RI-123` +**GitHub**: `Fixes #123` or `Closes #123` + +## Process + +1. Run `git status && git diff` +2. Identify scope: API → `api`, UI → `ui`, Both → separate commits +3. Identify type: New → `feat`, Bug → `fix`, Improvement → `refactor` +4. Write description (what changed and why) +5. Add issue reference in body + +## Multiple Scopes + +Split into separate commits: + +```bash +# ✅ Good +git commit -m "feat(api): add user endpoint + +References: #RI-123" + +git commit -m "feat(ui): add user interface + +References: #RI-123" + +# ❌ Bad +git commit -m "feat(api,ui): add user feature" +``` + +## Output Format + +Present in copyable format: + +```markdown +Based on the changes, here's your commit message: + +\`\`\` +feat(api): add OAuth 2.0 authentication + +Implements OAuth flow with token management +and refresh token support. + +References: #RI-123 +\`\`\` +``` + +If multiple scopes: + +```markdown +Changes span multiple scopes. I recommend two commits: + +**Commit 1:** +\`\`\` +feat(api): add OAuth endpoints + +References: #RI-123 +\`\`\` + +**Commit 2:** +\`\`\` +feat(ui): add OAuth login interface + +References: #RI-123 +\`\`\` +``` diff --git a/.ai/commands/pull-request-review.md b/.ai/commands/pull-request-review.md new file mode 100644 index 0000000000..5bd884d866 --- /dev/null +++ b/.ai/commands/pull-request-review.md @@ -0,0 +1,205 @@ +# PR Review Command + +## Purpose + +Reviews code changes in the current branch against requirements, best practices, and project standards. + +## Usage + +```bash +/pr:review +``` + +**Examples**: + +- JIRA ticket: `/pr:review RI-1234` +- GitHub issue: `/pr:review 456` + +## Prerequisites + +1. Checkout the branch to review locally +2. Ensure the ticket ID is valid and accessible +3. Have JIRA MCP tool configured (if using JIRA integration) + +## Process + +### 1. Gather Context + +- Fetch JIRA ticket details (if available) +- Read requirements and acceptance criteria +- Identify affected files in the PR +- Review recent commits + +### 2. Code Analysis + +Analyze the changes against: + +- **Code Quality**: Linting rules, TypeScript types, complexity +- **Testing**: Test coverage, test quality, edge cases +- **Performance**: Rendering optimizations +- **Security**: Input validation, XSS prevention, credential handling +- **Accessibility**: ARIA labels, keyboard navigation, semantic HTML +- **Best Practices**: React patterns, Redux usage, NestJS conventions + +### 3. Requirements Check + +- Verify all acceptance criteria are met +- Check for missing functionality +- Validate edge case handling +- Ensure proper error messages + +### 4. Testing Validation + +- Unit test coverage (80% minimum) +- Integration tests for API endpoints +- Component tests for React components +- E2E tests for critical flows +- No fixed timeouts or magic numbers +- Use of faker for test data + +### 5. Generate Report + +Create a markdown report in `docs/reviews/pr--.md` with: + +**Note**: Use appropriate ticket reference format: + +- JIRA tickets: `pr-RI-1234-2024-11-20.md` +- GitHub issues: `pr-456-2024-11-20.md` + +Report should include: + +- **Summary**: Overview of changes +- **Strengths**: What was done well +- **Issues**: Categorized by severity (Critical, High, Medium, Low) +- **Suggestions**: Improvements and optimizations +- **Requirements Coverage**: Acceptance criteria checklist +- **Testing Assessment**: Coverage and quality analysis +- **Risk Assessment**: Potential issues or impacts + +## Review Checklist + +### Code Quality + +- [ ] No linting errors +- [ ] TypeScript types are proper (no `any` without justification) +- [ ] Code follows project conventions +- [ ] No console.log statements +- [ ] Import order is correct +- [ ] Cognitive complexity within limits +- [ ] No duplicate code + +### Testing + +- [ ] Unit tests added/updated +- [ ] Test coverage meets thresholds +- [ ] Tests use faker for data generation +- [ ] No fixed timeouts in tests +- [ ] Edge cases are tested +- [ ] Mocks are properly configured + +### React/Frontend (if applicable) + +- [ ] Functional components with hooks +- [ ] Proper state management (Redux vs local) +- [ ] Effects cleanup properly +- [ ] No unnecessary re-renders +- [ ] Accessibility considerations +- [ ] Styled-components for styling (no new SCSS modules) +- [ ] Proper error boundaries +- [ ] Component folder structure follows guidelines + +### NestJS/Backend (if applicable) + +- [ ] Dependency injection used properly +- [ ] DTOs for validation +- [ ] Proper error handling +- [ ] Swagger documentation +- [ ] Service layer separation +- [ ] Database transactions where needed + +### Performance + +- [ ] No performance regressions +- [ ] Large lists virtualized +- [ ] Routes lazy loaded +- [ ] Expensive operations memoized +- [ ] Bundle size impact acceptable + +### Security + +- [ ] Input validation +- [ ] Output sanitization +- [ ] No sensitive data in logs +- [ ] Proper authentication/authorization +- [ ] SQL injection prevention (if applicable) + +### Documentation + +- [ ] README updated if needed +- [ ] Complex logic documented +- [ ] API documentation updated +- [ ] Breaking changes noted + +## Example Output + +**Note**: Use appropriate ticket format (RI-1234 for JIRA or #456 for GitHub issues) + +```markdown +# PR Review: RI-1234 - Add User Profile Editing + +**Date**: 2024-11-20 +**Reviewer**: AI Assistant +**Branch**: feature/RI-1234/user-profile-editing + +## Summary + +This PR implements user profile editing functionality including UI components, +API endpoints, and data persistence. The implementation follows project +standards with good test coverage. + +## High Priority Issues + +1. **Missing Input Validation** (Security) + - File: `redisinsight/api/src/user/user.service.ts:45` + - Issue: Email validation missing on backend + - Recommendation: Add class-validator decorator to DTO + +## Medium Priority Issues + +1. **Performance Concern** (Performance) + + - File: `redisinsight/ui/src/components/UserProfile.tsx:78` + - Issue: Inline function in render + - Recommendation: Extract to useCallback + +2. **Test Flakiness Risk** (Testing) + - File: `redisinsight/ui/src/components/UserProfile.spec.tsx:45` + - Issue: Direct state check without waitFor + - Recommendation: Wrap assertion in waitFor + +## Low Priority Issues + +1. **Code Style** (Style) + - File: Multiple files + - Issue: Inconsistent import ordering + - Recommendation: Run `yarn prettier:fix` + +## Risk Assessment + +**Low Risk** - Well-tested implementation with minor issues that can be +addressed before merge. No breaking changes or security vulnerabilities. + +## Recommendation + +**Approve with comments** - Address high priority issues before merging. +Consider suggestions for future improvements. +``` + +## Notes + +- Focus on constructive feedback +- Prioritize issues by severity +- Be specific with file locations and line numbers +- Provide actionable recommendations +- Balance criticism with recognition of good practices +- Consider the broader impact of changes diff --git a/.ai/rules/backend.md b/.ai/rules/backend.md new file mode 100644 index 0000000000..16eda75b8a --- /dev/null +++ b/.ai/rules/backend.md @@ -0,0 +1,217 @@ +# Backend Development (NestJS/API) + +## Module Structure + +### NestJS Architecture + +- Follow **modular architecture** (feature-based modules) +- Use **dependency injection** throughout +- **Separate concerns**: Controllers, Services, Repositories +- Use **DTOs** for validation and data transfer +- Apply **proper error handling** with NestJS exceptions + +### Module Folder Structure + +Each feature module in its own directory under `api/src/`: + +``` +feature/ +├── feature.module.ts # Module definition +├── feature.controller.ts # REST endpoints +├── feature.service.ts # Business logic +├── feature.service.spec.ts # Service tests +├── feature.controller.spec.ts # Controller tests +├── feature.types.ts # Interfaces and types related to the feature +├── dto/ # Data transfer objects +│ ├── create-feature.dto.ts +│ ├── update-feature.dto.ts +│ └── feature.dto.ts +├── entities/ # TypeORM entities +├── repositories/ # Custom repositories +├── exceptions/ # Custom exceptions +├── guards/ # Feature-specific guards +├── decorators/ # Custom decorators +└── constants/ # Feature constants +``` + +### File Naming + +- **Modules**: `feature.module.ts` +- **Controllers**: `feature.controller.ts` +- **Services**: `feature.service.ts` +- **DTOs**: `create-feature.dto.ts`, `update-feature.dto.ts` +- **Entities**: `feature.entity.ts` +- **Interfaces and types**: `feature.types.ts` +- **Tests**: `feature.service.spec.ts` +- **Constants**: `feature.constants.ts` +- **Exceptions**: `feature-not-found.exception.ts` + +### Constants Organization + +Store feature-specific constants in dedicated constants file: + +```typescript +export const FEATURE_CONSTANTS = { + MAX_NAME_LENGTH: 100, + DEFAULT_PAGE_SIZE: 20, +} as const; + +export const FEATURE_ERROR_MESSAGES = { + NOT_FOUND: 'Feature not found', + INVALID_INPUT: 'Invalid feature data', +} as const; +``` + +### Barrel Files + +Use barrel files (`index.ts`) for exporting **3 or more** related items only. + +### Imports Order + +1. Node.js built-in modules +2. External dependencies (`@nestjs/*`, etc.) +3. Internal modules (using `apiSrc/*` alias) +4. Local relative imports + +## Service Layer + +### Service Pattern + +- Inject dependencies via constructor +- Use TypeORM repositories +- Handle errors with NestJS exceptions +- Use Logger for important operations +- Keep business logic in services (not controllers) + +### Dependency Injection + +Always inject dependencies via constructor with proper decorators: + +```typescript +@Injectable() +export class UserService { + constructor( + @InjectRepository(User) + private readonly userRepository: Repository, + private readonly emailService: EmailService, + ) {} +} +``` + +## Controller Layer + +### Controller Pattern + +- Keep controllers thin (delegate to services) +- Use proper HTTP decorators (`@Get`, `@Post`, etc.) +- Use `@Body`, `@Param`, `@Query` for inputs +- Apply guards with `@UseGuards()` +- Document with Swagger decorators + +### HTTP Status Codes + +- Use `@HttpCode()` decorator for non-standard codes +- Return appropriate status codes (200, 201, 204, 400, 404, etc.) + +## Data Transfer Objects (DTOs) + +### Validation + +Use `class-validator` decorators for validation: + +- `@IsString()`, `@IsNumber()`, `@IsEmail()` +- `@IsNotEmpty()`, `@IsOptional()` +- `@MinLength()`, `@MaxLength()` +- `@Min()`, `@Max()` + +### Swagger Documentation + +Use `@ApiProperty()` and `@ApiPropertyOptional()` for Swagger docs. + +## Error Handling + +### NestJS Exceptions + +Use appropriate exception types: + +- `NotFoundException` - 404 +- `BadRequestException` - 400 +- `UnauthorizedException` - 401 +- `ForbiddenException` - 403 +- `ConflictException` - 409 +- `InternalServerErrorException` - 500 + +### Error Logging + +```typescript +private readonly logger = new Logger(ServiceName.name) + +this.logger.error('Error message', error.stack, { context }) +``` + +## Redis Integration + +### Redis Service Pattern + +- Use RedisClient from `apiSrc/modules/redis` +- Handle errors gracefully +- Log Redis operations +- Use try-catch for error handling + +## Database Operations + +### Transactions + +Use QueryRunner for transactions: + +```typescript +const queryRunner = this.dataSource.createQueryRunner(); +await queryRunner.connect(); +await queryRunner.startTransaction(); + +try { + // operations + await queryRunner.commitTransaction(); +} catch (error) { + await queryRunner.rollbackTransaction(); + throw error; +} finally { + await queryRunner.release(); +} +``` + +## Code Quality + +### Cognitive Complexity (≤ 15) + +- Use early returns to reduce nesting +- Extract complex logic to separate functions +- Avoid deeply nested conditions + +### No Duplicate Strings + +Extract repeated strings to constants in constants file. + +## API Documentation (Swagger) + +### Required Decorators + +- `@ApiTags()` - Group endpoints +- `@ApiOperation()` - Describe operation +- `@ApiResponse()` - Document responses +- `@ApiParam()` - Document params +- `@ApiQuery()` - Document query params +- `@ApiBearerAuth()` - Auth requirement + +## Checklist + +- [ ] Services use dependency injection +- [ ] DTOs have validation decorators +- [ ] Controllers have Swagger documentation +- [ ] Proper HTTP status codes used +- [ ] Error handling with appropriate exceptions +- [ ] Logging for important operations +- [ ] Transactions for related DB operations +- [ ] Configuration via ConfigService +- [ ] Guards for authentication/authorization +- [ ] Cognitive complexity ≤ 15 diff --git a/.ai/rules/branches.md b/.ai/rules/branches.md new file mode 100644 index 0000000000..561278f73a --- /dev/null +++ b/.ai/rules/branches.md @@ -0,0 +1,40 @@ +# Branch Naming Conventions + +Use lowercase kebab-case with type prefix and issue/ticket identifier: + +```bash +# Pattern: // + +# INTERNAL (JIRA - RI-XXX) +feature/RI-123/add-user-profile +bugfix/RI-789/memory-leak +fe/feature/RI-567/add-dark-mode +be/bugfix/RI-345/fix-redis-connection + +# OPEN SOURCE (GitHub - XXX) +feature/123/add-export-feature +bugfix/789/fix-connection-timeout + +# Other types +hotfix/critical-security-patch +refactor/RI-111/extract-service +docs/RI-333/update-docs +chore/RI-555/upgrade-deps +``` + +## Branch Types + +- `feature/` - New features +- `bugfix/` - Bug fixes +- `fe/feature/` - Frontend-only features +- `be/bugfix/` - Backend-only fixes +- `hotfix/` - Critical production fixes +- `refactor/` - Code refactoring +- `docs/` - Documentation changes +- `chore/` - Maintenance tasks + +## Issue References + +- **Internal**: `RI-XXX` (JIRA ticket) +- **Open Source**: `XXX` (GitHub issue number) +- Use `#` only in commit messages, not branch names diff --git a/.ai/rules/code-quality.md b/.ai/rules/code-quality.md new file mode 100644 index 0000000000..f0709f45fa --- /dev/null +++ b/.ai/rules/code-quality.md @@ -0,0 +1,73 @@ +# Code Quality Standards + +## Critical Rules + +- **ALWAYS run linter** after code changes: `yarn lint` +- Linter must pass before committing +- No console.log in production code (use console.warn/error only) + +## TypeScript Standards + +### Essential Rules + +- Use TypeScript for all new code +- **Avoid `any`** - use proper types or `unknown` +- **Prefer interfaces** for object shapes +- Use **type** for unions, intersections, primitives +- Add explicit return types for non-obvious functions +- Leverage type inference where clear + +## Import Organization + +### Required Order (enforced by ESLint) + +1. External libraries (`react`, `lodash`, etc.) +2. Built-in Node modules (`path`, `fs` - backend only) +3. Internal modules with aliases (`uiSrc/*`, `apiSrc/*`) +4. Sibling/parent relative imports +5. Style imports (ALWAYS LAST) + +### Module Aliases + +- `uiSrc/*` → `redisinsight/ui/src/*` +- `apiSrc/*` → `redisinsight/api/src/*` +- `desktopSrc/*` → `redisinsight/desktop/src/*` + +✅ **Use aliases**: `import { Button } from 'uiSrc/components/Button'` +❌ **Avoid relative**: `import { Button } from '../../../ui/src/components/Button'` + +## Naming Conventions + +- **Components**: `PascalCase` - `UserProfile` +- **Functions/Variables**: `camelCase` - `fetchUserProfile` +- **Constants**: `UPPER_SNAKE_CASE` - `MAX_RETRY_ATTEMPTS` +- **Booleans**: Use `is/has/should` prefix - `isLoading`, `hasError` + +## SonarJS Rules + +- Keep cognitive complexity low (refactor complex functions) +- Extract duplicate strings to constants +- Follow DRY principle - no duplicate code +- Use immediate return (avoid unnecessary intermediate variables) + +## Best Practices + +- Use destructuring for objects and arrays +- Use template literals over string concatenation +- Use `const` by default, `let` only when reassignment needed +- Use descriptive variable names +- Handle errors properly +- Clean up subscriptions and timers +- Use constants instead of magic numbers + +## Pre-Commit Checklist + +- [ ] `yarn lint` passes +- [ ] No TypeScript errors +- [ ] Import order is correct +- [ ] No `any` types without reason +- [ ] No console.log statements +- [ ] No magic numbers +- [ ] Descriptive variable names +- [ ] Low cognitive complexity +- [ ] No duplicate code diff --git a/.ai/rules/commits.md b/.ai/rules/commits.md new file mode 100644 index 0000000000..1b8b48c1e7 --- /dev/null +++ b/.ai/rules/commits.md @@ -0,0 +1,87 @@ +# Commit Message Guidelines + +Follow **Conventional Commits** format: + +``` +(): + + + +