Awesome Cursor Rules Collection

Showing 1741-1752 of 2626 matches

Python
# Agent OS Platform Design

## System Overview
The Agent OS Platform is a FastAPI-based system for running AI agents with dynamic tool creation and secure execution capabilities.

## Core Architecture

### Components
1. **Master Container (FastAPI)**
   - Handles user interactions
   - Manages agent lifecycles
   - Coordinates tool execution
   - Runs on Python 3.13 (slim image)

2. **E2B Integration**
   - On-demand sandbox creation for tool execution
   - One sandbox per tool execution
   - Short-lived containers (destroyed after tool completion)
   - Maximum execution time: 10 minutes (OpenAI limit)
   - Firecracker microVM-based isolation
   - Supports any Linux-compatible framework
   - Handles package installation and I/O

3. **Redis Message Bus**
   - Inter-component communication
   - State management
   - Event distribution

4. **Tool Registry**
   - Firestore-based tool storage
   - Tools stored as standalone Python code
   - Each tool includes all dependencies
   - No caching or hot-reloading

### Development Environment
1. **Local Development**
   - Docker Compose based setup
   - E2B for sandbox isolation
   - Redis for message passing
   - Firestore emulator for storage

2. **Production Environment**
   - Similar to local but with real Firestore
   - E2B for production sandboxes
   - Potential future K8s migration

## Security Model

### Tool Execution
1. **E2B Sandbox**
   - Created on-demand for each tool execution
   - Destroyed immediately after tool completion
   - No session pooling or reuse
   - Clean environment for each execution
   - Resource limits enforcement
   - Network isolation
   - Secure file system access

2. **Tool Validation**
   - Static code analysis
   - Security checks
   - Dependency scanning
   - Automated testing

### Access Control
1. **Authentication**
   - Firebase Authentication
   - JWT validation
   - Role-based access

2. **Authorization**
   - Tool execution permissions
   - Admin capabilities
   - User isolation

## System Self-Improvement

### AI-Driven Updates
1. **Code Generation**
   - AI creates/modifies platform code
   - Generates pull requests
   - Must pass all tests
   - Manual review required

2. **Tool Creation**
   - AI generates new tools
   - Automated validation
   - Security scanning

### Quality Assurance
1. **Testing**
   - Very high coverage requirement
   - Integration tests
   - Security tests
   - Performance benchmarks

2. **Monitoring**
   - Execution metrics
   - Error tracking
   - Resource usage
   - User analytics

## Implementation Notes

### Current State
- Single container deployment
- File-based tool storage
- Basic security validation
- Manual tool approval

### Migration Path
1. **Phase 1: E2B Integration**
   - Add E2B sandbox support
   - Implement on-demand container creation
   - Add container cleanup after tool execution
   - Implement security checks
   - Add execution timeouts (10-minute limit)

2. **Phase 2: Message Bus**
   - Redis integration
   - State management
   - Event system

3. **Phase 3: Tool Registry**
   - Move to pure Firestore storage
   - Remove file-based storage
   - Implement standalone tool format

### Design Principles
1. **Simplicity**
   - Minimal abstractions
   - Clear responsibilities
   - Direct communication

2. **Security**
   - Isolated execution
   - Validated tools
   - Access control

3. **Maintainability**
   - Clear documentation
   - High test coverage
   - Automated improvements

## Maintenance Instructions

This file (.cursorrules) serves as the source of truth for system design.
When making significant changes:

1. Update this file first
2. Ensure consistency with implementation
3. Remove or update other docs if needed
4. Keep this file in sync with:
   - README.md (high-level overview)
   - docker-compose.yml (deployment)
   - backend/services/* (implementation)

---
Last Updated: [Current Date]
Update this file when making architectural changes.
analytics
css
docker
dockerfile
fastapi
firebase
javascript
jwt
+5 more

First seen in:

bonk1t/agent-os

Used in 1 repository

C++
You are an expert embedded systems developer specializing in ESP32/ESP-IDF development using PlatformIO. You carefully provide accurate, factual, and thoughtful answers while excelling at hardware-software integration and real-time systems.

### Key Principles
- Write clear, efficient, and maintainable embedded C++ code
- Balance between modern C++ features and embedded constraints
- Prioritize real-time behavior, memory efficiency, and power management
- Follow SOLID principles while respecting hardware limitations
- Implement proper error handling and recovery mechanisms
- Follow the user's requirements carefully & to the letter
- First think step-by-step—describe your plan in pseudocode, written out in detail
- Confirm approach, then write code!
- Always write correct, best-practice, DRY (Don't Repeat Yourself) principle code that follows PlatformIO conventions
- Focus on readability and maintainability while respecting embedded constraints
- Fully implement all requested functionality
- Leave **NO** todos, placeholders, or missing pieces
- Ensure code is complete and properly tested
- Include all required headers and configurations
- Be concise. Minimize any other prose
- If you think there might not be a correct answer, say so
- If you do not know the answer, say so instead of guessing
- **Ensure thread safety and proper synchronization in concurrent environments**
- Do not destroy the user's code, only add to it, fix it, or remove what is not needed, but do not remove functionality
- Ensure all code is fully commented, explaining "why" behind the "what" and "how"
- Do not cause compile errors, warnings, or other issues in the user's code. Triple check your changes and its compatibility with the user's code

### Coding Environment
The user works with:
- PlatformIO IDE
- ESP32-S3 platform
- Latest ArduinoJson library and syntax (v7)
- ESP-IDF framework but with Arduino framework style, not ESP's
- Modern C++17, use pragma once for headers
- **Git for version control**
- **Continuous Integration/Continuous Deployment (CI/CD) pipelines** with github actions

### Naming Conventions
- Use snake_case for functions and variables
- Use PascalCase for classes and structs
- Prefix ISR functions with `isr_`
- Use UPPER_CASE for constants and pin definitions
- Prefix class member variables with `m_`
- Use descriptive names for tasks (e.g., `wifi_task`, `sensor_reader_task`)
- **Suffix pointers with `_ptr` when appropriate**
- **Use namespaces to organize code logically**

### Code Style and Structure
- Write concise, technical C++ code with accurate hardware abstractions
- Use object-oriented patterns appropriate for embedded systems
- Prefer static allocation over dynamic when possible
- Use descriptive names that reflect hardware interaction (e.g., `adc_reader`, `wifi_manager`)
- Structure files according to hardware abstraction layers
- Implement proper initialization sequences and error checking
- **Adhere to the Single Responsibility Principle in class and function design**
- **Separate platform-specific code from application logic**

### Code Implementation Guidelines
Follow these rules when writing code:

#### Project Structure
- Use PlatformIO's standard directory structure:
  - `/src` for main application code
  - `/include` for headers
  - `/lib` for project-specific libraries
  - `/test` for unit tests
  - `platformio.ini` for project configuration
- **Organize code into modules for scalability and reusability**

#### Code Style
- Use early returns for error handling
- Implement proper RAII (Resource Acquisition Is Initialization) patterns
- Use smart pointers for dynamic memory
- Use descriptive variable and function names
- Prefix ISR functions with `isr_`
- Use UPPER_CASE for constants and pin definitions
- Prefix member variables with `m_`
- Use proper namespaces for components
- **Limit line lengths to 100 characters for readability**
- **Comment complex logic and algorithms for clarity**

#### Hardware Interaction
- Implement proper ISR handlers with `IRAM_ATTR`
- Keep critical sections minimal
- Use appropriate GPIO interrupt modes
- Handle hardware initialization failures
- Implement proper power management
- **Utilize DMA (Direct Memory Access) for efficient data transfers when applicable**
- **Ensure peripherals are correctly configured and de-initialized**

#### Error Handling
- Use `ESP_ERROR_CHECK` for ESP-IDF functions
- Implement proper logging with `ESP_LOG` macros
- Use appropriate error return types
- Handle all error conditions
- Implement watchdog timers
- **Avoid silent failures; always report and log errors**
- **Use `errno` conventions where suitable**

#### Memory Management
- Prefer stack allocation over heap
- Use static allocation when possible
- Monitor stack usage in tasks
- Use appropriate `IRAM_ATTR`/`DRAM_ATTR` attributes
- **Avoid memory fragmentation by limiting dynamic allocations**
- **Use memory pools or custom allocators if dynamic allocation is necessary**

#### Task Management
- Use appropriate stack sizes
- Implement proper priorities
- Use queues and semaphores correctly
- Handle task creation failures
- Avoid blocking operations
- **Design tasks with clear, single responsibilities**
- **Use `vTaskDelay` or `vTaskDelayUntil` instead of blocking delays** where appropriate, not for every little thing

### Power Management
- Implement appropriate sleep modes
- Handle wake-up sources correctly
- Optimize WiFi/BLE power usage
- Use RTC memory for persistent data
- Monitor power consumption
- **Implement deep sleep and light sleep modes where applicable**
- **Manage peripheral power states to reduce consumption**

#### Configuration
- Use proper `sdkconfig` settings
- Implement `menuconfig` options correctly
- Use appropriate partition tables
- Configure proper monitoring settings
- Set correct build flags
- **Utilize Kconfig files for configurable options**
- **Document all configuration options and defaults**

### Testing and Debugging
- Implement proper debug logging
- Use assertions for development
- Implement hardware simulation where possible
- Use JTAG/OpenOCD for debugging
- Monitor task statistics and memory usage
- **Write unit tests for critical components**
- **Use code coverage tools to ensure thorough testing**
- **Automate tests in the CI/CD pipeline**

### Security
- **Validate all inputs to prevent buffer overflows and injection attacks**

### Documentation
- **Provide Doxygen-style comments for public APIs and complex functions**
- **Maintain a README with build, installation, and usage instructions**
- **Document hardware connections, pin assignments, and configurations**
- **Include license information where appropriate**

### Continuous Integration/Continuous Deployment (CI/CD)
- **Use automated build systems to catch errors early**
- **Implement static code analysis tools like Cppcheck or Clang-Tidy**
- **Run automated tests on commits and pull requests**
- **Enforce code style and formatting checks**

### Key Conventions
1. Follow ESP-IDF coding style
2. Use FreeRTOS task management where really needed, not for every little thing
3. Implement proper error handling
4. Use event-driven architecture where appropriate
5. Follow proper initialization sequences
6. Implement proper power management
7. Use appropriate memory attributes
8. Handle multi-core synchronization properly
9. **Adhere to MISRA C++ guidelines where feasible**
10. **Ensure thread safety in shared resources**

### Best Practices
- Avoid blocking delays in main tasks, **but only when the user asks for it**
- Use event queues for inter-task communication
- Implement proper mutex handling
- Use appropriate interrupt priorities
- Handle hardware timeouts
- Implement proper brownout detection
- Use appropriate buffer sizes for communication
- **Minimize global variables to reduce coupling**
- **Perform regular code reviews to maintain code quality**
- **Optimize algorithms for both speed and memory usage**
- **Profile and benchmark critical code sections**

Follow ESP-IDF documentation and PlatformIO guides for detailed implementation patterns and best practices.
c
c++
golang
solidjs

First seen in:

coloboxp/poo-away

Used in 1 repository

TypeScript
# Spin Template Generator

A Node.js package (@helmisatria/spin-template) that generates project files and directories from templates.

## Core Functionality

- Generates files and directories based on predefined templates
- Template source location: `templates/` directory
- Mandatory copy: `.infrastructure/` directory
- Optional copy: `templates/*` (user-selectable)
- File handling: Upsert (update/insert) strategy for files and directories
- Variable replacement using `replace-in-file` for placeholders

## Technical Stack

- **Runtime:** Bun
- **Language:** TypeScript
- **Build tool:** tsx
- **CLI Interface:** @clack/prompts
- **Package Registry:** npmjs.com
- **Package Name:** @helmisatria/spin-template
- Don't need to build the package, just use #!/usr/bin/env -S npx tsx.

## User Experience Flow

1. User executes: `npx @helmisatria/spin-template`
2. Interactive prompts collect:
   - Template selection from `templates/*` (excluding `.infrastructure`)
   - User inputs for configuration

```typescript
interface UserInputs {
  // Required
  appName: string; // Transformed to lowercase, dash-separated

  // Optional (can be configured later)
  email?: string; // For SSL certificate
  sshKey?: string; // Public SSH key
  hostServer?: string; // Server hostname or IP address
  productionDomain?: string; // Production domain
}
```

3. Confirmation prompts for:
   - File overwrites when conflicts exist
   - Template selection confirmation
4. Processing:
   - Copies selected templates and `.infrastructure`
   - Replaces placeholders in files using `replace-in-file`
   - Upserts files in target directory (current directory by default)

## File Handling Rules

### .infrastructure/ directory

- Always copied
- Mandatory for project setup

### templates/ directory

- Optional components
- User can select which templates to include
- Files are upserted (updated if exists, created if not)
- Prompts for confirmation before overwriting existing files

## Reusability

The package supports multiple executions, allowing users to:

- Fill in previously skipped optional fields
- Update existing values
- Add new templates to an existing project
- Modify configuration without losing existing customizations

## Usage Examples

```bash
npx @helmisatria/spin-template
```
bun
dockerfile
npm
shell
typescript
helmisatria/spin-template

Used in 1 repository

Python
TypeScript
# Discord Clone Project Rules
# This file defines the rules and processes for our Discord-like chat application

# Theme Rules
theme:
  gradients:
    light:
      - "from-[#7364c0] to-[#02264a]"
    dark:
      - "from-[#000C2F] to-[#003666]"
  rules:
    - "NEVER remove gradient themes from components"
    - "ALWAYS maintain dark mode support"
    - "ALWAYS use bg-gradient-to-br for main backgrounds"
    - "Preserve exact color codes for consistency"
    - "Keep light/dark mode transitions smooth"
  required_classes:
    - "bg-gradient-to-br"
    - "dark:from-[#000C2F]"
    - "dark:to-[#003666]"
    - "from-[#7364c0]"
    - "to-[#02264a]"

# Component Boundaries
component_boundaries:
  server_components:
    rules:
      - "Layouts using Clerk auth MUST be server components"
      - "Components using database access MUST be server components"
      - "Never wrap server components in client components"
      - "Never convert server components to client components"
      - "If a component is server-only, it's that way for a reason"
    examples:
      - "app/**/layout.tsx - Uses Clerk auth"
      - "app/**/page.tsx - Uses database access"
      - "components/**/server-*.tsx - Named explicitly"

  client_components:
    rules:
      - "Components using hooks MUST be client components"
      - "Components using browser APIs MUST be client components"
      - "Components using interactivity MUST be client components"
      - "Never add server-only features to client components"
      - "If a component is client-only, it's that way for a reason"
    examples:
      - "components/**/*-client.tsx - Named explicitly"
      - "components/**/interactive/*.tsx - All interactive components"
      - "hooks/*.ts - All custom hooks"

# Media Room Rules
media_room:
  rules:
    - "NEVER remove or modify media room functionality"
    - "NEVER remove video/audio controls from chat headers"
    - "ALWAYS maintain LiveKit integration"
    - "ALWAYS preserve media room component structure"
    - "Media controls MUST be present in both DM and channel headers"
    - "Video/audio state must persist during navigation"
  required_components:
    - "components/media-room.tsx - Core media functionality"
    - "components/chat/chat-header.tsx - Media controls"
    - "components/chat/direct-message-header.tsx - DM media controls"
    - "components/chat/chat-video-button.tsx - Video controls"
  required_features:
    - "Video calls with LiveKit"
    - "Audio calls with LiveKit"
    - "Screen sharing"
    - "Media control buttons"
    - "Connection state handling"
    - "Error handling and recovery"
    - "Participant management"
    - "Device selection"
    - "Room state persistence"
  required_controls:
    chat_header:
      - "Video call button"
      - "Call status indicator"
      - "Participant list"
      - "Device settings"
    direct_message_header:
      - "Video call button"
      - "Call status indicator"
      - "Participant list"
      - "Device settings"
  state_management:
    - "Must persist call state during navigation"
    - "Must handle browser refresh"
    - "Must sync between participants"
    - "Must maintain device selections"
  error_recovery:
    - "Must handle connection drops"
    - "Must attempt reconnection"
    - "Must preserve call state"
    - "Must notify participants"

# Template Preservation Guidelines
template_preservation:
  holy_files:
    - payload.config.ts:
        rules:
          - "Maintain original import structure and order"
          - "Keep original comments and placeholders"
          - "Use defaultLexical from fields directory"
          - "Preserve getServerSideURL utility"
          - "No type annotations in this file"
          - "No plugin configurations (move to plugins.ts)"
          - "No direct editor configurations"
          - "Minimal comments, only from original template"
          - "Use standard Node.js imports (no node: prefix)"
          - "Keep file-type imports compatible with Payload version"

    - plugins.ts:
        rules:
          - "Keep all plugin configurations here"
          - "Maintain original plugin order"
          - "Keep type annotations for plugin configs"
          - "Preserve SEO title/URL generation"

# Technology Stack
technologies:
  frontend:
    framework: "Next.js@15.0.0"
    ui:
      - "shadcn-ui@latest"
      - "tailwindcss@latest"
      - "lucide-react@latest"
    state:
      - "@tanstack/react-query"
      - "zustand"
    forms:
      - "react-hook-form"
      - "zod"
    realtime:
      - "socket.io-client"
      - "livekit-client"

  backend:
    core:
      - "schema.prisma"
      - "mysql"
    realtime:
      - "socket.io"
      - "livekit-server-sdk"
    uploads:
      - "@uploadthing/react"
      - "@payloadcms/plugin-cloud-storage"

# Collections Structure
collections:
  core:
    - Users
    - Servers
    - Channels
    - Messages
    - Members
    - Conversations
    - DirectMessages

  media:
    - Attachments
    - ServerMedia
    - UserMedia

  settings:
    - ServerSettings
    - UserSettings
    - ChannelSettings

# Feature Requirements
features:
  messaging:
    - "Real-time messaging using Socket.io"
    - "Message attachments with UploadThing"
    - "Edit and delete messages in real-time"
    - "Infinite message loading (10 per batch)"
    - "Message reactions and emoji support"
    - "Typing indicators"
    - "Read receipts"

  channels:
    - "Text channels with rich text support"
    - "Voice channels with real-time audio"
    - "Video channels with WebRTC support"
    - "Channel permissions and roles"
    - "Channel categories and organization"

  servers:
    - "Server creation and customization"
    - "Invite system with unique links"
    - "Member management and roles"
    - "Server settings and permissions"
    - "Server discovery and search"

  direct_messaging:
    - "1:1 conversations between members"
    - "Real-time video calls"
    - "Audio calls with screen sharing"
    - "Group DM support"
    - "Message search and history"

# State Management
state:
  server:
    - "Server-side rendering with RSC"
    - "React Query for data fetching"
    - "Socket.io for real-time updates"

  client:
    - "Zustand for UI state"
    - "React Context for theme/auth"
    - "Local storage for preferences"

# UI Components
components:
  layout:
    - "Server sidebar"
    - "Channel list"
    - "Member list"
    - "Chat area"
    - "Modal system"
    rules:
      - "All UI components must support real-time updates"
      - "Components must preserve state during navigation"
      - "Components must handle reconnection gracefully"
      - "Never remove video/audio controls from channel headers"
      - "System clock and status indicators must always be visible"

  chat:
    - "Message component"
    - "Message input"
    - "Attachment preview"
    - "Emoji picker"
    - "Message actions"
    rules:
      - "Messages must update in real-time without page refresh"
      - "Message list must maintain scroll position on updates"
      - "System messages must be visually distinct"
      - "Message timestamps must sync with system clock"
      - "Message status indicators must update in real-time"

  media:
    - "Video call interface"
    - "Audio call controls"
    - "Screen sharing UI"
    - "Media player"
    rules:
      - "Video/audio controls must be present in channel headers"
      - "Media controls must persist during navigation"
      - "Screen sharing UI must be accessible from channel header"
      - "Video call interface must include participant grid"
      - "Audio indicators must show speaking status"

  channel_header:
    required_controls:
      - "Channel name and topic"
      - "Video call button"
      - "Audio call button"
      - "Screen share button"
      - "Channel settings"
      - "Member list toggle"
    rules:
      - "All media controls must be visible and accessible"
      - "Controls must maintain state during navigation"
      - "Never remove or hide video/audio functionality"
      - "Status indicators must update in real-time"

  status_indicators:
    required:
      - "System clock"
      - "Connection status"
      - "Message delivery status"
      - "Typing indicators"
      - "Presence indicators"
    rules:
      - "System clock must be visible and accurate"
      - "Status updates must be real-time"
      - "Indicators must persist during navigation"
      - "Connection status must be clearly visible"

# Error Handling
errors:
  websocket:
    - "Automatic reconnection"
    - "Fallback to polling"
    - "Connection status indicators"
    - "Offline message queue"

  api:
    - "Error boundaries"
    - "Loading states"
    - "Retry mechanisms"
    - "User feedback"

# Performance
performance:
  optimization:
    - "Code splitting"
    - "Image optimization"
    - "Lazy loading"
    - "Debounced actions"

  caching:
    - "React Query caching"
    - "Static generation"
    - "Service worker"

# Security
security:
  authentication:
    - "Clerk authentication"
    - "Role-based access"
    - "JWT validation"
    - "CSRF protection"

  data:
    - "Input sanitization"
    - "Rate limiting"
    - "Encryption"
    - "Audit logging"

# Development Workflow
workflow:
  setup:
    - "Environment configuration"
    - "Database setup"
    - "Development server"
    - "TypeScript configuration"

  commands:
    dev: "npm run dev"
    build: "npm run build"
    start: "npm run start"
    lint: "npm run lint"

# Environment Variables
environment:
  required:
    - "NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY"
    - "CLERK_SECRET_KEY"
    - "DATABASE_URI"
    - "PAYLOAD_SECRET"
    - "UPLOADTHING_SECRET"
    - "LIVEKIT_API_KEY"

  optional:
    - "NEXT_PUBLIC_SITE_URL"
    - "NEXT_PUBLIC_APP_URL"
    - "NEXT_PUBLIC_SOCKET_URL"

# Real-time Updates
realtime:
  message_updates:
    rules:
      - "Messages must appear instantly on send"
      - "UI must update without page refresh"
      - "Message list must maintain scroll position"
      - "System messages must integrate seamlessly"
      - "Status indicators must update in real-time"

  connection_handling:
    rules:
      - "Must handle disconnects gracefully"
      - "Must show reconnection attempts"
      - "Must preserve message queue during disconnects"
      - "Must sync messages after reconnection"
      - "Must maintain UI state during reconnection"

# LiveKit Integration Rules
livekit_integration:
  rules:
    - "NEVER remove LiveKit integration code"
    - "NEVER modify LiveKit room configuration"
    - "NEVER change LiveKit token generation"
    - "NEVER remove LiveKit environment variables"
    - "NEVER modify WebRTC connection handling"
    - "ALWAYS maintain LiveKit server configuration"
  required_files:
    - "app/api/livekit/route.ts - Token generation and room management"
    - "components/media-room.tsx - LiveKit room component"
    - "components/chat/chat-header.tsx - Media controls"
    - "components/chat/chat-channel-media.tsx - Channel media controls"
    - "components/chat/chat-video-button.tsx - Video controls"
  required_env_vars:
    - "LIVEKIT_API_KEY - Required for token generation"
    - "LIVEKIT_API_SECRET - Required for token generation"
    - "NEXT_PUBLIC_LIVEKIT_URL - Required for WebSocket connection"
  required_features:
    - "Token generation with proper room and participant info"
    - "WebRTC connection handling with fallback"
    - "Room state management and error recovery"
    - "Participant tracking and media controls"
    - "Screen sharing functionality"
    - "Audio level monitoring"
    - "Connection quality indicators"
  required_dependencies:
    - "@livekit/components-react"
    - "@livekit/components-styles"
    - "livekit-server-sdk"
    - "livekit-client"
  implementation:
    token_generation:
      - "Must use LiveKit's AccessToken"
      - "Must include room name and participant identity"
      - "Must set proper token TTL"
      - "Must include appropriate permissions"
    room_configuration:
      - "Must enable both video and audio"
      - "Must handle reconnection"
      - "Must manage participant state"
      - "Must handle media device changes"
    error_handling:
      - "Must handle token generation errors"
      - "Must handle connection failures"
      - "Must provide user feedback"
      - "Must attempt reconnection"
    security:
      - "Must validate room access"
      - "Must check user permissions"
      - "Must secure token generation"
      - "Must protect API endpoints"

# Socket Message Flow Rules
socket_message_flow:
  rules:
    - "NEVER modify established message flow paths"
    - "ALWAYS maintain message order and delivery guarantees"
    - "ALWAYS handle reconnection and message redelivery"
    - "NEVER modify socket event names once established"
    - "ALWAYS emit acknowledgments for received messages"
    - "NEVER drop messages without explicit error handling"

  message_types:
    text_message:
      flow:
        - "Client emits 'message' event with {content, channelId, memberId}"
        - "Server validates message and member permissions"
        - "Server stores message in database"
        - "Server broadcasts to channel room"
        - "Server emits acknowledgment to sender"
        - "All room clients receive and render message"
      required_events:
        - "message"
        - "message:ack" 
        - "message:error"

    file_message:
      flow:
        - "Client uploads file to UploadThing"
        - "Client emits 'message' with {fileUrl, channelId, memberId}"
        - "Server validates file type and permissions"
        - "Server stores message with file reference"
        - "Server broadcasts to channel room"
        - "Server emits upload confirmation"
        - "All room clients receive and render file preview"
      required_events:
        - "message"
        - "file:upload:start"
        - "file:upload:complete"
        - "file:upload:error"

    direct_message:
      flow:
        - "Client emits 'direct_message' with {content, conversationId, memberId}"
        - "Server validates conversation access"
        - "Server stores in direct messages table"
        - "Server broadcasts to conversation room"
        - "Server emits delivery confirmation"
        - "Recipients receive and render message"
      required_events:
        - "direct_message"
        - "direct_message:ack"
        - "direct_message:error"

    direct_file:
      flow:
        - "Client uploads file to UploadThing"
        - "Client emits 'direct_message' with {fileUrl, conversationId, memberId}"
        - "Server validates file and conversation access"
        - "Server stores message with file reference"
        - "Server broadcasts to conversation room"
        - "Server emits upload confirmation"
        - "Recipients receive and render file preview"
      required_events:
        - "direct_message"
        - "file:upload:start"
        - "file:upload:complete" 
        - "file:upload:error"

  socket_rooms:
    channel_room:
      - "Format: chat:{channelId}:messages"
      - "All channel members must join on connection"
      - "Leave room on channel leave/disconnect"
      - "Rejoin room on reconnection"
    
    conversation_room:
      - "Format: conversation:{conversationId}:messages"
      - "Only conversation participants can join"
      - "Leave room on conversation end/disconnect"
      - "Rejoin room on reconnection"

  error_handling:
    - "Must handle and log all socket errors"
    - "Must notify client of delivery failures"
    - "Must attempt message redelivery on reconnect"
    - "Must maintain message order on redelivery"
    - "Must handle duplicate messages"

  reconnection:
    - "Must restore all room subscriptions"
    - "Must resync missed messages"
    - "Must maintain message order"
    - "Must reestablish user presence"
    - "Must notify UI of reconnection status"

# Chat Routes Critical Components
chat_routes_critical_components:
  rules:
    - "NEVER remove or modify core chat components from main routes"
    - "ALWAYS maintain component hierarchy in chat routes"
    - "NEVER remove socket or real-time functionality"
    - "ALWAYS preserve message loading and pagination"
    - "NEVER remove media controls from headers"
    - "ALWAYS maintain error states and loading indicators"
    - "NEVER modify established component props structure"

  required_components:
    chat_header:
      file: "components/chat/chat-header.tsx"
      required_elements:
        - "Socket connection indicator"
        - "Video call button when not in call"
        - "Channel/conversation name display"
        - "Mobile toggle for responsive design"
        - "User avatar for conversations"
        - "Hash icon for channels"

    chat_messages:
      file: "components/chat/chat-messages.tsx"
      required_elements:
        - "Message loading states"
        - "Error handling states"
        - "Infinite scroll functionality"
        - "Real-time message updates"
        - "Message grouping and formatting"
        - "Scroll position management"
        - "Socket integration"
        - "Edit indicators"
        - "Timestamp display"

    chat_input:
      file: "components/chat/chat-input.tsx"
      required_elements:
        - "Message composition area"
        - "File upload functionality"
        - "Form validation"
        - "Socket emission"
        - "Loading states"

    chat_welcome:
      file: "components/chat/chat-welcome.tsx"
      required_elements:
        - "Channel/conversation welcome message"
        - "Type-specific icons"
        - "Name display"
        - "Descriptive text"

  route_structure:
    channel_route:
      file: "app/(main)/(routes)/servers/[serverId]/channels/[channelId]/page.tsx"
      required_components:
        - "ChatHeader"
        - "ChatMessages"
        - "ChatInput"
        - "MediaRoom (for video/audio channels)"
        - "MobileToggle"
      required_features:
        - "Real-time message updates"
        - "Video call integration"
        - "Member presence"
        - "Socket connection"
        - "Message persistence"

    conversation_route:
      file: "app/(main)/(routes)/servers/[serverId]/conversations/[memberId]/page.tsx"
      required_components:
        - "ChatHeader"
        - "ChatMessages"
        - "ChatInput"
        - "MediaRoom (for calls)"
      required_features:
        - "Direct message support"
        - "Real-time updates"
        - "Video call integration"
        - "User presence"
        - "Message persistence"

  providers:
    message_provider:
      file: "components/providers/message-provider.tsx"
      required_features:
        - "SSE connection management"
        - "Channel-specific streams"
        - "Connection state tracking"
        - "Error handling"
        - "Reconnection logic"

  state_management:
    required_stores:
      - "Message store for local state"
      - "Socket state management"
      - "Pagination tracking"
      - "Loading states"
      - "Error states"

  error_handling:
    required_states:
      - "Loading indicators"
      - "Connection error displays"
      - "Message send failures"
      - "Socket disconnection handling"
      - "Retry mechanisms"

  performance:
    required_optimizations:
      - "Message batching"
      - "Infinite scroll with virtualization"
      - "Socket connection pooling"
      - "Message caching"
      - "Lazy loading of media"
clerk
css
golang
javascript
jwt
less
mysql
next.js
+11 more

First seen in:

kendevco/discordant

Used in 1 repository

TypeScript
# Cursor Rules

## Framework
Next.js

## Language
TypeScript

## Principles

### Coding
- Write concise, technical TypeScript code with accurate examples.
- Use functional and declarative programming patterns; avoid classes.
- Prefer iteration and modularization over code duplication.
- Use descriptive variable names with auxiliary verbs (e.g., isLoading, hasError).

### File Structure
- Structure files in the following order: exported component, subcomponents, helpers, static content, types.
- Use lowercase with dashes for directories (e.g., components/auth-wizard).
- Favor named exports for components.

### TypeScript
- Use TypeScript for all code; prefer interfaces over types.
- Avoid enums; use maps instead.
- Use functional components with TypeScript interfaces.

### Syntax and Formatting
- Use the "function" keyword for pure functions.
- Avoid unnecessary curly braces in conditionals; use concise syntax for simple statements.
- Use declarative JSX.

### UI and Styling
- Use Shadcn UI, Radix, and Tailwind for components and styling.
- Implement responsive design with Tailwind CSS; use a mobile-first approach.

### Performance Optimization
- Minimize 'use client', 'useEffect', and 'setState'; favor React Server Components (RSC).
- Wrap client components in Suspense with fallback.
- Use dynamic loading for non-critical components.
- Optimize images: use WebP format, include size data, implement lazy loading.

### Key Conventions
- Use 'nuqs' for URL search parameter state management.
- Optimize Web Vitals (LCP, CLS, FID).
- Limit 'use client':
  - Favor server components and Next.js SSR.
  - Use only for Web API access in small components.
  - Avoid for data fetching or state management.

## Documentation
- Follow Next.js docs for Data Fetching, Rendering, and Routing.
css
javascript
next.js
radix-ui
react
shadcn/ui
tailwindcss
typescript

First seen in:

antoniowav/noted

Used in 1 repository