# AgenticIQ Coding Standards and Best Practices

## 1. Introduction and Purpose
This document establishes comprehensive coding standards and best practices for all developers working on the AgenticIQ enterprise application. Following these guidelines ensures code consistency, maintainability, and scalability across the entire development team.

### 1.1 Document Objectives
- Establish uniform coding standards across all development teams
- Reduce technical debt and improve code quality
- Facilitate easier onboarding of new team members
- Enable efficient code reviews and collaboration
- Ensure application performs optimally across all devices

### 1.2 Technology Stack
AgenticIQ is built using modern enterprise technologies. All code must align with the architectural patterns and technology constraints defined for this application.

## 2. General Coding Standards
### 2.1 Code Formatting Rules
1. Use 4 spaces for indentation (no tabs)
2. Maximum line length: 120 characters
3. Use UTF-8 encoding for all source files
4. End files with a single newline character
5. Remove trailing whitespace from all lines
6. Use consistent brace style (opening brace on same line for JS/TS, new line for C#)

### 2.2 Code Organization Principles
- Single Responsibility Principle (SRP): Each file/class/function should have one purpose
- DRY (Don't Repeat Yourself): Extract common logic into reusable functions/components
- KISS (Keep It Simple): Avoid over-engineering; prefer clarity over cleverness
- YAGNI (You Aren't Gonna Need It): Don't add functionality until it's required

### 2.3 File Size Guidelines
- Maximum file length: 400 lines (excluding comments)
- Maximum function/method length: 50 lines
- Maximum class length: 300 lines
- If limits are exceeded, refactor into smaller units

## 3. Naming Conventions
Consistent naming is critical for code readability and maintainability. All naming must be meaningful, descriptive, and follow the patterns defined below.

### 3.1 General Naming Rules
1. Use meaningful, descriptive names that reveal intent
2. Avoid single-letter names except for loop counters (i, j, k)
3. Avoid abbreviations unless universally understood (e.g., URL, HTTP, ID)
4. Use American English spelling consistently
5. Boolean variables should indicate true/false (isActive, hasPermission, canEdit)

### 3.2 Naming Convention Reference Table
| Element         | Convention     | Example               | Notes                       |
| --------------- | -------------- | --------------------- | --------------------------- |
| Class/Interface | PascalCase     | UserService, IRepository | Prefix I for interfaces (C#) |
| Function/Method | camelCase      | getUserById, calculateTotal | Start with verb             |
| Variable        | camelCase      | userName, orderItems  | Descriptive nouns           |
| Constant        | SCREAMING_SNAKE| MAX_RETRY_COUNT       | All uppercase               |
| Private Field   | _camelCase     | _userRepository       | Underscore prefix           |
| Component       | PascalCase     | UserDashboard.tsx     | Match filename              |
| CSS Class       | kebab-case     | user-profile-card     | BEM methodology             |
| File (General)  | kebab-case     | user-service.ts       | Lowercase                   |
| Database Table  | PascalCase Singular | UserProfile, OrderItem | Match entity name         |
| API Endpoint    | kebab-case plural | /api/user-profiles  | RESTful conventions         |

### 3.3 Function Naming Patterns
Function names should clearly describe the action performed. Use consistent verb prefixes to indicate the operation type.

| Prefix     | Purpose            | Examples                                       |
| ---------- | ------------------ | ---------------------------------------------- |
| get        | Retrieve data      | getUserById(), getOrderList(), getActiveUsers()|
| set        | Assign value       | setUserName(), setOrderStatus()                |
| create     | Create new entity  | createUser(), createOrder(), createReport()    |
| update     | Modify existing    | updateUserProfile(), updateOrderQuantity()     |
| delete/remove | Remove data     | deleteUser(), removeCartItem()                 |
| is/has/can | Boolean checks     | isActive(), hasPermission(), canEdit()         |
| validate   | Check validity     | validateEmail(), validateUserInput()           |
| calculate  | Compute values     | calculateTotal(), calculateDiscount()          |
| handle     | Event handling     | handleSubmit(), handleClick(), handleError()   |
| fetch/load | Async data load    | fetchUserData(), loadConfiguration()           |
| render     | UI rendering       | renderHeader(), renderUserList()               |
| format/parse | Data transformation | formatDate(), parseJson(), formatCurrency() |

## 4. Function Design Guidelines
### 4.1 Function Structure Best Practices
1. Single Purpose: Each function should do exactly one thing well
2. Parameter Limit: Maximum 4 parameters; use objects for more
3. Pure Functions: Prefer functions without side effects when possible
4. Early Returns: Use guard clauses to handle edge cases first
5. Avoid Deep Nesting: Maximum 3 levels of nesting; refactor if deeper

### 4.2 Function Signature Guidelines
- Return Type: Always specify explicit return types in TypeScript
- Parameter Types: Use strong typing; avoid `any`
- Default Values: Provide sensible defaults for optional parameters
- Async Functions: Return `Promise<T>` with proper typing

### 4.3 Function Documentation Template
Every public function must include JSDoc/XML documentation with:
- `@description` - Brief explanation of what the function does
- `@param {Type} name` - Description of each parameter
- `@returns {Type}` - Description of the return value
- `@throws {ErrorType}` - Exceptions that may be thrown
- `@example` - Usage example (for complex functions)

## 5. Responsive Design & Screen Optimization
### 5.1 Breakpoint Standards
| Device         | Breakpoint       | CSS Variable    | Target Devices      |
| -------------- | ---------------- | --------------- | ------------------- |
| Mobile S       | < 375px          | --screen-xs     | Small phones        |
| Mobile M       | 375px - 424px    | --screen-sm     | Standard phones     |
| Mobile L       | 425px - 767px    | --screen-md     | Large phones        |
| Tablet         | 768px - 1023px   | --screen-lg     | iPad, Tablets       |
| Laptop         | 1024px - 1439px  | --screen-xl     | Laptops, small desktops |
| Desktop        | 1440px - 1919px  | --screen-xxl    | Standard monitors   |
| Large Display  | ≥ 1920px         | --screen-xxxl   | Large/4K monitors   |

### 5.2 Mobile-First Development
1. Start with mobile layout and progressively enhance for larger screens
2. Use min-width media queries to add complexity as screen size increases
3. Design touch-friendly interfaces with minimum 44px touch targets
4. Optimize images for mobile using srcset and responsive images
5. Test on actual devices, not just browser developer tools

### 5.3 Layout Guidelines
- Flexbox: Use for one-dimensional layouts (rows or columns)
- CSS Grid: Use for two-dimensional layouts and complex designs
- Container Queries: Use for component-level responsiveness
- Relative Units: Use rem/em for typography, % for widths, vh/vw for viewports
- Avoid fixed pixel widths for containers; prefer max-width constraints

### 5.4 Typography Scaling
| Element | Mobile        | Tablet        | Desktop       |
| ------- | ------------- | ------------- | ------------- |
| H1      | 1.75rem (28px)| 2rem (32px)   | 2.5rem (40px) |
| H2      | 1.5rem (24px) | 1.75rem (28px)| 2rem (32px)   |
| H3      | 1.25rem (20px)| 1.375rem (22px)| 1.5rem (24px)|
| Body    | 0.875rem (14px)| 0.9375rem (15px)| 1rem (16px) |
| Caption | 0.75rem (12px)| 0.8125rem (13px)| 0.875rem (14px)|

## 6. Code Architecture Principles
### 6.1 Folder Structure Standards
Maintain consistent folder organization across all modules:
- `/src/components`: Reusable UI components
- `/src/pages`: Route-level page components
- `/src/hooks`: Custom React hooks
- `/src/services`: API calls and external integrations
- `/src/utils`: Utility functions and helpers
- `/src/types`: TypeScript type definitions
- `/src/constants`: Application constants and enums
- `/src/styles`: Global styles and theme configuration

### 6.2 Component Design Patterns
1. Container/Presentational Pattern: Separate logic from presentation
2. Compound Components: Create flexible, composable component APIs
3. Render Props/HOCs: Share behavior between components
4. Custom Hooks: Extract reusable stateful logic
5. Context Pattern: Share state across component tree

### 6.3 State Management Guidelines
- Local State: Use `useState` for component-specific state
- Server State: Use React Query/TanStack Query for API data
- Global State: Use Zustand/Redux for app-wide state
- Form State: Use React Hook Form for complex forms

## 7. Error Handling Best Practices
### 7.1 Error Handling Principles
1. Fail Fast: Detect and report errors as early as possible
2. Be Specific: Use specific error types, not generic exceptions
3. Log Appropriately: Include context but exclude sensitive data
4. User-Friendly Messages: Show helpful messages, not stack traces
5. Recover Gracefully: Implement fallback behavior where possible

### 7.2 Error Categories
| Error Type     | Handling Strategy              | Example                  |
| -------------- | ------------------------------ | ------------------------ |
| Validation     | Show inline field errors       | Invalid email format     |
| Network        | Retry with exponential backoff | API timeout              |
| Authentication | Redirect to login              | Token expired            |
| Authorization  | Show access denied message     | 403 Forbidden            |
| Not Found      | Show 404 page or fallback      | Resource not found       |
| Server Error   | Show error page with support contact | 500 Internal Error |

### 7.3 Try-Catch Guidelines
- Catch specific errors, not generic Exception/Error
- Never swallow exceptions silently without logging
- Use finally blocks for cleanup operations
- Avoid try-catch for flow control
- Re-throw with additional context when appropriate

## 8. Performance Optimization
### 8.1 Frontend Performance
1. Code Splitting: Use dynamic imports for route-level splitting
2. Lazy Loading: Defer loading of below-the-fold content
3. Image Optimization: Use WebP format, responsive images, lazy loading
4. Bundle Analysis: Regularly analyze and optimize bundle size
5. Caching: Implement proper caching headers and service workers
6. Memoization: Use `useMemo`, `useCallback`, `React.memo` appropriately

### 8.2 React Performance Tips
- Use virtualization for long lists (react-window, react-virtualized)
- Avoid inline function definitions in render
- Use stable keys for list items
- Avoid unnecessary re-renders with proper state structure
- Profile with React DevTools before optimizing

### 8.3 Performance Metrics Targets
| Metric                   | Target          | Measurement          |
| ------------------------ | --------------- | -------------------- |
| First Contentful Paint (FCP) | < 1.8 seconds | Lighthouse           |
| Largest Contentful Paint (LCP) | < 2.5 seconds | Lighthouse         |
| Cumulative Layout Shift (CLS)  | < 0.1         | Lighthouse           |
| Time to Interactive (TTI)      | < 3.8 seconds | Lighthouse           |
| Bundle Size (main)             | < 250KB gzipped | Webpack analyzer   |

## 9. Security Guidelines
### 9.1 Input Validation & Sanitization
1. Validate all inputs on both client and server side
2. Sanitize user inputs to prevent XSS attacks
3. Use parameterized queries to prevent SQL injection
4. Implement rate limiting on API endpoints
5. Validate file uploads (type, size, content)

### 9.2 Authentication & Authorization
- Never store sensitive data in localStorage/sessionStorage
- Use HTTP-only, Secure cookies for session tokens
- Implement proper CORS configuration
- Use CSRF tokens for state-changing operations
- Always verify authorization on the server

### 9.3 Data Protection
- Never log sensitive information (passwords, tokens, PII)
- Use environment variables for secrets
- Encrypt sensitive data at rest and in transit
- Implement proper error messages (no stack traces in production)
- Follow principle of least privilege

## 10. Documentation Standards
### 10.1 Code Comments Guidelines
- WHY, not WHAT: Explain the reasoning, not what the code does
- Self-Documenting Code: Use clear names; add comments only when necessary
- Update Comments: Keep comments in sync with code changes
- TODO Comments: Include ticket number, e.g., `// TODO(JIRA-123): Fix edge case`
- Avoid obvious comments

### 10.2 README Requirements
Every project/module must have a README.md with:
- Project overview and purpose
- Prerequisites and dependencies
- Installation and setup instructions
- Environment configuration
- Available scripts and commands
- Contributing guidelines

### 10.3 API Documentation
All APIs must be documented using OpenAPI/Swagger specification with endpoint descriptions, request/response schemas, authentication requirements, error codes and responses, and usage examples.

## 11. Version Control Guidelines
### 11.1 Git Commit Message Format
Follow the Conventional Commits specification: `<type>(<scope>): <subject>`

| Type   | Description                                   |
| ------ | --------------------------------------------- |
| feat   | New feature for the user                      |
| fix    | Bug fix for the user                          |
| docs   | Documentation only changes                    |
| style  | Formatting, missing semicolons (no code change) |
| refactor | Code change that neither fixes a bug nor adds a feature |
| test   | Adding or updating tests                      |
| chore  | Build process or auxiliary tool changes       |

### 11.2 Branching Strategy
- `main`: Production-ready code only
- `develop`: Integration branch for features
- `feature/JIRA-XXX-description`: Feature branches
- `bugfix/JIRA-XXX-description`: Bug fix branches
- `hotfix/JIRA-XXX-description`: Production hotfixes
- `release/vX.X.X`: Release preparation branches

## 12. Testing Standards
### 12.1 Testing Pyramid
- Unit Tests (70%): Test individual functions/components in isolation
- Integration Tests (20%): Test component interactions and API integrations
- E2E Tests (10%): Test critical user journeys end-to-end

### 12.2 Test Naming Convention
Use the pattern: describe what is being tested + under what conditions + expected outcome.
- Example: `getUserById returns user object when valid ID is provided`
- Example: `calculateTotal throws error when items array is empty`

### 12.3 Code Coverage Requirements
- Minimum line coverage: 80%
- Minimum branch coverage: 75%
- Critical paths: 100% coverage required
- New code must maintain or improve coverage


