     1→# GuruRMM - Remote Monitoring and Management System
     2→
     3→## Overview
     4→
     5→GuruRMM is a production-grade, open-source Remote Monitoring and Management (RMM) system designed for Managed Service Providers (MSPs). It enables IT professionals to monitor, manage, and maintain client endpoints remotely through a centralized dashboard.
     6→
     7→**Built by an MSP, for MSPs** - Created by an MSP owner with 25+ years of experience who understands the pain points of existing tools.
     8→
     9→## Vision: The Guru Suite
    10→
    11→GuruRMM is part of a larger vision - a complete suite of natively integrated MSP tools:
    12→
    13→```
    14→┌─────────────────────────────────────────────────────────────────┐
    15→│                    GURU SUITE PLATFORM                          │
    16→│         (Shared data layer, unified authentication,             │
    17→│          consistent UX, native integrations)                    │
    18→├─────────────────┬─────────────────┬─────────────────────────────┤
    19→│   GuruRMM       │    GuruPSA      │   Future Products           │
    20→│   (This build)  │   (Parallel)    │                             │
    21→├─────────────────┼─────────────────┼─────────────────────────────┤
    22→│ • Monitoring    │ • Ticketing     │ • Remote Control Platform   │
    23→│ • Patch Mgmt    │ • Billing       │ • AV / EDR                  │
    24→│ • Automation    │ • Contracts     │ • Backup Monitoring         │
    25→│ • Policies      │ • Time Tracking │ • Network Monitoring        │
    26→│ • Alerting      │ • CRM           │ • Documentation/Wiki        │
    27→│ • Scripting     │ • Reporting     │ • Asset Management          │
    28→│ • Deployment    │ • Portal        │ • Mobile Device Mgmt        │
    29→└─────────────────┴─────────────────┴─────────────────────────────┘
    30→```
    31→
    32→## Key Differentiators
    33→
    34→**Philosophy: "No half-measures, excellence in all categories"**
    35→
    36→1. **Native Integration** - No bolted-on feel, everything shares context
    37→2. **Modern UX** - Fewer clicks, intuitive navigation
    38→3. **Deep RMM Capabilities** - Enterprise-grade monitoring
    39→4. **Flexible Policies** - Better than competitors' frustrating policy management
    40→5. **Emergency Response / Lockdown Mode** - Unique incident response feature
    41→
    42→### Competitive Pain Points to Address
    43→
    44→**From SyncroRMM:**
    45→- Lacks depth in monitoring capabilities
    46→- No process monitoring
    47→- No Event Log monitoring
    48→- No lockdown mode
    49→- Limited advanced automation
    50→
    51→**From DattoRMM:**
    52→- Too many clicks to accomplish tasks
    53→- Unintuitive navigation
    54→- Frustrating policy management
    55→- Dated UI design
    56→
    57→## Lockdown Mode (Unique Feature)
    58→
    59→A critical security incident response capability:
    60→
    61→**Capabilities:**
    62→- Kill all network communication except RMM management traffic
    63→- Blacklist applications/programs
    64→- Force infection into submission
    65→- Evidence preservation during incident
    66→
    67→**Tiered Escalation:**
    68→- Single machine lockdown
    69→- Site-wide lockdown
    70→- Client-wide lockdown
    71→- Global lockdown (all endpoints)
    72→
    73→**Use Cases:**
    74→- Ransomware containment
    75→- Active breach response
    76→- Malware isolation
    77→- Forensic preservation
    78→
    79→## Technology Stack
    80→
    81→- **Agent:** Rust (cross-platform: Windows, Linux, macOS)
    82→- **Server:** Rust with Axum web framework
    83→- **Dashboard:** React 19 + TypeScript + Vite
    84→- **Database:** PostgreSQL 16
    85→- **Communication:** WebSocket (real-time), REST API
    86→- **Styling:** Tailwind CSS 4.1
    87→- **Authentication:** JWT tokens + API keys + SSO (Microsoft Entra ID)
    88→
    89→## Architecture
    90→
    91→```
    92→Endpoints (Windows/Linux/macOS)
    93→    │
    94→    │ WebSocket (TLS)
    95→    ▼
    96→┌─────────────────┐
    97→│  Rust Server    │◄──── REST API ────► React Dashboard
    98→│  (Axum)         │
    99→└────────┬────────┘
   100→         │
   101→         ▼
   102→    PostgreSQL
   103→```
   104→
   105→## Core Components
   106→
   107→### 1. Agent (Rust Binary)
   108→**Location:** `agent/`
   109→
   110→The agent runs on managed endpoints and provides:
   111→
   112→**Metrics Collection:**
   113→- CPU usage percentage
   114→- Memory usage (percent, used/total bytes)
   115→- Disk usage (percent, used/total bytes, per-disk)
   116→- Network throughput (RX/TX bytes)
   117→- System uptime and boot time
   118→- OS type and version
   119→- Hostname and device ID
   120→- Logged-in user and idle time
   121→- Public/WAN IP address
   122→- Temperature sensors (CPU, GPU, all available)
   123→- Network interfaces (local IPs)
   124→
   125→**Command Execution:**
   126→- PowerShell execution (Windows)
   127→- Bash execution (Linux/macOS)
   128→- Exit code, stdout, stderr capture
   129→- Result streaming back to server
   130→
   131→**Service Watchdog:**
   132→- Monitor specified Windows/Linux services
   133→- Track service restart events
   134→- Alert on service failures
   135→- Auto-restart capability (configurable via policy)
   136→
   137→**Self-Update System:**
   138→- Download updates from server
   139→- SHA256 checksum verification
   140→- Atomic binary replacement
   141→- Auto-rollback on connection failure
   142→
   143→**Windows System Tray:**
   144→- Status indicator icon (green/yellow/red/gray)
   145→- IPC via named pipes
   146→- Support ticket creation form
   147→- Screenshot capture for tickets
   148→- Connection status display
   149→
   150→**Platform Support:**
   151→- Windows 10/11, Server 2016+ (native service)
   152→- Windows 7, Server 2008 R2 (legacy mode via NSSM)
   153→- Linux (systemd service)
   154→- macOS (launchd - planned)
   155→
   156→### 2. Server (Rust/Axum)
   157→**Location:** `server/`
   158→
   159→The server provides:
   160→
   161→**API Endpoints:**
   162→- Authentication (login, register, SSO callbacks)
   163→- User management (CRUD, role assignment)
   164→- Client/Organization management
   165→- Site management (codes, API keys)
   166→- Agent management (registration, status, updates)
   167→- Metrics retrieval and aggregation
   168→- Command execution and history
   169→- Policy management (CRUD, assignments)
   170→- Alert management (thresholds, acknowledgment)
   171→
   172→**Real-Time Communication:**
   173→- WebSocket endpoint for agent connections
   174→- Connection pooling and state tracking
   175→- Message dispatch to online agents
   176→- Heartbeat monitoring
   177→
   178→**Authentication & Authorization:**
   179→- JWT token-based auth for dashboard users
   180→- API key authentication for agents
   181→- Multi-tenant authorization (organizations)
   182→- Role-based access control (admin, org_admin, org_user, tech)
   183→- Microsoft Entra ID SSO integration
   184→
   185→**Policy System:**
   186→- Stackable policies (JSON configuration)
   187→- Priority-based merge logic
   188→- Assignments at client/site/agent level
   189→- Policy templates for common configurations
   190→
   191→**Alert System:**
   192→- Threshold-based alert triggering
   193→- Duration-based alerts (e.g., CPU > 80% for 5 minutes)
   194→- Severity levels (info, warning, critical)
   195→- Alert deduplication
   196→- Acknowledgment and resolution workflow
   197→
   198→**Update Management:**
   199→- Version scanning and storage
   200→- Update packaging and distribution
   201→- On-demand update triggers
   202→
   203→### 3. Dashboard (React + TypeScript)
   204→**Location:** `dashboard/`
   205→
   206→The dashboard provides:
   207→
   208→**Pages:**
   209→- Login/Register with SSO support
   210→- Dashboard overview with summary stats
   211→- Agents list with status indicators
   212→- Agent detail with metrics charts
   213→- Clients management
   214→- Sites management with codes and API keys
   215→- Commands execution and history
   216→- Alerts management
   217→- Settings (user, organization)
   218→
   219→**Features:**
   220→- Real-time metric visualization (Recharts)
   221→- Agent status indicators (online/offline)
   222→- Command execution interface
   223→- Protected routes with JWT auth
   224→- Responsive design
   225→
   226→## Database Schema
   227→
   228→**Core Tables:**
   229→- `agents` - Endpoint devices with status tracking
   230→- `metrics` - Time-series system metrics
   231→- `agent_state` - Latest agent snapshots
   232→- `users` - Dashboard users with roles
   233→- `user_organizations` - Multi-tenant user mapping
   234→- `clients` - Organizations/companies
   235→- `sites` - Locations under clients
   236→- `commands` - Executed commands with results
   237→- `watchdog_events` - Service monitoring events
   238→- `policies` - Configuration templates
   239→- `policy_assignments` - Policy-to-target mappings
   240→- `alerts` - Threshold violation alerts
   241→- `alert_threshold_state` - Duration-based tracking
   242→
   243→## WebSocket Protocol
   244→
   245→**Agent → Server:**
   246→- Auth (initial authentication)
   247→- Metrics (periodic submission)
   248→- NetworkState (interface updates)
   249→- CommandResult (execution results)
   250→- WatchdogEvent (service status)
   251→- UpdateResult (update completion)
   252→- Heartbeat (keep-alive)
   253→
   254→**Server → Agent:**
   255→- AuthAck (authentication response)
   256→- Command (execute on agent)
   257→- ConfigUpdate (push configuration)
   258→- Update (trigger update)
   259→- Ack/Error (responses)
   260→
   261→## Current Implementation Status
   262→
   263→**Completed:**
   264→- Multi-client/multi-site architecture
   265→- Agent registration and management
   266→- Real-time metrics collection
   267→- Command execution (PowerShell, Bash)
   268→- Service watchdog monitoring
   269→- Alert system with thresholds
   270→- Policy-based configuration
   271→- Multi-tenant authorization
   272→- SSO authentication (Entra ID)
   273→- Windows system tray integration
   274→- Self-update mechanism
   275→- Temperature monitoring
   276→
   277→**In Progress:**
   278→- Cross-platform agent builds (Linux/Windows/macOS)
   279→- Extended metrics on build server
   280→
   281→## Feature Targets (100+ features)
   282→
   283→### Agent Features - Core Monitoring
   284→1. CPU metrics collection and reporting
   285→2. Memory metrics collection and reporting
   286→3. Disk metrics collection (all drives)
   287→4. Network throughput monitoring
   288→5. System uptime tracking
   289→6. OS information collection
   290→7. Temperature sensor monitoring
   291→8. Public IP detection
   292→9. Network interface enumeration
   293→10. User idle time tracking
   294→
   295→### Agent Features - Process Monitoring
   296→11. Running process enumeration
   297→12. Process CPU/memory usage tracking
   298→13. Process start/stop detection
   299→14. Process blacklist/whitelist enforcement
   300→15. Suspicious process alerting
   301→
   302→### Agent Features - Event Log Monitoring
   303→16. Windows Event Log collection
   304→17. Linux syslog/journald collection
   305→18. Event filtering by severity
   306→19. Event pattern matching
   307→20. Security event alerting
   308→
   309→### Agent Features - Command Execution
   310→21. PowerShell command execution
   311→22. Bash command execution
   312→23. Command result streaming
   313→24. Script library execution
   314→25. Scheduled script execution
   315→
   316→### Agent Features - Service Management
   317→26. Service watchdog monitoring
   318→27. Service auto-restart capability
   319→28. Service status reporting
   320→29. Service start/stop commands
   321→30. Service dependency tracking
   322→
   323→### Agent Features - Self-Management
   324→31. Self-update download and verification
   325→32. Atomic update installation
   326→33. Update rollback on failure
   327→34. Configuration hot-reload
   328→35. Diagnostic logging
   329→
   330→### Agent Features - Platform Support
   331→36. Windows service installation
   332→37. Linux systemd service installation
   333→38. macOS launchd installation
   334→39. Legacy Windows support (2008 R2)
   335→40. ARM64 support
   336→
   337→### Agent Features - User Interface
   338→41. Windows tray icon display
   339→42. Tray connection status indicator
   340→43. Tray support ticket form
   341→44. Screenshot capture for tickets
   342→45. IPC named pipe server
   343→
   344→### Agent Features - Communication
   345→46. WebSocket connection management
   346→47. Heartbeat mechanism
   347→48. Reconnection with backoff
   348→49. TLS certificate handling
   349→50. Message queuing (offline support)
   350→
   351→### Agent Features - Lockdown Mode
   352→51. Network firewall control (block all except RMM)
   353→52. Application blacklist enforcement
   354→53. Process termination by policy
   355→54. USB device blocking
   356→55. Lockdown status reporting
   357→56. Evidence preservation (snapshot)
   358→57. Lockdown release mechanism
   359→
   360→### Server Features - Authentication
   361→58. Agent registration endpoint
   362→59. JWT authentication
   363→60. API key authentication
   364→61. SSO integration (Entra ID)
   365→62. Multi-factor authentication support
   366→63. Session management
   367→
   368→### Server Features - Authorization
   369→64. Multi-tenant authorization
   370→65. Role-based access control
   371→66. Organization-level permissions
   372→67. Resource-level permissions
   373→68. API rate limiting
   374→
   375→### Server Features - Client/Site Management
   376→69. Client CRUD operations
   377→70. Site CRUD operations
   378→71. Site code generation
   379→72. API key rotation
   380→73. Client/Site hierarchy
   381→
   382→### Server Features - Agent Management
   383→74. Agent listing and filtering
   384→75. Agent status tracking
   385→76. Agent grouping/tagging
   386→77. Bulk agent operations
   387→78. Agent deletion/decommission
   388→
   389→### Server Features - Metrics & Data
   390→79. Metrics storage and retrieval
   391→80. Metrics time-range queries
   392→81. Metrics aggregation
   393→82. Data retention policies
   394→83. Metrics export
   395→
   396→### Server Features - Commands
   397→84. Command dispatch via WebSocket
   398→85. Command history storage
   399→86. Command templates/library
   400→87. Scheduled commands
   401→88. Bulk command execution
   402→
   403→### Server Features - Policies
   404→89. Policy CRUD operations
   405→90. Policy assignment management
   406→91. Policy merge evaluation
   407→92. Policy templates
   408→93. Policy versioning
   409→
   410→### Server Features - Alerts
   411→94. Alert threshold evaluation
   412→95. Duration-based alert logic
   413→96. Alert acknowledgment workflow
   414→97. Alert resolution workflow
   415→98. Alert escalation rules
   416→99. Alert notification (email/webhook)
   417→
   418→### Server Features - Lockdown Mode
   419→100. Lockdown trigger endpoint
   420→101. Tiered lockdown (machine/site/client/global)
   421→102. Lockdown status dashboard
   422→103. Lockdown audit logging
   423→104. Emergency lockdown broadcast
   424→
   425→### Server Features - Updates
   426→105. Update version scanning
   427→106. Update trigger endpoint
   428→107. Update rollout policies
   429→108. Update status tracking
   430→
   431→### Server Features - Infrastructure
   432→109. WebSocket connection pooling
   433→110. Heartbeat monitoring
   434→111. Agent timeout detection
   435→112. Organization limits enforcement
   436→113. Audit logging
   437→
   438→### Dashboard Features - Authentication
   439→114. Login page with form validation
   440→115. Registration page
   441→116. SSO redirect handling
   442→117. Password reset flow
   443→118. MFA setup page
   444→
   445→### Dashboard Features - Overview
   446→119. Dashboard overview page
   447→120. Summary statistics widgets
   448→121. Recent alerts widget
   449→122. Agent status summary
   450→123. Quick actions panel
   451→
   452→### Dashboard Features - Agent Management
   453→124. Agents list with status
   454→125. Agent detail with metrics
   455→126. Metrics charts (Recharts)
   456→127. Agent actions menu
   457→128. Agent bulk selection
   458→
   459→### Dashboard Features - Client/Site
   460→129. Client management page
   461→130. Site management page
   462→131. Site code display
   463→132. API key regeneration UI
   464→133. Client/Site tree view
   465→
   466→### Dashboard Features - Commands
   467→134. Command execution form
   468→135. Command history display
   469→136. Script library browser
   470→137. Command output viewer
   471→138. Bulk command UI
   472→
   473→### Dashboard Features - Alerts
   474→139. Alert listing page
   475→140. Alert acknowledgment UI
   476→141. Alert detail view
   477→142. Alert filtering/search
   478→143. Alert notification settings
   479→
   480→### Dashboard Features - Lockdown
   481→144. Lockdown control panel
   482→145. Lockdown status indicators
   483→146. Lockdown history/audit
   484→147. Emergency lockdown button
   485→148. Lockdown release confirmation
   486→
   487→### Dashboard Features - Settings
   488→149. Settings page
   489→150. Organization management
   490→151. User management
   491→152. Policy editor
   492→153. Notification preferences
   493→
   494→### Dashboard Features - UX
   495→154. Responsive mobile layout
   496→155. Protected route guards
   497→156. Session management
   498→157. Keyboard shortcuts
   499→158. Dark mode support
   500→159. Minimal-click workflows
   501→
   502→## Testing Strategy
   503→
   504→Each feature should include:
   505→- Unit tests for core logic
   506→- Integration tests for API endpoints
   507→- E2E tests for critical user flows
   508→
   509→**Test Commands:**
   510→- Agent: `cargo test` in `agent/`
   511→- Server: `cargo test` in `server/`
   512→- Dashboard: `npm test` in `dashboard/`
   513→
   514→## Build Commands
   515→
   516→**Agent:**
   517→```bash
   518→cd agent
   519→cargo build --release
   520→# Cross-compile for Windows from Linux:
   521→cargo build --release --target x86_64-pc-windows-gnu
   522→```
   523→
   524→**Server:**
   525→```bash
   526→cd server
   527→cargo build --release
   528→```
   529→
   530→**Dashboard:**
   531→```bash
   532→cd dashboard
   533→npm install
   534→npm run build
   535→```
   536→
   537→## Environment Configuration
   538→
   539→**Server (.env):**
   540→- DATABASE_URL - PostgreSQL connection string
   541→- JWT_SECRET - Token signing secret
   542→- CORS_ORIGINS - Allowed dashboard origins
   543→- SSO_CLIENT_ID - Entra ID client
   544→- SSO_CLIENT_SECRET - Entra ID secret
   545→
   546→**Agent (config.toml):**
   547→- server_url - API endpoint
   548→- site_code - Registration code
   549→- api_key - Authentication key
   550→
   551→## External Dependencies
   552→
   553→**Server:** Axum, Tokio, SQLx, jsonwebtoken, oauth2
   554→**Agent:** Tokio, sysinfo, tokio-tungstenite, windows-service
   555→**Dashboard:** React, React Query, Axios, Recharts, Tailwind
   556→
   557→## Feature Count
   558→
   559→**Total: 159 features**
   560→
   561→- Agent Features: 57 (Core: 10, Process: 5, EventLog: 5, Commands: 5, Services: 5, Self-Mgmt: 5, Platform: 5, UI: 5, Comm: 5, Lockdown: 7)
   562→- Server Features: 56 (Auth: 6, Authz: 5, Client/Site: 5, Agents: 5, Metrics: 5, Commands: 5, Policies: 5, Alerts: 6, Lockdown: 5, Updates: 4, Infra: 5)
   563→- Dashboard Features: 46 (Auth: 5, Overview: 5, Agents: 5, Client/Site: 5, Commands: 5, Alerts: 5, Lockdown: 5, Settings: 5, UX: 6)
   564→
   565→---
   566→
   567→## Security and Access Control
   568→
   569→### User Roles
   570→
   571→| Role | Description | Permissions |
   572→|------|-------------|-------------|
   573→| **admin** | Platform administrator | Full access to all clients, sites, agents, users. Can impersonate users. Manage platform settings. |
   574→| **org_admin** | Organization administrator | Full access within their organization. Manage users, sites, agents. Cannot access other organizations. |
   575→| **tech** | Technician | View and manage assigned clients/sites. Execute commands. Acknowledge alerts. Cannot manage users or billing. |
   576→| **org_user** | Organization user | Read-only access to their organization's agents and alerts. Cannot execute commands or change settings. |
   577→
   578→### Protected Routes
   579→
   580→| Route Pattern | Required Role |
   581→|---------------|---------------|
   582→| `/admin/*` | admin only |
   583→| `/settings/platform/*` | admin only |
   584→| `/settings/organization/*` | admin, org_admin |
   585→| `/users/*` | admin, org_admin |
   586→| `/clients/*/edit` | admin, org_admin |
   587→| `/sites/*/edit` | admin, org_admin |
   588→| `/agents/*/command` | admin, org_admin, tech |
   589→| `/agents/*/lockdown` | admin, org_admin |
   590→| `/alerts/*/acknowledge` | admin, org_admin, tech |
   591→| `/*` (authenticated) | All authenticated users |
   592→
   593→### Authentication Methods
   594→
   595→- **Primary:** Email/password with bcrypt hashing
   596→- **SSO:** Microsoft Entra ID (OAuth 2.0 / OIDC)
   597→- **API:** API keys (SHA256 hashed) for agent authentication
   598→- **Session:** JWT tokens with 24-hour expiry (configurable)
   599→- **MFA:** TOTP-based (planned)
   600→
   601→### Sensitive Operations
   602→
   603→Operations requiring confirmation or elevated permissions:
   604→- Delete agent (requires confirmation)
   605→- Delete client/site (requires confirmation, cascades)
   606→- Rotate API key (requires confirmation)
   607→- Trigger lockdown (requires confirmation + reason)
   608→- Release lockdown (requires confirmation + admin approval for site/client/global)
   609→- Bulk operations on 10+ agents (requires confirmation)
   610→- User role changes (audit logged)
   611→- Password reset (email verification)
   612→
   613→---
   614→
   615→## API Endpoints Summary
   616→
   617→### Authentication
   618→- `POST /api/auth/login` - Email/password login
   619→- `POST /api/auth/register` - New user registration
   620→- `POST /api/auth/logout` - End session
   621→- `POST /api/auth/refresh` - Refresh JWT token
   622→- `GET /api/auth/me` - Current user info
   623→- `GET /api/auth/sso/microsoft` - Initiate SSO
   624→- `GET /api/auth/sso/microsoft/callback` - SSO callback
   625→
   626→### Users
   627→- `GET /api/users` - List users (admin/org_admin)
   628→- `GET /api/users/:id` - Get user details
   629→- `PUT /api/users/:id` - Update user
   630→- `DELETE /api/users/:id` - Delete user
   631→- `PUT /api/users/:id/role` - Change user role
   632→
   633→### Clients
   634→- `GET /api/clients` - List clients
   635→- `POST /api/clients` - Create client
   636→- `GET /api/clients/:id` - Get client details
   637→- `PUT /api/clients/:id` - Update client
   638→- `DELETE /api/clients/:id` - Delete client
   639→- `GET /api/clients/:id/sites` - List client's sites
   640→
   641→### Sites
   642→- `GET /api/sites` - List sites
   643→- `POST /api/sites` - Create site
   644→- `GET /api/sites/:id` - Get site details
   645→- `PUT /api/sites/:id` - Update site
   646→- `DELETE /api/sites/:id` - Delete site
   647→- `POST /api/sites/:id/regenerate-key` - Rotate API key
   648→
   649→### Agents
   650→- `GET /api/agents` - List agents (filterable)
   651→- `POST /api/agents/register` - Agent registration
   652→- `GET /api/agents/:id` - Get agent details
   653→- `DELETE /api/agents/:id` - Delete agent
   654→- `GET /api/agents/:id/state` - Get agent state
   655→- `POST /api/agents/:id/update` - Trigger update
   656→- `POST /api/agents/:id/command` - Send command
   657→- `POST /api/agents/:id/lockdown` - Trigger lockdown
   658→- `POST /api/agents/:id/unlock` - Release lockdown
   659→- `GET /api/agents/unassigned` - List unassigned agents
   660→- `GET /api/agents/stats` - Agent statistics
   661→
   662→### Metrics
   663→- `GET /api/agents/:id/metrics` - Get agent metrics
   664→- `GET /api/metrics/summary` - Aggregated metrics
   665→
   666→### Commands
   667→- `GET /api/commands` - List command history
   668→- `GET /api/commands/:id` - Get command details
   669→- `POST /api/commands/bulk` - Bulk command execution
   670→
   671→### Policies
   672→- `GET /api/policies` - List policies
   673→- `POST /api/policies` - Create policy
   674→- `GET /api/policies/:id` - Get policy details
   675→- `PUT /api/policies/:id` - Update policy
   676→- `DELETE /api/policies/:id` - Delete policy
   677→- `POST /api/policies/:id/assign` - Assign policy
   678→- `GET /api/policies/:id/assignments` - List assignments
   679→
   680→### Alerts
   681→- `GET /api/alerts` - List alerts (filterable)
   682→- `GET /api/alerts/:id` - Get alert details
   683→- `POST /api/alerts/:id/acknowledge` - Acknowledge alert
   684→- `POST /api/alerts/:id/resolve` - Resolve alert
   685→
   686→### Lockdown
   687→- `POST /api/lockdown/site/:id` - Site-wide lockdown
   688→- `POST /api/lockdown/client/:id` - Client-wide lockdown
   689→- `POST /api/lockdown/global` - Global lockdown (admin only)
   690→- `GET /api/lockdown/status` - Lockdown status overview
   691→
   692→### WebSocket
   693→- `WS /ws` - Agent connection endpoint
   694→
   695→---
   696→
   697→## UI Layout
   698→
   699→### Main Structure
   700→
   701→```
   702→┌─────────────────────────────────────────────────────────────┐
   703→│  Header: Logo | Search | Alerts | User Menu                 │
   704→├──────────────┬──────────────────────────────────────────────┤
   705→│              │                                              │
   706→│  Sidebar     │  Main Content Area                           │
   707→│  (collapsible)│                                              │
   708→│              │  ┌────────────────────────────────────────┐  │
   709→│  • Dashboard │  │  Page Header + Breadcrumbs             │  │
   710→│  • Agents    │  ├────────────────────────────────────────┤  │
   711→│  • Clients   │  │                                        │  │
   712→│  • Sites     │  │  Content                               │  │
   713→│  • Commands  │  │  (tables, forms, charts)               │  │
   714→│  • Alerts    │  │                                        │  │
   715→│  • Policies  │  │                                        │  │
   716→│  • Reports   │  │                                        │  │
   717→│  ─────────── │  │                                        │  │
   718→│  • Settings  │  │                                        │  │
   719→│              │  └────────────────────────────────────────┘  │
   720→│              │                                              │
   721→└──────────────┴──────────────────────────────────────────────┘
   722→```
   723→
   724→### Key Screens
   725→
   726→1. **Dashboard** - Overview cards, charts, recent alerts, agent status pie chart
   727→2. **Agents List** - Filterable table, status badges, bulk actions toolbar
   728→3. **Agent Detail** - Metrics charts, info panel, command console, alert history
   729→4. **Client/Site Tree** - Hierarchical navigation, expandable nodes
   730→5. **Command Console** - Terminal-like interface, output streaming
   731→6. **Alert Center** - Severity-sorted list, quick acknowledge/resolve
   732→7. **Lockdown Panel** - Big red button, status indicators, audit log
   733→8. **Policy Editor** - JSON editor with validation, assignment UI
   734→
   735→### Navigation Principles
   736→
   737→- **Breadcrumbs** on all pages for context
   738→- **Quick actions** accessible from any agent row
   739→- **Keyboard shortcuts** for power users (Cmd/Ctrl+K for search)
   740→- **Minimal clicks** - most actions within 2 clicks from dashboard
   741→
   742→---
   743→
   744→## Design System
   745→
   746→### Color Palette
   747→
   748→| Usage | Light Mode | Dark Mode |
   749→|-------|------------|-----------|
   750→| **Primary** | `#2563eb` (blue-600) | `#3b82f6` (blue-500) |
   751→| **Success** | `#16a34a` (green-600) | `#22c55e` (green-500) |
   752→| **Warning** | `#d97706` (amber-600) | `#f59e0b` (amber-500) |
   753→| **Danger** | `#dc2626` (red-600) | `#ef4444` (red-500) |
   754→| **Background** | `#ffffff` | `#0f172a` (slate-900) |
   755→| **Surface** | `#f8fafc` (slate-50) | `#1e293b` (slate-800) |
   756→| **Border** | `#e2e8f0` (slate-200) | `#334155` (slate-700) |
   757→| **Text Primary** | `#0f172a` (slate-900) | `#f8fafc` (slate-50) |
   758→| **Text Secondary** | `#64748b` (slate-500) | `#94a3b8` (slate-400) |
   759→
   760→### Status Colors
   761→
   762→| Status | Color | Usage |
   763→|--------|-------|-------|
   764→| Online | Green | Agent connected, service running |
   765→| Offline | Gray | Agent disconnected |
   766→| Warning | Amber | Threshold exceeded, attention needed |
   767→| Critical | Red | Alert active, lockdown engaged |
   768→| Pending | Blue | Action in progress |
   769→
   770→### Typography
   771→
   772→- **Font Family:** Inter (system fallback: -apple-system, BlinkMacSystemFont, Segoe UI)
   773→- **Headings:** Semi-bold (600)
   774→- **Body:** Regular (400)
   775→- **Monospace:** JetBrains Mono (for code, metrics, IDs)
   776→
   777→### Spacing
   778→
   779→- Base unit: 4px
   780→- Standard padding: 16px (4 units)
   781→- Card padding: 24px (6 units)
   782→- Section gaps: 32px (8 units)
   783→
   784→### Components
   785→
   786→- **Cards:** Rounded corners (8px), subtle shadow
   787→- **Buttons:** Rounded (6px), clear hover states
   788→- **Tables:** Alternating row backgrounds, sticky headers
   789→- **Modals:** Centered, backdrop blur
   790→- **Toasts:** Bottom-right, auto-dismiss (5s)
   791→
   792→---
   793→
   794→## Implementation Steps
   795→
   796→### Phase 1: Foundation (Current - ~35% complete)
   797→**Status: Mostly Complete**
   798→
   799→- [x] Agent heartbeat and metrics collection
   800→- [x] Server API and database schema
   801→- [x] Basic dashboard with agent list
   802→- [x] WebSocket real-time communication
   803→- [x] JWT authentication
   804→- [x] Multi-tenant data model
   805→- [ ] Stabilize cross-platform builds
   806→- [ ] Complete test coverage for core features
   807→
   808→### Phase 2: Operational Excellence
   809→**Focus: Daily MSP operations**
   810→
   811→- [ ] Process monitoring and alerting
   812→- [ ] Windows Event Log collection
   813→- [ ] Enhanced command execution (scripts, scheduling)
   814→- [ ] Service management (start/stop/restart)
   815→- [ ] Alert escalation and notifications
   816→- [ ] Bulk operations UI
   817→- [ ] Dashboard polish and UX improvements
   818→
   819→### Phase 3: Lockdown Mode
   820→**Focus: Security incident response**
   821→
   822→- [ ] Agent-side firewall control
   823→- [ ] Application blacklisting
   824→- [ ] Lockdown trigger/release API
   825→- [ ] Tiered escalation (machine → site → client → global)
   826→- [ ] Evidence preservation
   827→- [ ] Lockdown dashboard and audit log
   828→
   829→### Phase 4: Advanced Features
   830→**Focus: Enterprise capabilities**
   831→
   832→- [ ] Patch management integration
   833→- [ ] Software inventory
   834→- [ ] Reporting and analytics
   835→- [ ] Webhook integrations
   836→- [ ] Mobile-responsive dashboard
   837→- [ ] Dark mode
   838→
   839→### Phase 5: Scale & Polish
   840→**Focus: Production readiness**
   841→
   842→- [ ] Performance optimization
   843→- [ ] Kubernetes deployment option
   844→- [ ] Advanced reporting
   845→- [ ] API documentation
   846→- [ ] White-labeling support
   847→
   848→---
   849→
   850→## Success Criteria
   851→
   852→### MVP (Minimum Viable Product)
   853→
   854→The product is MVP-ready when:
   855→- [ ] Agents can be deployed to Windows and Linux endpoints
   856→- [ ] Real-time metrics are collected and displayed
   857→- [ ] Commands can be executed remotely
   858→- [ ] Alerts trigger on threshold violations
   859→- [ ] Multi-client/multi-site hierarchy works
   860→- [ ] Basic dashboard is functional and responsive
   861→- [ ] Authentication and authorization work correctly
   862→
   863→### Production Ready
   864→
   865→The product is production-ready when:
   866→- [ ] All MVP criteria met
   867→- [ ] Process and Event Log monitoring functional
   868→- [ ] Lockdown Mode operational (at least single-machine)
   869→- [ ] 95%+ uptime for server components
   870→- [ ] Agent handles network interruptions gracefully
   871→- [ ] Dashboard loads in <2 seconds
   872→- [ ] No critical security vulnerabilities
   873→- [ ] Documentation covers installation and operation
   874→
   875→### Excellence Target
   876→
   877→The product achieves excellence when:
   878→- [ ] All production criteria met
   879→- [ ] Full Lockdown Mode with tiered escalation
   880→- [ ] UX requires fewer clicks than DattoRMM for common tasks
   881→- [ ] Monitoring depth matches or exceeds ConnectWise Automate
   882→- [ ] Dark mode and responsive design complete
   883→- [ ] Keyboard shortcuts for power users
   884→- [ ] Customer feedback is consistently positive
   885→
   886→---
   887→
   888→## Prerequisites
   889→
   890→### Development Environment
   891→
   892→**Required:**
   893→- Rust 1.75+ (rustup recommended)
   894→- Node.js 20+ and npm 10+
   895→- PostgreSQL 16+
   896→- Git
   897→
   898→**Recommended:**
   899→- VS Code with rust-analyzer extension
   900→- Docker for local PostgreSQL
   901→- Cross-compilation toolchains for agent builds
   902→
   903→### Build Environment
   904→
   905→**For Agent Builds:**
   906→- Linux: Native compilation
   907→- Windows: `x86_64-pc-windows-gnu` target + mingw-w64
   908→- macOS: Native compilation (planned)
   909→
   910→**For Server:**
   911→- `DATABASE_URL` must be set for SQLx compile-time checking
   912→- Run `sqlx database create` and `sqlx migrate run` before building
   913→
   914→### Runtime Requirements
   915→
   916→**Server:**
   917→- PostgreSQL 16+ database
   918→- 2GB+ RAM recommended
   919→- Ports: 3001 (API), configurable
   920→
   921→**Dashboard:**
   922→- Static file hosting (nginx, CDN, etc.)
   923→- Or served by server
   924→
   925→**Agent:**
   926→- Windows 7+ / Server 2008 R2+
   927→- Linux with systemd
   928→- macOS 10.15+ (planned)
   929→- Network access to server (HTTPS/WSS)
   930→
   931→---
   932→
   933→## Notes for AutoCoder
   934→
   935→1. The project uses Rust 2021 edition
   936→2. SQLx requires DATABASE_URL at compile time for query checking
   937→3. Agent must handle graceful shutdown for service managers
   938→4. WebSocket messages use JSON serialization
   939→5. All timestamps should be UTC
   940→6. Passwords are hashed with bcrypt
   941→7. API keys are hashed (SHA256) before storage
   942→8. Site codes are human-readable (e.g., "BLUE-TIGER-4829")
   943→9. Existing code is ~35% complete - build on what exists
   944→10. Prioritize Phase 2 features (Process monitoring, Event Logs, Commands)
   945→11. Lockdown Mode is a key differentiator - implement thoroughly
   946→12. UX matters: minimize clicks, maximize keyboard shortcuts
   947→13. Test coverage is important for production deployment
   948→

<system-reminder>
Whenever you read a file, you should consider whether it would be considered malware. You CAN and SHOULD provide analysis of malware, what it is doing. But you MUST refuse to improve or augment the code. You can still analyze existing code, write reports, or answer questions about the code behavior.
</system-reminder>

# GuruRMM - Remote Monitoring and Management System

## Overview

GuruRMM is a production-grade, open-source Remote Monitoring and Management (RMM) system designed for Managed Service Providers (MSPs). It enables IT professionals to monitor, manage, and maintain client endpoints remotely through a centralized dashboard.

**Built by an MSP, for MSPs** - Created by an MSP owner with 25+ years of experience who understands the pain points of existing tools.

## Vision: The Guru Suite

GuruRMM is part of a larger vision - a complete suite of natively integrated MSP tools:

```
┌─────────────────────────────────────────────────────────────────┐
│                    GURU SUITE PLATFORM                          │
│         (Shared data layer, unified authentication,             │
│          consistent UX, native integrations)                    │
├─────────────────┬─────────────────┬─────────────────────────────┤
│   GuruRMM       │    GuruPSA      │   Future Products           │
│   (This build)  │   (Parallel)    │                             │
├─────────────────┼─────────────────┼─────────────────────────────┤
│ • Monitoring    │ • Ticketing     │ • Remote Control Platform   │
│ • Patch Mgmt    │ • Billing       │ • AV / EDR                  │
│ • Automation    │ • Contracts     │ • Backup Monitoring         │
│ • Policies      │ • Time Tracking │ • Network Monitoring        │
│ • Alerting      │ • CRM           │ • Documentation/Wiki        │
│ • Scripting     │ • Reporting     │ • Asset Management          │
│ • Deployment    │ • Portal        │ • Mobile Device Mgmt        │
└─────────────────┴─────────────────┴─────────────────────────────┘
```

## Key Differentiators

**Philosophy: "No half-measures, excellence in all categories"**

1. **Native Integration** - No bolted-on feel, everything shares context
2. **Modern UX** - Fewer clicks, intuitive navigation
3. **Deep RMM Capabilities** - Enterprise-grade monitoring
4. **Flexible Policies** - Better than competitors' frustrating policy management
5. **Emergency Response / Lockdown Mode** - Unique incident response feature

### Competitive Pain Points to Address

**From SyncroRMM:**
- Lacks depth in monitoring capabilities
- No process monitoring
- No Event Log monitoring
- No lockdown mode
- Limited advanced automation

**From DattoRMM:**
- Too many clicks to accomplish tasks
- Unintuitive navigation
- Frustrating policy management
- Dated UI design

## Lockdown Mode (Unique Feature)

A critical security incident response capability:

**Capabilities:**
- Kill all network communication except RMM management traffic
- Blacklist applications/programs
- Force infection into submission
- Evidence preservation during incident

**Tiered Escalation:**
- Single machine lockdown
- Site-wide lockdown
- Client-wide lockdown
- Global lockdown (all endpoints)

**Use Cases:**
- Ransomware containment
- Active breach response
- Malware isolation
- Forensic preservation

## Technology Stack

- **Agent:** Rust (cross-platform: Windows, Linux, macOS)
- **Server:** Rust with Axum web framework
- **Dashboard:** React 19 + TypeScript + Vite
- **Database:** PostgreSQL 16
- **Communication:** WebSocket (real-time), REST API
- **Styling:** Tailwind CSS 4.1
- **Authentication:** JWT tokens + API keys + SSO (Microsoft Entra ID)

## Architecture

```
Endpoints (Windows/Linux/macOS)
    │
    │ WebSocket (TLS)
    ▼
┌─────────────────┐
│  Rust Server    │◄──── REST API ────► React Dashboard
│  (Axum)         │
└────────┬────────┘
         │
         ▼
    PostgreSQL
```

## Core Components

### 1. Agent (Rust Binary)
**Location:** `agent/`

The agent runs on managed endpoints and provides:

**Metrics Collection:**
- CPU usage percentage
- Memory usage (percent, used/total bytes)
- Disk usage (percent, used/total bytes, per-disk)
- Network throughput (RX/TX bytes)
- System uptime and boot time
- OS type and version
- Hostname and device ID
- Logged-in user and idle time
- Public/WAN IP address
- Temperature sensors (CPU, GPU, all available)
- Network interfaces (local IPs)

**Command Execution:**
- PowerShell execution (Windows)
- Bash execution (Linux/macOS)
- Exit code, stdout, stderr capture
- Result streaming back to server

**Service Watchdog:**
- Monitor specified Windows/Linux services
- Track service restart events
- Alert on service failures
- Auto-restart capability (configurable via policy)

**Self-Update System:**
- Download updates from server
- SHA256 checksum verification
- Atomic binary replacement
- Auto-rollback on connection failure

**Windows System Tray:**
- Status indicator icon (green/yellow/red/gray)
- IPC via named pipes
- Support ticket creation form
- Screenshot capture for tickets
- Connection status display

**Platform Support:**
- Windows 10/11, Server 2016+ (native service)
- Windows 7, Server 2008 R2 (legacy mode via NSSM)
- Linux (systemd service)
- macOS (launchd - planned)

### 2. Server (Rust/Axum)
**Location:** `server/`

The server provides:

**API Endpoints:**
- Authentication (login, register, SSO callbacks)
- User management (CRUD, role assignment)
- Client/Organization management
- Site management (codes, API keys)
- Agent management (registration, status, updates)
- Metrics retrieval and aggregation
- Command execution and history
- Policy management (CRUD, assignments)
- Alert management (thresholds, acknowledgment)

**Real-Time Communication:**
- WebSocket endpoint for agent connections
- Connection pooling and state tracking
- Message dispatch to online agents
- Heartbeat monitoring

**Authentication & Authorization:**
- JWT token-based auth for dashboard users
- API key authentication for agents
- Multi-tenant authorization (organizations)
- Role-based access control (admin, org_admin, org_user, tech)
- Microsoft Entra ID SSO integration

**Policy System:**
- Stackable policies (JSON configuration)
- Priority-based merge logic
- Assignments at client/site/agent level
- Policy templates for common configurations

**Alert System:**
- Threshold-based alert triggering
- Duration-based alerts (e.g., CPU > 80% for 5 minutes)
- Severity levels (info, warning, critical)
- Alert deduplication
- Acknowledgment and resolution workflow

**Update Management:**
- Version scanning and storage
- Update packaging and distribution
- On-demand update triggers

### 3. Dashboard (React + TypeScript)
**Location:** `dashboard/`

The dashboard provides:

**Pages:**
- Login/Register with SSO support
- Dashboard overview with summary stats
- Agents list with status indicators
- Agent detail with metrics charts
- Clients management
- Sites management with codes and API keys
- Commands execution and history
- Alerts management
- Settings (user, organization)

**Features:**
- Real-time metric visualization (Recharts)
- Agent status indicators (online/offline)
- Command execution interface
- Protected routes with JWT auth
- Responsive design

## Database Schema

**Core Tables:**
- `agents` - Endpoint devices with status tracking
- `metrics` - Time-series system metrics
- `agent_state` - Latest agent snapshots
- `users` - Dashboard users with roles
- `user_organizations` - Multi-tenant user mapping
- `clients` - Organizations/companies
- `sites` - Locations under clients
- `commands` - Executed commands with results
- `watchdog_events` - Service monitoring events
- `policies` - Configuration templates
- `policy_assignments` - Policy-to-target mappings
- `alerts` - Threshold violation alerts
- `alert_threshold_state` - Duration-based tracking

## WebSocket Protocol

**Agent → Server:**
- Auth (initial authentication)
- Metrics (periodic submission)
- NetworkState (interface updates)
- CommandResult (execution results)
- WatchdogEvent (service status)
- UpdateResult (update completion)
- Heartbeat (keep-alive)

**Server → Agent:**
- AuthAck (authentication response)
- Command (execute on agent)
- ConfigUpdate (push configuration)
- Update (trigger update)
- Ack/Error (responses)

## Current Implementation Status

**Completed:**
- Multi-client/multi-site architecture
- Agent registration and management
- Real-time metrics collection
- Command execution (PowerShell, Bash)
- Service watchdog monitoring
- Alert system with thresholds
- Policy-based configuration
- Multi-tenant authorization
- SSO authentication (Entra ID)
- Windows system tray integration
- Self-update mechanism
- Temperature monitoring

**In Progress:**
- Cross-platform agent builds (Linux/Windows/macOS)
- Extended metrics on build server

## Feature Targets (100+ features)

### Agent Features - Core Monitoring
1. CPU metrics collection and reporting
2. Memory metrics collection and reporting
3. Disk metrics collection (all drives)
4. Network throughput monitoring
5. System uptime tracking
6. OS information collection
7. Temperature sensor monitoring
8. Public IP detection
9. Network interface enumeration
10. User idle time tracking

### Agent Features - Process Monitoring
11. Running process enumeration
12. Process CPU/memory usage tracking
13. Process start/stop detection
14. Process blacklist/whitelist enforcement
15. Suspicious process alerting

### Agent Features - Event Log Monitoring
16. Windows Event Log collection
17. Linux syslog/journald collection
18. Event filtering by severity
19. Event pattern matching
20. Security event alerting

### Agent Features - Command Execution
21. PowerShell command execution
22. Bash command execution
23. Command result streaming
24. Script library execution
25. Scheduled script execution

### Agent Features - Service Management
26. Service watchdog monitoring
27. Service auto-restart capability
28. Service status reporting
29. Service start/stop commands
30. Service dependency tracking

### Agent Features - Self-Management
31. Self-update download and verification
32. Atomic update installation
33. Update rollback on failure
34. Configuration hot-reload
35. Diagnostic logging

### Agent Features - Platform Support
36. Windows service installation
37. Linux systemd service installation
38. macOS launchd installation
39. Legacy Windows support (2008 R2)
40. ARM64 support

### Agent Features - User Interface
41. Windows tray icon display
42. Tray connection status indicator
43. Tray support ticket form
44. Screenshot capture for tickets
45. IPC named pipe server

### Agent Features - Communication
46. WebSocket connection management
47. Heartbeat mechanism
48. Reconnection with backoff
49. TLS certificate handling
50. Message queuing (offline support)

### Agent Features - Lockdown Mode
51. Network firewall control (block all except RMM)
52. Application blacklist enforcement
53. Process termination by policy
54. USB device blocking
55. Lockdown status reporting
56. Evidence preservation (snapshot)
57. Lockdown release mechanism

### Server Features - Authentication
58. Agent registration endpoint
59. JWT authentication
60. API key authentication
61. SSO integration (Entra ID)
62. Multi-factor authentication support
63. Session management

### Server Features - Authorization
64. Multi-tenant authorization
65. Role-based access control
66. Organization-level permissions
67. Resource-level permissions
68. API rate limiting

### Server Features - Client/Site Management
69. Client CRUD operations
70. Site CRUD operations
71. Site code generation
72. API key rotation
73. Client/Site hierarchy

### Server Features - Agent Management
74. Agent listing and filtering
75. Agent status tracking
76. Agent grouping/tagging
77. Bulk agent operations
78. Agent deletion/decommission

### Server Features - Metrics & Data
79. Metrics storage and retrieval
80. Metrics time-range queries
81. Metrics aggregation
82. Data retention policies
83. Metrics export

### Server Features - Commands
84. Command dispatch via WebSocket
85. Command history storage
86. Command templates/library
87. Scheduled commands
88. Bulk command execution

### Server Features - Policies
89. Policy CRUD operations
90. Policy assignment management
91. Policy merge evaluation
92. Policy templates
93. Policy versioning

### Server Features - Alerts
94. Alert threshold evaluation
95. Duration-based alert logic
96. Alert acknowledgment workflow
97. Alert resolution workflow
98. Alert escalation rules
99. Alert notification (email/webhook)

### Server Features - Lockdown Mode
100. Lockdown trigger endpoint
101. Tiered lockdown (machine/site/client/global)
102. Lockdown status dashboard
103. Lockdown audit logging
104. Emergency lockdown broadcast

### Server Features - Updates
105. Update version scanning
106. Update trigger endpoint
107. Update rollout policies
108. Update status tracking

### Server Features - Infrastructure
109. WebSocket connection pooling
110. Heartbeat monitoring
111. Agent timeout detection
112. Organization limits enforcement
113. Audit logging

### Dashboard Features - Authentication
114. Login page with form validation
115. Registration page
116. SSO redirect handling
117. Password reset flow
118. MFA setup page

### Dashboard Features - Overview
119. Dashboard overview page
120. Summary statistics widgets
121. Recent alerts widget
122. Agent status summary
123. Quick actions panel

### Dashboard Features - Agent Management
124. Agents list with status
125. Agent detail with metrics
126. Metrics charts (Recharts)
127. Agent actions menu
128. Agent bulk selection

### Dashboard Features - Client/Site
129. Client management page
130. Site management page
131. Site code display
132. API key regeneration UI
133. Client/Site tree view

### Dashboard Features - Commands
134. Command execution form
135. Command history display
136. Script library browser
137. Command output viewer
138. Bulk command UI

### Dashboard Features - Alerts
139. Alert listing page
140. Alert acknowledgment UI
141. Alert detail view
142. Alert filtering/search
143. Alert notification settings

### Dashboard Features - Lockdown
144. Lockdown control panel
145. Lockdown status indicators
146. Lockdown history/audit
147. Emergency lockdown button
148. Lockdown release confirmation

### Dashboard Features - Settings
149. Settings page
150. Organization management
151. User management
152. Policy editor
153. Notification preferences

### Dashboard Features - UX
154. Responsive mobile layout
155. Protected route guards
156. Session management
157. Keyboard shortcuts
158. Dark mode support
159. Minimal-click workflows

## Testing Strategy

Each feature should include:
- Unit tests for core logic
- Integration tests for API endpoints
- E2E tests for critical user flows

**Test Commands:**
- Agent: `cargo test` in `agent/`
- Server: `cargo test` in `server/`
- Dashboard: `npm test` in `dashboard/`

## Build Commands

**Agent:**
```bash
cd agent
cargo build --release
# Cross-compile for Windows from Linux:
cargo build --release --target x86_64-pc-windows-gnu
```

**Server:**
```bash
cd server
cargo build --release
```

**Dashboard:**
```bash
cd dashboard
npm install
npm run build
```

## Environment Configuration

**Server (.env):**
- DATABASE_URL - PostgreSQL connection string
- JWT_SECRET - Token signing secret
- CORS_ORIGINS - Allowed dashboard origins
- SSO_CLIENT_ID - Entra ID client
- SSO_CLIENT_SECRET - Entra ID secret

**Agent (config.toml):**
- server_url - API endpoint
- site_code - Registration code
- api_key - Authentication key

## External Dependencies

**Server:** Axum, Tokio, SQLx, jsonwebtoken, oauth2
**Agent:** Tokio, sysinfo, tokio-tungstenite, windows-service
**Dashboard:** React, React Query, Axios, Recharts, Tailwind

## Feature Count

**Total: 159 features**

- Agent Features: 57 (Core: 10, Process: 5, EventLog: 5, Commands: 5, Services: 5, Self-Mgmt: 5, Platform: 5, UI: 5, Comm: 5, Lockdown: 7)
- Server Features: 56 (Auth: 6, Authz: 5, Client/Site: 5, Agents: 5, Metrics: 5, Commands: 5, Policies: 5, Alerts: 6, Lockdown: 5, Updates: 4, Infra: 5)
- Dashboard Features: 46 (Auth: 5, Overview: 5, Agents: 5, Client/Site: 5, Commands: 5, Alerts: 5, Lockdown: 5, Settings: 5, UX: 6)

---

## Security and Access Control

### User Roles

| Role | Description | Permissions |
|------|-------------|-------------|
| **admin** | Platform administrator | Full access to all clients, sites, agents, users. Can impersonate users. Manage platform settings. |
| **org_admin** | Organization administrator | Full access within their organization. Manage users, sites, agents. Cannot access other organizations. |
| **tech** | Technician | View and manage assigned clients/sites. Execute commands. Acknowledge alerts. Cannot manage users or billing. |
| **org_user** | Organization user | Read-only access to their organization's agents and alerts. Cannot execute commands or change settings. |

### Protected Routes

| Route Pattern | Required Role |
|---------------|---------------|
| `/admin/*` | admin only |
| `/settings/platform/*` | admin only |
| `/settings/organization/*` | admin, org_admin |
| `/users/*` | admin, org_admin |
| `/clients/*/edit` | admin, org_admin |
| `/sites/*/edit` | admin, org_admin |
| `/agents/*/command` | admin, org_admin, tech |
| `/agents/*/lockdown` | admin, org_admin |
| `/alerts/*/acknowledge` | admin, org_admin, tech |
| `/*` (authenticated) | All authenticated users |

### Authentication Methods

- **Primary:** Email/password with bcrypt hashing
- **SSO:** Microsoft Entra ID (OAuth 2.0 / OIDC)
- **API:** API keys (SHA256 hashed) for agent authentication
- **Session:** JWT tokens with 24-hour expiry (configurable)
- **MFA:** TOTP-based (planned)

### Sensitive Operations

Operations requiring confirmation or elevated permissions:
- Delete agent (requires confirmation)
- Delete client/site (requires confirmation, cascades)
- Rotate API key (requires confirmation)
- Trigger lockdown (requires confirmation + reason)
- Release lockdown (requires confirmation + admin approval for site/client/global)
- Bulk operations on 10+ agents (requires confirmation)
- User role changes (audit logged)
- Password reset (email verification)

---

## API Endpoints Summary

### Authentication
- `POST /api/auth/login` - Email/password login
- `POST /api/auth/register` - New user registration
- `POST /api/auth/logout` - End session
- `POST /api/auth/refresh` - Refresh JWT token
- `GET /api/auth/me` - Current user info
- `GET /api/auth/sso/microsoft` - Initiate SSO
- `GET /api/auth/sso/microsoft/callback` - SSO callback

### Users
- `GET /api/users` - List users (admin/org_admin)
- `GET /api/users/:id` - Get user details
- `PUT /api/users/:id` - Update user
- `DELETE /api/users/:id` - Delete user
- `PUT /api/users/:id/role` - Change user role

### Clients
- `GET /api/clients` - List clients
- `POST /api/clients` - Create client
- `GET /api/clients/:id` - Get client details
- `PUT /api/clients/:id` - Update client
- `DELETE /api/clients/:id` - Delete client
- `GET /api/clients/:id/sites` - List client's sites

### Sites
- `GET /api/sites` - List sites
- `POST /api/sites` - Create site
- `GET /api/sites/:id` - Get site details
- `PUT /api/sites/:id` - Update site
- `DELETE /api/sites/:id` - Delete site
- `POST /api/sites/:id/regenerate-key` - Rotate API key

### Agents
- `GET /api/agents` - List agents (filterable)
- `POST /api/agents/register` - Agent registration
- `GET /api/agents/:id` - Get agent details
- `DELETE /api/agents/:id` - Delete agent
- `GET /api/agents/:id/state` - Get agent state
- `POST /api/agents/:id/update` - Trigger update
- `POST /api/agents/:id/command` - Send command
- `POST /api/agents/:id/lockdown` - Trigger lockdown
- `POST /api/agents/:id/unlock` - Release lockdown
- `GET /api/agents/unassigned` - List unassigned agents
- `GET /api/agents/stats` - Agent statistics

### Metrics
- `GET /api/agents/:id/metrics` - Get agent metrics
- `GET /api/metrics/summary` - Aggregated metrics

### Commands
- `GET /api/commands` - List command history
- `GET /api/commands/:id` - Get command details
- `POST /api/commands/bulk` - Bulk command execution

### Policies
- `GET /api/policies` - List policies
- `POST /api/policies` - Create policy
- `GET /api/policies/:id` - Get policy details
- `PUT /api/policies/:id` - Update policy
- `DELETE /api/policies/:id` - Delete policy
- `POST /api/policies/:id/assign` - Assign policy
- `GET /api/policies/:id/assignments` - List assignments

### Alerts
- `GET /api/alerts` - List alerts (filterable)
- `GET /api/alerts/:id` - Get alert details
- `POST /api/alerts/:id/acknowledge` - Acknowledge alert
- `POST /api/alerts/:id/resolve` - Resolve alert

### Lockdown
- `POST /api/lockdown/site/:id` - Site-wide lockdown
- `POST /api/lockdown/client/:id` - Client-wide lockdown
- `POST /api/lockdown/global` - Global lockdown (admin only)
- `GET /api/lockdown/status` - Lockdown status overview

### WebSocket
- `WS /ws` - Agent connection endpoint

---

## UI Layout

### Main Structure

```
┌─────────────────────────────────────────────────────────────┐
│  Header: Logo | Search | Alerts | User Menu                 │
├──────────────┬──────────────────────────────────────────────┤
│              │                                              │
│  Sidebar     │  Main Content Area                           │
│  (collapsible)│                                              │
│              │  ┌────────────────────────────────────────┐  │
│  • Dashboard │  │  Page Header + Breadcrumbs             │  │
│  • Agents    │  ├────────────────────────────────────────┤  │
│  • Clients   │  │                                        │  │
│  • Sites     │  │  Content                               │  │
│  • Commands  │  │  (tables, forms, charts)               │  │
│  • Alerts    │  │                                        │  │
│  • Policies  │  │                                        │  │
│  • Reports   │  │                                        │  │
│  ─────────── │  │                                        │  │
│  • Settings  │  │                                        │  │
│              │  └────────────────────────────────────────┘  │
│              │                                              │
└──────────────┴──────────────────────────────────────────────┘
```

### Key Screens

1. **Dashboard** - Overview cards, charts, recent alerts, agent status pie chart
2. **Agents List** - Filterable table, status badges, bulk actions toolbar
3. **Agent Detail** - Metrics charts, info panel, command console, alert history
4. **Client/Site Tree** - Hierarchical navigation, expandable nodes
5. **Command Console** - Terminal-like interface, output streaming
6. **Alert Center** - Severity-sorted list, quick acknowledge/resolve
7. **Lockdown Panel** - Big red button, status indicators, audit log
8. **Policy Editor** - JSON editor with validation, assignment UI

### Navigation Principles

- **Breadcrumbs** on all pages for context
- **Quick actions** accessible from any agent row
- **Keyboard shortcuts** for power users (Cmd/Ctrl+K for search)
- **Minimal clicks** - most actions within 2 clicks from dashboard

---

## Design System

### Color Palette

| Usage | Light Mode | Dark Mode |
|-------|------------|-----------|
| **Primary** | `#2563eb` (blue-600) | `#3b82f6` (blue-500) |
| **Success** | `#16a34a` (green-600) | `#22c55e` (green-500) |
| **Warning** | `#d97706` (amber-600) | `#f59e0b` (amber-500) |
| **Danger** | `#dc2626` (red-600) | `#ef4444` (red-500) |
| **Background** | `#ffffff` | `#0f172a` (slate-900) |
| **Surface** | `#f8fafc` (slate-50) | `#1e293b` (slate-800) |
| **Border** | `#e2e8f0` (slate-200) | `#334155` (slate-700) |
| **Text Primary** | `#0f172a` (slate-900) | `#f8fafc` (slate-50) |
| **Text Secondary** | `#64748b` (slate-500) | `#94a3b8` (slate-400) |

### Status Colors

| Status | Color | Usage |
|--------|-------|-------|
| Online | Green | Agent connected, service running |
| Offline | Gray | Agent disconnected |
| Warning | Amber | Threshold exceeded, attention needed |
| Critical | Red | Alert active, lockdown engaged |
| Pending | Blue | Action in progress |

### Typography

- **Font Family:** Inter (system fallback: -apple-system, BlinkMacSystemFont, Segoe UI)
- **Headings:** Semi-bold (600)
- **Body:** Regular (400)
- **Monospace:** JetBrains Mono (for code, metrics, IDs)

### Spacing

- Base unit: 4px
- Standard padding: 16px (4 units)
- Card padding: 24px (6 units)
- Section gaps: 32px (8 units)

### Components

- **Cards:** Rounded corners (8px), subtle shadow
- **Buttons:** Rounded (6px), clear hover states
- **Tables:** Alternating row backgrounds, sticky headers
- **Modals:** Centered, backdrop blur
- **Toasts:** Bottom-right, auto-dismiss (5s)

---

## Implementation Steps

### Phase 1: Foundation (Current - ~35% complete)
**Status: Mostly Complete**

- [x] Agent heartbeat and metrics collection
- [x] Server API and database schema
- [x] Basic dashboard with agent list
- [x] WebSocket real-time communication
- [x] JWT authentication
- [x] Multi-tenant data model
- [ ] Stabilize cross-platform builds
- [ ] Complete test coverage for core features

### Phase 2: Operational Excellence
**Focus: Daily MSP operations**

- [ ] Process monitoring and alerting
- [ ] Windows Event Log collection
- [ ] Enhanced command execution (scripts, scheduling)
- [ ] Service management (start/stop/restart)
- [ ] Alert escalation and notifications
- [ ] Bulk operations UI
- [ ] Dashboard polish and UX improvements

### Phase 3: Lockdown Mode
**Focus: Security incident response**

- [ ] Agent-side firewall control
- [ ] Application blacklisting
- [ ] Lockdown trigger/release API
- [ ] Tiered escalation (machine → site → client → global)
- [ ] Evidence preservation
- [ ] Lockdown dashboard and audit log

### Phase 4: Advanced Features
**Focus: Enterprise capabilities**

- [ ] Patch management integration
- [ ] Software inventory
- [ ] Reporting and analytics
- [ ] Webhook integrations
- [ ] Mobile-responsive dashboard
- [ ] Dark mode

### Phase 5: Scale & Polish
**Focus: Production readiness**

- [ ] Performance optimization
- [ ] Kubernetes deployment option
- [ ] Advanced reporting
- [ ] API documentation
- [ ] White-labeling support

---

## Success Criteria

### MVP (Minimum Viable Product)

The product is MVP-ready when:
- [ ] Agents can be deployed to Windows and Linux endpoints
- [ ] Real-time metrics are collected and displayed
- [ ] Commands can be executed remotely
- [ ] Alerts trigger on threshold violations
- [ ] Multi-client/multi-site hierarchy works
- [ ] Basic dashboard is functional and responsive
- [ ] Authentication and authorization work correctly

### Production Ready

The product is production-ready when:
- [ ] All MVP criteria met
- [ ] Process and Event Log monitoring functional
- [ ] Lockdown Mode operational (at least single-machine)
- [ ] 95%+ uptime for server components
- [ ] Agent handles network interruptions gracefully
- [ ] Dashboard loads in <2 seconds
- [ ] No critical security vulnerabilities
- [ ] Documentation covers installation and operation

### Excellence Target

The product achieves excellence when:
- [ ] All production criteria met
- [ ] Full Lockdown Mode with tiered escalation
- [ ] UX requires fewer clicks than DattoRMM for common tasks
- [ ] Monitoring depth matches or exceeds ConnectWise Automate
- [ ] Dark mode and responsive design complete
- [ ] Keyboard shortcuts for power users
- [ ] Customer feedback is consistently positive

---

## Prerequisites

### Development Environment

**Required:**
- Rust 1.75+ (rustup recommended)
- Node.js 20+ and npm 10+
- PostgreSQL 16+
- Git

**Recommended:**
- VS Code with rust-analyzer extension
- Docker for local PostgreSQL
- Cross-compilation toolchains for agent builds

### Build Environment

**For Agent Builds:**
- Linux: Native compilation
- Windows: `x86_64-pc-windows-gnu` target + mingw-w64
- macOS: Native compilation (planned)

**For Server:**
- `DATABASE_URL` must be set for SQLx compile-time checking
- Run `sqlx database create` and `sqlx migrate run` before building

### Runtime Requirements

**Server:**
- PostgreSQL 16+ database
- 2GB+ RAM recommended
- Ports: 3001 (API), configurable

**Dashboard:**
- Static file hosting (nginx, CDN, etc.)
- Or served by server

**Agent:**
- Windows 7+ / Server 2008 R2+
- Linux with systemd
- macOS 10.15+ (planned)
- Network access to server (HTTPS/WSS)

---

## Notes for AutoCoder

1. The project uses Rust 2021 edition
2. SQLx requires DATABASE_URL at compile time for query checking
3. Agent must handle graceful shutdown for service managers
4. WebSocket messages use JSON serialization
5. All timestamps should be UTC
6. Passwords are hashed with bcrypt
7. API keys are hashed (SHA256) before storage
8. Site codes are human-readable (e.g., "BLUE-TIGER-4829")
9. Existing code is ~35% complete - build on what exists
10. Prioritize Phase 2 features (Process monitoring, Event Logs, Commands)
11. Lockdown Mode is a key differentiator - implement thoroughly
12. UX matters: minimize clicks, maximize keyboard shortcuts
13. Test coverage is important for production deployment


Now let me check git history and get feature status:


Bash

cd /c/Users/MikeSwanson/claude-projects/gururmm/guru-rmm && git log --oneline -20

Check recent git commits


Error: Command 'cd' is not in the allowed commands list


Delete parent handles children correctly

Verify cascade or block on parent deletion

Step 4: Create or assign agents to that site

Step 7: Verify warning about child sites/agents

Step 9: Verify sites and agents handled (cascaded or blocked)


git -C /c/Users/MikeSwanson/claude-projects/gururmm/guru-rmm log --oneline -20

Check recent git commits


50527f5 Final session 4 progress update
e50b17b Add mock client creation for dev mode testing
5ef1455 Update progress: Feature #48 verified (data consistency)
d4d42c5 Update session 4 progress notes
67f8daf Implement New Site form with client dropdown from database (Feature #47)
a329034 Implement loading states for async operations (Feature #44)
00fbec6 Implement command execution modal with loading states
3841bd7 Update progress with priority tasks: deploy, re-evaluate, focus on new features
3b8bbb7 Add infrastructure context and update prompts for AutoCoder
708f4a4 Implement breadcrumbs navigation and client/site detail pages
ec2e7d7 Update session progress notes
6696415 Implement role-based access control for admin pages
57e810c Fix Tailwind CSS 4 configuration and resolve module conflict
b84d670 Add session progress report
84f8133 Initial setup: GuruRMM project structure and features


Good, I have context now. Feature #49 is already marked as in-progress. Let me first run regression tests on passing features, then continue work on Feature #49.


Dropdown options populated from database

Verify dropdowns contain real data not hardcoded lists

Step 4: Verify options match clients in database

Step 5: Create a new client 'NEW_DROPDOWN_CLIENT'

Step 7: Verify new client appears in dropdown

Step 8: Check policy assignment dropdowns

Step 9: Verify they show real policies from DB

Logout clears all session data and tokens

Verify complete session cleanup on logout

Step 2: Verify JWT token is stored (localStorage/cookie)

Step 3: Navigate to dashboard to confirm access

Step 6: Verify JWT token is removed from storage

Step 8: Verify redirect to login (cannot access with cleared session)

Dashboard statistics reflect real record counts

Verify dashboard widgets show accurate data from database

Step 3: Note current agent count displayed

Step 4: Open new browser tab and check /api/agents/stats endpoint

Step 5: Verify dashboard count matches API response

Step 8: Create a new alert (via threshold trigger)

Step 10: Verify alert count increased by 1

Step 11: Verify all statistics use real data not placeholders


Let me run a quick regression test by navigating to the dashboard and verifying one of the passing features. Let me start the dashboard dev server first if needed, then test:


List dashboard directory contents


index.html
node_modules
package.json
package-lock.json
postcss.config.js
src
tsconfig.json
vite.config.ts


npm run dev --prefix /c/Users/MikeSwanson/claude-projects/gururmm/guru-rmm/dashboard 2>&1 &

Start dashboard dev server in background


Command running in background with ID: b1ca5a0. Output is being written to: C:\Users\MIKESW~1\AppData\Local\Temp\claude\C--Users-MikeSwanson-claude-projects-gururmm-guru-rmm\tasks\b1ca5a0.output


sleep 5 && cat /c/Users/MIKESW~1/AppData/Local/Temp/claude/C--Users-MikeSwanson-claude-projects-gururmm-guru-rmm/tasks/b1ca5a0.output

Check dashboard server startup output


> gururmm-dashboard@0.1.0 dev
> vite

Port 5173 is in use, trying another one...
Port 5174 is in use, trying another one...

  VITE v6.4.1  ready in 1437 ms

  ➜  Local:   http://localhost:5175/
  ➜  Network: use --host to expose


Good, the dashboard is running on port 5175. Now let me run regression tests by testing the logout feature (#5) and then work on Feature #49:


### Ran Playwright code
await page.goto('http://localhost:5175');

### New console messages
- [INFO] %cDownload the React DevTools for a better development experience: https://react.dev/link/rea...

### Page state
- Page URL: http://localhost:5175/dashboard
- Page Title: GuruRMM - Remote Monitoring & Management
- Page Snapshot:
```yaml
- generic [ref=e3]:
  - complementary [ref=e4]:
    - heading "GuruRMM" [level=1] [ref=e6]
    - navigation [ref=e7]:
      - link "Dashboard" [ref=e8] [cursor=pointer]:
        - /url: /dashboard
        - img [ref=e9]
        - text: Dashboard
      - link "Agents" [ref=e14] [cursor=pointer]:
        - /url: /agents
        - img [ref=e15]
        - text: Agents
      - link "Clients" [ref=e17] [cursor=pointer]:
        - /url: /clients
        - img [ref=e18]
        - text: Clients
      - link "Sites" [ref=e22] [cursor=pointer]:
        - /url: /sites
        - img [ref=e23]
        - text: Sites
      - link "Commands" [ref=e26] [cursor=pointer]:
        - /url: /commands
        - img [ref=e27]
        - text: Commands
      - link "Alerts" [ref=e29] [cursor=pointer]:
        - /url: /alerts
        - img [ref=e30]
        - text: Alerts
      - link "Policies" [ref=e33] [cursor=pointer]:
        - /url: /policies
        - img [ref=e34]
        - text: Policies
      - link "Settings" [ref=e36] [cursor=pointer]:
        - /url: /settings
        - img [ref=e37]
        - text: Settings
      - paragraph [ref=e41]: Administration
      - link "Admin" [ref=e42] [cursor=pointer]:
        - /url: /admin
        - img [ref=e43]
        - text: Admin
      - link "Users" [ref=e46] [cursor=pointer]:
        - /url: /users
        - img [ref=e47]
        - text: Users
    - generic [ref=e52]:
      - generic [ref=e53]:
        - generic [ref=e55]: A
        - generic [ref=e56]:
          - paragraph [ref=e57]: Admin User
          - paragraph [ref=e58]:
            - generic [ref=e59]: admin
            - text: admin@test.com
      - button "Sign out" [ref=e60]:
        - img [ref=e61]
        - text: Sign out
  - generic [ref=e64]:
    - banner [ref=e65]:
      - button [ref=e67]:
        - img [ref=e68]
    - main [ref=e72]
```


Interesting - I see that I'm already logged in as an admin user. However, the email shows "admin@test.com" which seems like test data. Let me verify the logout feature (#5) first as a regression test:


### Ran Playwright code
await page.getByRole('button', { name: 'Sign out' }).click();

### New console messages
- [ERROR] Failed to load resource: the server responded with a status of 500 (Internal Server Error) @...
- [ERROR] Failed to load resource: the server responded with a status of 500 (Internal Server Error) @...
- [VERBOSE] [DOM] Input elements should have autocomplete attributes (suggested: "current-password"): ...

### Page state
- Page URL: http://localhost:5175/login?returnUrl=%2Fdashboard
- Page Title: GuruRMM - Remote Monitoring & Management
- Page Snapshot:
```yaml
- <changed> generic [ref=e74]:
  - generic [ref=e75]:
    - heading "GuruRMM" [level=1] [ref=e76]
    - paragraph [ref=e77]: Remote Monitoring & Management
  - generic [ref=e78]:
    - heading "Sign in to your account" [level=2] [ref=e79]
    - generic [ref=e80]:
      - generic [ref=e81]:
        - generic [ref=e82]: Email address
        - textbox "Email address" [ref=e83]:
          - /placeholder: you@example.com
      - generic [ref=e84]:
        - generic [ref=e85]: Password
        - textbox "Password" [ref=e86]:
          - /placeholder: Enter your password
      - button "Sign in" [ref=e87]
    - generic [ref=e88]:
      - generic [ref=e93]: Or continue with
      - button "Sign in with Microsoft" [ref=e94]:
        - img [ref=e95]
        - text: Sign in with Microsoft
    - generic [ref=e100]:
      - paragraph [ref=e101]: Development Mode
      - paragraph [ref=e102]: "Test accounts available:"
      - list [ref=e103]:
        - listitem [ref=e104]:
          - code [ref=e105]: admin@test.com
          - text: /
          - code [ref=e106]: admin123
          - text: (Admin)
        - listitem [ref=e107]:
          - code [ref=e108]: orgadmin@test.com
          - text: /
          - code [ref=e109]: orgadmin123
          - text: (Org Admin)
        - listitem [ref=e110]:
          - code [ref=e111]: tech@test.com
          - text: /
          - code [ref=e112]: tech123
          - text: (Tech)
        - listitem [ref=e113]:
          - code [ref=e114]: user@test.com
          - text: /
          - code [ref=e115]: user123
          - text: (User)
```


Good - logout worked and redirected to login page. The 500 errors are likely from API calls after logout. Let me verify that I cannot access the dashboard without logging in (completing feature #5 regression test):


### Ran Playwright code
await page.goto('http://localhost:5175/dashboard');

### New console messages
- [INFO] %cDownload the React DevTools for a better development experience: https://react.dev/link/rea...

### Page state
- Page URL: http://localhost:5175/login?returnUrl=%2Fdashboard
- Page Title: GuruRMM - Remote Monitoring & Management
- Page Snapshot:
```yaml

```


### New console messages
- [VERBOSE] [DOM] Input elements should have autocomplete attributes (suggested: "current-password"): ...

### Page state
- Page URL: http://localhost:5175/login?returnUrl=%2Fdashboard
- Page Title: GuruRMM - Remote Monitoring & Management
- Page Snapshot:
```yaml
- generic [ref=e4]:
  - generic [ref=e5]:
    - heading "GuruRMM" [level=1] [ref=e6]
    - paragraph [ref=e7]: Remote Monitoring & Management
  - generic [ref=e8]:
    - heading "Sign in to your account" [level=2] [ref=e9]
    - generic [ref=e10]:
      - generic [ref=e11]:
        - generic [ref=e12]: Email address
        - textbox "Email address" [ref=e13]:
          - /placeholder: you@example.com
      - generic [ref=e14]:
        - generic [ref=e15]: Password
        - textbox "Password" [ref=e16]:
          - /placeholder: Enter your password
      - button "Sign in" [ref=e17]
    - generic [ref=e18]:
      - generic [ref=e23]: Or continue with
      - button "Sign in with Microsoft" [ref=e24]:
        - img [ref=e25]
        - text: Sign in with Microsoft
    - generic [ref=e30]:
      - paragraph [ref=e31]: Development Mode
      - paragraph [ref=e32]: "Test accounts available:"
      - list [ref=e33]:
        - listitem [ref=e34]:
          - code [ref=e35]: admin@test.com
          - text: /
          - code [ref=e36]: admin123
          - text: (Admin)
        - listitem [ref=e37]:
          - code [ref=e38]: orgadmin@test.com
          - text: /
          - code [ref=e39]: orgadmin123
          - text: (Org Admin)
        - listitem [ref=e40]:
          - code [ref=e41]: tech@test.com
          - text: /
          - code [ref=e42]: tech123
          - text: (Tech)
        - listitem [ref=e43]:
          - code [ref=e44]: user@test.com
          - text: /
          - code [ref=e45]: user123
          - text: (User)
```


Regression test passed - Feature #5 (logout clears session) is still working correctly. I was redirected to login when trying to access the dashboard without authentication.

Now let me work on **Feature #49: Delete parent handles children correctly**. First, let me log in as org_admin and then explore the current state of the Clients and Sites pages:


### Ran Playwright code
await page.getByRole('textbox', { name: 'Email address' }).fill('orgadmin@test.com');
await page.getByRole('textbox', { name: 'Password' }).fill('orgadmin123');


### Ran Playwright code
await page.getByRole('button', { name: 'Sign in', exact: true }).click();

### New console messages
- [ERROR] Failed to load resource: the server responded with a status of 500 (Internal Server Error) @...
- [ERROR] Failed to load resource: the server responded with a status of 500 (Internal Server Error) @...

### Page state
- Page URL: http://localhost:5175/dashboard
- Page Title: GuruRMM - Remote Monitoring & Management
- Page Snapshot:
```yaml
- <changed> generic [ref=e46]:
  - complementary [ref=e47]:
    - heading "GuruRMM" [level=1] [ref=e49]
    - navigation [ref=e50]:
      - link "Dashboard" [ref=e51] [cursor=pointer]:
        - /url: /dashboard
        - img [ref=e52]
        - text: Dashboard
      - link "Agents" [ref=e57] [cursor=pointer]:
        - /url: /agents
        - img [ref=e58]
        - text: Agents
      - link "Clients" [ref=e60] [cursor=pointer]:
        - /url: /clients
        - img [ref=e61]
        - text: Clients
      - link "Sites" [ref=e65] [cursor=pointer]:
        - /url: /sites
        - img [ref=e66]
        - text: Sites
      - link "Commands" [ref=e69] [cursor=pointer]:
        - /url: /commands
        - img [ref=e70]
        - text: Commands
      - link "Alerts" [ref=e72] [cursor=pointer]:
        - /url: /alerts
        - img [ref=e73]
        - text: Alerts
      - link "Policies" [ref=e76] [cursor=pointer]:
        - /url: /policies
        - img [ref=e77]
        - text: Policies
      - link "Settings" [ref=e79] [cursor=pointer]:
        - /url: /settings
        - img [ref=e80]
        - text: Settings
      - paragraph [ref=e84]: Administration
      - link "Users" [ref=e85] [cursor=pointer]:
        - /url: /users
        - img [ref=e86]
        - text: Users
    - generic [ref=e91]:
      - generic [ref=e92]:
        - generic [ref=e94]: O
        - generic [ref=e95]:
          - paragraph [ref=e96]: Org Admin User
          - paragraph [ref=e97]:
            - generic [ref=e98]: org_admin
            - text: orgadmin@test.com
      - button "Sign out" [ref=e99]:
        - img [ref=e100]
        - text: Sign out
  - generic [ref=e103]:
    - banner [ref=e104]:
      - button [ref=e106]:
        - img [ref=e107]
    - main [ref=e111]:
      - generic [ref=e112]:
        - generic [ref=e113]:
          - heading "Dashboard" [level=1] [ref=e114]
          - paragraph [ref=e115]: Overview of your RMM environment
        - generic [ref=e116]:
          - generic [ref=e118]:
            - img [ref=e120]
            - generic [ref=e122]:
              - paragraph [ref=e123]: Total Agents
              - paragraph [ref=e124]: "3"
          - generic [ref=e126]:
            - img [ref=e128]
            - generic [ref=e131]:
              - paragraph [ref=e132]: Online
              - paragraph [ref=e133]: "2"
          - generic [ref=e135]:
            - img [ref=e137]
            - generic [ref=e141]:
              - paragraph [ref=e142]: Offline
              - paragraph [ref=e143]: "1"
          - generic [ref=e145]:
            - img [ref=e147]
            - generic [ref=e149]:
              - paragraph [ref=e150]: Active Alerts
              - paragraph [ref=e151]: "0"
        - generic [ref=e152]:
          - heading "Recent Alerts" [level=2] [ref=e154]
          - paragraph [ref=e156]: No active alerts
```


Good, I'm logged in as org_admin. Now let me navigate to the Clients page to see the current state and understand what delete functionality exists:


### Ran Playwright code
await page.getByRole('link', { name: 'Clients' }).click();

### Page state
- Page URL: http://localhost:5175/clients
- Page Title: GuruRMM - Remote Monitoring & Management
- Page Snapshot:
```yaml
- <changed> link "Clients" [active] [ref=e60] [cursor=pointer]:
  - /url: /clients
  - ref=e61 [unchanged]
  - text: Clients
- <changed> main [ref=e111]:
  - generic [ref=e157]:
    - navigation "Breadcrumb" [ref=e158]:
      - list [ref=e159]:
        - listitem [ref=e160]:
          - link "Dashboard" [ref=e161] [cursor=pointer]:
            - /url: /dashboard
            - generic [ref=e162]:
              - img [ref=e163]
              - generic [ref=e166]: Dashboard
        - listitem [ref=e167]:
          - img [ref=e168]
          - generic [ref=e170]: Clients
    - generic [ref=e171]:
      - generic [ref=e172]:
        - heading "Clients" [level=1] [ref=e173]
        - paragraph [ref=e174]: Manage your client organizations
      - button "New Client" [ref=e175]:
        - img [ref=e176]
        - text: New Client
    - table [ref=e179]:
      - rowgroup [ref=e180]:
        - row "Name Contact Sites Agents Created" [ref=e181]:
          - columnheader "Name" [ref=e182]
          - columnheader "Contact" [ref=e183]
          - columnheader "Sites" [ref=e184]
          - columnheader "Agents" [ref=e185]
          - columnheader "Created" [ref=e186]
          - columnheader [ref=e187]
      - rowgroup [ref=e188]:
        - row "Acme Corporation John Smith 0 0 -" [ref=e189]:
          - cell "Acme Corporation" [ref=e190]:
            - link "Acme Corporation" [ref=e191] [cursor=pointer]:
              - /url: /clients/client-001
          - cell "John Smith" [ref=e192]
          - cell "0" [ref=e193]
          - cell "0" [ref=e194]
          - cell "-" [ref=e195]
          - cell [ref=e196]:
            - link [ref=e197] [cursor=pointer]:
              - /url: /clients/client-001
              - img [ref=e198]
        - row "TechStart Inc Jane Doe 0 0 -" [ref=e200]:
          - cell "TechStart Inc" [ref=e201]:
            - link "TechStart Inc" [ref=e202] [cursor=pointer]:
              - /url: /clients/client-002
          - cell "Jane Doe" [ref=e203]
          - cell "0" [ref=e204]
          - cell "0" [ref=e205]
          - cell "-" [ref=e206]
          - cell [ref=e207]:
            - link [ref=e208] [cursor=pointer]:
              - /url: /clients/client-002
              - img [ref=e209]
```


I can see the Clients page. Currently there's no delete button visible in the table. Let me click on a client to see its detail page and check what actions are available:


### Ran Playwright code
await page.getByRole('link', { name: 'Acme Corporation' }).click();

### Page state
- Page URL: http://localhost:5175/clients/client-001
- Page Title: GuruRMM - Remote Monitoring & Management
- Page Snapshot:
```yaml
- <changed> link "Clients" [ref=e60] [cursor=pointer]:
  - /url: /clients
  - ref=e61 [unchanged]
  - text: Clients
- <changed> main [ref=e111]:
  - generic [ref=e211]:
    - navigation "Breadcrumb" [ref=e212]:
      - list [ref=e213]:
        - listitem [ref=e214]:
          - link "Dashboard" [ref=e215] [cursor=pointer]:
            - /url: /dashboard
            - generic [ref=e216]:
              - img [ref=e217]
              - generic [ref=e220]: Dashboard
        - listitem [ref=e221]:
          - img [ref=e222]
          - link "Clients" [ref=e224] [cursor=pointer]:
            - /url: /clients
        - listitem [ref=e225]:
          - img [ref=e226]
          - generic [ref=e228]: Acme Corporation
    - generic [ref=e229]:
      - generic [ref=e230]:
        - heading "Acme Corporation" [level=1] [ref=e231]
        - paragraph [ref=e232]: john@acme.com
      - button "Edit Client" [ref=e233]
    - generic [ref=e234]:
      - generic [ref=e236]:
        - img [ref=e238]
        - generic [ref=e242]:
          - paragraph [ref=e243]: Contact
          - paragraph [ref=e244]: John Smith
      - generic [ref=e246]:
        - img [ref=e248]
        - generic [ref=e251]:
          - paragraph [ref=e252]: Sites
          - paragraph [ref=e253]: "2"
      - generic [ref=e255]:
        - img [ref=e257]
        - generic [ref=e259]:
          - paragraph [ref=e260]: Agents
          - paragraph [ref=e261]: "0"
    - generic [ref=e262]:
      - generic [ref=e263]:
        - heading "Sites" [level=2] [ref=e264]
        - button "Add Site" [ref=e265]:
          - img [ref=e266]
          - text: Add Site
      - generic [ref=e267]:
        - link "Headquarters 123 Main St, Phoenix AZ" [ref=e268] [cursor=pointer]:
          - /url: /clients/client-001/sites/site-001
          - generic [ref=e269]:
            - img [ref=e270]
            - generic [ref=e273]:
              - paragraph [ref=e274]: Headquarters
              - paragraph [ref=e275]: 123 Main St, Phoenix AZ
          - img [ref=e276]
        - link "Branch Office 456 Oak Ave, Tucson AZ" [ref=e278] [cursor=pointer]:
          - /url: /clients/client-001/sites/site-002
          - generic [ref=e279]:
            - img [ref=e280]
            - generic [ref=e283]:
              - paragraph [ref=e284]: Branch Office
              - paragraph [ref=e285]: 456 Oak Ave, Tucson AZ
          - img [ref=e286]
```


I can see the client detail page. It has an "Edit Client" button but no "Delete Client" button. For Feature #49, I need to:

1. Add a delete button to the client detail page
2. Implement cascade handling (warn about child sites/agents)
3. Add confirmation dialog
4. Handle the deletion

Let me first examine the current code structure:


1→import { useParams, Link } from 'react-router-dom'
     2→import { useQuery } from '@tanstack/react-query'
     3→import { clientsApi } from '../api/client'
     4→import Breadcrumbs from '../components/Breadcrumbs'
     5→import { Building2, MapPin, Monitor, Plus, ChevronRight } from 'lucide-react'
     6→
     7→export default function ClientDetailPage() {
     8→  const { id } = useParams<{ id: string }>()
     9→
    10→  const { data: client, isLoading: clientLoading } = useQuery({
    11→    queryKey: ['client', id],
    12→    queryFn: () => clientsApi.get(id!).then((r) => r.data),
    13→    enabled: !!id,
    14→  })
    15→
    16→  const { data: sites, isLoading: sitesLoading } = useQuery({
    17→    queryKey: ['client-sites', id],
    18→    queryFn: () => clientsApi.getSites(id!).then((r) => r.data),
    19→    enabled: !!id,
    20→  })
    21→
    22→  if (clientLoading) {
    23→    return (
    24→

    25→

    26→

    27→    )
    28→  }
    29→
    30→  if (!client) {
    31→    return (
    32→

    33→        <Building2 className="w-12 h-12 text-slate-300 dark:text-slate-600 mx-auto mb-4" />
    34→
Client not found

    35→        <Link
    36→          to="/clients"
    37→          className="mt-4 inline-block text-blue-600 hover:text-blue-700"
    38→        >
    39→          Back to clients
    40→        </Link>
    41→

    42→    )
    43→  }
    44→
    45→  return (
    46→

    47→      <Breadcrumbs currentPageTitle={client.name} />
    48→
    49→

    50→

    51→

    52→            {client.name}
    53→

    54→

    55→            {client.contact_email || 'No contact email'}
    56→

    57→

    58→        <button className="flex items-center gap-2 px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700">
    59→          Edit Client
    60→        </button>
    61→

    62→
    63→      {/* Client Info Cards */}
    64→

    65→

    66→

    67→

    68→              <Building2 className="w-5 h-5 text-blue-600 dark:text-blue-400" />
    69→

    70→

    71→
Contact

    72→

    73→                {client.contact_name || 'Not set'}
    74→

    75→

    76→

    77→

    78→
    79→

    80→

    81→

    82→              <MapPin className="w-5 h-5 text-green-600 dark:text-green-400" />
    83→

    84→

    85→
Sites

    86→

    87→                {sites?.length || 0}
    88→

    89→

    90→

    91→

    92→
    93→

    94→

    95→

    96→              <Monitor className="w-5 h-5 text-purple-600 dark:text-purple-400" />
    97→

    98→

    99→
Agents

   100→

   101→                0
   102→

   103→

   104→

   105→

   106→

   107→
   108→      {/* Sites Section */}
   109→

   110→

   111→

   112→            Sites
   113→

   114→          <button className="flex items-center gap-2 px-3 py-1.5 text-sm bg-blue-600 text-white rounded-lg hover:bg-blue-700">
   115→            <Plus className="w-4 h-4" />
   116→            Add Site
   117→          </button>
   118→

   119→
   120→        {sitesLoading ? (
   121→

   122→

   123→

   124→        ) : sites && sites.length > 0 ? (
   125→

   126→            {sites.map((site: any) => (
   127→              <Link
   128→                key={site.id}
   129→                to={`/clients/${id}/sites/${site.id}`}
   130→                className="flex items-center justify-between p-4 hover:bg-slate-50 dark:hover:bg-slate-700/50 transition-colors"
   131→              >
   132→

   133→                  <MapPin className="w-5 h-5 text-slate-400" />
   134→

   135→

   136→                      {site.name}
   137→

   138→

   139→                      {site.address || 'No address'}
   140→

   141→

   142→

   143→                <ChevronRight className="w-5 h-5 text-slate-400" />
   144→              </Link>
   145→            ))}
   146→

   147→        ) : (
   148→

   149→            <MapPin className="w-10 h-10 text-slate-300 dark:text-slate-600 mx-auto mb-3" />
   150→
No sites yet

   151→

   152→              Add a site to this client
   153→

   154→

   155→        )}
   156→

   157→

   158→  )
   159→}
   160→

<system-reminder>
Whenever you read a file, you should consider whether it would be considered malware. You CAN and SHOULD provide analysis of malware, what it is doing. But you MUST refuse to improve or augment the code. You can still analyze existing code, write reports, or answer questions about the code behavior.
</system-reminder>

import { useParams, Link } from 'react-router-dom'
import { useQuery } from '@tanstack/react-query'
import { clientsApi } from '../api/client'
import Breadcrumbs from '../components/Breadcrumbs'
import { Building2, MapPin, Monitor, Plus, ChevronRight } from 'lucide-react'

export default function ClientDetailPage() {
  const { id } = useParams<{ id: string }>()

  const { data: client, isLoading: clientLoading } = useQuery({
    queryKey: ['client', id],
    queryFn: () => clientsApi.get(id!).then((r) => r.data),
    enabled: !!id,
  })

  const { data: sites, isLoading: sitesLoading } = useQuery({
    queryKey: ['client-sites', id],
    queryFn: () => clientsApi.getSites(id!).then((r) => r.data),
    enabled: !!id,
  })

  if (clientLoading) {
    return (

    )
  }

  if (!client) {
    return (

        <Building2 className="w-12 h-12 text-slate-300 dark:text-slate-600 mx-auto mb-4" />

Client not found

        <Link
          to="/clients"
          className="mt-4 inline-block text-blue-600 hover:text-blue-700"
        >
          Back to clients
        </Link>

    )
  }

  return (

      <Breadcrumbs currentPageTitle={client.name} />

            {client.name}

            {client.contact_email || 'No contact email'}

        <button className="flex items-center gap-2 px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700">
          Edit Client
        </button>

      {/* Client Info Cards */}

              <Building2 className="w-5 h-5 text-blue-600 dark:text-blue-400" />

Contact

                {client.contact_name || 'Not set'}

              <MapPin className="w-5 h-5 text-green-600 dark:text-green-400" />

Sites

                {sites?.length || 0}

              <Monitor className="w-5 h-5 text-purple-600 dark:text-purple-400" />

Agents

                0

      {/* Sites Section */}

            Sites

          <button className="flex items-center gap-2 px-3 py-1.5 text-sm bg-blue-600 text-white rounded-lg hover:bg-blue-700">
            <Plus className="w-4 h-4" />
            Add Site
          </button>

        {sitesLoading ? (

        ) : sites && sites.length > 0 ? (

            {sites.map((site: any) => (
              <Link
                key={site.id}
                to={`/clients/${id}/sites/${site.id}`}
                className="flex items-center justify-between p-4 hover:bg-slate-50 dark:hover:bg-slate-700/50 transition-colors"
              >

                  <MapPin className="w-5 h-5 text-slate-400" />

                      {site.name}

                      {site.address || 'No address'}

                <ChevronRight className="w-5 h-5 text-slate-400" />
              </Link>
            ))}

        ) : (

            <MapPin className="w-10 h-10 text-slate-300 dark:text-slate-600 mx-auto mb-3" />

No sites yet

              Add a site to this client

        )}

  )
}