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/pr-plan.md b/.ai/commands/pr-plan.md new file mode 100644 index 0000000000..d00fdeca63 --- /dev/null +++ b/.ai/commands/pr-plan.md @@ -0,0 +1,320 @@ +--- +description: Analyze a JIRA ticket and create a detailed implementation plan +argument-hint: +--- + +Create a comprehensive implementation plan for a JIRA ticket. + +## 1. Fetch JIRA Ticket + +**If ticket ID is not provided as an argument, prompt the user for it.** + +Fetch all the information from the ticket, its comments, linked documents, and parent ticket. + +Use the `jira` tool to fetch the ticket details. + +## 4. Create Implementation Plan + +Use `sequential-thinking` tool for complex analysis. Break down into thoughts: + +### Thought 1-5: Requirements Analysis + +- Parse acceptance criteria into specific tasks +- Identify functional requirements +- Identify non-functional requirements (performance, security, cost) +- Map requirements to system components +- Identify dependencies and blockers + +### Thought 6-10: Architecture Planning + +- Determine which services are affected +- Identify new components needed +- Identify existing components to modify +- Plan data flow and interactions +- Consider error handling and edge cases + +### Thought 16-20: Implementation Breakdown + +- Break work into logical phases +- Identify dependencies between phases +- Consider testing strategy for each phase +- Plan for incremental delivery + +### Thought 21-25: Testing Strategy + +- Identify test scenarios from acceptance criteria +- Plan unit tests (behavior-based, not implementation) +- Plan integration tests +- Consider edge cases and error scenarios +- Plan test data needs + +### Thought 26-30: Risk Assessment + +- Identify technical risks +- Identify integration risks +- Identify timeline risks +- Identify knowledge gaps +- Plan mitigation strategies + +## 5. Generate Implementation Plan Document + +**CRITICAL: You MUST create and save a plan document. This is NOT optional.** + +Create a comprehensive Markdown document and save it to `docs/pr-plan-{ticket-id}-{brief-description}.md` using the `write` tool. + +**The document structure MUST include all sections below:** + +```markdown +# Implementation Plan: [Ticket Title] + +**JIRA Ticket:** [MOD-XXXXX](https://redislabs.atlassian.net/browse/MOD-XXXXX) +**Epic:** [EPIC-XXX](link) (if applicable) +**Parent:** [PARENT-XXX](link) (if applicable) +**Plan Date:** [Date] +**Planner:** Augment Agent + +--- + +## Executive Summary + +**Components Affected:** + +- [component name] + +**Key Risks:** + +1. [Risk with mitigation] +2. [Risk with mitigation] +3. [Risk with mitigation] + +--- + +## 1. Requirements Summary + +**Story (Why):** +[Quote or summarize the story from the ticket] + +**Acceptance Criteria (What):** + +1. [AC1] +2. [AC2] +3. [AC3] + +**Functional Requirements:** + +- [Requirement 1] +- [Requirement 2] + +**Non-Functional Requirements:** + +- [NFR 1 - e.g., Performance: <100ms response time] +- [NFR 2 - e.g., Security: Requires authentication] + +**Resources Provided:** + +- [Link 1: Description] +- [Link 2: Description] + +## 2. Current State Analysis + +### Frontend Changes + +**Components to Modify:** + +- [Component 1]: [What changes are needed] +- [Component 2]: [What changes are needed] + +**Components to Create:** + +- [Component 1]: [Why it's needed] +- [Component 2]: [Why it's needed] + +**Components to Reuse:** + +- [Component 1]: [How it will be used] +- [Component 2]: [How it will be used] + +### Backend Changes + +**Services to Modify:** + +- [Service 1]: [What changes are needed] +- [Service 2]: [What changes are needed] + +**Services to Create:** + +- [Service 1]: [Why it's needed] +- [Service 2]: [Why it's needed] + +**APIs to Modify:** + +- [API 1]: [What's changing] +- [API 2]: [What's changing] + +**APIs to Create:** + +- [API 1]: [Why it's needed] +- [API 2]: [Why it's needed] + +**Data Models:** + +- [Model 1]: [Description and whether it needs extension] +- [Model 2]: [Description and whether it needs extension] + +**Repositories:** + +- [Repo 1]: [Description and whether it can be reused] + +--- + +## 3. Implementation Plan + +### Phase 1: [Phase Name] + +**Goal:** [What this phase achieves] + +**Tasks:** + +1. [ ] [Task 1 - specific, actionable] + - Files: [List of files to create/modify] + - Acceptance: [How to verify this task is done] +2. [ ] [Task 2] + - Files: [List of files] + - Acceptance: [Verification criteria] + +**Deliverables:** + +- [Deliverable 1] +- [Deliverable 2] + +**Testing:** + +- [Test scenario 1] +- [Test scenario 2] + +### Phase 2: [Phase Name] + +[Same structure as Phase 1] + +### Phase 3: [Phase Name] + +[Same structure as Phase 1] + +--- + +## 5. Testing Strategy + +### Test Scenarios (from Acceptance Criteria) + +**AC1: [Acceptance Criterion]** + +- Test Scenario: [Given-When-Then] +- Test Type: Unit/Integration +- Test Location: [File path] + +**AC2: [Acceptance Criterion]** + +- Test Scenario: [Given-When-Then] +- Test Type: Unit/Integration +- Test Location: [File path] + +### Edge Cases and Error Scenarios + +1. **[Edge Case 1]** + + - Scenario: [Description] + - Expected Behavior: [What should happen] + - Test: [How to test] + +2. **[Error Scenario 1]** + - Scenario: [Description] + - Expected Error: [Error type/code] + - Test: [How to test] + +### Test Data Needs + +- [Test data 1]: [Description] +- [Test data 2]: [Description] + +--- + +## 6. Risk Assessment and Mitigation + +### Technical Risks + +| Risk | Likelihood | Impact | Mitigation | +| -------- | --------------- | --------------- | --------------------- | +| [Risk 1] | High/Medium/Low | High/Medium/Low | [Mitigation strategy] | +| [Risk 2] | High/Medium/Low | High/Medium/Low | [Mitigation strategy] | + +### Integration Risks + +| Risk | Likelihood | Impact | Mitigation | +| -------- | --------------- | --------------- | --------------------- | +| [Risk 1] | High/Medium/Low | High/Medium/Low | [Mitigation strategy] | + +### Timeline Risks + +| Risk | Likelihood | Impact | Mitigation | +| -------- | --------------- | --------------- | --------------------- | +| [Risk 1] | High/Medium/Low | High/Medium/Low | [Mitigation strategy] | + +### Knowledge Gaps + +- [Gap 1]: [What we don't know and how to find out] +- [Gap 2]: [What we don't know and how to find out] +``` + +--- + +## 6. Save the Plan Document + +**CRITICAL: You MUST save the plan document using the `write` tool.** + +1. **Generate the complete plan document** following the structure in section 5 +2. **Save it** to `docs/pr-plan-{ticket-id}-{brief-description}.md` using `write` tool +3. **Verify the file was created** by confirming the write tool succeeded + +**Example filename:** `docs/pr-plan-MOD-11280-dp-services-clean-architecture.md` + +--- + +## 7. Follow-up Actions + +After saving the plan document: + +1. **Confirm document was saved** - Show the file path to the user +2. **Summarize key findings** for the user: + - Key risks + - Recommended approach + - **Confirm plan document was saved** (file path) +3. **Ask if user wants to:** + - Review the plan document + - Proceed with implementation + +--- + +## Important Notes + +- **ALWAYS save the plan document** - use `write` tool to save to `docs/pr-plan-{ticket-id}-{brief-description}.md` +- **Use main branch as baseline** - all analysis should be against current main +- **Be specific and actionable** - every task should be clear and verifiable +- **Consider PR stacking** - plan for small, reviewable PRs (see `.ai/rules/pull-requests.md`). plan breaking the implementation in a stack of PRs. +- **Follow all project standards** - reference rules in `.ai/rules/` +- **Document assumptions** - if anything is unclear, document the assumption made +- **Identify blockers early** - surface dependencies and knowledge gaps upfront + +## Execution Order Summary + +**The correct order of operations is:** + +1. ✅ Fetch JIRA ticket +2. ✅ Analyze current codebase state +3. ✅ Create implementation plan using sequential-thinking +4. ✅ Generate implementation plan document content +5. ✅ **Save plan document to `docs/pr-plan-{ticket-id}-{brief-description}.md`** (CRITICAL - use write tool) +6. ✅ Present results to user and confirm document location + +**Do NOT skip step 5 - it is mandatory and must be done during command execution.** + +**Step 5 is MANDATORY:** You MUST use the `write` tool to save the plan document. Do NOT just present the plan to the user without saving it. 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..e8a373247d --- /dev/null +++ b/.ai/rules/backend.md @@ -0,0 +1,195 @@ +--- +alwaysApply: true +--- + +# 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; +``` + +### 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 + +## 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..98e084f7ab --- /dev/null +++ b/.ai/rules/branches.md @@ -0,0 +1,48 @@ +--- +alwaysApply: true +--- + +# Branch Naming Conventions + +Use lowercase kebab-case with type prefix and issue/ticket identifier. **Branch names must match GitHub Actions workflow rules** (see `.github/workflows/enforce-branch-name-rules.yml`). + +```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 +docs/RI-333/update-docs +test/RI-444/add-unit-tests +e2e/RI-555/add-integration-tests + +# OPEN SOURCE (GitHub - XXX) +feature/123/add-export-feature +bugfix/789/fix-connection-timeout + +# Special branches +release/v2.0.0 +ric/RI-666/custom-prefix +``` + +## Allowed Branch Types (GitHub Actions Enforced) + +- `feature/` - New features and refactoring +- `bugfix/` - Bug fixes +- `fe/feature/` - Frontend-only features +- `fe/bugfix/` - Frontend-only bug fixes +- `be/feature/` - Backend-only features +- `be/bugfix/` - Backend-only bug fixes +- `docs/` - Documentation changes +- `test/` - Test-related changes +- `e2e/` - End-to-end test changes +- `release/` - Release branches +- `ric/` - Custom prefix for special cases + +## 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..6b4058f766 --- /dev/null +++ b/.ai/rules/code-quality.md @@ -0,0 +1,77 @@ +--- +alwaysApply: true +--- + +# 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..06d9ba9520 --- /dev/null +++ b/.ai/rules/commits.md @@ -0,0 +1,91 @@ +--- +alwaysApply: true +--- + +# Commit Message Guidelines + +Follow **Conventional Commits** format: + +``` +(): + + + +