## YOUR ROLE - CODING AGENT

You are continuing work on a long-running autonomous development task.
This is a FRESH context window - you have no memory of previous sessions.

### STEP 1: GET YOUR BEARINGS (MANDATORY)

Start by orienting yourself:

```bash
# 1. See your working directory
pwd

# 2. List files to understand project structure
ls -la

# 3. Read the project specification to understand what you're building
cat app_spec.txt

# 4. Read progress notes from previous sessions
cat claude-progress.txt

# 5. Check recent git history
git log --oneline -20
```

Then use MCP tools to check feature status:

```
# 6. Get progress statistics (passing/total counts)
Use the feature_get_stats tool

# 7. Get the next feature to work on
Use the feature_get_next tool
```

Understanding the `app_spec.txt` is critical - it contains the full requirements
for the application you're building.

### STEP 2: START SERVERS (IF NOT RUNNING)

If `init.sh` exists, run it:

```bash
chmod +x init.sh
./init.sh
```

Otherwise, start servers manually and document the process.

### STEP 3: VERIFICATION TEST (CRITICAL!)

**MANDATORY BEFORE NEW WORK:**

The previous session may have introduced bugs. Before implementing anything
new, you MUST run verification tests.

Run 1-2 of the features marked as passing that are most core to the app's functionality to verify they still work.

To get passing features for regression testing:

```
Use the feature_get_for_regression tool (returns up to 3 random passing features)
```

For example, if this were a chat app, you should perform a test that logs into the app, sends a message, and gets a response.

**If you find ANY issues (functional or visual):**

- Mark that feature as "passes": false immediately
- Add issues to a list
- Fix all issues BEFORE moving to new features
- This includes UI bugs like:
  - White-on-white text or poor contrast
  - Random characters displayed
  - Incorrect timestamps
  - Layout issues or overflow
  - Buttons too close together
  - Missing hover states
  - Console errors

### STEP 4: CHOOSE ONE FEATURE TO IMPLEMENT

#### TEST-DRIVEN DEVELOPMENT MINDSET (CRITICAL)

Features are **test cases** that drive development. This is test-driven development:

- **If you can't test a feature because functionality doesn't exist → BUILD IT**
- You are responsible for implementing ALL required functionality
- Never assume another process will build it later
- "Missing functionality" is NOT a blocker - it's your job to create it

**Example:** Feature says "User can filter flashcards by difficulty level"
- WRONG: "Flashcard page doesn't exist yet" → skip feature
- RIGHT: "Flashcard page doesn't exist yet" → build flashcard page → implement filter → test feature

Get the next feature to implement:

```
# Get the highest-priority pending feature
Use the feature_get_next tool
```

Once you've retrieved the feature, **immediately mark it as in-progress**:

```
# Mark feature as in-progress to prevent other sessions from working on it
Use the feature_mark_in_progress tool with feature_id=42
```

Focus on completing one feature perfectly and completing its testing steps in this session before moving on to other features.
It's ok if you only complete one feature in this session, as there will be more sessions later that continue to make progress.

#### When to Skip a Feature (EXTREMELY RARE)

**Skipping should almost NEVER happen.** Only skip for truly external blockers you cannot control:

- **External API not configured**: Third-party service credentials missing (e.g., Stripe keys, OAuth secrets)
- **External service unavailable**: Dependency on service that's down or inaccessible
- **Environment limitation**: Hardware or system requirement you cannot fulfill

**NEVER skip because:**

| Situation | Wrong Action | Correct Action |
|-----------|--------------|----------------|
| "Page doesn't exist" | Skip | Create the page |
| "API endpoint missing" | Skip | Implement the endpoint |
| "Database table not ready" | Skip | Create the migration |
| "Component not built" | Skip | Build the component |
| "No data to test with" | Skip | Create test data or build data entry flow |
| "Feature X needs to be done first" | Skip | Build feature X as part of this feature |

If a feature requires building other functionality first, **build that functionality**. You are the coding agent - your job is to make the feature work, not to defer it.

If you must skip (truly external blocker only):

```
Use the feature_skip tool with feature_id={id}
```

Document the SPECIFIC external blocker in `claude-progress.txt`. "Functionality not built" is NEVER a valid reason.

### STEP 5: IMPLEMENT THE FEATURE

Implement the chosen feature thoroughly:

1. Write the code (frontend and/or backend as needed)
2. Test manually using browser automation (see Step 6)
3. Fix any issues discovered
4. Verify the feature works end-to-end

### STEP 6: VERIFY WITH BROWSER AUTOMATION

**CRITICAL:** You MUST verify features through the actual UI.

Use browser automation tools:

- Navigate to the app in a real browser
- Interact like a human user (click, type, scroll)
- Take screenshots at each step
- Verify both functionality AND visual appearance

**DO:**

- Test through the UI with clicks and keyboard input
- Take screenshots to verify visual appearance
- Check for console errors in browser
- Verify complete user workflows end-to-end

**DON'T:**

- Only test with curl commands (backend testing alone is insufficient)
- Use JavaScript evaluation to bypass UI (no shortcuts)
- Skip visual verification
- Mark tests passing without thorough verification

### STEP 6.5: MANDATORY VERIFICATION CHECKLIST (BEFORE MARKING ANY TEST PASSING)

**You MUST complete ALL of these checks before marking any feature as "passes": true**

#### Security Verification (for protected features)

- [ ] Feature respects user role permissions
- [ ] Unauthenticated access is blocked (redirects to login)
- [ ] API endpoint checks authorization (returns 401/403 appropriately)
- [ ] Cannot access other users' data by manipulating URLs

#### Real Data Verification (CRITICAL - NO MOCK DATA)

- [ ] Created unique test data via UI (e.g., "TEST_12345_VERIFY_ME")
- [ ] Verified the EXACT data I created appears in UI
- [ ] Refreshed page - data persists (proves database storage)
- [ ] Deleted the test data - verified it's gone everywhere
- [ ] NO unexplained data appeared (would indicate mock data)
- [ ] Dashboard/counts reflect real numbers after my changes

#### Navigation Verification

- [ ] All buttons on this page link to existing routes
- [ ] No 404 errors when clicking any interactive element
- [ ] Back button returns to correct previous page
- [ ] Related links (edit, view, delete) have correct IDs in URLs

#### Integration Verification

- [ ] Console shows ZERO JavaScript errors
- [ ] Network tab shows successful API calls (no 500s)
- [ ] Data returned from API matches what UI displays
- [ ] Loading states appeared during API calls
- [ ] Error states handle failures gracefully

### STEP 6.6: MOCK DATA DETECTION SWEEP

**Run this sweep AFTER EVERY FEATURE before marking it as passing:**

#### 1. Code Pattern Search

Search the codebase for forbidden patterns:

```bash
# Search for mock data patterns
grep -r "mockData\|fakeData\|sampleData\|dummyData\|testData" --include="*.js" --include="*.ts" --include="*.jsx" --include="*.tsx"
grep -r "// TODO\|// FIXME\|// STUB\|// MOCK" --include="*.js" --include="*.ts" --include="*.jsx" --include="*.tsx"
grep -r "hardcoded\|placeholder" --include="*.js" --include="*.ts" --include="*.jsx" --include="*.tsx"
```

**If ANY matches found related to your feature - FIX THEM before proceeding.**

#### 2. Runtime Verification

For ANY data displayed in UI:

1. Create NEW data with UNIQUE content (e.g., "TEST_12345_DELETE_ME")
2. Verify that EXACT content appears in the UI
3. Delete the record
4. Verify it's GONE from the UI
5. **If you see data that wasn't created during testing - IT'S MOCK DATA. Fix it.**

#### 3. Database Verification

Check that:

- Database tables contain only data you created during tests
- Counts/statistics match actual database record counts
- No seed data is masquerading as user data

#### 4. API Response Verification

For API endpoints used by this feature:

- Call the endpoint directly
- Verify response contains actual database data
- Empty database = empty response (not pre-populated mock data)

### STEP 7: UPDATE FEATURE STATUS (CAREFULLY!)

**YOU CAN ONLY MODIFY ONE FIELD: "passes"**

After thorough verification, mark the feature as passing:

```
# Mark feature #42 as passing (replace 42 with the actual feature ID)
Use the feature_mark_passing tool with feature_id=42
```

**NEVER:**

- Delete features
- Edit feature descriptions
- Modify feature steps
- Combine or consolidate features
- Reorder features

**ONLY MARK A FEATURE AS PASSING AFTER VERIFICATION WITH SCREENSHOTS.**

### STEP 8: COMMIT YOUR PROGRESS

Make a descriptive git commit:

```bash
git add .
git commit -m "Implement [feature name] - verified end-to-end

- Added [specific changes]
- Tested with browser automation
- Marked feature #X as passing
- Screenshots in verification/ directory
"
```

### STEP 9: UPDATE PROGRESS NOTES

Update `claude-progress.txt` with:

- What you accomplished this session
- Which test(s) you completed
- Any issues discovered or fixed
- What should be worked on next
- Current completion status (e.g., "45/200 tests passing")

### STEP 10: END SESSION CLEANLY

Before context fills up:

1. Commit all working code
2. Update claude-progress.txt
3. Mark features as passing if tests verified
4. Ensure no uncommitted changes
5. Leave app in working state (no broken features)

---

## TESTING REQUIREMENTS

**ALL testing must use browser automation tools.**

Available tools:

**Navigation & Screenshots:**

- browser_navigate - Navigate to a URL
- browser_navigate_back - Go back to previous page
- browser_take_screenshot - Capture screenshot (use for visual verification)
- browser_snapshot - Get accessibility tree snapshot (structured page data)

**Element Interaction:**

- browser_click - Click elements (has built-in auto-wait)
- browser_type - Type text into editable elements
- browser_fill_form - Fill multiple form fields at once
- browser_select_option - Select dropdown options
- browser_hover - Hover over elements
- browser_drag - Drag and drop between elements
- browser_press_key - Press keyboard keys

**Debugging & Monitoring:**

- browser_console_messages - Get browser console output (check for errors)
- browser_network_requests - Monitor API calls and responses
- browser_evaluate - Execute JavaScript (USE SPARINGLY - debugging only, NOT for bypassing UI)

**Browser Management:**

- browser_close - Close the browser
- browser_resize - Resize browser window (use to test mobile: 375x667, tablet: 768x1024, desktop: 1280x720)
- browser_tabs - Manage browser tabs
- browser_wait_for - Wait for text/element/time
- browser_handle_dialog - Handle alert/confirm dialogs
- browser_file_upload - Upload files

**Key Benefits:**

- All interaction tools have **built-in auto-wait** - no manual timeouts needed
- Use `browser_console_messages` to detect JavaScript errors
- Use `browser_network_requests` to verify API calls succeed

Test like a human user with mouse and keyboard. Don't take shortcuts by using JavaScript evaluation.

---

## FEATURE TOOL USAGE RULES (CRITICAL - DO NOT VIOLATE)

The feature tools exist to reduce token usage. **DO NOT make exploratory queries.**

### ALLOWED Feature Tools (ONLY these):

```
# 1. Get progress stats (passing/in_progress/total counts)
feature_get_stats

# 2. Get the NEXT feature to work on (one feature only)
feature_get_next

# 3. Mark a feature as in-progress (call immediately after feature_get_next)
feature_mark_in_progress with feature_id={id}

# 4. Get up to 3 random passing features for regression testing
feature_get_for_regression

# 5. Mark a feature as passing (after verification)
feature_mark_passing with feature_id={id}

# 6. Skip a feature (moves to end of queue) - ONLY when blocked by dependency
feature_skip with feature_id={id}

# 7. Clear in-progress status (when abandoning a feature)
feature_clear_in_progress with feature_id={id}
```

### RULES:

- Do NOT try to fetch lists of all features
- Do NOT query features by category
- Do NOT list all pending features

**You do NOT need to see all features.** The feature_get_next tool tells you exactly what to work on. Trust it.

---

## EMAIL INTEGRATION (DEVELOPMENT MODE)

When building applications that require email functionality (password resets, email verification, notifications, etc.), you typically won't have access to a real email service or the ability to read email inboxes.

**Solution:** Configure the application to log emails to the terminal instead of sending them.

- Password reset links should be printed to the console
- Email verification links should be printed to the console
- Any notification content should be logged to the terminal

**During testing:**

1. Trigger the email action (e.g., click "Forgot Password")
2. Check the terminal/server logs for the generated link
3. Use that link directly to verify the functionality works

This allows you to fully test email-dependent flows without needing external email services.

---

## IMPORTANT REMINDERS

**Your Goal:** Production-quality application with all tests passing

**This Session's Goal:** Complete at least one feature perfectly

**Priority:** Fix broken tests before implementing new features

**Quality Bar:**

- Zero console errors
- Polished UI matching the design specified in app_spec.txt
- All features work end-to-end through the UI
- Fast, responsive, professional
- **NO MOCK DATA - all data from real database**
- **Security enforced - unauthorized access blocked**
- **All navigation works - no 404s or broken links**

**You have unlimited time.** Take as long as needed to get it right. The most important thing is that you
leave the code base in a clean state before terminating the session (Step 10).

---

Begin by running Step 1 (Get Your Bearings).


Bash

Check current working directory


List files in project directory


total 218
drwxr-xr-x 1 AzureAD+MikeSwanson 4096      0 Jan  8 11:26 ./
drwxr-xr-x 1 AzureAD+MikeSwanson 4096      0 Jan  8 08:07 ../
-rw-r--r-- 1 AzureAD+MikeSwanson 4096      5 Jan  8 10:11 .agent.lock
-rw-r--r-- 1 AzureAD+MikeSwanson 4096    375 Jan  8 09:32 .claude_assistant_settings.json
-rw-r--r-- 1 AzureAD+MikeSwanson 4096   1590 Jan  8 11:28 .claude_settings.json
drwxr-xr-x 1 AzureAD+MikeSwanson 4096      0 Jan  8 11:28 .git/
-rw-r--r-- 1 AzureAD+MikeSwanson 4096    573 Jan  8 10:38 .gitignore
drwxr-xr-x 1 AzureAD+MikeSwanson 4096      0 Jan  8 11:07 .playwright-mcp/
drwxr-xr-x 1 AzureAD+MikeSwanson 4096      0 Jan  8 10:41 agent/
-rw-r--r-- 1 AzureAD+MikeSwanson 4096  30544 Jan  8 10:11 app_spec.txt
-rw-r--r-- 1 AzureAD+MikeSwanson 4096   2536 Jan  8 11:09 claude-progress.txt
drwxr-xr-x 1 AzureAD+MikeSwanson 4096      0 Jan  8 10:49 dashboard/
-rw-r--r-- 1 AzureAD+MikeSwanson 4096 106496 Jan  8 11:26 features.db
-rwxr-xr-x 1 AzureAD+MikeSwanson 4096   6549 Jan  8 10:21 init.sh*
drwxr-xr-x 1 AzureAD+MikeSwanson 4096      0 Jan  8 10:09 prompts/
-rw-r--r-- 1 AzureAD+MikeSwanson 4096   5035 Jan  8 10:21 README.md
drwxr-xr-x 1 AzureAD+MikeSwanson 4096      0 Jan  8 10:43 server/


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

Check recent git history


<tool_use_error>File does not exist.</tool_use_error>


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


Check recent git history


     1→# GuruRMM - Session 2 Progress Report
     2→# ====================================
     3→# Date: 2025-01-08
     4→# Agent: Coding Agent
     5→# Status: IN PROGRESS
     6→
     7→## Summary
     8→
     9→This session implemented authentication and authorization features for the GuruRMM dashboard.
    10→Two security-related features are now passing.
    11→
    12→## Completed Features
    13→
    14→### Feature #1: Unauthenticated user cannot access protected routes
    15→- Verified all protected routes redirect to /login
    16→- Fixed Tailwind CSS 4 configuration (added @tailwindcss/postcss)
    17→- Removed redundant api.rs file (kept api/mod.rs)
    18→
    19→### Feature #2: Regular user cannot access admin-only pages
    20→- Implemented AuthContext with React Context API
    21→- Created RoleGuard component for role-based route protection
    22→- Added admin pages: AdminPage, PlatformSettingsPage, UsersPage
    23→- Added development mode with mock authentication for testing
    24→- Updated Layout with role-based navigation visibility
    25→
    26→## New Files Created
    27→
    28→### Dashboard
    29→- dashboard/src/contexts/AuthContext.tsx - Auth state management with dev mode
    30→- dashboard/src/components/RoleGuard.tsx - Role-based route guards
    31→- dashboard/src/pages/AdminPage.tsx - Admin dashboard
    32→- dashboard/src/pages/PlatformSettingsPage.tsx - Platform settings (admin-only)
    33→- dashboard/src/pages/UsersPage.tsx - User management page
    34→- dashboard/postcss.config.js - PostCSS config for Tailwind CSS 4
    35→
    36→## Development Mode Test Accounts
    37→
    38→For testing without a backend:
    39→- admin@test.com / admin123 (Admin role)
    40→- orgadmin@test.com / orgadmin123 (Org Admin role)
    41→- tech@test.com / tech123 (Technician role)
    42→- user@test.com / user123 (Org User role)
    43→
    44→## Git Commits
    45→
    46→1. 57e810c - Fix Tailwind CSS 4 configuration and resolve module conflict
    47→2. 6696415 - Implement role-based access control for admin pages
    48→
    49→## Technical Notes
    50→
    51→- Dashboard dev server is running on dynamic ports (check output)
    52→- Tailwind CSS 4 requires @tailwindcss/postcss plugin
    53→- AuthContext provides hasRole() function for checking permissions
    54→- Dev mode is enabled when import.meta.env.DEV is true and VITE_USE_REAL_API is not set
    55→
    56→## Next Steps
    57→
    58→1. Continue with Feature #3 (get using feature_get_next)
    59→2. Run backend server if implementing API features
    60→3. Run regression tests periodically (feature_get_for_regression)
    61→
    62→## Feature Statistics (End of Session 2)
    63→- Total: 159
    64→- Passing: 2
    65→- In Progress: 0
    66→- Pending: 157
    67→- Completion: 1.3%
    68→
    69→## Previous Session Summary
    70→
    71→Session 1 (Initializer Agent):
    72→- Created 159 features in features.db
    73→- Set up project structure (agent, server, dashboard)
    74→- Initialized git repository
    75→

<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 - Session 2 Progress Report
# ====================================
# Date: 2025-01-08
# Agent: Coding Agent
# Status: IN PROGRESS

## Summary

This session implemented authentication and authorization features for the GuruRMM dashboard.
Two security-related features are now passing.

## Completed Features

### Feature #1: Unauthenticated user cannot access protected routes
- Verified all protected routes redirect to /login
- Fixed Tailwind CSS 4 configuration (added @tailwindcss/postcss)
- Removed redundant api.rs file (kept api/mod.rs)

### Feature #2: Regular user cannot access admin-only pages
- Implemented AuthContext with React Context API
- Created RoleGuard component for role-based route protection
- Added admin pages: AdminPage, PlatformSettingsPage, UsersPage
- Added development mode with mock authentication for testing
- Updated Layout with role-based navigation visibility

## New Files Created

### Dashboard
- dashboard/src/contexts/AuthContext.tsx - Auth state management with dev mode
- dashboard/src/components/RoleGuard.tsx - Role-based route guards
- dashboard/src/pages/AdminPage.tsx - Admin dashboard
- dashboard/src/pages/PlatformSettingsPage.tsx - Platform settings (admin-only)
- dashboard/src/pages/UsersPage.tsx - User management page
- dashboard/postcss.config.js - PostCSS config for Tailwind CSS 4

## Development Mode Test Accounts

For testing without a backend:
- admin@test.com / admin123 (Admin role)
- orgadmin@test.com / orgadmin123 (Org Admin role)
- tech@test.com / tech123 (Technician role)
- user@test.com / user123 (Org User role)

## Git Commits

1. 57e810c - Fix Tailwind CSS 4 configuration and resolve module conflict
2. 6696415 - Implement role-based access control for admin pages

## Technical Notes

- Dashboard dev server is running on dynamic ports (check output)
- Tailwind CSS 4 requires @tailwindcss/postcss plugin
- AuthContext provides hasRole() function for checking permissions
- Dev mode is enabled when import.meta.env.DEV is true and VITE_USE_REAL_API is not set

## Next Steps

1. Continue with Feature #3 (get using feature_get_next)
2. Run backend server if implementing API features
3. Run regression tests periodically (feature_get_for_regression)

## Feature Statistics (End of Session 2)
- Total: 159
- Passing: 2
- In Progress: 0
- Pending: 157
- Completion: 1.3%

## Previous Session Summary

Session 1 (Initializer Agent):
- Created 159 features in features.db
- Set up project structure (agent, server, dashboard)
- Initialized git repository


     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


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


Now let me check the feature status:


After login redirect to intended destination

Verify deep link preservation after authentication

Step 1: Navigate to /agents/123 without logging in

Step 2: Verify redirect to login page with return URL saved

Step 3: Complete login with valid credentials

Step 4: Verify automatic redirect to /agents/123


Good - I can see that:
- **8 features passing** (5.0% completion)
- **1 feature in progress**: Feature #15 "After login redirect to intended destination"

Let me first run the init script to start servers, then check on passing features for regression testing:


Run init script to start servers