### FastAPI Testing with TestClient Source: https://github.com/sahin/ai-rules/blob/main/rules/general-policies/testing/implementation-guide.md Shows how to test FastAPI applications using `TestClient`. Includes examples for testing POST requests to create users and GET requests to retrieve user data, asserting status codes and response content. ```python from fastapi.testclient import TestClient from app.main import app client = TestClient(app) def test_create_user(): response = client.post( "/api/users", json={"name": "Jane", "email": "jane@example.com"} ) assert response.status_code == 201 assert response.json()["email"] == "jane@example.com" def test_get_user(): response = client.get("/api/users/1") assert response.status_code == 200 assert "id" in response.json() ``` -------------------------------- ### Project Setup and Execution Source: https://github.com/sahin/ai-rules/blob/main/README.md Provides commands to clone the repository, navigate into the project directory, and execute the installation script. ```bash git clone https://github.com/yourusername/sahin-ai-rules.git cd sahin-ai-rules ./install.sh ``` -------------------------------- ### Usage Guide Reference Source: https://github.com/sahin/ai-rules/blob/main/rules/general-policies/ops/continuous-work-loop.md Points to the main usage guide for the project, located at `/docs/todos/continuous-work-loop-usage-guide.md`, which contains quick references and examples. ```markdown ## πŸ“š Usage Guide - See `/docs/todos/continuous-work-loop-usage-guide.md` for quick reference and examples ``` -------------------------------- ### Example User Endpoint Documentation Source: https://github.com/sahin/ai-rules/blob/main/rules/general-policies/backend/api-design.md Provides an example of documenting a '/api/v1/users' GET endpoint using an OpenAPI-like structure, detailing parameters, responses, and schema references. ```typescript const userEndpointDoc = { '/api/v1/users': { get: { summary: 'List users', description: 'Retrieve a paginated list of users', parameters: [ { name: 'page', in: 'query', schema: { type: 'integer', default: 1 }, description: 'Page number' }, { name: 'limit', in: 'query', schema: { type: 'integer', default: 20, maximum: 100 }, description: 'Items per page' } ], responses: { 200: { description: 'Success', content: { 'application/json': { schema: { type: 'object', properties: { success: { type: 'boolean' }, data: { type: 'array', items: { $ref: '#/components/schemas/User' } }, metadata: { $ref: '#/components/schemas/PaginationMetadata' } } } } } }, 400: { $ref: '#/components/responses/BadRequest' }, 401: { $ref: '#/components/responses/Unauthorized' }, 500: { $ref: '#/components/responses/InternalServerError' } } } } }; ``` -------------------------------- ### Testing Commands Example Source: https://github.com/sahin/ai-rules/blob/main/rules/_mandatory/01-plan-template.md Example commands for executing tests and building the project, commonly used within the testing phase of the project plan. ```bash npm run test:smart --dry-run npm run test:smart npm run build ``` -------------------------------- ### TypeScript: Legacy Code Typing Source: https://github.com/sahin/ai-rules/blob/main/rules/general-policies/frontend/typescript.md Example of typing legacy TypeScript code. Shows how to handle existing functions with `any` types, with a comment indicating future refactoring. It also demonstrates making small, opportunistic type improvements, such as casting `data` to `UserData`. ```typescript // ⚠️ LEGACY: Fix types opportunistically function legacyFunction(data: any) { // TODO: Type this when refactoring // When you touch this file, gradually improve types const typedData = data as UserData; // Small improvements OK return processUser(typedData); } ``` -------------------------------- ### Example Work Session: File Organization Source: https://github.com/sahin/ai-rules/blob/main/rules/general-policies/ops/continuous-work-loop.md A markdown example demonstrating a file organization work session, including the task queue and progress updates. ```markdown ## πŸ”„ CONTINUOUS WORK SESSION: Organize Project Files **Total Tasks**: 8 items **Estimated Time**: ~12 minutes **Progress**: 0% [β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘] ### Task Queue: 1. ⏳ Analyze current file structure 2. ⏳ Create file index 3. ⏳ Move misplaced files 4. ⏳ Update imports 5. ⏳ Generate documentation 6. ⏳ Test file paths 7. ⏳ Update PROJECT_MAP.md 8. ⏳ Commit changes ⏱️ **Starting in 5 seconds** - Interrupt to cancel 5... 4... 3... 2... 1... --- ### Task 1/8: Analyzing file structure πŸ” Scanning directories... Progress: 12% [β–ˆβ–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘] [Work output here] βœ… Task 1 Complete: Found 245 files ⏸️ **Next task in 5 seconds** - Interrupt to stop --- ``` -------------------------------- ### Todo File Structure Example Source: https://github.com/sahin/ai-rules/blob/main/README.md Provides an example of a todo file structure, detailing task information such as status, dependencies, associated files, lines of code (LoC), context, return on investment (ROI), and acceptance criteria. ```markdown # Tasks: Authentication System Created: 2024-01-15 Priority: High Context Budget: 70% per task ## Task Queue ### Task 1: Login UI - [ ] Status: Pending - **Files**: LoginForm.tsx, login.css - **LoC**: ~50 - **Context**: ~30% - **ROI**: High (10Γ—10/50 = 2.0) - **Acceptance**: - [ ] Form renders - [ ] Validation works - [ ] E2E test passes ### Task 2: Auth Service - [ ] Status: Pending - **Dependencies**: Task 1 ``` -------------------------------- ### k6 Load Testing Script Source: https://github.com/sahin/ai-rules/blob/main/rules/general-policies/testing/implementation-guide.md A k6 script for performance load testing. It defines test options including virtual user stages and response time thresholds, and includes a default function to make HTTP GET requests to a specified API endpoint, checking for success status and response time. ```javascript import http from 'k6/http'; import { check } from 'k6'; export let options = { stages: [ { duration: '2m', target: 100 }, { duration: '5m', target: 100 }, { duration: '2m', target: 0 }, ], thresholds: { http_req_duration: ['p(95)<500'], }, }; export default function() { let response = http.get('https://api.example.com/users'); check(response, { 'status is 200': (r) => r.status === 200, 'response time < 500ms': (r) => r.timings.duration < 500, }); } ``` -------------------------------- ### Testing Commands Example Source: https://github.com/sahin/ai-rules/blob/main/rules/core-standards/core-workflow.md Illustrates the sequence of commands to be executed during the testing phase, including a dry run, the actual test execution, and a build command. ```shell npm run test:smart --dry-run npm run test:smart npm run build ``` -------------------------------- ### Express/Node.js API Testing with Supertest Source: https://github.com/sahin/ai-rules/blob/main/rules/general-policies/testing/implementation-guide.md Provides examples for testing Express.js API endpoints using `supertest`. Demonstrates testing POST requests for creating resources, including request body validation and response assertions. ```typescript import request from 'supertest'; import app from '../app'; describe('POST /api/users', () => { it('should create a new user', async () => { const newUser = { name: 'Jane Doe', email: 'jane@example.com', password: 'SecurePass123!' }; const response = await request(app) .post('/api/users') .send(newUser) .expect(201); expect(response.body).toMatchObject({ id: expect.any(Number), name: newUser.name, email: newUser.email }); expect(response.body.password).toBeUndefined(); }); it('should validate required fields', async () => { const response = await request(app) .post('/api/users') .send({ email: 'test@example.com' }) .expect(400); expect(response.body.errors).toContainEqual( expect.objectContaining({ field: 'name', message: 'Name is required' }) ); }); }); ``` -------------------------------- ### TypeScript: New Feature Typing Source: https://github.com/sahin/ai-rules/blob/main/rules/general-policies/frontend/typescript.md Example of strongly typed code for new features in TypeScript. Demonstrates defining explicit types for function parameters (`CreateUserDto`) and return values (`Promise`), adhering to strict typing standards. ```typescript // βœ… REQUIRED: New code must be properly typed export function createUser(userData: CreateUserDto): Promise { // All parameters and return types explicit return userService.create(userData); } ``` -------------------------------- ### Testing Helper Functions Source: https://github.com/sahin/ai-rules/blob/main/rules/general-policies/testing/e2e-playwright.md Provides utility functions for common testing tasks, such as logging in users with different roles and seeding test data via API requests. These helpers abstract complex setup steps. ```typescript // e2e/helpers/auth.ts export async function loginAs(page: Page, role: 'admin' | 'user') { const credentials = { admin: { email: 'admin@test.com', password: 'AdminPass123!' }, user: { email: 'user@test.com', password: 'UserPass123!' }, }; await page.goto('/login'); await page.getByLabel('Email').fill(credentials[role].email); await page.getByLabel('Password').fill(credentials[role].password); await page.getByRole('button', { name: 'Log in' }).click(); await page.waitForURL('/dashboard'); } // e2e/helpers/data.ts export async function seedTestData(page: Page) { await page.request.post('/api/test/seed', { data: { users: 10, products: 50, orders: 100 }, }); } ``` -------------------------------- ### TypeScript Authentication and Form Validation Tests Source: https://github.com/sahin/ai-rules/blob/main/rules/general-policies/testing/implementation-guide.md Provides examples of common testing scenarios in TypeScript using a testing framework like Jest or Vitest. It includes tests for user authentication with valid credentials and route protection, as well as form validation for email format and required fields. ```typescript describe('Authentication', () => { it('should login with valid credentials', async () => { const response = await request(app) .post('/api/auth/login') .send({ email: 'user@example.com', password: 'password123' }); expect(response.status).toBe(200); expect(response.body).toHaveProperty('accessToken'); expect(response.body).toHaveProperty('refreshToken'); }); it('should protect routes', async () => { await request(app) .get('/api/protected') .expect(401); await request(app) .get('/api/protected') .set('Authorization', 'Bearer valid-token') .expect(200); }); }); describe('Form Validation', () => { it('should validate email format', async () => { render(); await userEvent.type(screen.getByLabelText('Email'), 'invalid-email'); await userEvent.tab(); expect(screen.getByText('Invalid email format')).toBeInTheDocument(); }); it('should validate required fields', async () => { render(); await userEvent.click(screen.getByRole('button', { name: 'Submit' })); expect(screen.getByText('Name is required')).toBeInTheDocument(); expect(screen.getByText('Email is required')).toBeInTheDocument(); }); }); ``` -------------------------------- ### High-ROI Code Example: Leverage Existing Libraries Source: https://github.com/sahin/ai-rules/blob/main/README.md Contrasts low Return on Investment (ROI) custom code with high ROI code that leverages existing libraries. The example shows a concise implementation using a library versus a verbose custom solution. ```typescript // ❌ LOW ROI - Custom everything (500 LoC) class CustomAuthSystem { // Complex custom implementation } // βœ… HIGH ROI - Leverage existing (50 LoC) const useAuth = () => { return useExistingAuthLibrary({ provider: 'email', callbacks: { onSuccess, onError } }); }; ``` -------------------------------- ### Rule Manifest Update Example Source: https://github.com/sahin/ai-rules/blob/main/rules/README.md Illustrates the process of updating the `rule-manifest.json` file to include new rules, specifying their scope and extensions. ```json { "rules": [ { "id": "rule-001", "title": "Example Rule", "scope": "project", "extends": "general-policies/base-rule.md" } ] } ``` -------------------------------- ### Commit Message Examples Source: https://github.com/sahin/ai-rules/blob/main/rules/general-policies/ops/git-workflow.md Provides practical examples of commit messages following the Conventional Commits format for various types such as feature, fix, docs, refactor, test, and chore. ```bash # Feature commits feat(auth): add OAuth2 integration with Google feat(payments): implement Stripe payment processing feat: add user profile dashboard # Bug fix commits fix(login): resolve redirect loop after authentication fix(api): handle null pointer in user lookup fix: prevent memory leak in image processing # Documentation commits docs(README): update installation instructions docs(api): add endpoint documentation for payments docs: add troubleshooting guide # Refactoring commits refactor(database): extract connection pool logic refactor(components): simplify user profile component refactor: optimize database query performance # Test commits test(auth): add integration tests for login flow test(payments): add unit tests for payment validation test: increase coverage for user service # Chore commits chore(deps): update React to v18.2.0 chore(build): optimize webpack configuration chore: update Node.js to LTS version ``` -------------------------------- ### Data Tables ROI Example Source: https://github.com/sahin/ai-rules/blob/main/rules/general-policies/high-roi-development.md Illustrates the ROI difference between a custom data table component and using an existing library, highlighting the benefits of simplicity and reuse. ```markdown LOW ROI APPROACH: - Custom table component - Advanced sorting/filtering - Column customization - Export functionality - 1500+ LoC HIGH ROI APPROACH: - Use existing table library - Basic display only - Add sorting if needed - Simple, functional design - 100 LoC ROI Difference: 15x improvement ``` -------------------------------- ### RESTful URL Design Examples Source: https://github.com/sahin/ai-rules/blob/main/rules/general-policies/backend/api-design.md Demonstrates good and bad practices for designing RESTful API URLs, emphasizing resource-based design and avoiding RPC-style patterns. ```typescript const apiRoutes = { // Resource collections 'GET /api/v1/users': 'List all users', 'POST /api/v1/users': 'Create new user', // Specific resources 'GET /api/v1/users/{id}': 'Get specific user', 'PUT /api/v1/users/{id}': 'Update entire user', 'PATCH /api/v1/users/{id}': 'Partial user update', 'DELETE /api/v1/users/{id}': 'Delete user', // Nested resources 'GET /api/v1/users/{id}/posts': 'Get user posts', 'POST /api/v1/users/{id}/posts': 'Create post for user' }; // ❌ Bad: Non-RESTful design const badRoutes = { 'GET /api/getUser?id=123': 'RPC-style endpoint', 'POST /api/updateUser': 'Verb in URL', 'GET /api/user-posts': 'Unclear resource hierarchy' }; ``` -------------------------------- ### Install Sahin AI Rules Source: https://github.com/sahin/ai-rules/blob/main/README.md Steps to clone the repository and set up the Sahin AI Rules framework in your project. This involves copying the rules directory and the main configuration file. ```bash git clone https://github.com/yourusername/sahin-ai-rules.git cd sahin-ai-rules # Copy the rules directory to your project cp -r rules /your/project/.cursor/rules/ # Create the main configuration file cp CLAUDE.md /your/project/CLAUDE.md ``` -------------------------------- ### Review Feedback Standards and Examples Source: https://github.com/sahin/ai-rules/blob/main/rules/general-policies/ops/code-review.md Defines standards for effective and ineffective review feedback, providing concrete examples for each category. This interface helps guide reviewers in providing constructive and actionable feedback. ```typescript // MANDATORY: Professional review communication standards interface ReviewFeedbackStandards { // βœ… Exemplary review feedback approaches effectiveFeedback: { specificAndActionable: string; constructiveAndHelpful: string; educationalAndInformative: string; questioningWithPurpose: string; positiveAndEncouraging: string; }; // ❌ Counterproductive feedback patterns to avoid ineffectiveFeedback: { vagueAndUnhelpful: string; negativeAndDestructive: string; overlandNitpicking: string; personalizedCriticism: string; overwhelmingRequests: string; }; } const reviewFeedbackExamples: ReviewFeedbackStandards = { effectiveFeedback: { specificAndActionable: "Line 127: This O(nΒ²) operation will be problematic with datasets >1000 items. Consider implementing pagination or using a more efficient algorithm like binary search.", constructiveAndHelpful: "This business logic could be extracted into a service class for better testability and reusability across components.", educationalAndInformative: "This async pattern without proper error boundaries could lead to unhandled promise rejections. Here's our error handling guide: [link]", questioningWithPurpose: "I notice we're implementing custom validation here. Could we leverage our existing validation library to maintain consistency?", positiveAndEncouraging: "Excellent use of the factory pattern here! This makes the code much more maintainable and follows our architectural guidelines perfectly." }, ineffectiveFeedback: { vagueAndUnhelpful: "This looks wrong", negativeAndDestructive: "This entire approach is fundamentally flawed", overlandNitpicking: "Add a space after this comma", personalizedCriticism: "You always overcomplicate things", overwhelmingRequests: "Rewrite everything using different patterns" } }; ``` -------------------------------- ### TypeScript Compiler Options for Strictness Source: https://github.com/sahin/ai-rules/blob/main/rules/general-policies/frontend/typescript-strict.md Provides JSON configurations for enabling progressively stricter TypeScript compiler options, starting with `strictNullChecks`, then `noImplicitAny`, and finally the full `strict` mode. ```json { "compilerOptions": { "strictNullChecks": true, "noUncheckedIndexedAccess": true } } ``` ```json { "compilerOptions": { "noImplicitAny": true } } ``` ```json { "compilerOptions": { "strict": true } } ``` -------------------------------- ### Error Boundary Testing Source: https://github.com/sahin/ai-rules/blob/main/rules/general-policies/testing/implementation-guide.md Provides an example of testing React Error Boundaries using Jest and React Testing Library. It simulates an error within a component and asserts that the fallback UI is rendered. ```typescript it('should catch errors and display fallback', () => { const ThrowError = () => { throw new Error('Test error'); }; render( Error occurred}> ); expect(screen.getByText('Error occurred')).toBeInTheDocument(); }); ``` -------------------------------- ### Pre-release Tagging Source: https://github.com/sahin/ai-rules/blob/main/rules/general-policies/ops/git-workflow.md Shows how to create pre-release tags for alpha, beta, or release candidate versions using semantic versioning conventions. ```bash # For beta/alpha releases git tag v1.2.0-beta.1 git tag v1.2.0-alpha.3 git tag v1.2.0-rc.1 # Release candidate ``` -------------------------------- ### Typed React Functional Components Source: https://github.com/sahin/ai-rules/blob/main/rules/general-policies/frontend/typescript-strict.md Demonstrates how to define typed functional components in React using interfaces for props. Includes examples for a basic Button component and a Card component that accepts children. ```typescript // βœ… Typed functional component interface ButtonProps { label: string; onClick: () => void; disabled?: boolean; variant?: 'primary' | 'secondary'; } const Button: React.FC = ({ label, onClick, disabled = false, variant = 'primary' }) => { return ( ); }; // βœ… With children interface CardProps { title: string; children: React.ReactNode; } const Card: React.FC = ({ title, children }) => { return (

{title}

{children}
); }; ``` -------------------------------- ### Parameterized Testing with describe.each Source: https://github.com/sahin/ai-rules/blob/main/rules/general-policies/testing/implementation-guide.md Shows how to use Jest's `describe.each` to run the same test suite with different sets of parameters, making tests more concise and covering various scenarios efficiently. ```typescript describe.each([ ['admin', true], ['user', false], ['guest', false], ])('User role %s', (role, canDelete) => { it(`should ${canDelete ? '' : 'not '}allow deletion`, () => { const user = { role }; expect(permissions.canDelete(user)).toBe(canDelete); }); }); ``` -------------------------------- ### Dockerfile Best Practices Source: https://github.com/sahin/ai-rules/blob/main/rules/general-policies/ops/deployment.md Demonstrates essential Dockerfile practices for building efficient and secure container images, including using minimal base images, reproducible builds, exposing ports, and running as a non-root user. ```dockerfile # Required container practices FROM node:18-alpine # Use official, minimal base images WORKDIR /app COPY package*.json ./ RUN npm ci --only=production # Reproducible installs COPY . . RUN npm run build EXPOSE 3000 USER node # Non-root user HEALTHCHECK --interval=30s --timeout=3s --start-period=5s --retries=3 \ CMD curl -f http://localhost:3000/health || exit 1 CMD ["npm", "start"] ``` -------------------------------- ### User Story to Test Translation Example Source: https://github.com/sahin/ai-rules/blob/main/rules/general-policies/testing/playwright-first.md Illustrates the translation of a user story into a concrete End-to-End (E2E) test plan, including setup, navigation, verification steps, and the corresponding code required to build the feature. ```markdown USER STORY: "As a farmer, I want to view tank levels so I can prevent overflows" E2E TEST: 1. Login as farmer user 2. Navigate to dashboard 3. Verify tank level widgets visible 4. Check level data displays correctly 5. Confirm alerts show when levels high 6. Verify user can take action CODE TO BUILD: - Dashboard route - Tank level API - Tank widget component - Alert system - User actions ``` -------------------------------- ### Allowed Opening Format Source: https://github.com/sahin/ai-rules/blob/main/rules/_mandatory/00-circuit-breaker.md This is the only acceptable way to begin a response. It requires a 'Plan:' section followed by a description of the intended action or plan. ```markdown ## Plan: [Description] ``` -------------------------------- ### High ROI Feature Example (Search) Source: https://github.com/sahin/ai-rules/blob/main/rules/general-policies/feature-development-roi.md Demonstrates a high ROI feature implementation, starting with an E2E test and followed by a concise React component that reuses existing hooks and components. ```typescript // E2E Test (Written First) test('user can search data', async ({ page }) => { await page.goto('/dashboard'); await page.getByPlaceholder('Search').fill('test'); await expect(page.getByText('test result')).toBeVisible(); }); // Implementation (~30 LoC including imports/structure) const SearchFeature = () => { const [query, setQuery] = useState(''); const [debouncedQuery] = useDebounce(query, 300); const { data, loading } = useExistingDataHook(); const filtered = useMemo(() => data?.filter(d => d.name.toLowerCase().includes(debouncedQuery.toLowerCase()) ), [data, debouncedQuery] ); return (
{loading && }
); }; ``` -------------------------------- ### Sahin AI Rules System Overview Source: https://github.com/sahin/ai-rules/blob/main/README.md A visual representation of the complete Sahin AI Rules workflow system, detailing the flow from user request to changelog tracking, including intermediate steps like analysis, planning, approval, and execution. ```markdown β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚ CLAUDE WORKFLOW SYSTEM β”‚ β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ β”‚ β”‚ β”‚ User Request β†’ Analysis β†’ Plan β†’ Approval β†’ Todo β†’ Execute β†’ Changelog β”‚ β”‚ ↓ ↓ ↓ ↓ ↓ ↓ ↓ β”‚ β”‚ [Natural [Context] [Task [User [Auto [Work [History] β”‚ β”‚ Language] Rules] List] OK/NO] File] Loop] Track] β”‚ β”‚ β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ ``` -------------------------------- ### API Request Logging Middleware Source: https://github.com/sahin/ai-rules/blob/main/rules/general-policies/ops/observability.md An example of a TypeScript middleware for Express.js applications that logs the start and end of each API request, including details like method, URL, status code, and duration. It utilizes a correlation ID for tracing requests across services. ```typescript // API middleware for automatic logging app.use((req: Request, res: Response, next: NextFunction) => { const startTime = Date.now(); const correlationId = req.headers['x-correlation-id'] || generateId(); // Log request entry logger.info('API request started', { event: 'api_request_start', method: req.method, url: req.url, correlationId, userAgent: req.headers['user-agent'], sourceIP: req.ip, userId: req.user?.id }); // Capture response res.on('finish', () => { const duration = Date.now() - startTime; logger.info('API request completed', { event: 'api_request_end', method: req.method, url: req.url, statusCode: res.statusCode, duration, correlationId, userId: req.user?.id }); }); next(); }); ``` -------------------------------- ### Function Testing with Jest's .each Source: https://github.com/sahin/ai-rules/blob/main/rules/general-policies/testing/implementation-guide.md Illustrates testing pure functions using Jest's `.each` for parameterized tests. Covers calculating discounts with various inputs and testing for invalid input handling. ```typescript describe('calculateDiscount', () => { it.each([ { price: 100, discount: 10, expected: 90 }, { price: 50, discount: 50, expected: 25 }, { price: 0, discount: 10, expected: 0 }, ])('should calculate $expected for price $price with $discount% discount', ({ price, discount, expected }) => { expect(calculateDiscount(price, discount)).toBe(expected); } ); it('should throw for invalid inputs', () => { expect(() => calculateDiscount(-10, 20)).toThrow('Invalid price'); expect(() => calculateDiscount(100, 101)).toThrow('Invalid discount'); }); }); ``` -------------------------------- ### Coverage Configuration Example Source: https://github.com/sahin/ai-rules/blob/main/rules/general-policies/testing/core-standards.md Configures global and specific directory coverage thresholds for statement, branch, function, and line counts. Ensures critical business logic meets higher coverage targets. ```javascript module.exports = { coverageThreshold: { global: { statements: 80, branches: 75, functions: 80, lines: 80 }, './src/core/': { statements: 90 // Higher coverage for critical code } } }; ``` -------------------------------- ### Phase 2: Todo Creation & Task Management Workflow Source: https://github.com/sahin/ai-rules/blob/main/README.md Illustrates the process of generating a todo file and managing tasks after user approval of the plan. It covers task generation, file creation, and context window size checks. ```text β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚ PHASE 2: TODO CREATION β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ User Approves Plan β”‚ β–Ό β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚ Generate Todo β”‚ β”‚ File β”‚ β”‚ β”‚ β”‚ tasks-YYYY.md β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚ β–Ό β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚ Task 1 β”‚ β”‚ Task 2 β”‚ β”‚ Task 3 β”‚ β”‚ [ ] Login UI β”‚ β”‚ [ ] Auth Logic β”‚ β”‚ [ ] Tests β”‚ β”‚ β”‚ β”‚ β”‚ β”‚ β”‚ β”‚ Files: 3 β”‚ β”‚ Files: 2 β”‚ β”‚ Files: 5 β”‚ β”‚ LOC: ~50 β”‚ β”‚ LOC: ~30 β”‚ β”‚ LOC: ~100 β”‚ β”‚ Priority: High β”‚ β”‚ Priority: High β”‚ β”‚ Priority: Med β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚ β”‚ β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚ β–Ό β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚ Context Window β”‚ β”‚ Size Check β”‚ β”‚ β”‚ β”‚ Split if > 80% β”‚ β”‚ of context limit β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ ``` -------------------------------- ### Implementation Rules: DOs Source: https://github.com/sahin/ai-rules/blob/main/rules/general-policies/todo-driven-workflow.md Lists the recommended practices for implementation, such as creating todos from plans, sizing tasks appropriately, executing sequentially, testing with real user flows, tracking progress, minimizing code, and maximizing user impact. ```markdown DO βœ… - Create todos from approved plans - Size tasks for context limits - Execute tasks sequentially - Test with real user flows - Track progress in changelog - Minimize lines of code - Maximize user impact ``` -------------------------------- ### Example Work Session: Code Refactoring Source: https://github.com/sahin/ai-rules/blob/main/rules/general-policies/ops/continuous-work-loop.md A markdown example of a code refactoring session, showing completed, current, and remaining tasks with progress indicators. ```markdown ## πŸ”„ CONTINUOUS WORK SESSION: Refactor Authentication **Total Tasks**: 12 items **Progress**: 42% [β–ˆβ–ˆβ–ˆβ–ˆβ–‘β–‘β–‘β–‘β–‘β–‘] ### Completed (5/12): βœ… Extract auth logic to hook βœ… Create auth context βœ… Update LoginForm component βœ… Add type definitions βœ… Update imports ### Current (6/12): πŸ”„ Writing unit tests... Progress: 50% [β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–‘β–‘β–‘β–‘β–‘] ### Remaining (6): ⏳ Integration tests ⏳ Update documentation ⏳ Migration guide ⏳ Deprecation notices ⏳ Final review ⏳ Commit changes ⏸️ **Continue in 5 seconds** - Interrupt to pause ``` -------------------------------- ### Mandatory Table Structure Example Source: https://github.com/sahin/ai-rules/blob/main/rules/general-policies/backend/database-schema.md Provides an example of a mandatory table structure including primary keys, unique constraints, NOT NULL constraints, and soft delete support. ```sql CREATE TABLE users ( id SERIAL PRIMARY KEY, email VARCHAR(255) UNIQUE NOT NULL, password_hash VARCHAR(255) NOT NULL, created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(), updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(), deleted_at TIMESTAMP WITH TIME ZONE NULL -- Soft delete support ); -- MANDATORY: Add indexes for performance CREATE INDEX idx_users_email ON users(email); CREATE INDEX idx_users_created_at ON users(created_at); ``` -------------------------------- ### Recommended Smart Testing Equivalents Source: https://github.com/sahin/ai-rules/blob/main/rules/testing/smart-testing.md Provides the recommended smart testing commands as alternatives to the banned traditional commands, ensuring efficient test execution. ```bash npm run test:smart npm run test:smart:unit npm run test:smart:integration npm run e2e:smart ``` -------------------------------- ### Custom Test Helpers (React) Source: https://github.com/sahin/ai-rules/blob/main/rules/general-policies/testing/implementation-guide.md Illustrates creating custom testing utilities for React applications, such as a helper function to render components with necessary providers and utilities for waiting for asynchronous operations. ```typescript // Custom render with providers export const renderWithProviders = (ui: React.ReactElement) => { return render( {ui} ); }; // Wait for async updates export const waitForLoadingToFinish = () => waitForElementToBeRemoved(() => screen.queryAllByTestId(/loading/i)); // Generate test data export const createMockUser = (overrides = {}) => ({ id: faker.datatype.uuid(), name: faker.name.fullName(), email: faker.internet.email(), ...overrides }); ``` -------------------------------- ### Forbidden Opening Examples Source: https://github.com/sahin/ai-rules/blob/main/rules/_mandatory/00-circuit-breaker.md These are examples of phrases that are strictly prohibited at the beginning of any AI response. Offering immediate assistance violates the core rule. ```markdown - "I'll help you..." - "Let me help..." - "I can help..." - "I'll do..." - "Let me..." - Any variation of immediate assistance ``` -------------------------------- ### Phase 1: Request Analysis & Planning Workflow Source: https://github.com/sahin/ai-rules/blob/main/README.md Visualizes the steps involved in analyzing user requests and creating a project plan. It includes stages like User Request, Load Rules, Analyze Requirements, Create Plan, and Show to User. ```text β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚ PHASE 1: ANALYSIS β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚ β–Ό β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚ User Request β”‚ β”‚ β”‚ β”‚ "Build login β”‚ β”‚ with tests" β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚ β–Ό β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚ Load Rules β”‚ β”‚ β”‚ β”‚ β€’ Workflow β”‚ β”‚ β€’ Testing β”‚ β”‚ β€’ High-ROI β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚ β–Ό β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚ Analyze β”‚ β”‚ Requirements β”‚ β”‚ β”‚ β”‚ β€’ Features β”‚ β”‚ β€’ User Flows β”‚ β”‚ β€’ Dependencies β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚ β–Ό β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚ Create Plan β”‚ β”‚ β”‚ β”‚ β€’ Task List β”‚ β”‚ β€’ Priorities β”‚ β”‚ β€’ Estimates β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚ β–Ό β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚ Show to User β”‚ ←── "Would you like me to proceed?" β”‚ β”‚ β”‚ Plan Format β”‚ β”‚ with Tasks β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ ``` -------------------------------- ### Bad E2E Test Examples - Playwright Source: https://github.com/sahin/ai-rules/blob/main/rules/general-policies/testing/playwright-first.md Provides examples of poorly written End-to-End (E2E) tests that focus on implementation details or are too granular. These tests should ideally be integration or unit tests. ```javascript // ❌ BAD - Tests implementation details test('tank level component renders correct props', async ({ page }) => { // This tests implementation, not user value await page.goto('/components/tank-level'); await expect(page.locator('.tank-level-component')).toHaveClass('rendered'); }); // ❌ BAD - Too granular for E2E test('tank level API returns JSON', async ({ page }) => { // This should be an integration test, not E2E const response = await page.request.get('/api/tanks'); expect(response.status()).toBe(200); }); ``` -------------------------------- ### Database Integration Tests Source: https://github.com/sahin/ai-rules/blob/main/rules/general-policies/testing/implementation-guide.md Tests for user repository operations including creation, retrieval, and handling concurrent updates. It uses Jest for testing and assumes a database connection and seeding mechanism. ```typescript describe('UserRepository', () => { beforeEach(async () => { await db.migrate.latest(); await db.seed.run(); }); afterEach(async () => { await db.migrate.rollback(); }); it('should create and retrieve user', async () => { const user = await UserRepository.create({ name: 'Test User', email: 'test@example.com' }); expect(user.id).toBeDefined(); const retrieved = await UserRepository.findById(user.id); expect(retrieved).toMatchObject({ name: 'Test User', email: 'test@example.com' }); }); it('should handle concurrent updates', async () => { const user = await UserRepository.create({ name: 'Initial' }); // Simulate concurrent updates await Promise.all([ UserRepository.update(user.id, { name: 'Update 1' }), UserRepository.update(user.id, { name: 'Update 2' }) ]); const final = await UserRepository.findById(user.id); expect(['Update 1', 'Update 2']).toContain(final.name); }); }); ``` -------------------------------- ### ROI Scoring Formula and Examples Source: https://github.com/sahin/ai-rules/blob/main/rules/general-policies/todo-driven-workflow.md Explains the formula for calculating Return on Investment (ROI) as (User Impact Γ— Frequency) / Lines of Code, and provides examples of how to score tasks based on this formula. ```markdown ROI = (User Impact Γ— Frequency) / Lines of Code High ROI (>10): πŸš€ Do immediately Medium ROI (3-10): βœ… Do soon Low ROI (<3): ⏳ Consider deferring Examples: - Login button: High impact, used always, 5 LoC = ROI: 20 - Admin panel: Medium impact, used rarely, 200 LoC = ROI: 2 - Error page: Low impact, used never (hopefully), 50 LoC = ROI: 1 ``` -------------------------------- ### Business Event Logging Examples Source: https://github.com/sahin/ai-rules/blob/main/rules/general-policies/ops/observability.md Provides examples of logging key business events such as user registration, order placement, and payment processing. These logs help in understanding user behavior and business flow. ```typescript // Business event logging const businessEvents = { userRegistration: (userId: string, email: string) => { logger.info('User registered', { event: 'user_registered', userId, email, timestamp: new Date().toISOString(), source: 'web_app' }); }, orderPlaced: (orderId: string, userId: string, amount: number) => { logger.info('Order placed', { event: 'order_placed', orderId, userId, amount, timestamp: new Date().toISOString(), currency: 'USD' }); }, paymentProcessed: (paymentId: string, amount: number, status: string) => { logger.info('Payment processed', { event: 'payment_processed', paymentId, amount, status, timestamp: new Date().toISOString() }); } }; ``` -------------------------------- ### User Authentication ROI Example Source: https://github.com/sahin/ai-rules/blob/main/rules/general-policies/high-roi-development.md Compares a low ROI approach (custom system) with a high ROI approach (using existing libraries) for user authentication, demonstrating a significant improvement in efficiency. ```markdown LOW ROI APPROACH: - Custom auth system - Multiple login methods - Complex user roles - Advanced security features - 2000+ LoC HIGH ROI APPROACH: - Use existing auth library - Simple email/password - Basic role checking - Standard security practices - 200 LoC ROI Difference: 10x improvement ``` -------------------------------- ### Usage Example: Auth Component Change Source: https://github.com/sahin/ai-rules/blob/main/rules/testing/smart-testing.md Demonstrates the smart testing workflow when a change is made to an authentication component. It shows the dry run output and the actual execution, highlighting the time saved. ```bash # You edited: src/components/auth/LoginForm.tsx npm run test:smart:dry # Output: Will run 4 auth tests + 4 E2E routes npm run test:smart # Runs: auth unit tests + auth integration + auth E2E routes # Time: 20 seconds (vs 3 minutes for all tests) ``` -------------------------------- ### High ROI Success Pattern Example Source: https://github.com/sahin/ai-rules/blob/main/rules/general-policies/high-roi-development.md An example demonstrating the application of the High ROI Success Pattern, contrasting a low ROI approach with a high ROI solution for a user problem. ```markdown Problem: Users can't find their data Low ROI: Advanced search with filters, tags, AI High ROI: Simple search box on existing page Results: 90% of searches successful, 5 LoC added Key Learning: Users just needed basic search ``` -------------------------------- ### Mandatory Plan Format and Execution Source: https://github.com/sahin/ai-rules/blob/main/rules/core-standards/core-workflow.md This section details the required format for development plans, including action steps, file modifications, testing phases, and potential impacts. It also specifies the exact phrasing for seeking user approval before proceeding with any development tasks. ```markdown ## Plan: 1. **[Action Category]**: [Brief description] - Specific file/component affected - What will change - Why this is needed 2. **[Next Action]**: [Description] - Details... 3. **πŸ§ͺ TESTING PHASE** (REQUIRED): - **Reference**: See `.cursor/rules/general-policies/testing/core-standards.md` for complete testing requirements - **Code changes**: Unit, integration, user, performance, error handling, regression tests - **Config/schema changes**: Full test suite validation required - **Documentation changes**: Link validation and format review only - **Commands**: `npm run test:smart --dry-run` β†’ `npm run test:smart` β†’ `npm run build` Files to be modified: - [List of all files that will be created, modified, or deleted] Testing files to create/update: - [List of test files that will be created or modified] Potential Impact: - [Any risks or considerations] Would you like me to proceed with this plan? ``` -------------------------------- ### JSDoc Function Comment Example Source: https://github.com/sahin/ai-rules/blob/main/rules/core-standards/coding-standards.md Demonstrates the use of JSDoc for documenting a TypeScript function, including parameters, return values, exceptions, and usage examples. This function calculates compound interest with daily compounding. ```typescript /** * Calculate compound interest with daily compounding * @param principal - Initial amount in cents to avoid floating point issues * @param rate - Annual interest rate as decimal (0.05 = 5%) * @param days - Number of days to compound * @returns Total amount in cents after compounding * @throws {InvalidRateError} If rate is negative or > 1 * @example * calculateInterest(100000, 0.05, 365) // Returns 105127 (5.127% actual) * @see https://docs.company.com/financial-calculations */ export function calculateCompoundInterest( principal: number, rate: number, days: number ): number { if (rate < 0 || rate > 1) { throw new InvalidRateError('Rate must be between 0 and 1'); } // Using daily compounding formula: A = P(1 + r/365)^(365*t) // where t = days/365 for partial years const dailyRate = rate / 365; const periods = days; return Math.round(principal * Math.pow(1 + dailyRate, periods)); } ``` -------------------------------- ### Introduce Parameter Object Refactoring Source: https://github.com/sahin/ai-rules/blob/main/rules/general-policies/refactoring.md Shows how to refactor a function with too many parameters by introducing a parameter object. The 'before' example has a function with numerous individual parameters, while the 'after' example uses a `UserCreationData` interface to group related parameters. ```typescript // BEFORE - Too many parameters function createUser( firstName: string, lastName: string, email: string, phoneNumber: string, address: string, city: string, state: string, zipCode: string, country: string ): User { // Implementation } // AFTER - Parameter object interface UserCreationData { firstName: string; lastName: string; email: string; phoneNumber: string; address: { street: string; city: string; state: string; zipCode: string; country: string; }; } function createUser(userData: UserCreationData): User { // Implementation } ``` -------------------------------- ### Basic NPM Package Updates and Testing Source: https://github.com/sahin/ai-rules/blob/main/rules/general-policies/dependencies.md Demonstrates common npm commands for updating packages to specific versions and running various test scripts like unit tests, end-to-end tests, and build processes. ```bash npm install package@^1.3.0 npm test npm run e2e npm run build npm run start ```