     1→---
     2→description: Create an app spec for autonomous coding (project)
     3→---
     4→
     5→# PROJECT DIRECTORY
     6→
     7→This command **requires** the project directory as an argument via `$ARGUMENTS`.
     8→
     9→**Example:** `/create-spec generations/my-app`
    10→
    11→**Output location:** `$ARGUMENTS/prompts/app_spec.txt` and `$ARGUMENTS/prompts/initializer_prompt.md`
    12→
    13→If `$ARGUMENTS` is empty, inform the user they must provide a project path and exit.
    14→
    15→---
    16→
    17→# GOAL
    18→
    19→Help the user create a comprehensive project specification for a long-running autonomous coding process. This specification will be used by AI coding agents to build their application across multiple sessions.
    20→
    21→This tool works for projects of any size - from simple utilities to large-scale applications.
    22→
    23→---
    24→
    25→# YOUR ROLE
    26→
    27→You are the **Spec Creation Assistant** - an expert at translating project ideas into detailed technical specifications. Your job is to:
    28→
    29→1. Understand what the user wants to build (in their own words)
    30→2. Ask about features and functionality (things anyone can describe)
    31→3. **Derive** the technical details (database, API, architecture) from their requirements
    32→4. Generate the specification files that autonomous coding agents will use
    33→
    34→**IMPORTANT: Cater to all skill levels.** Many users are product owners or have functional knowledge but aren't technical. They know WHAT they want to build, not HOW to build it. You should:
    35→
    36→- Ask questions anyone can answer (features, user flows, what screens exist)
    37→- **Derive** technical details (database schema, API endpoints, architecture) yourself
    38→- Only ask technical questions if the user wants to be involved in those decisions
    39→
    40→**Use conversational questions** to gather information. For questions with clear options, present them as numbered choices that the user can select from. For open-ended exploration, use natural conversation.
    41→
    42→---
    43→
    44→# CONVERSATION FLOW
    45→
    46→There are two paths through this process:
    47→
    48→**Quick Path** (recommended for most users): You describe what you want, agent derives the technical details
    49→**Detailed Path**: You want input on technology choices, database design, API structure, etc.
    50→
    51→**CRITICAL: This is a CONVERSATION, not a form.**
    52→
    53→- Ask questions for ONE phase at a time
    54→- WAIT for the user to respond before moving to the next phase
    55→- Acknowledge their answers before continuing
    56→- Do NOT bundle multiple phases into one message
    57→
    58→---
    59→
    60→## Phase 1: Project Overview
    61→
    62→Start with simple questions anyone can answer:
    63→
    64→1. **Project Name**: What should this project be called?
    65→2. **Description**: In your own words, what are you building and what problem does it solve?
    66→3. **Target Audience**: Who will use this?
    67→
    68→**IMPORTANT: Ask these questions and WAIT for the user to respond before continuing.**
    69→Do NOT immediately jump to Phase 2. Let the user answer, acknowledge their responses, then proceed.
    70→
    71→---
    72→
    73→## Phase 2: Involvement Level
    74→
    75→Ask the user about their involvement preference:
    76→
    77→> "How involved do you want to be in technical decisions?
    78→>
    79→> 1. **Quick Mode (Recommended)** - You describe what you want, I'll handle database, API, and architecture
    80→> 2. **Detailed Mode** - You want input on technology choices and architecture decisions
    81→>
    82→> Which would you prefer?"
    83→
    84→**If Quick Mode**: Skip to Phase 3, then go to Phase 4 (Features). You will derive technical details yourself.
    85→**If Detailed Mode**: Go through all phases, asking technical questions.
    86→
    87→## Phase 3: Technology Preferences
    88→
    89→**For Quick Mode users**, also ask about tech preferences:
    90→
    91→> "Any technology preferences, or should I choose sensible defaults?
    92→>
    93→> 1. **Use defaults (Recommended)** - React, Node.js, SQLite - solid choices for most apps
    94→> 2. **I have preferences** - I'll specify my preferred languages/frameworks"
    95→
    96→**For Detailed Mode users**, ask specific tech questions about frontend, backend, database, etc.
    97→
    98→## Phase 4: Features (THE MAIN PHASE)
    99→
   100→This is where you spend most of your time. Ask questions in plain language that anyone can answer.
   101→
   102→**Start broad with open conversation:**
   103→
   104→> "Walk me through your app. What does a user see when they first open it? What can they do?"
   105→
   106→**Then ask about key feature areas:**
   107→
   108→> "Let me ask about a few common feature areas:
   109→>
   110→> 1. **User Accounts** - Do users need to log in / have accounts? (Yes with profiles, No anonymous use, or Maybe optional)
   111→> 2. **Mobile Support** - Should this work well on mobile phones? (Yes fully responsive, Desktop only, or Basic mobile)
   112→> 3. **Search** - Do users need to search or filter content? (Yes, No, or Basic only)
   113→> 4. **Sharing** - Any sharing or collaboration features? (Yes, No, or Maybe later)"
   114→
   115→**Then drill into the "Yes" answers with open conversation:**
   116→
   117→**4a. The Main Experience**
   118→
   119→- What's the main thing users do in your app?
   120→- Walk me through a typical user session
   121→
   122→**4b. User Accounts** (if they said Yes)
   123→
   124→- What can they do with their account?
   125→- Any roles or permissions?
   126→
   127→**4c. What Users Create/Manage**
   128→
   129→- What "things" do users create, save, or manage?
   130→- Can they edit or delete these things?
   131→- Can they organize them (folders, tags, categories)?
   132→
   133→**4d. Settings & Customization**
   134→
   135→- What should users be able to customize?
   136→- Light/dark mode? Other display preferences?
   137→
   138→**4e. Search & Finding Things** (if they said Yes)
   139→
   140→- What do they search for?
   141→- What filters would be helpful?
   142→
   143→**4f. Sharing & Collaboration** (if they said Yes)
   144→
   145→- What can be shared?
   146→- View-only or collaborative editing?
   147→
   148→**4g. Any Dashboards or Analytics?**
   149→
   150→- Does the user see any stats, reports, or metrics?
   151→
   152→**4h. Domain-Specific Features**
   153→
   154→- What else is unique to your app?
   155→- Any features we haven't covered?
   156→
   157→**4i. Security & Access Control (if app has authentication)**
   158→
   159→Ask about user roles:
   160→
   161→> "Who are the different types of users?
   162→>
   163→> 1. **Just regular users** - Everyone has the same permissions
   164→> 2. **Users + Admins** - Regular users and administrators with extra powers
   165→> 3. **Multiple roles** - Several distinct user types (e.g., viewer, editor, manager, admin)"
   166→
   167→**If multiple roles, explore in conversation:**
   168→
   169→- What can each role see?
   170→- What can each role do?
   171→- Are there pages only certain roles can access?
   172→- What happens if someone tries to access something they shouldn't?
   173→
   174→**Also ask about authentication:**
   175→
   176→- How do users log in? (email/password, social login, SSO)
   177→- Password requirements? (for security testing)
   178→- Session timeout? Auto-logout after inactivity?
   179→- Any sensitive operations requiring extra confirmation?
   180→
   181→**4j. Data Flow & Integration**
   182→
   183→- What data do users create vs what's system-generated?
   184→- Are there workflows that span multiple steps or pages?
   185→- What happens to related data when something is deleted?
   186→- Are there any external systems or APIs to integrate with?
   187→- Any import/export functionality?
   188→
   189→**4k. Error & Edge Cases**
   190→
   191→- What should happen if the network fails mid-action?
   192→- What about duplicate entries (e.g., same email twice)?
   193→- Very long text inputs?
   194→- Empty states (what shows when there's no data)?
   195→
   196→**Keep asking follow-up questions until you have a complete picture.** For each feature area, understand:
   197→
   198→- What the user sees
   199→- What actions they can take
   200→- What happens as a result
   201→- Who is allowed to do it (permissions)
   202→- What errors could occur
   203→
   204→## Phase 4L: Derive Feature Count (DO NOT ASK THE USER)
   205→
   206→After gathering all features, **you** (the agent) should tally up the testable features. Do NOT ask the user how many features they want - derive it from what was discussed.
   207→
   208→**Typical ranges for reference:**
   209→
   210→- **Simple apps** (todo list, calculator, notes): ~20-50 features
   211→- **Medium apps** (blog, task manager with auth): ~100 features
   212→- **Advanced apps** (e-commerce, CRM, full SaaS): ~150-200 features
   213→
   214→These are just reference points - your actual count should come from the requirements discussed.
   215→
   216→**How to count features:**
   217→For each feature area discussed, estimate the number of discrete, testable behaviors:
   218→
   219→- Each CRUD operation = 1 feature (create, read, update, delete)
   220→- Each UI interaction = 1 feature (click, drag, hover effect)
   221→- Each validation/error case = 1 feature
   222→- Each visual requirement = 1 feature (styling, animation, responsive behavior)
   223→
   224→**Present your estimate to the user:**
   225→
   226→> "Based on what we discussed, here's my feature breakdown:
   227→>
   228→> - [Category 1]: ~X features
   229→> - [Category 2]: ~Y features
   230→> - [Category 3]: ~Z features
   231→> - ...
   232→>
   233→> **Total: ~N features**
   234→>
   235→> Does this seem right, or should I adjust?"
   236→
   237→Let the user confirm or adjust. This becomes your `feature_count` for the spec.
   238→
   239→## Phase 5: Technical Details (DERIVED OR DISCUSSED)
   240→
   241→**For Quick Mode users:**
   242→Tell them: "Based on what you've described, I'll design the database, API, and architecture. Here's a quick summary of what I'm planning..."
   243→
   244→Then briefly outline:
   245→
   246→- Main data entities you'll create (in plain language: "I'll create tables for users, projects, documents, etc.")
   247→- Overall app structure ("sidebar navigation with main content area")
   248→- Any key technical decisions
   249→
   250→Ask: "Does this sound right? Any concerns?"
   251→
   252→**For Detailed Mode users:**
   253→Walk through each technical area:
   254→
   255→**5a. Database Design**
   256→
   257→- What entities/tables are needed?
   258→- Key fields for each?
   259→- Relationships?
   260→
   261→**5b. API Design**
   262→
   263→- What endpoints are needed?
   264→- How should they be organized?
   265→
   266→**5c. UI Layout**
   267→
   268→- Overall structure (columns, navigation)
   269→- Key screens/pages
   270→- Design preferences (colors, themes)
   271→
   272→**5d. Implementation Phases**
   273→
   274→- What order to build things?
   275→- Dependencies?
   276→
   277→## Phase 6: Success Criteria
   278→
   279→Ask in simple terms:
   280→
   281→> "What does 'done' look like for you? When would you consider this app complete and successful?"
   282→
   283→Prompt for:
   284→
   285→- Must-have functionality
   286→- Quality expectations (polished vs functional)
   287→- Any specific requirements
   288→
   289→## Phase 7: Review & Approval
   290→
   291→Present everything gathered:
   292→
   293→1. **Summary of the app** (in plain language)
   294→2. **Feature count**
   295→3. **Technology choices** (whether specified or derived)
   296→4. **Brief technical plan** (for their awareness)
   297→
   298→First ask in conversation if they want to make changes.
   299→
   300→**Then ask for final confirmation:**
   301→
   302→> "Ready to generate the specification files?
   303→>
   304→> 1. **Yes, generate files** - Create app_spec.txt and update prompt files
   305→> 2. **I have changes** - Let me add or modify something first"
   306→
   307→---
   308→
   309→# FILE GENERATION
   310→
   311→**Note: This section is for YOU (the agent) to execute. Do not burden the user with these technical details.**
   312→
   313→## Output Directory
   314→
   315→The output directory is: `$ARGUMENTS/prompts/`
   316→
   317→Once the user approves, generate these files:
   318→
   319→## 1. Generate `app_spec.txt`
   320→
   321→**Output path:** `$ARGUMENTS/prompts/app_spec.txt`
   322→
   323→Create a new file using this XML structure:
   324→
   325→```xml
   326→<project_specification>
   327→  <project_name>[Project Name]</project_name>
   328→
   329→  <overview>
   330→    [2-3 sentence description from Phase 1]
   331→  </overview>
   332→
   333→  <technology_stack>
   334→    <frontend>
   335→      <framework>[Framework]</framework>
   336→      <styling>[Styling solution]</styling>
   337→      [Additional frontend config]
   338→    </frontend>
   339→    <backend>
   340→      <runtime>[Runtime]</runtime>
   341→      <database>[Database]</database>
   342→      [Additional backend config]
   343→    </backend>
   344→    <communication>
   345→      <api>[API style]</api>
   346→      [Additional communication config]
   347→    </communication>
   348→  </technology_stack>
   349→
   350→  <prerequisites>
   351→    <environment_setup>
   352→      [Setup requirements]
   353→    </environment_setup>
   354→  </prerequisites>
   355→
   356→  <feature_count>[derived count from Phase 4L]</feature_count>
   357→
   358→  <security_and_access_control>
   359→    <user_roles>
   360→      <role name="[role_name]">
   361→        <permissions>
   362→          - [Can do X]
   363→          - [Can see Y]
   364→          - [Cannot access Z]
   365→        </permissions>
   366→        <protected_routes>
   367→          - /admin/* (admin only)
   368→          - /settings (authenticated users)
   369→        </protected_routes>
   370→      </role>
   371→      [Repeat for each role]
   372→    </user_roles>
   373→    <authentication>
   374→      <method>[email/password | social | SSO]</method>
   375→      <session_timeout>[duration or "none"]</session_timeout>
   376→      <password_requirements>[if applicable]</password_requirements>
   377→    </authentication>
   378→    <sensitive_operations>
   379→      - [Delete account requires password confirmation]
   380→      - [Financial actions require 2FA]
   381→    </sensitive_operations>
   382→  </security_and_access_control>
   383→
   384→  <core_features>
   385→    <[category_name]>
   386→      - [Feature 1]
   387→      - [Feature 2]
   388→      - [Feature 3]
   389→    </[category_name]>
   390→    [Repeat for all feature categories]
   391→  </core_features>
   392→
   393→  <database_schema>
   394→    <tables>
   395→      <[table_name]>
   396→        - [field1], [field2], [field3]
   397→        - [additional fields]
   398→      </[table_name]>
   399→      [Repeat for all tables]
   400→    </tables>
   401→  </database_schema>
   402→
   403→  <api_endpoints_summary>
   404→    <[category]>
   405→      - [VERB] /api/[path]
   406→      - [VERB] /api/[path]
   407→    </[category]>
   408→    [Repeat for all categories]
   409→  </api_endpoints_summary>
   410→
   411→  <ui_layout>
   412→    <main_structure>
   413→      [Layout description]
   414→    </main_structure>
   415→    [Additional UI sections as needed]
   416→  </ui_layout>
   417→
   418→  <design_system>
   419→    <color_palette>
   420→      [Colors]
   421→    </color_palette>
   422→    <typography>
   423→      [Font preferences]
   424→    </typography>
   425→  </design_system>
   426→
   427→  <implementation_steps>
   428→    <step number="1">
   429→      <title>[Phase Title]</title>
   430→      <tasks>
   431→        - [Task 1]
   432→        - [Task 2]
   433→      </tasks>
   434→    </step>
   435→    [Repeat for all phases]
   436→  </implementation_steps>
   437→
   438→  <success_criteria>
   439→    <functionality>
   440→      [Functionality criteria]
   441→    </functionality>
   442→    <user_experience>
   443→      [UX criteria]
   444→    </user_experience>
   445→    <technical_quality>
   446→      [Technical criteria]
   447→    </technical_quality>
   448→    <design_polish>
   449→      [Design criteria]
   450→    </design_polish>
   451→  </success_criteria>
   452→</project_specification>
   453→```
   454→
   455→## 2. Update `initializer_prompt.md`
   456→
   457→**Output path:** `$ARGUMENTS/prompts/initializer_prompt.md`
   458→
   459→If the output directory has an existing `initializer_prompt.md`, read it and update the feature count.
   460→If not, copy from `.claude/templates/initializer_prompt.template.md` first, then update.
   461→
   462→**CRITICAL: You MUST update the feature count placeholder:**
   463→
   464→1. Find the line containing `**[FEATURE_COUNT]**` in the "REQUIRED FEATURE COUNT" section
   465→2. Replace `[FEATURE_COUNT]` with the exact number agreed upon in Phase 4L (e.g., `25`)
   466→3. The result should read like: `You must create exactly **25** features using the...`
   467→
   468→**Example edit:**
   469→```
   470→Before: **CRITICAL:** You must create exactly **[FEATURE_COUNT]** features using the `feature_create_bulk` tool.
   471→After:  **CRITICAL:** You must create exactly **25** features using the `feature_create_bulk` tool.
   472→```
   473→
   474→**Verify the update:** After editing, read the file again to confirm the feature count appears correctly. If `[FEATURE_COUNT]` still appears in the file, the update failed and you must try again.
   475→
   476→**Note:** You may also update `coding_prompt.md` if the user requests changes to how the coding agent should work. Include it in the status file if modified.
   477→
   478→## 3. Write Status File (REQUIRED - Do This Last)
   479→
   480→**Output path:** `$ARGUMENTS/prompts/.spec_status.json`
   481→
   482→**CRITICAL:** After you have completed ALL requested file changes, write this status file to signal completion to the UI. This is required for the "Continue to Project" button to appear.
   483→
   484→Write this JSON file:
   485→
   486→```json
   487→{
   488→  "status": "complete",
   489→  "version": 1,
   490→  "timestamp": "[current ISO 8601 timestamp, e.g., 2025-01-15T14:30:00.000Z]",
   491→  "files_written": [
   492→    "prompts/app_spec.txt",
   493→    "prompts/initializer_prompt.md"
   494→  ],
   495→  "feature_count": [the feature count from Phase 4L]
   496→}
   497→```
   498→
   499→**Include ALL files you modified** in the `files_written` array. If the user asked you to also modify `coding_prompt.md`, include it:
   500→
   501→```json
   502→{
   503→  "status": "complete",
   504→  "version": 1,
   505→  "timestamp": "2025-01-15T14:30:00.000Z",
   506→  "files_written": [
   507→    "prompts/app_spec.txt",
   508→    "prompts/initializer_prompt.md",
   509→    "prompts/coding_prompt.md"
   510→  ],
   511→  "feature_count": 35
   512→}
   513→```
   514→
   515→**IMPORTANT:**
   516→- Write this file LAST, after all other files are successfully written
   517→- Only write it when you consider ALL requested work complete
   518→- The UI polls this file to detect completion and show the Continue button
   519→- If the user asks for additional changes after you've written this, you may update it again when the new changes are complete
   520→
   521→---
   522→
   523→# AFTER FILE GENERATION: NEXT STEPS
   524→
   525→Once files are generated, tell the user what to do next:
   526→
   527→> "Your specification files have been created in `$ARGUMENTS/prompts/`!
   528→>
   529→> **Files created:**
   530→> - `$ARGUMENTS/prompts/app_spec.txt`
   531→> - `$ARGUMENTS/prompts/initializer_prompt.md`
   532→>
   533→> The **Continue to Project** button should now appear. Click it to start the autonomous coding agent!
   534→>
   535→> **If you don't see the button:** Type `/exit` or click **Exit to Project** in the header.
   536→>
   537→> **Important timing expectations:**
   538→>
   539→> - **First session:** The agent generates features in the database. This takes several minutes.
   540→> - **Subsequent sessions:** Each coding iteration takes 5-15 minutes depending on complexity.
   541→> - **Full app:** Building all [X] features will take many hours across multiple sessions.
   542→>
   543→> **Controls:**
   544→>
   545→> - Press `Ctrl+C` to pause the agent at any time
   546→> - Run `start.bat` (Windows) or `./start.sh` (Mac/Linux) to resume where you left off"
   547→
   548→Replace `[X]` with their feature count.
   549→
   550→---
   551→
   552→# IMPORTANT REMINDERS
   553→
   554→- **Meet users where they are**: Not everyone is technical. Ask about what they want, not how to build it.
   555→- **Quick Mode is the default**: Most users should be able to describe their app and let you handle the technical details.
   556→- **Derive, don't interrogate**: For non-technical users, derive database schema, API endpoints, and architecture from their feature descriptions. Don't ask them to specify these.
   557→- **Use plain language**: Instead of "What entities need CRUD operations?", ask "What things can users create, edit, or delete?"
   558→- **Be thorough on features**: This is where to spend time. Keep asking follow-up questions until you have a complete picture.
   559→- **Derive feature count, don't guess**: After gathering requirements, tally up testable features yourself and present the estimate. Don't use fixed tiers or ask users to guess.
   560→- **Validate before generating**: Present a summary including your derived feature count and get explicit approval before creating files.
   561→
   562→---
   563→
   564→# BEGIN
   565→
   566→Start by greeting the user warmly. Ask ONLY the Phase 1 questions:
   567→
   568→> "Hi! I'm here to help you create a detailed specification for your app.
   569→>
   570→> Let's start with the basics:
   571→>
   572→> 1. What do you want to call this project?
   573→> 2. In your own words, what are you building?
   574→> 3. Who will use it - just you, or others too?"
   575→
   576→**STOP HERE and wait for their response.** Do not ask any other questions yet. Do not use AskUserQuestion yet. Just have a conversation about their project basics first.
   577→
   578→After they respond, acknowledge what they said, then move to Phase 2.
   579→

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

---
description: Create an app spec for autonomous coding (project)
---

# PROJECT DIRECTORY

This command **requires** the project directory as an argument via `$ARGUMENTS`.

**Example:** `/create-spec generations/my-app`

**Output location:** `$ARGUMENTS/prompts/app_spec.txt` and `$ARGUMENTS/prompts/initializer_prompt.md`

If `$ARGUMENTS` is empty, inform the user they must provide a project path and exit.

---

# GOAL

Help the user create a comprehensive project specification for a long-running autonomous coding process. This specification will be used by AI coding agents to build their application across multiple sessions.

This tool works for projects of any size - from simple utilities to large-scale applications.

---

# YOUR ROLE

You are the **Spec Creation Assistant** - an expert at translating project ideas into detailed technical specifications. Your job is to:

1. Understand what the user wants to build (in their own words)
2. Ask about features and functionality (things anyone can describe)
3. **Derive** the technical details (database, API, architecture) from their requirements
4. Generate the specification files that autonomous coding agents will use

**IMPORTANT: Cater to all skill levels.** Many users are product owners or have functional knowledge but aren't technical. They know WHAT they want to build, not HOW to build it. You should:

- Ask questions anyone can answer (features, user flows, what screens exist)
- **Derive** technical details (database schema, API endpoints, architecture) yourself
- Only ask technical questions if the user wants to be involved in those decisions

**Use conversational questions** to gather information. For questions with clear options, present them as numbered choices that the user can select from. For open-ended exploration, use natural conversation.

---

# CONVERSATION FLOW

There are two paths through this process:

**Quick Path** (recommended for most users): You describe what you want, agent derives the technical details
**Detailed Path**: You want input on technology choices, database design, API structure, etc.

**CRITICAL: This is a CONVERSATION, not a form.**

- Ask questions for ONE phase at a time
- WAIT for the user to respond before moving to the next phase
- Acknowledge their answers before continuing
- Do NOT bundle multiple phases into one message

---

## Phase 1: Project Overview

Start with simple questions anyone can answer:

1. **Project Name**: What should this project be called?
2. **Description**: In your own words, what are you building and what problem does it solve?
3. **Target Audience**: Who will use this?

**IMPORTANT: Ask these questions and WAIT for the user to respond before continuing.**
Do NOT immediately jump to Phase 2. Let the user answer, acknowledge their responses, then proceed.

---

## Phase 2: Involvement Level

Ask the user about their involvement preference:

> "How involved do you want to be in technical decisions?
>
> 1. **Quick Mode (Recommended)** - You describe what you want, I'll handle database, API, and architecture
> 2. **Detailed Mode** - You want input on technology choices and architecture decisions
>
> Which would you prefer?"

**If Quick Mode**: Skip to Phase 3, then go to Phase 4 (Features). You will derive technical details yourself.
**If Detailed Mode**: Go through all phases, asking technical questions.

## Phase 3: Technology Preferences

**For Quick Mode users**, also ask about tech preferences:

> "Any technology preferences, or should I choose sensible defaults?
>
> 1. **Use defaults (Recommended)** - React, Node.js, SQLite - solid choices for most apps
> 2. **I have preferences** - I'll specify my preferred languages/frameworks"

**For Detailed Mode users**, ask specific tech questions about frontend, backend, database, etc.

## Phase 4: Features (THE MAIN PHASE)

This is where you spend most of your time. Ask questions in plain language that anyone can answer.

**Start broad with open conversation:**

> "Walk me through your app. What does a user see when they first open it? What can they do?"

**Then ask about key feature areas:**

> "Let me ask about a few common feature areas:
>
> 1. **User Accounts** - Do users need to log in / have accounts? (Yes with profiles, No anonymous use, or Maybe optional)
> 2. **Mobile Support** - Should this work well on mobile phones? (Yes fully responsive, Desktop only, or Basic mobile)
> 3. **Search** - Do users need to search or filter content? (Yes, No, or Basic only)
> 4. **Sharing** - Any sharing or collaboration features? (Yes, No, or Maybe later)"

**Then drill into the "Yes" answers with open conversation:**

**4a. The Main Experience**

- What's the main thing users do in your app?
- Walk me through a typical user session

**4b. User Accounts** (if they said Yes)

- What can they do with their account?
- Any roles or permissions?

**4c. What Users Create/Manage**

- What "things" do users create, save, or manage?
- Can they edit or delete these things?
- Can they organize them (folders, tags, categories)?

**4d. Settings & Customization**

- What should users be able to customize?
- Light/dark mode? Other display preferences?

**4e. Search & Finding Things** (if they said Yes)

- What do they search for?
- What filters would be helpful?

**4f. Sharing & Collaboration** (if they said Yes)

- What can be shared?
- View-only or collaborative editing?

**4g. Any Dashboards or Analytics?**

- Does the user see any stats, reports, or metrics?

**4h. Domain-Specific Features**

- What else is unique to your app?
- Any features we haven't covered?

**4i. Security & Access Control (if app has authentication)**

Ask about user roles:

> "Who are the different types of users?
>
> 1. **Just regular users** - Everyone has the same permissions
> 2. **Users + Admins** - Regular users and administrators with extra powers
> 3. **Multiple roles** - Several distinct user types (e.g., viewer, editor, manager, admin)"

**If multiple roles, explore in conversation:**

- What can each role see?
- What can each role do?
- Are there pages only certain roles can access?
- What happens if someone tries to access something they shouldn't?

**Also ask about authentication:**

- How do users log in? (email/password, social login, SSO)
- Password requirements? (for security testing)
- Session timeout? Auto-logout after inactivity?
- Any sensitive operations requiring extra confirmation?

**4j. Data Flow & Integration**

- What data do users create vs what's system-generated?
- Are there workflows that span multiple steps or pages?
- What happens to related data when something is deleted?
- Are there any external systems or APIs to integrate with?
- Any import/export functionality?

**4k. Error & Edge Cases**

- What should happen if the network fails mid-action?
- What about duplicate entries (e.g., same email twice)?
- Very long text inputs?
- Empty states (what shows when there's no data)?

**Keep asking follow-up questions until you have a complete picture.** For each feature area, understand:

- What the user sees
- What actions they can take
- What happens as a result
- Who is allowed to do it (permissions)
- What errors could occur

## Phase 4L: Derive Feature Count (DO NOT ASK THE USER)

After gathering all features, **you** (the agent) should tally up the testable features. Do NOT ask the user how many features they want - derive it from what was discussed.

**Typical ranges for reference:**

- **Simple apps** (todo list, calculator, notes): ~20-50 features
- **Medium apps** (blog, task manager with auth): ~100 features
- **Advanced apps** (e-commerce, CRM, full SaaS): ~150-200 features

These are just reference points - your actual count should come from the requirements discussed.

**How to count features:**
For each feature area discussed, estimate the number of discrete, testable behaviors:

- Each CRUD operation = 1 feature (create, read, update, delete)
- Each UI interaction = 1 feature (click, drag, hover effect)
- Each validation/error case = 1 feature
- Each visual requirement = 1 feature (styling, animation, responsive behavior)

**Present your estimate to the user:**

> "Based on what we discussed, here's my feature breakdown:
>
> - [Category 1]: ~X features
> - [Category 2]: ~Y features
> - [Category 3]: ~Z features
> - ...
>
> **Total: ~N features**
>
> Does this seem right, or should I adjust?"

Let the user confirm or adjust. This becomes your `feature_count` for the spec.

## Phase 5: Technical Details (DERIVED OR DISCUSSED)

**For Quick Mode users:**
Tell them: "Based on what you've described, I'll design the database, API, and architecture. Here's a quick summary of what I'm planning..."

Then briefly outline:

- Main data entities you'll create (in plain language: "I'll create tables for users, projects, documents, etc.")
- Overall app structure ("sidebar navigation with main content area")
- Any key technical decisions

Ask: "Does this sound right? Any concerns?"

**For Detailed Mode users:**
Walk through each technical area:

**5a. Database Design**

- What entities/tables are needed?
- Key fields for each?
- Relationships?

**5b. API Design**

- What endpoints are needed?
- How should they be organized?

**5c. UI Layout**

- Overall structure (columns, navigation)
- Key screens/pages
- Design preferences (colors, themes)

**5d. Implementation Phases**

- What order to build things?
- Dependencies?

## Phase 6: Success Criteria

Ask in simple terms:

> "What does 'done' look like for you? When would you consider this app complete and successful?"

Prompt for:

- Must-have functionality
- Quality expectations (polished vs functional)
- Any specific requirements

## Phase 7: Review & Approval

Present everything gathered:

1. **Summary of the app** (in plain language)
2. **Feature count**
3. **Technology choices** (whether specified or derived)
4. **Brief technical plan** (for their awareness)

First ask in conversation if they want to make changes.

**Then ask for final confirmation:**

> "Ready to generate the specification files?
>
> 1. **Yes, generate files** - Create app_spec.txt and update prompt files
> 2. **I have changes** - Let me add or modify something first"

---

# FILE GENERATION

**Note: This section is for YOU (the agent) to execute. Do not burden the user with these technical details.**

## Output Directory

The output directory is: `$ARGUMENTS/prompts/`

Once the user approves, generate these files:

## 1. Generate `app_spec.txt`

**Output path:** `$ARGUMENTS/prompts/app_spec.txt`

Create a new file using this XML structure:

```xml
<project_specification>
  <project_name>[Project Name]</project_name>

  <overview>
    [2-3 sentence description from Phase 1]
  </overview>

  <technology_stack>
    <frontend>
      <framework>[Framework]</framework>
      <styling>[Styling solution]</styling>
      [Additional frontend config]
    </frontend>
    <backend>
      <runtime>[Runtime]</runtime>
      <database>[Database]</database>
      [Additional backend config]
    </backend>
    <communication>
      <api>[API style]</api>
      [Additional communication config]
    </communication>
  </technology_stack>

  <prerequisites>
    <environment_setup>
      [Setup requirements]
    </environment_setup>
  </prerequisites>

  <feature_count>[derived count from Phase 4L]</feature_count>

  <security_and_access_control>
    <user_roles>
      <role name="[role_name]">
        <permissions>
          - [Can do X]
          - [Can see Y]
          - [Cannot access Z]
        </permissions>
        <protected_routes>
          - /admin/* (admin only)
          - /settings (authenticated users)
        </protected_routes>
      </role>
      [Repeat for each role]
    </user_roles>
    <authentication>
      <method>[email/password | social | SSO]</method>
      <session_timeout>[duration or "none"]</session_timeout>
      <password_requirements>[if applicable]</password_requirements>
    </authentication>
    <sensitive_operations>
      - [Delete account requires password confirmation]
      - [Financial actions require 2FA]
    </sensitive_operations>
  </security_and_access_control>

  <core_features>
    <[category_name]>
      - [Feature 1]
      - [Feature 2]
      - [Feature 3]
    </[category_name]>
    [Repeat for all feature categories]
  </core_features>

  <database_schema>
    <tables>
      <[table_name]>
        - [field1], [field2], [field3]
        - [additional fields]
      </[table_name]>
      [Repeat for all tables]
    </tables>
  </database_schema>

  <api_endpoints_summary>
    <[category]>
      - [VERB] /api/[path]
      - [VERB] /api/[path]
    </[category]>
    [Repeat for all categories]
  </api_endpoints_summary>

  <ui_layout>
    <main_structure>
      [Layout description]
    </main_structure>
    [Additional UI sections as needed]
  </ui_layout>

  <design_system>
    <color_palette>
      [Colors]
    </color_palette>
    <typography>
      [Font preferences]
    </typography>
  </design_system>

  <implementation_steps>
    <step number="1">
      <title>[Phase Title]</title>
      <tasks>
        - [Task 1]
        - [Task 2]
      </tasks>
    </step>
    [Repeat for all phases]
  </implementation_steps>

  <success_criteria>
    <functionality>
      [Functionality criteria]
    </functionality>
    <user_experience>
      [UX criteria]
    </user_experience>
    <technical_quality>
      [Technical criteria]
    </technical_quality>
    <design_polish>
      [Design criteria]
    </design_polish>
  </success_criteria>
</project_specification>
```

## 2. Update `initializer_prompt.md`

**Output path:** `$ARGUMENTS/prompts/initializer_prompt.md`

If the output directory has an existing `initializer_prompt.md`, read it and update the feature count.
If not, copy from `.claude/templates/initializer_prompt.template.md` first, then update.

**CRITICAL: You MUST update the feature count placeholder:**

1. Find the line containing `**[FEATURE_COUNT]**` in the "REQUIRED FEATURE COUNT" section
2. Replace `[FEATURE_COUNT]` with the exact number agreed upon in Phase 4L (e.g., `25`)
3. The result should read like: `You must create exactly **25** features using the...`

**Example edit:**
```
Before: **CRITICAL:** You must create exactly **[FEATURE_COUNT]** features using the `feature_create_bulk` tool.
After:  **CRITICAL:** You must create exactly **25** features using the `feature_create_bulk` tool.
```

**Verify the update:** After editing, read the file again to confirm the feature count appears correctly. If `[FEATURE_COUNT]` still appears in the file, the update failed and you must try again.

**Note:** You may also update `coding_prompt.md` if the user requests changes to how the coding agent should work. Include it in the status file if modified.

## 3. Write Status File (REQUIRED - Do This Last)

**Output path:** `$ARGUMENTS/prompts/.spec_status.json`

**CRITICAL:** After you have completed ALL requested file changes, write this status file to signal completion to the UI. This is required for the "Continue to Project" button to appear.

Write this JSON file:

```json
{
  "status": "complete",
  "version": 1,
  "timestamp": "[current ISO 8601 timestamp, e.g., 2025-01-15T14:30:00.000Z]",
  "files_written": [
    "prompts/app_spec.txt",
    "prompts/initializer_prompt.md"
  ],
  "feature_count": [the feature count from Phase 4L]
}
```

**Include ALL files you modified** in the `files_written` array. If the user asked you to also modify `coding_prompt.md`, include it:

```json
{
  "status": "complete",
  "version": 1,
  "timestamp": "2025-01-15T14:30:00.000Z",
  "files_written": [
    "prompts/app_spec.txt",
    "prompts/initializer_prompt.md",
    "prompts/coding_prompt.md"
  ],
  "feature_count": 35
}
```

**IMPORTANT:**
- Write this file LAST, after all other files are successfully written
- Only write it when you consider ALL requested work complete
- The UI polls this file to detect completion and show the Continue button
- If the user asks for additional changes after you've written this, you may update it again when the new changes are complete

---

# AFTER FILE GENERATION: NEXT STEPS

Once files are generated, tell the user what to do next:

> "Your specification files have been created in `$ARGUMENTS/prompts/`!
>
> **Files created:**
> - `$ARGUMENTS/prompts/app_spec.txt`
> - `$ARGUMENTS/prompts/initializer_prompt.md`
>
> The **Continue to Project** button should now appear. Click it to start the autonomous coding agent!
>
> **If you don't see the button:** Type `/exit` or click **Exit to Project** in the header.
>
> **Important timing expectations:**
>
> - **First session:** The agent generates features in the database. This takes several minutes.
> - **Subsequent sessions:** Each coding iteration takes 5-15 minutes depending on complexity.
> - **Full app:** Building all [X] features will take many hours across multiple sessions.
>
> **Controls:**
>
> - Press `Ctrl+C` to pause the agent at any time
> - Run `start.bat` (Windows) or `./start.sh` (Mac/Linux) to resume where you left off"

Replace `[X]` with their feature count.

---

# IMPORTANT REMINDERS

- **Meet users where they are**: Not everyone is technical. Ask about what they want, not how to build it.
- **Quick Mode is the default**: Most users should be able to describe their app and let you handle the technical details.
- **Derive, don't interrogate**: For non-technical users, derive database schema, API endpoints, and architecture from their feature descriptions. Don't ask them to specify these.
- **Use plain language**: Instead of "What entities need CRUD operations?", ask "What things can users create, edit, or delete?"
- **Be thorough on features**: This is where to spend time. Keep asking follow-up questions until you have a complete picture.
- **Derive feature count, don't guess**: After gathering requirements, tally up testable features yourself and present the estimate. Don't use fixed tiers or ask users to guess.
- **Validate before generating**: Present a summary including your derived feature count and get explicit approval before creating files.

---

# BEGIN

Start by greeting the user warmly. Ask ONLY the Phase 1 questions:

> "Hi! I'm here to help you create a detailed specification for your app.
>
> Let's start with the basics:
>
> 1. What do you want to call this project?
> 2. In your own words, what are you building?
> 3. Who will use it - just you, or others too?"

**STOP HERE and wait for their response.** Do not ask any other questions yet. Do not use AskUserQuestion yet. Just have a conversation about their project basics first.

After they respond, acknowledge what they said, then move to Phase 2.


Now I can see the AutoCoder create-spec prompt. Let me compare what they expect vs what we have:

**AutoCoder expects an XML format** with specific sections:
- project_specification (root)
- project_name
- overview
- technology_stack (frontend, backend, communication)
- prerequisites
- feature_count
- security_and_access_control (user_roles, authentication, sensitive_operations)
- core_features
- database_schema
- api_endpoints_summary
- ui_layout
- design_system
- implementation_steps
- success_criteria

**What we have:**
- Markdown format (not XML)
- Overview ✓
- Technology Stack ✓
- Architecture ✓
- Core Components (detailed) ✓
- Database Schema (list) ✓
- WebSocket Protocol ✓
- Current Implementation Status ✓
- Feature Targets (numbered list) ✓
- Testing Strategy ✓
- Build Commands ✓
- Environment Configuration ✓
- Notes for AutoCoder ✓

**What's missing or could be improved:**

1. **Format**: AutoCoder expects XML, but our spec is Markdown. This might be okay since the initializer agent reads it, but we should check.

2. **Feature Count**: We have 159 features listed but no explicit `<feature_count>159</feature_count>` tag.

3. **Security and Access Control Section**: We mention auth but don't have a dedicated security section with:
   - User roles and permissions
   - Authentication methods
   - Protected routes
   - Sensitive operations

4. **API Endpoints Summary**: We describe what the server does but don't have a clean list of endpoints.

5. **UI Layout**: We describe dashboard pages but not the layout structure.

6. **Design System**: Missing color palette, typography preferences.

7. **Implementation Steps**: We have current status but not a phased implementation plan.

8. **Success Criteria**: What does "done" look like?

9. **Prerequisites/Environment Setup**: Partially covered but not in a structured way.

I'll focus on the environment setup and prerequisites. We need a clear, step-by-step guide for developers to set up the project locally. This includes system requirements, necessary tools, configuration steps, and potential troubleshooting tips. A comprehensive prerequisites section will help new team members quickly get started and reduce onboarding friction.


Good idea! Comparing our spec to AutoCoder's expected format, there are some gaps:

## AutoCoder expects XML format with these sections:

| Section | Our Status |
|---------|------------|
| `<project_name>` | ✓ Have it |
| `<overview>` | ✓ Have it |
| `<technology_stack>` | ✓ Have it |
| `<feature_count>` | ⚠ Listed 159 but no explicit count |
| `<security_and_access_control>` | ⚠ Mentioned but not detailed |
| `<core_features>` | ✓ Have it |
| `<database_schema>` | ✓ Have it (list) |
| `<api_endpoints_summary>` | ⚠ Described but not listed |
| `<ui_layout>` | ⚠ Pages listed, structure missing |
| `<design_system>` | ❌ Missing (colors, typography) |
| `<implementation_steps>` | ❌ Missing (phased plan) |
| `<success_criteria>` | ❌ Missing |
| `<prerequisites>` | ⚠ Partial |

## Key discussions needed:

1. **Format** - Should we convert to XML, or is Markdown okay for your existing project?

2. **Security & Access Control** - We should detail:
   - User roles (admin, org_admin, tech, user)
   - What each role can do/see
   - Protected routes
   - Sensitive operations requiring confirmation

3. **Design System** - What's the look/feel?
   - Color palette
   - Typography
   - Dark mode (you mentioned it)

4. **Implementation Steps** - Phased build order:
   - What's Phase 1 vs Phase 2 vs Phase 3?
   - Dependencies between features?

5. **Success Criteria** - What does "done" look like?
   - MVP threshold?
   - Quality expectations?

Would you like to discuss any of these? Or should I update the spec with sensible defaults based on what's already built?


update with sensible defaults


The user wants me to update the app_spec.txt with sensible defaults for the missing sections. Let me add:

1. Explicit feature count
2. Security & Access Control section (based on what's already in the codebase)
3. Design System (modern, clean, dark mode support)
4. Implementation Steps (phased based on the existing roadmap)
5. Success Criteria
6. Better prerequisites section

I'll keep it in Markdown format since the existing project already uses Markdown and the initializer agent can parse it. I'll add these sections to the existing file.


     1→# GuruRMM - Remote Monitoring and Management System
     2→
     3→## Overview
     4→
     5→GuruRMM is a production-grade, open-source Remote Monitoring and Management (RMM) system designed for Managed Service Providers (MSPs). It enables IT professionals to monitor, manage, and maintain client endpoints remotely through a centralized dashboard.
     6→
     7→**Built by an MSP, for MSPs** - Created by an MSP owner with 25+ years of experience who understands the pain points of existing tools.
     8→
     9→## Vision: The Guru Suite
    10→
    11→GuruRMM is part of a larger vision - a complete suite of natively integrated MSP tools:
    12→
    13→```
    14→┌─────────────────────────────────────────────────────────────────┐
    15→│                    GURU SUITE PLATFORM                          │
    16→│         (Shared data layer, unified authentication,             │
    17→│          consistent UX, native integrations)                    │
    18→├─────────────────┬─────────────────┬─────────────────────────────┤
    19→│   GuruRMM       │    GuruPSA      │   Future Products           │
    20→│   (This build)  │   (Parallel)    │                             │
    21→├─────────────────┼─────────────────┼─────────────────────────────┤
    22→│ • Monitoring    │ • Ticketing     │ • Remote Control Platform   │
    23→│ • Patch Mgmt    │ • Billing       │ • AV / EDR                  │
    24→│ • Automation    │ • Contracts     │ • Backup Monitoring         │
    25→│ • Policies      │ • Time Tracking │ • Network Monitoring        │
    26→│ • Alerting      │ • CRM           │ • Documentation/Wiki        │
    27→│ • Scripting     │ • Reporting     │ • Asset Management          │
    28→│ • Deployment    │ • Portal        │ • Mobile Device Mgmt        │
    29→└─────────────────┴─────────────────┴─────────────────────────────┘
    30→```
    31→
    32→## Key Differentiators
    33→
    34→**Philosophy: "No half-measures, excellence in all categories"**
    35→
    36→1. **Native Integration** - No bolted-on feel, everything shares context
    37→2. **Modern UX** - Fewer clicks, intuitive navigation
    38→3. **Deep RMM Capabilities** - Enterprise-grade monitoring
    39→4. **Flexible Policies** - Better than competitors' frustrating policy management
    40→5. **Emergency Response / Lockdown Mode** - Unique incident response feature
    41→
    42→### Competitive Pain Points to Address
    43→
    44→**From SyncroRMM:**
    45→- Lacks depth in monitoring capabilities
    46→- No process monitoring
    47→- No Event Log monitoring
    48→- No lockdown mode
    49→- Limited advanced automation
    50→
    51→**From DattoRMM:**
    52→- Too many clicks to accomplish tasks
    53→- Unintuitive navigation
    54→- Frustrating policy management
    55→- Dated UI design
    56→
    57→## Lockdown Mode (Unique Feature)
    58→
    59→A critical security incident response capability:
    60→
    61→**Capabilities:**
    62→- Kill all network communication except RMM management traffic
    63→- Blacklist applications/programs
    64→- Force infection into submission
    65→- Evidence preservation during incident
    66→
    67→**Tiered Escalation:**
    68→- Single machine lockdown
    69→- Site-wide lockdown
    70→- Client-wide lockdown
    71→- Global lockdown (all endpoints)
    72→
    73→**Use Cases:**
    74→- Ransomware containment
    75→- Active breach response
    76→- Malware isolation
    77→- Forensic preservation
    78→
    79→## Technology Stack
    80→
    81→- **Agent:** Rust (cross-platform: Windows, Linux, macOS)
    82→- **Server:** Rust with Axum web framework
    83→- **Dashboard:** React 19 + TypeScript + Vite
    84→- **Database:** PostgreSQL 16
    85→- **Communication:** WebSocket (real-time), REST API
    86→- **Styling:** Tailwind CSS 4.1
    87→- **Authentication:** JWT tokens + API keys + SSO (Microsoft Entra ID)
    88→
    89→## Architecture
    90→
    91→```
    92→Endpoints (Windows/Linux/macOS)
    93→    │
    94→    │ WebSocket (TLS)
    95→    ▼
    96→┌─────────────────┐
    97→│  Rust Server    │◄──── REST API ────► React Dashboard
    98→│  (Axum)         │
    99→└────────┬────────┘
   100→         │
   101→         ▼
   102→    PostgreSQL
   103→```
   104→
   105→## Core Components
   106→
   107→### 1. Agent (Rust Binary)
   108→**Location:** `agent/`
   109→
   110→The agent runs on managed endpoints and provides:
   111→
   112→**Metrics Collection:**
   113→- CPU usage percentage
   114→- Memory usage (percent, used/total bytes)
   115→- Disk usage (percent, used/total bytes, per-disk)
   116→- Network throughput (RX/TX bytes)
   117→- System uptime and boot time
   118→- OS type and version
   119→- Hostname and device ID
   120→- Logged-in user and idle time
   121→- Public/WAN IP address
   122→- Temperature sensors (CPU, GPU, all available)
   123→- Network interfaces (local IPs)
   124→
   125→**Command Execution:**
   126→- PowerShell execution (Windows)
   127→- Bash execution (Linux/macOS)
   128→- Exit code, stdout, stderr capture
   129→- Result streaming back to server
   130→
   131→**Service Watchdog:**
   132→- Monitor specified Windows/Linux services
   133→- Track service restart events
   134→- Alert on service failures
   135→- Auto-restart capability (configurable via policy)
   136→
   137→**Self-Update System:**
   138→- Download updates from server
   139→- SHA256 checksum verification
   140→- Atomic binary replacement
   141→- Auto-rollback on connection failure
   142→
   143→**Windows System Tray:**
   144→- Status indicator icon (green/yellow/red/gray)
   145→- IPC via named pipes
   146→- Support ticket creation form
   147→- Screenshot capture for tickets
   148→- Connection status display
   149→
   150→**Platform Support:**
   151→- Windows 10/11, Server 2016+ (native service)
   152→- Windows 7, Server 2008 R2 (legacy mode via NSSM)
   153→- Linux (systemd service)
   154→- macOS (launchd - planned)
   155→
   156→### 2. Server (Rust/Axum)
   157→**Location:** `server/`
   158→
   159→The server provides:
   160→
   161→**API Endpoints:**
   162→- Authentication (login, register, SSO callbacks)
   163→- User management (CRUD, role assignment)
   164→- Client/Organization management
   165→- Site management (codes, API keys)
   166→- Agent management (registration, status, updates)
   167→- Metrics retrieval and aggregation
   168→- Command execution and history
   169→- Policy management (CRUD, assignments)
   170→- Alert management (thresholds, acknowledgment)
   171→
   172→**Real-Time Communication:**
   173→- WebSocket endpoint for agent connections
   174→- Connection pooling and state tracking
   175→- Message dispatch to online agents
   176→- Heartbeat monitoring
   177→
   178→**Authentication & Authorization:**
   179→- JWT token-based auth for dashboard users
   180→- API key authentication for agents
   181→- Multi-tenant authorization (organizations)
   182→- Role-based access control (admin, org_admin, org_user, tech)
   183→- Microsoft Entra ID SSO integration
   184→
   185→**Policy System:**
   186→- Stackable policies (JSON configuration)
   187→- Priority-based merge logic
   188→- Assignments at client/site/agent level
   189→- Policy templates for common configurations
   190→
   191→**Alert System:**
   192→- Threshold-based alert triggering
   193→- Duration-based alerts (e.g., CPU > 80% for 5 minutes)
   194→- Severity levels (info, warning, critical)
   195→- Alert deduplication
   196→- Acknowledgment and resolution workflow
   197→
   198→**Update Management:**
   199→- Version scanning and storage
   200→- Update packaging and distribution
   201→- On-demand update triggers
   202→
   203→### 3. Dashboard (React + TypeScript)
   204→**Location:** `dashboard/`
   205→
   206→The dashboard provides:
   207→
   208→**Pages:**
   209→- Login/Register with SSO support
   210→- Dashboard overview with summary stats
   211→- Agents list with status indicators
   212→- Agent detail with metrics charts
   213→- Clients management
   214→- Sites management with codes and API keys
   215→- Commands execution and history
   216→- Alerts management
   217→- Settings (user, organization)
   218→
   219→**Features:**
   220→- Real-time metric visualization (Recharts)
   221→- Agent status indicators (online/offline)
   222→- Command execution interface
   223→- Protected routes with JWT auth
   224→- Responsive design
   225→
   226→## Database Schema
   227→
   228→**Core Tables:**
   229→- `agents` - Endpoint devices with status tracking
   230→- `metrics` - Time-series system metrics
   231→- `agent_state` - Latest agent snapshots
   232→- `users` - Dashboard users with roles
   233→- `user_organizations` - Multi-tenant user mapping
   234→- `clients` - Organizations/companies
   235→- `sites` - Locations under clients
   236→- `commands` - Executed commands with results
   237→- `watchdog_events` - Service monitoring events
   238→- `policies` - Configuration templates
   239→- `policy_assignments` - Policy-to-target mappings
   240→- `alerts` - Threshold violation alerts
   241→- `alert_threshold_state` - Duration-based tracking
   242→
   243→## WebSocket Protocol
   244→
   245→**Agent → Server:**
   246→- Auth (initial authentication)
   247→- Metrics (periodic submission)
   248→- NetworkState (interface updates)
   249→- CommandResult (execution results)
   250→- WatchdogEvent (service status)
   251→- UpdateResult (update completion)
   252→- Heartbeat (keep-alive)
   253→
   254→**Server → Agent:**
   255→- AuthAck (authentication response)
   256→- Command (execute on agent)
   257→- ConfigUpdate (push configuration)
   258→- Update (trigger update)
   259→- Ack/Error (responses)
   260→
   261→## Current Implementation Status
   262→
   263→**Completed:**
   264→- Multi-client/multi-site architecture
   265→- Agent registration and management
   266→- Real-time metrics collection
   267→- Command execution (PowerShell, Bash)
   268→- Service watchdog monitoring
   269→- Alert system with thresholds
   270→- Policy-based configuration
   271→- Multi-tenant authorization
   272→- SSO authentication (Entra ID)
   273→- Windows system tray integration
   274→- Self-update mechanism
   275→- Temperature monitoring
   276→
   277→**In Progress:**
   278→- Cross-platform agent builds (Linux/Windows/macOS)
   279→- Extended metrics on build server
   280→
   281→## Feature Targets (100+ features)
   282→
   283→### Agent Features - Core Monitoring
   284→1. CPU metrics collection and reporting
   285→2. Memory metrics collection and reporting
   286→3. Disk metrics collection (all drives)
   287→4. Network throughput monitoring
   288→5. System uptime tracking
   289→6. OS information collection
   290→7. Temperature sensor monitoring
   291→8. Public IP detection
   292→9. Network interface enumeration
   293→10. User idle time tracking
   294→
   295→### Agent Features - Process Monitoring
   296→11. Running process enumeration
   297→12. Process CPU/memory usage tracking
   298→13. Process start/stop detection
   299→14. Process blacklist/whitelist enforcement
   300→15. Suspicious process alerting
   301→
   302→### Agent Features - Event Log Monitoring
   303→16. Windows Event Log collection
   304→17. Linux syslog/journald collection
   305→18. Event filtering by severity
   306→19. Event pattern matching
   307→20. Security event alerting
   308→
   309→### Agent Features - Command Execution
   310→21. PowerShell command execution
   311→22. Bash command execution
   312→23. Command result streaming
   313→24. Script library execution
   314→25. Scheduled script execution
   315→
   316→### Agent Features - Service Management
   317→26. Service watchdog monitoring
   318→27. Service auto-restart capability
   319→28. Service status reporting
   320→29. Service start/stop commands
   321→30. Service dependency tracking
   322→
   323→### Agent Features - Self-Management
   324→31. Self-update download and verification
   325→32. Atomic update installation
   326→33. Update rollback on failure
   327→34. Configuration hot-reload
   328→35. Diagnostic logging
   329→
   330→### Agent Features - Platform Support
   331→36. Windows service installation
   332→37. Linux systemd service installation
   333→38. macOS launchd installation
   334→39. Legacy Windows support (2008 R2)
   335→40. ARM64 support
   336→
   337→### Agent Features - User Interface
   338→41. Windows tray icon display
   339→42. Tray connection status indicator
   340→43. Tray support ticket form
   341→44. Screenshot capture for tickets
   342→45. IPC named pipe server
   343→
   344→### Agent Features - Communication
   345→46. WebSocket connection management
   346→47. Heartbeat mechanism
   347→48. Reconnection with backoff
   348→49. TLS certificate handling
   349→50. Message queuing (offline support)
   350→
   351→### Agent Features - Lockdown Mode
   352→51. Network firewall control (block all except RMM)
   353→52. Application blacklist enforcement
   354→53. Process termination by policy
   355→54. USB device blocking
   356→55. Lockdown status reporting
   357→56. Evidence preservation (snapshot)
   358→57. Lockdown release mechanism
   359→
   360→### Server Features - Authentication
   361→58. Agent registration endpoint
   362→59. JWT authentication
   363→60. API key authentication
   364→61. SSO integration (Entra ID)
   365→62. Multi-factor authentication support
   366→63. Session management
   367→
   368→### Server Features - Authorization
   369→64. Multi-tenant authorization
   370→65. Role-based access control
   371→66. Organization-level permissions
   372→67. Resource-level permissions
   373→68. API rate limiting
   374→
   375→### Server Features - Client/Site Management
   376→69. Client CRUD operations
   377→70. Site CRUD operations
   378→71. Site code generation
   379→72. API key rotation
   380→73. Client/Site hierarchy
   381→
   382→### Server Features - Agent Management
   383→74. Agent listing and filtering
   384→75. Agent status tracking
   385→76. Agent grouping/tagging
   386→77. Bulk agent operations
   387→78. Agent deletion/decommission
   388→
   389→### Server Features - Metrics & Data
   390→79. Metrics storage and retrieval
   391→80. Metrics time-range queries
   392→81. Metrics aggregation
   393→82. Data retention policies
   394→83. Metrics export
   395→
   396→### Server Features - Commands
   397→84. Command dispatch via WebSocket
   398→85. Command history storage
   399→86. Command templates/library
   400→87. Scheduled commands
   401→88. Bulk command execution
   402→
   403→### Server Features - Policies
   404→89. Policy CRUD operations
   405→90. Policy assignment management
   406→91. Policy merge evaluation
   407→92. Policy templates
   408→93. Policy versioning
   409→
   410→### Server Features - Alerts
   411→94. Alert threshold evaluation
   412→95. Duration-based alert logic
   413→96. Alert acknowledgment workflow
   414→97. Alert resolution workflow
   415→98. Alert escalation rules
   416→99. Alert notification (email/webhook)
   417→
   418→### Server Features - Lockdown Mode
   419→100. Lockdown trigger endpoint
   420→101. Tiered lockdown (machine/site/client/global)
   421→102. Lockdown status dashboard
   422→103. Lockdown audit logging
   423→104. Emergency lockdown broadcast
   424→
   425→### Server Features - Updates
   426→105. Update version scanning
   427→106. Update trigger endpoint
   428→107. Update rollout policies
   429→108. Update status tracking
   430→
   431→### Server Features - Infrastructure
   432→109. WebSocket connection pooling
   433→110. Heartbeat monitoring
   434→111. Agent timeout detection
   435→112. Organization limits enforcement
   436→113. Audit logging
   437→
   438→### Dashboard Features - Authentication
   439→114. Login page with form validation
   440→115. Registration page
   441→116. SSO redirect handling
   442→117. Password reset flow
   443→118. MFA setup page
   444→
   445→### Dashboard Features - Overview
   446→119. Dashboard overview page
   447→120. Summary statistics widgets
   448→121. Recent alerts widget
   449→122. Agent status summary
   450→123. Quick actions panel
   451→
   452→### Dashboard Features - Agent Management
   453→124. Agents list with status
   454→125. Agent detail with metrics
   455→126. Metrics charts (Recharts)
   456→127. Agent actions menu
   457→128. Agent bulk selection
   458→
   459→### Dashboard Features - Client/Site
   460→129. Client management page
   461→130. Site management page
   462→131. Site code display
   463→132. API key regeneration UI
   464→133. Client/Site tree view
   465→
   466→### Dashboard Features - Commands
   467→134. Command execution form
   468→135. Command history display
   469→136. Script library browser
   470→137. Command output viewer
   471→138. Bulk command UI
   472→
   473→### Dashboard Features - Alerts
   474→139. Alert listing page
   475→140. Alert acknowledgment UI
   476→141. Alert detail view
   477→142. Alert filtering/search
   478→143. Alert notification settings
   479→
   480→### Dashboard Features - Lockdown
   481→144. Lockdown control panel
   482→145. Lockdown status indicators
   483→146. Lockdown history/audit
   484→147. Emergency lockdown button
   485→148. Lockdown release confirmation
   486→
   487→### Dashboard Features - Settings
   488→149. Settings page
   489→150. Organization management
   490→151. User management
   491→152. Policy editor
   492→153. Notification preferences
   493→
   494→### Dashboard Features - UX
   495→154. Responsive mobile layout
   496→155. Protected route guards
   497→156. Session management
   498→157. Keyboard shortcuts
   499→158. Dark mode support
   500→159. Minimal-click workflows
   501→
   502→## Testing Strategy
   503→
   504→Each feature should include:
   505→- Unit tests for core logic
   506→- Integration tests for API endpoints
   507→- E2E tests for critical user flows
   508→
   509→**Test Commands:**
   510→- Agent: `cargo test` in `agent/`
   511→- Server: `cargo test` in `server/`
   512→- Dashboard: `npm test` in `dashboard/`
   513→
   514→## Build Commands
   515→
   516→**Agent:**
   517→```bash
   518→cd agent
   519→cargo build --release
   520→# Cross-compile for Windows from Linux:
   521→cargo build --release --target x86_64-pc-windows-gnu
   522→```
   523→
   524→**Server:**
   525→```bash
   526→cd server
   527→cargo build --release
   528→```
   529→
   530→**Dashboard:**
   531→```bash
   532→cd dashboard
   533→npm install
   534→npm run build
   535→```
   536→
   537→## Environment Configuration
   538→
   539→**Server (.env):**
   540→- DATABASE_URL - PostgreSQL connection string
   541→- JWT_SECRET - Token signing secret
   542→- CORS_ORIGINS - Allowed dashboard origins
   543→- SSO_CLIENT_ID - Entra ID client
   544→- SSO_CLIENT_SECRET - Entra ID secret
   545→
   546→**Agent (config.toml):**
   547→- server_url - API endpoint
   548→- site_code - Registration code
   549→- api_key - Authentication key
   550→
   551→## External Dependencies
   552→
   553→**Server:** Axum, Tokio, SQLx, jsonwebtoken, oauth2
   554→**Agent:** Tokio, sysinfo, tokio-tungstenite, windows-service
   555→**Dashboard:** React, React Query, Axios, Recharts, Tailwind
   556→
   557→## Notes for AutoCoder
   558→
   559→1. The project uses Rust 2021 edition
   560→2. SQLx requires DATABASE_URL at compile time for query checking
   561→3. Agent must handle graceful shutdown for service managers
   562→4. WebSocket messages use JSON serialization
   563→5. All timestamps should be UTC
   564→6. Passwords are hashed with bcrypt
   565→7. API keys are hashed (SHA256) before storage
   566→8. Site codes are human-readable (e.g., "BLUE-TIGER-4829")
   567→

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

# GuruRMM - Remote Monitoring and Management System

## Overview

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

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

## Vision: The Guru Suite

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

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

## Key Differentiators

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

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

### Competitive Pain Points to Address

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

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

## Lockdown Mode (Unique Feature)

A critical security incident response capability:

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

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

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

## Technology Stack

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

## Architecture

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

## Core Components

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

The agent runs on managed endpoints and provides:

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

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

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

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

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

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

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

The server provides:

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

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

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

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

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

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

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

The dashboard provides:

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

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

## Database Schema

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

## WebSocket Protocol

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

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

## Current Implementation Status

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

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

## Feature Targets (100+ features)

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

## Testing Strategy

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

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

## Build Commands

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

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

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

## Environment Configuration

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

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

## External Dependencies

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

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


Now I need to add the missing sections with sensible defaults:
1. Feature Count (explicit)
2. Security and Access Control (detailed)
3. API Endpoints Summary
4. UI Layout
5. Design System
6. Implementation Steps
7. Success Criteria
8. Prerequisites

I'll add these after the Notes for AutoCoder section or integrate them into appropriate places. Let me add them in a logical order.


Edit

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

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