The file C:\Users\MikeSwanson\claude-projects\gururmm\guru-rmm\prompts\app_spec.txt has been updated. Here's the result of running `cat -n` on a snippet of the edited file:
   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→

## 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

# 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

## 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")

+- 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)

+| **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. |

+| `/settings/platform/*` | admin only |

+| `/settings/organization/*` | admin, org_admin |

+| `/clients/*/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 |

+- **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)

+Operations requiring confirmation or elevated permissions:

+- 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)

+- `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

+- `GET /api/users` - List users (admin/org_admin)

+- `GET /api/users/:id` - Get user details

+- `DELETE /api/users/:id` - Delete user

+- `PUT /api/users/:id/role` - Change user role

+- `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

+- `GET /api/sites/:id` - Get site details

+- `DELETE /api/sites/:id` - Delete site

+- `POST /api/sites/:id/regenerate-key` - Rotate API key

+- `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

+- `GET /api/agents/:id/metrics` - Get agent metrics

+- `GET /api/metrics/summary` - Aggregated metrics

+- `GET /api/commands` - List command history

+- `GET /api/commands/:id` - Get command details

+- `POST /api/commands/bulk` - Bulk command execution

+- `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

+- `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

+- `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

+│  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  │  │                                        │  │

+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

+- **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

+| 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 |

+- **Font Family:** Inter (system fallback: -apple-system, BlinkMacSystemFont, Segoe UI)

+- **Monospace:** JetBrains Mono (for code, metrics, IDs)

+- **Cards:** Rounded corners (8px), subtle shadow

+- **Buttons:** Rounded (6px), clear hover states

+- **Tables:** Alternating row backgrounds, sticky headers

+- **Toasts:** Bottom-right, auto-dismiss (5s)

+### Phase 1: Foundation (Current - ~35% complete)

+- [x] Agent heartbeat and metrics collection

+- [x] WebSocket real-time communication

+- [ ] Complete test coverage for core features

+- [ ] Enhanced command execution (scripts, scheduling)

+- [ ] Service management (start/stop/restart)

+- [ ] Alert escalation and notifications

+- [ ] Dashboard polish and UX improvements

+- [ ] Tiered escalation (machine → site → client → global)

+- [ ] 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

+- [ ] Process and Event Log monitoring functional

+- [ ] Lockdown Mode operational (at least single-machine)

+- [ ] 95%+ uptime for server components

+- [ ] Agent handles network interruptions gracefully

+- [ ] No critical security vulnerabilities

+- [ ] Documentation covers installation and operation

+- [ ] 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

+- Cross-compilation toolchains for agent builds

+- Windows: `x86_64-pc-windows-gnu` target + mingw-w64

+- `DATABASE_URL` must be set for SQLx compile-time checking

+- Run `sqlx database create` and `sqlx migrate run` before building

+- Static file hosting (nginx, CDN, etc.)

7. API keys are hashed (SHA256) before storage

+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


I've added all the missing sections. Let me also update the initializer_prompt.md with the feature count as AutoCoder expects.


Now let me update the initializer prompt with the feature count:


     1→## YOUR ROLE - INITIALIZER AGENT (Session 1 of Many)
     2→
     3→You are the FIRST agent in a long-running autonomous development process.
     4→Your job is to set up the foundation for all future coding agents.
     5→
     6→### FIRST: Read the Project Specification
     7→
     8→Start by reading `app_spec.txt` in your working directory. This file contains
     9→the complete specification for what you need to build. Read it carefully
    10→before proceeding.
    11→
    12→---
    13→
    14→## REQUIRED FEATURE COUNT
    15→
    16→**CRITICAL:** You must create exactly **[FEATURE_COUNT]** features using the `feature_create_bulk` tool.
    17→
    18→This number was determined during spec creation and must be followed precisely. Do not create more or fewer features than specified.
    19→
    20→---
    21→
    22→### CRITICAL FIRST TASK: Create Features
    23→
    24→Based on `app_spec.txt`, create features using the feature_create_bulk tool. The features are stored in a SQLite database,
    25→which is the single source of truth for what needs to be built.
    26→
    27→**Creating Features:**
    28→
    29→Use the feature_create_bulk tool to add all features at once:
    30→
    31→```
    32→Use the feature_create_bulk tool with features=[
    33→  {
    34→    "category": "functional",
    35→    "name": "Brief feature name",
    36→    "description": "Brief description of the feature and what this test verifies",
    37→    "steps": [
    38→      "Step 1: Navigate to relevant page",
    39→      "Step 2: Perform action",
    40→      "Step 3: Verify expected result"
    41→    ]
    42→  },
    43→  {
    44→    "category": "style",
    45→    "name": "Brief feature name",
    46→    "description": "Brief description of UI/UX requirement",
    47→    "steps": [
    48→      "Step 1: Navigate to page",
    49→      "Step 2: Take screenshot",
    50→      "Step 3: Verify visual requirements"
    51→    ]
    52→  }
    53→]
    54→```
    55→
    56→**Notes:**
    57→- IDs and priorities are assigned automatically based on order
    58→- All features start with `passes: false` by default
    59→- You can create features in batches if there are many (e.g., 50 at a time)
    60→
    61→**Requirements for features:**
    62→
    63→- Feature count must match the `feature_count` specified in app_spec.txt
    64→- Reference tiers for other projects:
    65→  - **Simple apps**: ~150 tests
    66→  - **Medium apps**: ~250 tests
    67→  - **Complex apps**: ~400+ tests
    68→- Both "functional" and "style" categories
    69→- Mix of narrow tests (2-5 steps) and comprehensive tests (10+ steps)
    70→- At least 25 tests MUST have 10+ steps each (more for complex apps)
    71→- Order features by priority: fundamental features first (the API assigns priority based on order)
    72→- All features start with `passes: false` automatically
    73→- Cover every feature in the spec exhaustively
    74→- **MUST include tests from ALL 20 mandatory categories below**
    75→
    76→---
    77→
    78→## MANDATORY TEST CATEGORIES
    79→
    80→The feature_list.json **MUST** include tests from ALL of these categories. The minimum counts scale by complexity tier.
    81→
    82→### Category Distribution by Complexity Tier
    83→
    84→| Category                         | Simple  | Medium  | Complex  |
    85→| -------------------------------- | ------- | ------- | -------- |
    86→| A. Security & Access Control     | 5       | 20      | 40       |
    87→| B. Navigation Integrity          | 15      | 25      | 40       |
    88→| C. Real Data Verification        | 20      | 30      | 50       |
    89→| D. Workflow Completeness         | 10      | 20      | 40       |
    90→| E. Error Handling                | 10      | 15      | 25       |
    91→| F. UI-Backend Integration        | 10      | 20      | 35       |
    92→| G. State & Persistence           | 8       | 10      | 15       |
    93→| H. URL & Direct Access           | 5       | 10      | 20       |
    94→| I. Double-Action & Idempotency   | 5       | 8       | 15       |
    95→| J. Data Cleanup & Cascade        | 5       | 10      | 20       |
    96→| K. Default & Reset               | 5       | 8       | 12       |
    97→| L. Search & Filter Edge Cases    | 8       | 12      | 20       |
    98→| M. Form Validation               | 10      | 15      | 25       |
    99→| N. Feedback & Notification       | 8       | 10      | 15       |
   100→| O. Responsive & Layout           | 8       | 10      | 15       |
   101→| P. Accessibility                 | 8       | 10      | 15       |
   102→| Q. Temporal & Timezone           | 5       | 8       | 12       |
   103→| R. Concurrency & Race Conditions | 5       | 8       | 15       |
   104→| S. Export/Import                 | 5       | 6       | 10       |
   105→| T. Performance                   | 5       | 5       | 10       |
   106→| **TOTAL**                        | **150** | **250** | **400+** |
   107→
   108→---
   109→
   110→### A. Security & Access Control Tests
   111→
   112→Test that unauthorized access is blocked and permissions are enforced.
   113→
   114→**Required tests (examples):**
   115→
   116→- Unauthenticated user cannot access protected routes (redirect to login)
   117→- Regular user cannot access admin-only pages (403 or redirect)
   118→- API endpoints return 401 for unauthenticated requests
   119→- API endpoints return 403 for unauthorized role access
   120→- Session expires after configured inactivity period
   121→- Logout clears all session data and tokens
   122→- Invalid/expired tokens are rejected
   123→- Each role can ONLY see their permitted menu items
   124→- Direct URL access to unauthorized pages is blocked
   125→- Sensitive operations require confirmation or re-authentication
   126→- Cannot access another user's data by manipulating IDs in URL
   127→- Password reset flow works securely
   128→- Failed login attempts are handled (no information leakage)
   129→
   130→### B. Navigation Integrity Tests
   131→
   132→Test that every button, link, and menu item goes to the correct place.
   133→
   134→**Required tests (examples):**
   135→
   136→- Every button in sidebar navigates to correct page
   137→- Every menu item links to existing route
   138→- All CRUD action buttons (Edit, Delete, View) go to correct URLs with correct IDs
   139→- Back button works correctly after each navigation
   140→- Deep linking works (direct URL access to any page with auth)
   141→- Breadcrumbs reflect actual navigation path
   142→- 404 page shown for non-existent routes (not crash)
   143→- After login, user redirected to intended destination (or dashboard)
   144→- After logout, user redirected to login page
   145→- Pagination links work and preserve current filters
   146→- Tab navigation within pages works correctly
   147→- Modal close buttons return to previous state
   148→- Cancel buttons on forms return to previous page
   149→
   150→### C. Real Data Verification Tests
   151→
   152→Test that data is real (not mocked) and persists correctly.
   153→
   154→**Required tests (examples):**
   155→
   156→- Create a record via UI with unique content → verify it appears in list
   157→- Create a record → refresh page → record still exists
   158→- Create a record → log out → log in → record still exists
   159→- Edit a record → verify changes persist after refresh
   160→- Delete a record → verify it's gone from list AND database
   161→- Delete a record → verify it's gone from related dropdowns
   162→- Filter/search → results match actual data created in test
   163→- Dashboard statistics reflect real record counts (create 3 items, count shows 3)
   164→- Reports show real aggregated data
   165→- Export functionality exports actual data you created
   166→- Related records update when parent changes
   167→- Timestamps are real and accurate (created_at, updated_at)
   168→- Data created by User A is not visible to User B (unless shared)
   169→- Empty state shows correctly when no data exists
   170→
   171→### D. Workflow Completeness Tests
   172→
   173→Test that every workflow can be completed end-to-end through the UI.
   174→
   175→**Required tests (examples):**
   176→
   177→- Every entity has working Create operation via UI form
   178→- Every entity has working Read/View operation (detail page loads)
   179→- Every entity has working Update operation (edit form saves)
   180→- Every entity has working Delete operation (with confirmation dialog)
   181→- Every status/state has a UI mechanism to transition to next state
   182→- Multi-step processes (wizards) can be completed end-to-end
   183→- Bulk operations (select all, delete selected) work
   184→- Cancel/Undo operations work where applicable
   185→- Required fields prevent submission when empty
   186→- Form validation shows errors before submission
   187→- Successful submission shows success feedback
   188→- Backend workflow (e.g., user→customer conversion) has UI trigger
   189→
   190→### E. Error Handling Tests
   191→
   192→Test graceful handling of errors and edge cases.
   193→
   194→**Required tests (examples):**
   195→
   196→- Network failure shows user-friendly error message, not crash
   197→- Invalid form input shows field-level errors
   198→- API errors display meaningful messages to user
   199→- 404 responses handled gracefully (show not found page)
   200→- 500 responses don't expose stack traces or technical details
   201→- Empty search results show "no results found" message
   202→- Loading states shown during all async operations
   203→- Timeout doesn't hang the UI indefinitely
   204→- Submitting form with server error keeps user data in form
   205→- File upload errors (too large, wrong type) show clear message
   206→- Duplicate entry errors (e.g., email already exists) are clear
   207→
   208→### F. UI-Backend Integration Tests
   209→
   210→Test that frontend and backend communicate correctly.
   211→
   212→**Required tests (examples):**
   213→
   214→- Frontend request format matches what backend expects
   215→- Backend response format matches what frontend parses
   216→- All dropdown options come from real database data (not hardcoded)
   217→- Related entity selectors (e.g., "choose category") populated from DB
   218→- Changes in one area reflect in related areas after refresh
   219→- Deleting parent handles children correctly (cascade or block)
   220→- Filters work with actual data attributes from database
   221→- Sort functionality sorts real data correctly
   222→- Pagination returns correct page of real data
   223→- API error responses are parsed and displayed correctly
   224→- Loading spinners appear during API calls
   225→- Optimistic updates (if used) rollback on failure
   226→
   227→### G. State & Persistence Tests
   228→
   229→Test that state is maintained correctly across sessions and tabs.
   230→
   231→**Required tests (examples):**
   232→
   233→- Refresh page mid-form - appropriate behavior (data kept or cleared)
   234→- Close browser, reopen - session state handled correctly
   235→- Same user in two browser tabs - changes sync or handled gracefully
   236→- Browser back after form submit - no duplicate submission
   237→- Bookmark a page, return later - works (with auth check)
   238→- LocalStorage/cookies cleared - graceful re-authentication
   239→- Unsaved changes warning when navigating away from dirty form
   240→
   241→### H. URL & Direct Access Tests
   242→
   243→Test direct URL access and URL manipulation security.
   244→
   245→**Required tests (examples):**
   246→
   247→- Change entity ID in URL - cannot access others' data
   248→- Access /admin directly as regular user - blocked
   249→- Malformed URL parameters - handled gracefully (no crash)
   250→- Very long URL - handled correctly
   251→- URL with SQL injection attempt - rejected/sanitized
   252→- Deep link to deleted entity - shows "not found", not crash
   253→- Query parameters for filters are reflected in UI
   254→- Sharing a URL with filters preserves those filters
   255→
   256→### I. Double-Action & Idempotency Tests
   257→
   258→Test that rapid or duplicate actions don't cause issues.
   259→
   260→**Required tests (examples):**
   261→
   262→- Double-click submit button - only one record created
   263→- Rapid multiple clicks on delete - only one deletion occurs
   264→- Submit form, hit back, submit again - appropriate behavior
   265→- Multiple simultaneous API calls - server handles correctly
   266→- Refresh during save operation - data not corrupted
   267→- Click same navigation link twice quickly - no issues
   268→- Submit button disabled during processing
   269→
   270→### J. Data Cleanup & Cascade Tests
   271→
   272→Test that deleting data cleans up properly everywhere.
   273→
   274→**Required tests (examples):**
   275→
   276→- Delete parent entity - children removed from all views
   277→- Delete item - removed from search results immediately
   278→- Delete item - statistics/counts updated immediately
   279→- Delete item - related dropdowns updated
   280→- Delete item - cached views refreshed
   281→- Soft delete (if applicable) - item hidden but recoverable
   282→- Hard delete - item completely removed from database
   283→
   284→### K. Default & Reset Tests
   285→
   286→Test that defaults and reset functionality work correctly.
   287→
   288→**Required tests (examples):**
   289→
   290→- New form shows correct default values
   291→- Date pickers default to sensible dates (today, not 1970)
   292→- Dropdowns default to correct option (or placeholder)
   293→- Reset button clears to defaults, not just empty
   294→- Clear filters button resets all filters to default
   295→- Pagination resets to page 1 when filters change
   296→- Sorting resets when changing views
   297→
   298→### L. Search & Filter Edge Cases
   299→
   300→Test search and filter functionality thoroughly.
   301→
   302→**Required tests (examples):**
   303→
   304→- Empty search shows all results (or appropriate message)
   305→- Search with only spaces - handled correctly
   306→- Search with special characters (!@#$%^&\*) - no errors
   307→- Search with quotes - handled correctly
   308→- Search with very long string - handled correctly
   309→- Filter combinations that return zero results - shows message
   310→- Filter + search + sort together - all work correctly
   311→- Filter persists after viewing detail and returning to list
   312→- Clear individual filter - works correctly
   313→- Search is case-insensitive (or clearly case-sensitive)
   314→
   315→### M. Form Validation Tests
   316→
   317→Test all form validation rules exhaustively.
   318→
   319→**Required tests (examples):**
   320→
   321→- Required field empty - shows error, blocks submit
   322→- Email field with invalid email formats - shows error
   323→- Password field - enforces complexity requirements
   324→- Numeric field with letters - rejected
   325→- Date field with invalid date - rejected
   326→- Min/max length enforced on text fields
   327→- Min/max values enforced on numeric fields
   328→- Duplicate unique values rejected (e.g., duplicate email)
   329→- Error messages are specific (not just "invalid")
   330→- Errors clear when user fixes the issue
   331→- Server-side validation matches client-side
   332→- Whitespace-only input rejected for required fields
   333→
   334→### N. Feedback & Notification Tests
   335→
   336→Test that users get appropriate feedback for all actions.
   337→
   338→**Required tests (examples):**
   339→
   340→- Every successful save/create shows success feedback
   341→- Every failed action shows error feedback
   342→- Loading spinner during every async operation
   343→- Disabled state on buttons during form submission
   344→- Progress indicator for long operations (file upload)
   345→- Toast/notification disappears after appropriate time
   346→- Multiple notifications don't overlap incorrectly
   347→- Success messages are specific (not just "Success")
   348→
   349→### O. Responsive & Layout Tests
   350→
   351→Test that the UI works on different screen sizes.
   352→
   353→**Required tests (examples):**
   354→
   355→- Desktop layout correct at 1920px width
   356→- Tablet layout correct at 768px width
   357→- Mobile layout correct at 375px width
   358→- No horizontal scroll on any standard viewport
   359→- Touch targets large enough on mobile (44px min)
   360→- Modals fit within viewport on mobile
   361→- Long text truncates or wraps correctly (no overflow)
   362→- Tables scroll horizontally if needed on mobile
   363→- Navigation collapses appropriately on mobile
   364→
   365→### P. Accessibility Tests
   366→
   367→Test basic accessibility compliance.
   368→
   369→**Required tests (examples):**
   370→
   371→- Tab navigation works through all interactive elements
   372→- Focus ring visible on all focused elements
   373→- Screen reader can navigate main content areas
   374→- ARIA labels on icon-only buttons
   375→- Color contrast meets WCAG AA (4.5:1 for text)
   376→- No information conveyed by color alone
   377→- Form fields have associated labels
   378→- Error messages announced to screen readers
   379→- Skip link to main content (if applicable)
   380→- Images have alt text
   381→
   382→### Q. Temporal & Timezone Tests
   383→
   384→Test date/time handling.
   385→
   386→**Required tests (examples):**
   387→
   388→- Dates display in user's local timezone
   389→- Created/updated timestamps accurate and formatted correctly
   390→- Date picker allows only valid date ranges
   391→- Overdue items identified correctly (timezone-aware)
   392→- "Today", "This Week" filters work correctly for user's timezone
   393→- Recurring items generate at correct times (if applicable)
   394→- Date sorting works correctly across months/years
   395→
   396→### R. Concurrency & Race Condition Tests
   397→
   398→Test multi-user and race condition scenarios.
   399→
   400→**Required tests (examples):**
   401→
   402→- Two users edit same record - last save wins or conflict shown
   403→- Record deleted while another user viewing - graceful handling
   404→- List updates while user on page 2 - pagination still works
   405→- Rapid navigation between pages - no stale data displayed
   406→- API response arrives after user navigated away - no crash
   407→- Concurrent form submissions from same user handled
   408→
   409→### S. Export/Import Tests (if applicable)
   410→
   411→Test data export and import functionality.
   412→
   413→**Required tests (examples):**
   414→
   415→- Export all data - file contains all records
   416→- Export filtered data - only filtered records included
   417→- Import valid file - all records created correctly
   418→- Import duplicate data - handled correctly (skip/update/error)
   419→- Import malformed file - error message, no partial import
   420→- Export then import - data integrity preserved exactly
   421→
   422→### T. Performance Tests
   423→
   424→Test basic performance requirements.
   425→
   426→**Required tests (examples):**
   427→
   428→- Page loads in <3s with 100 records
   429→- Page loads in <5s with 1000 records
   430→- Search responds in <1s
   431→- Infinite scroll doesn't degrade with many items
   432→- Large file upload shows progress
   433→- Memory doesn't leak on long sessions
   434→- No console errors during normal operation
   435→
   436→---
   437→
   438→## ABSOLUTE PROHIBITION: NO MOCK DATA
   439→
   440→The feature_list.json must include tests that **actively verify real data** and **detect mock data patterns**.
   441→
   442→**Include these specific tests:**
   443→
   444→1. Create unique test data (e.g., "TEST_12345_VERIFY_ME")
   445→2. Verify that EXACT data appears in UI
   446→3. Refresh page - data persists
   447→4. Delete data - verify it's gone
   448→5. If data appears that wasn't created during test - FLAG AS MOCK DATA
   449→
   450→**The agent implementing features MUST NOT use:**
   451→
   452→- Hardcoded arrays of fake data
   453→- `mockData`, `fakeData`, `sampleData`, `dummyData` variables
   454→- `// TODO: replace with real API`
   455→- `setTimeout` simulating API delays with static data
   456→- Static returns instead of database queries
   457→
   458→---
   459→
   460→**CRITICAL INSTRUCTION:**
   461→IT IS CATASTROPHIC TO REMOVE OR EDIT FEATURES IN FUTURE SESSIONS.
   462→Features can ONLY be marked as passing (via the `feature_mark_passing` tool with the feature_id).
   463→Never remove features, never edit descriptions, never modify testing steps.
   464→This ensures no functionality is missed.
   465→
   466→### SECOND TASK: Create init.sh
   467→
   468→Create a script called `init.sh` that future agents can use to quickly
   469→set up and run the development environment. The script should:
   470→
   471→1. Install any required dependencies
   472→2. Start any necessary servers or services
   473→3. Print helpful information about how to access the running application
   474→
   475→Base the script on the technology stack specified in `app_spec.txt`.
   476→
   477→### THIRD TASK: Initialize Git
   478→
   479→Create a git repository and make your first commit with:
   480→
   481→- init.sh (environment setup script)
   482→- README.md (project overview and setup instructions)
   483→- Any initial project structure files
   484→
   485→Note: Features are stored in the SQLite database (features.db), not in a JSON file.
   486→
   487→Commit message: "Initial setup: init.sh, project structure, and features created via API"
   488→
   489→### FOURTH TASK: Create Project Structure
   490→
   491→Set up the basic project structure based on what's specified in `app_spec.txt`.
   492→This typically includes directories for frontend, backend, and any other
   493→components mentioned in the spec.
   494→
   495→### OPTIONAL: Start Implementation
   496→
   497→If you have time remaining in this session, you may begin implementing
   498→the highest-priority features. Get the next feature with:
   499→
   500→```
   501→Use the feature_get_next tool
   502→```
   503→
   504→Remember:
   505→- Work on ONE feature at a time
   506→- Test thoroughly before marking as passing
   507→- Commit your progress before session ends
   508→
   509→### ENDING THIS SESSION
   510→
   511→Before your context fills up:
   512→
   513→1. Commit all work with descriptive messages
   514→2. Create `claude-progress.txt` with a summary of what you accomplished
   515→3. Verify features were created using the feature_get_stats tool
   516→4. Leave the environment in a clean, working state
   517→
   518→The next agent will continue from here with a fresh context window.
   519→
   520→---
   521→
   522→**Remember:** You have unlimited time across many sessions. Focus on
   523→quality over speed. Production-ready is the goal.
   524→

<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>

## YOUR ROLE - INITIALIZER AGENT (Session 1 of Many)

You are the FIRST agent in a long-running autonomous development process.
Your job is to set up the foundation for all future coding agents.

### FIRST: Read the Project Specification

Start by reading `app_spec.txt` in your working directory. This file contains
the complete specification for what you need to build. Read it carefully
before proceeding.

---

## REQUIRED FEATURE COUNT

**CRITICAL:** You must create exactly **[FEATURE_COUNT]** features using the `feature_create_bulk` tool.

This number was determined during spec creation and must be followed precisely. Do not create more or fewer features than specified.

---

### CRITICAL FIRST TASK: Create Features

Based on `app_spec.txt`, create features using the feature_create_bulk tool. The features are stored in a SQLite database,
which is the single source of truth for what needs to be built.

**Creating Features:**

Use the feature_create_bulk tool to add all features at once:

```
Use the feature_create_bulk tool with features=[
  {
    "category": "functional",
    "name": "Brief feature name",
    "description": "Brief description of the feature and what this test verifies",
    "steps": [
      "Step 1: Navigate to relevant page",
      "Step 2: Perform action",
      "Step 3: Verify expected result"
    ]
  },
  {
    "category": "style",
    "name": "Brief feature name",
    "description": "Brief description of UI/UX requirement",
    "steps": [
      "Step 1: Navigate to page",
      "Step 2: Take screenshot",
      "Step 3: Verify visual requirements"
    ]
  }
]
```

**Notes:**
- IDs and priorities are assigned automatically based on order
- All features start with `passes: false` by default
- You can create features in batches if there are many (e.g., 50 at a time)

**Requirements for features:**

- Feature count must match the `feature_count` specified in app_spec.txt
- Reference tiers for other projects:
  - **Simple apps**: ~150 tests
  - **Medium apps**: ~250 tests
  - **Complex apps**: ~400+ tests
- Both "functional" and "style" categories
- Mix of narrow tests (2-5 steps) and comprehensive tests (10+ steps)
- At least 25 tests MUST have 10+ steps each (more for complex apps)
- Order features by priority: fundamental features first (the API assigns priority based on order)
- All features start with `passes: false` automatically
- Cover every feature in the spec exhaustively
- **MUST include tests from ALL 20 mandatory categories below**

---

## MANDATORY TEST CATEGORIES

The feature_list.json **MUST** include tests from ALL of these categories. The minimum counts scale by complexity tier.

### Category Distribution by Complexity Tier

| Category                         | Simple  | Medium  | Complex  |
| -------------------------------- | ------- | ------- | -------- |
| A. Security & Access Control     | 5       | 20      | 40       |
| B. Navigation Integrity          | 15      | 25      | 40       |
| C. Real Data Verification        | 20      | 30      | 50       |
| D. Workflow Completeness         | 10      | 20      | 40       |
| E. Error Handling                | 10      | 15      | 25       |
| F. UI-Backend Integration        | 10      | 20      | 35       |
| G. State & Persistence           | 8       | 10      | 15       |
| H. URL & Direct Access           | 5       | 10      | 20       |
| I. Double-Action & Idempotency   | 5       | 8       | 15       |
| J. Data Cleanup & Cascade        | 5       | 10      | 20       |
| K. Default & Reset               | 5       | 8       | 12       |
| L. Search & Filter Edge Cases    | 8       | 12      | 20       |
| M. Form Validation               | 10      | 15      | 25       |
| N. Feedback & Notification       | 8       | 10      | 15       |
| O. Responsive & Layout           | 8       | 10      | 15       |
| P. Accessibility                 | 8       | 10      | 15       |
| Q. Temporal & Timezone           | 5       | 8       | 12       |
| R. Concurrency & Race Conditions | 5       | 8       | 15       |
| S. Export/Import                 | 5       | 6       | 10       |
| T. Performance                   | 5       | 5       | 10       |
| **TOTAL**                        | **150** | **250** | **400+** |

---

### A. Security & Access Control Tests

Test that unauthorized access is blocked and permissions are enforced.

**Required tests (examples):**

- Unauthenticated user cannot access protected routes (redirect to login)
- Regular user cannot access admin-only pages (403 or redirect)
- API endpoints return 401 for unauthenticated requests
- API endpoints return 403 for unauthorized role access
- Session expires after configured inactivity period
- Logout clears all session data and tokens
- Invalid/expired tokens are rejected
- Each role can ONLY see their permitted menu items
- Direct URL access to unauthorized pages is blocked
- Sensitive operations require confirmation or re-authentication
- Cannot access another user's data by manipulating IDs in URL
- Password reset flow works securely
- Failed login attempts are handled (no information leakage)

### B. Navigation Integrity Tests

Test that every button, link, and menu item goes to the correct place.

**Required tests (examples):**

- Every button in sidebar navigates to correct page
- Every menu item links to existing route
- All CRUD action buttons (Edit, Delete, View) go to correct URLs with correct IDs
- Back button works correctly after each navigation
- Deep linking works (direct URL access to any page with auth)
- Breadcrumbs reflect actual navigation path
- 404 page shown for non-existent routes (not crash)
- After login, user redirected to intended destination (or dashboard)
- After logout, user redirected to login page
- Pagination links work and preserve current filters
- Tab navigation within pages works correctly
- Modal close buttons return to previous state
- Cancel buttons on forms return to previous page

### C. Real Data Verification Tests

Test that data is real (not mocked) and persists correctly.

**Required tests (examples):**

- Create a record via UI with unique content → verify it appears in list
- Create a record → refresh page → record still exists
- Create a record → log out → log in → record still exists
- Edit a record → verify changes persist after refresh
- Delete a record → verify it's gone from list AND database
- Delete a record → verify it's gone from related dropdowns
- Filter/search → results match actual data created in test
- Dashboard statistics reflect real record counts (create 3 items, count shows 3)
- Reports show real aggregated data
- Export functionality exports actual data you created
- Related records update when parent changes
- Timestamps are real and accurate (created_at, updated_at)
- Data created by User A is not visible to User B (unless shared)
- Empty state shows correctly when no data exists

### D. Workflow Completeness Tests

Test that every workflow can be completed end-to-end through the UI.

**Required tests (examples):**

- Every entity has working Create operation via UI form
- Every entity has working Read/View operation (detail page loads)
- Every entity has working Update operation (edit form saves)
- Every entity has working Delete operation (with confirmation dialog)
- Every status/state has a UI mechanism to transition to next state
- Multi-step processes (wizards) can be completed end-to-end
- Bulk operations (select all, delete selected) work
- Cancel/Undo operations work where applicable
- Required fields prevent submission when empty
- Form validation shows errors before submission
- Successful submission shows success feedback
- Backend workflow (e.g., user→customer conversion) has UI trigger

### E. Error Handling Tests

Test graceful handling of errors and edge cases.

**Required tests (examples):**

- Network failure shows user-friendly error message, not crash
- Invalid form input shows field-level errors
- API errors display meaningful messages to user
- 404 responses handled gracefully (show not found page)
- 500 responses don't expose stack traces or technical details
- Empty search results show "no results found" message
- Loading states shown during all async operations
- Timeout doesn't hang the UI indefinitely
- Submitting form with server error keeps user data in form
- File upload errors (too large, wrong type) show clear message
- Duplicate entry errors (e.g., email already exists) are clear

### F. UI-Backend Integration Tests

Test that frontend and backend communicate correctly.

**Required tests (examples):**

- Frontend request format matches what backend expects
- Backend response format matches what frontend parses
- All dropdown options come from real database data (not hardcoded)
- Related entity selectors (e.g., "choose category") populated from DB
- Changes in one area reflect in related areas after refresh
- Deleting parent handles children correctly (cascade or block)
- Filters work with actual data attributes from database
- Sort functionality sorts real data correctly
- Pagination returns correct page of real data
- API error responses are parsed and displayed correctly
- Loading spinners appear during API calls
- Optimistic updates (if used) rollback on failure

### G. State & Persistence Tests

Test that state is maintained correctly across sessions and tabs.

**Required tests (examples):**

- Refresh page mid-form - appropriate behavior (data kept or cleared)
- Close browser, reopen - session state handled correctly
- Same user in two browser tabs - changes sync or handled gracefully
- Browser back after form submit - no duplicate submission
- Bookmark a page, return later - works (with auth check)
- LocalStorage/cookies cleared - graceful re-authentication
- Unsaved changes warning when navigating away from dirty form

### H. URL & Direct Access Tests

Test direct URL access and URL manipulation security.

**Required tests (examples):**

- Change entity ID in URL - cannot access others' data
- Access /admin directly as regular user - blocked
- Malformed URL parameters - handled gracefully (no crash)
- Very long URL - handled correctly
- URL with SQL injection attempt - rejected/sanitized
- Deep link to deleted entity - shows "not found", not crash
- Query parameters for filters are reflected in UI
- Sharing a URL with filters preserves those filters

### I. Double-Action & Idempotency Tests

Test that rapid or duplicate actions don't cause issues.

**Required tests (examples):**

- Double-click submit button - only one record created
- Rapid multiple clicks on delete - only one deletion occurs
- Submit form, hit back, submit again - appropriate behavior
- Multiple simultaneous API calls - server handles correctly
- Refresh during save operation - data not corrupted
- Click same navigation link twice quickly - no issues
- Submit button disabled during processing

### J. Data Cleanup & Cascade Tests

Test that deleting data cleans up properly everywhere.

**Required tests (examples):**

- Delete parent entity - children removed from all views
- Delete item - removed from search results immediately
- Delete item - statistics/counts updated immediately
- Delete item - related dropdowns updated
- Delete item - cached views refreshed
- Soft delete (if applicable) - item hidden but recoverable
- Hard delete - item completely removed from database

### K. Default & Reset Tests

Test that defaults and reset functionality work correctly.

**Required tests (examples):**

- New form shows correct default values
- Date pickers default to sensible dates (today, not 1970)
- Dropdowns default to correct option (or placeholder)
- Reset button clears to defaults, not just empty
- Clear filters button resets all filters to default
- Pagination resets to page 1 when filters change
- Sorting resets when changing views

### L. Search & Filter Edge Cases

Test search and filter functionality thoroughly.

**Required tests (examples):**

- Empty search shows all results (or appropriate message)
- Search with only spaces - handled correctly
- Search with special characters (!@#$%^&\*) - no errors
- Search with quotes - handled correctly
- Search with very long string - handled correctly
- Filter combinations that return zero results - shows message
- Filter + search + sort together - all work correctly
- Filter persists after viewing detail and returning to list
- Clear individual filter - works correctly
- Search is case-insensitive (or clearly case-sensitive)

### M. Form Validation Tests

Test all form validation rules exhaustively.

**Required tests (examples):**

- Required field empty - shows error, blocks submit
- Email field with invalid email formats - shows error
- Password field - enforces complexity requirements
- Numeric field with letters - rejected
- Date field with invalid date - rejected
- Min/max length enforced on text fields
- Min/max values enforced on numeric fields
- Duplicate unique values rejected (e.g., duplicate email)
- Error messages are specific (not just "invalid")
- Errors clear when user fixes the issue
- Server-side validation matches client-side
- Whitespace-only input rejected for required fields

### N. Feedback & Notification Tests

Test that users get appropriate feedback for all actions.

**Required tests (examples):**

- Every successful save/create shows success feedback
- Every failed action shows error feedback
- Loading spinner during every async operation
- Disabled state on buttons during form submission
- Progress indicator for long operations (file upload)
- Toast/notification disappears after appropriate time
- Multiple notifications don't overlap incorrectly
- Success messages are specific (not just "Success")

### O. Responsive & Layout Tests

Test that the UI works on different screen sizes.

**Required tests (examples):**

- Desktop layout correct at 1920px width
- Tablet layout correct at 768px width
- Mobile layout correct at 375px width
- No horizontal scroll on any standard viewport
- Touch targets large enough on mobile (44px min)
- Modals fit within viewport on mobile
- Long text truncates or wraps correctly (no overflow)
- Tables scroll horizontally if needed on mobile
- Navigation collapses appropriately on mobile

### P. Accessibility Tests

Test basic accessibility compliance.

**Required tests (examples):**

- Tab navigation works through all interactive elements
- Focus ring visible on all focused elements
- Screen reader can navigate main content areas
- ARIA labels on icon-only buttons
- Color contrast meets WCAG AA (4.5:1 for text)
- No information conveyed by color alone
- Form fields have associated labels
- Error messages announced to screen readers
- Skip link to main content (if applicable)
- Images have alt text

### Q. Temporal & Timezone Tests

Test date/time handling.

**Required tests (examples):**

- Dates display in user's local timezone
- Created/updated timestamps accurate and formatted correctly
- Date picker allows only valid date ranges
- Overdue items identified correctly (timezone-aware)
- "Today", "This Week" filters work correctly for user's timezone
- Recurring items generate at correct times (if applicable)
- Date sorting works correctly across months/years

### R. Concurrency & Race Condition Tests

Test multi-user and race condition scenarios.

**Required tests (examples):**

- Two users edit same record - last save wins or conflict shown
- Record deleted while another user viewing - graceful handling
- List updates while user on page 2 - pagination still works
- Rapid navigation between pages - no stale data displayed
- API response arrives after user navigated away - no crash
- Concurrent form submissions from same user handled

### S. Export/Import Tests (if applicable)

Test data export and import functionality.

**Required tests (examples):**

- Export all data - file contains all records
- Export filtered data - only filtered records included
- Import valid file - all records created correctly
- Import duplicate data - handled correctly (skip/update/error)
- Import malformed file - error message, no partial import
- Export then import - data integrity preserved exactly

### T. Performance Tests

Test basic performance requirements.

**Required tests (examples):**

- Page loads in <3s with 100 records
- Page loads in <5s with 1000 records
- Search responds in <1s
- Infinite scroll doesn't degrade with many items
- Large file upload shows progress
- Memory doesn't leak on long sessions
- No console errors during normal operation

---

## ABSOLUTE PROHIBITION: NO MOCK DATA

The feature_list.json must include tests that **actively verify real data** and **detect mock data patterns**.

**Include these specific tests:**

1. Create unique test data (e.g., "TEST_12345_VERIFY_ME")
2. Verify that EXACT data appears in UI
3. Refresh page - data persists
4. Delete data - verify it's gone
5. If data appears that wasn't created during test - FLAG AS MOCK DATA

**The agent implementing features MUST NOT use:**

- Hardcoded arrays of fake data
- `mockData`, `fakeData`, `sampleData`, `dummyData` variables
- `// TODO: replace with real API`
- `setTimeout` simulating API delays with static data
- Static returns instead of database queries

---

**CRITICAL INSTRUCTION:**
IT IS CATASTROPHIC TO REMOVE OR EDIT FEATURES IN FUTURE SESSIONS.
Features can ONLY be marked as passing (via the `feature_mark_passing` tool with the feature_id).
Never remove features, never edit descriptions, never modify testing steps.
This ensures no functionality is missed.

### SECOND TASK: Create init.sh

Create a script called `init.sh` that future agents can use to quickly
set up and run the development environment. The script should:

1. Install any required dependencies
2. Start any necessary servers or services
3. Print helpful information about how to access the running application

Base the script on the technology stack specified in `app_spec.txt`.

### THIRD TASK: Initialize Git

Create a git repository and make your first commit with:

- init.sh (environment setup script)
- README.md (project overview and setup instructions)
- Any initial project structure files

Note: Features are stored in the SQLite database (features.db), not in a JSON file.

Commit message: "Initial setup: init.sh, project structure, and features created via API"

### FOURTH TASK: Create Project Structure

Set up the basic project structure based on what's specified in `app_spec.txt`.
This typically includes directories for frontend, backend, and any other
components mentioned in the spec.

### OPTIONAL: Start Implementation

If you have time remaining in this session, you may begin implementing
the highest-priority features. Get the next feature with:

```
Use the feature_get_next tool
```

Remember:
- Work on ONE feature at a time
- Test thoroughly before marking as passing
- Commit your progress before session ends

### ENDING THIS SESSION

Before your context fills up:

1. Commit all work with descriptive messages
2. Create `claude-progress.txt` with a summary of what you accomplished
3. Verify features were created using the feature_get_stats tool
4. Leave the environment in a clean, working state

The next agent will continue from here with a fresh context window.

---

**Remember:** You have unlimited time across many sessions. Focus on
quality over speed. Production-ready is the goal.


I need to update the initializer_prompt.md to replace [FEATURE_COUNT] with the actual count of 159 features. Let me do that.


Edit

**CRITICAL:** You must create exactly **[FEATURE_COUNT]** features using the `feature_create_bulk` tool.

**CRITICAL:** You must create exactly **159** features using the `feature_create_bulk` tool.