# Phase 2.5: Personal Tree Branching & Step Library

> **Status:** Planned (to begin after Phase 2 completion)  
> **Timeline:** Weeks 7-8  
> **Dependencies:** Phase 2 Tree Editor, Session History, User Permissions

---

## Overview

This feature allows users to customize their troubleshooting experience without modifying official trees. Users can add custom steps during active sessions, save modified trees as personal versions, and pull reusable steps from a shared library.

**Key Principle:** Non-destructive customization. Original trees remain untouched while users build personalized workflows.

---

## Feature Specification

### 10. Personal Tree Branching

**Description:** Allow users to insert custom steps during an active troubleshooting session, then optionally save the modified tree as their own version.

**User Flow:**
1. User navigates an official tree
2. At any decision point, clicks "+ Add Custom Step"
3. Chooses to type a custom step OR select from Step Library
4. Custom step is inserted into their session only
5. Session continues with custom step included
6. Export includes all custom steps with clear marking
7. After session, user is prompted to save as personal tree (optional)

**UI Components:**
- **Add Custom Step Button:** Appears at each decision node
- **Step Creation Modal:**
  - Tab 1: "Type My Own" - free-form step creation
  - Tab 2: "Browse Library" - searchable step repository
- **Custom Step Indicator:** Visual badge showing step is user-added
- **Save as Tree Prompt:** Post-session dialog to save modifications

**Custom Step Creation Form:**
```
┌─────────────────────────────────────────────────────────────┐
│ ADD CUSTOM STEP                                    [X Close]│
├─────────────────────────────────────────────────────────────┤
│ [Type My Own]  [Browse Library]                             │
├─────────────────────────────────────────────────────────────┤
│                                                             │
│ Step Type:  ○ Decision (Yes/No question)                    │
│             ○ Action (Task to perform)                      │
│             ○ Resolution (Issue resolved)                   │
│                                                             │
│ Title/Question: ________________________________________    │
│                                                             │
│ Help Text (optional):                                       │
│ ┌─────────────────────────────────────────────────────┐    │
│ │                                                     │    │
│ └─────────────────────────────────────────────────────┘    │
│                                                             │
│ Commands/Scripts (optional):                                │
│ ┌─────────────────────────────────────────────────────┐    │
│ │ Get-Service BrokerAgent | Restart-Service           │    │
│ └─────────────────────────────────────────────────────┘    │
│                                                             │
│ □ Save to My Step Library for reuse                         │
│                                                             │
│                              [Cancel]  [Insert Step]        │
└─────────────────────────────────────────────────────────────┘
```

**Technical Requirements:**
- Custom steps stored separately from original tree structure
- Session tracks insertion points (after which node)
- Export template handles custom step rendering
- Tree fork creates deep copy with user as owner
- Forked trees maintain reference to original (for analytics)

**Edge Cases:**
- Original tree updated after fork → Notify user, offer to merge changes
- User deletes custom step mid-session → Remove from session, continue
- Circular reference from custom step → Validate before insertion
- Custom step at terminal node → Allow, becomes new branch

---

### 11. Step Library

**Description:** A repository of reusable troubleshooting steps that users can pull into any session, organized by visibility, categories, tags, and user ratings.

**Library Hierarchy:**
```
Step Library
├── My Steps (private to user)
├── Team Steps (visible to team members)
├── Admin Curated (org-wide, managed by admins)
└── Community Steps (public, user-contributed, rated by users)
```

**Features:**
- **Search & Filter:**
  - Full-text search across titles, descriptions, commands
  - Filter by step type (decision, action, resolution)
  - Filter by category (admin-managed)
  - Filter by tags (user-defined)
  - Filter by visibility level
  - Filter by minimum rating (e.g., 4+ stars)
  - Sort by: recent, popular, highest rated, most used
- **Step Preview:**
  - View full step details before inserting
  - See usage count and rating breakdown
  - View author, creation date, and last updated
  - See category and tags
- **Step Management:**
  - Create new steps (saved to "My Steps")
  - Assign category and add tags during creation
  - Edit own steps
  - Delete own steps
  - Promote to Team (if permitted)
  - Submit to Community (requires approval)
- **Admin Controls:**
  - Approve/reject community submissions
  - Curate "Admin Curated" collection
  - Manage categories (create, rename, archive)
  - Set default visibility for new steps
  - Moderate inappropriate content

---

#### Categories (Admin-Managed)

Categories provide structured organization for steps. Admins define and manage categories to ensure consistency.

**Default Categories:**
| Category | Description |
|----------|-------------|
| Citrix / VDI | Virtual desktop, XenApp, XenDesktop, VDA issues |
| Active Directory | AD, LDAP, Group Policy, authentication |
| Microsoft 365 | Exchange Online, Teams, SharePoint, OneDrive |
| Networking | DNS, DHCP, VPN, firewall, connectivity |
| File Services | File shares, permissions, DFS, storage |
| Printing | Print servers, drivers, spooler issues |
| Backup & Recovery | Backup software, disaster recovery, restore |
| Security | Antivirus, permissions, security incidents |
| Hardware | Servers, workstations, peripherals |
| Other | Miscellaneous steps |

**Category Management (Admin UI):**
```
┌─────────────────────────────────────────────────────────────┐
│ MANAGE CATEGORIES                                  [+ Add]  │
├─────────────────────────────────────────────────────────────┤
│ Category              │ Steps │ Status   │ Actions         │
├───────────────────────┼───────┼──────────┼─────────────────┤
│ Citrix / VDI          │ 24    │ Active   │ [Edit] [Archive]│
│ Active Directory      │ 18    │ Active   │ [Edit] [Archive]│
│ Microsoft 365         │ 31    │ Active   │ [Edit] [Archive]│
│ Networking            │ 15    │ Active   │ [Edit] [Archive]│
│ Legacy Systems        │ 3     │ Archived │ [Restore]       │
└─────────────────────────────────────────────────────────────┘
```

---

#### Tags (User-Defined)

Tags provide flexible, user-driven organization. Users can create and apply tags freely.

**Tag Characteristics:**
- Created by any user when adding/editing a step
- Lowercase, alphanumeric with hyphens (e.g., `vda-registration`, `powershell`)
- Auto-suggest existing tags while typing
- Popular tags shown as quick-filters
- No limit on tags per step (recommended: 3-5)

**Popular Tags Example:**
`powershell` `quick-fix` `restart-service` `diagnostic` `permissions` `dns` `vpn` `cache-clear` `registry` `group-policy`

---

#### User Ratings & Reviews

Public and team steps can be rated by users to help surface the most helpful content.

**Rating System:**
- **Star Rating:** 1-5 stars (required when rating)
- **Helpful Vote:** Quick "Was this helpful?" Yes/No after using a step
- **Written Review:** Optional text feedback (max 500 chars)
- **One rating per user per step** (can update rating later)

**Rating Display:**
```
⭐⭐⭐⭐⭐ 4.7 (128 ratings)
├── 5 stars: ████████████████░░░░ 78%
├── 4 stars: ████░░░░░░░░░░░░░░░░ 15%
├── 3 stars: █░░░░░░░░░░░░░░░░░░░ 4%
├── 2 stars: ░░░░░░░░░░░░░░░░░░░░ 2%
└── 1 star:  ░░░░░░░░░░░░░░░░░░░░ 1%

👍 94% found this helpful (156 votes)
```

**Review Display:**
```
┌─────────────────────────────────────────────────────────────┐
│ ⭐⭐⭐⭐⭐ "Saved me hours of troubleshooting!"              │
│ @SarahM • Jan 20, 2026 • Verified Use                       │
├─────────────────────────────────────────────────────────────┤
│ ⭐⭐⭐⭐☆ "Good step, but needed to modify for our env"     │
│ @TechJohn • Jan 18, 2026 • Verified Use                     │
└─────────────────────────────────────────────────────────────┘
```

**Rating Rules:**
- Only users who have actually used the step can rate it ("Verified Use" badge)
- Step author cannot rate their own step
- Ratings update the step's average in real-time
- Steps with <5 ratings show "Not enough ratings" instead of average
- Admin can remove abusive reviews

---

**Step Library Browser UI:**
```
┌─────────────────────────────────────────────────────────────┐
│ STEP LIBRARY                                       [X Close]│
├─────────────────────────────────────────────────────────────┤
│ Search: [_________________________] [🔍]                    │
│                                                             │
│ Category: [All Categories ▼]  Type: [All Types ▼]           │
│ Source:   [All Sources ▼]     Min Rating: [Any ▼]           │
│                                                             │
│ Popular Tags: [powershell] [quick-fix] [diagnostic] [dns]   │
├─────────────────────────────────────────────────────────────┤
│                                                             │
│ ┌─ MY STEPS (3) ──────────────────────────────────────────┐│
│ │ ⚡ Check Event Viewer for Citrix Errors                 ││
│ │    Action • Citrix / VDI • Used 12 times                ││
│ │    Tags: citrix, event-viewer, vda                      ││
│ │                                                [Insert] ││
│ └─────────────────────────────────────────────────────────┘│
│                                                             │
│ ┌─ TEAM STEPS (12) ───────────────────────────────────────┐│
│ │ ⚡ Clear Teams Cache                                    ││
│ │    Action • Microsoft 365 • By Sarah M.                 ││
│ │    ⭐ 4.8 (23 ratings) • 👍 96% helpful                 ││
│ │    Tags: teams, cache-clear, quick-fix                  ││
│ │                                                [Insert] ││
│ └─────────────────────────────────────────────────────────┘│
│                                                             │
│ ┌─ COMMUNITY (47) ────────────────────────────────────────┐│
│ │ ⚡ Reset Windows Update Components                      ││
│ │    Action • Security • By @yourMSP                      ││
│ │    ⭐ 4.9 (1.2k ratings) • 👍 98% helpful • 🔥 Popular  ││
│ │    Tags: windows-update, powershell, fix                ││
│ │                                       [Preview] [Insert]││
│ └─────────────────────────────────────────────────────────┘│
│                                                             │
│                                    [+ Create New Step]      │
└─────────────────────────────────────────────────────────────┘
```

**Step Detail / Preview Modal:**
```
┌─────────────────────────────────────────────────────────────┐
│ STEP DETAILS                                       [X Close]│
├─────────────────────────────────────────────────────────────┤
│ ⚡ Reset Windows Update Components                          │
│                                                             │
│ Category: Security                                          │
│ Tags: [windows-update] [powershell] [fix] [troubleshooting] │
│                                                             │
│ ⭐⭐⭐⭐⭐ 4.9 (1,247 ratings) • 👍 98% found helpful       │
│ Used 3,842 times • By @yourMSP • Created Nov 12, 2025       │
├─────────────────────────────────────────────────────────────┤
│ INSTRUCTIONS:                                               │
│ This script stops Windows Update services, clears the       │
│ download cache, and restarts the services.                  │
│                                                             │
│ COMMANDS:                                                   │
│ ┌─────────────────────────────────────────────────────────┐│
│ │ # Run as Administrator                                  ││
│ │ Stop-Service wuauserv, bits, cryptsvc -Force            ││
│ │ Remove-Item $env:systemroot\SoftwareDistribution -Rec.. ││
│ │ Start-Service wuauserv, bits, cryptsvc                  ││
│ └─────────────────────────────────────────────────────────┘│
│                                              [📋 Copy]      │
│                                                             │
│ HELP TEXT:                                                  │
│ Run this when Windows Update is stuck or showing errors.    │
│ May require a reboot after running.                         │
├─────────────────────────────────────────────────────────────┤
│ TOP REVIEWS:                                                │
│ ⭐⭐⭐⭐⭐ "Fixed a month-long update issue!" - @ITpro      │
│ ⭐⭐⭐⭐☆ "Works great, added a reboot step" - @helpdesk   │
│                                        [See all 89 reviews] │
├─────────────────────────────────────────────────────────────┤
│                              [Cancel]  [Insert Into Session]│
└─────────────────────────────────────────────────────────────┘
```

---

**Data Structure:**
```json
{
  "step_id": "step_abc123",
  "title": "Check Event Viewer for Citrix Errors",
  "step_type": "action",
  "content": {
    "instructions": "Open Event Viewer and navigate to Applications and Services Logs > Citrix",
    "help_text": "Look for errors in the last 30 minutes that coincide with the reported issue time",
    "commands": [
      {
        "label": "Open Event Viewer",
        "command": "eventvwr.msc",
        "type": "run"
      },
      {
        "label": "PowerShell - Get Citrix Errors",
        "command": "Get-WinEvent -LogName 'Citrix-*' -MaxEvents 50 | Where-Object {$_.LevelDisplayName -eq 'Error'}",
        "type": "powershell"
      }
    ],
    "documentation_links": [
      {
        "title": "Citrix Event Log Reference",
        "url": "https://docs.citrix.com/...",
        "type": "vendor_docs"
      }
    ]
  },
  "organization": {
    "category_id": "cat_citrix_vdi",
    "category_name": "Citrix / VDI",
    "tags": ["citrix", "event-viewer", "vda", "diagnostics"]
  },
  "ratings": {
    "average": 4.7,
    "count": 128,
    "distribution": {
      "5": 100,
      "4": 19,
      "3": 5,
      "2": 3,
      "1": 1
    },
    "helpful_yes": 147,
    "helpful_no": 9,
    "helpful_percentage": 94
  },
  "metadata": {
    "created_by": "user_123",
    "author_display_name": "@MichaelC",
    "created_at": "2026-01-15T10:30:00Z",
    "updated_at": "2026-01-20T14:15:00Z",
    "visibility": "public",
    "team_id": null,
    "usage_count": 342,
    "is_featured": false,
    "is_verified": true
  }
}
```

---

### 12. Personal Tree Management

**Description:** Users can save, organize, and share their customized tree versions.

**Features:**
- **My Trees Dashboard:**
  - List of user's forked/custom trees
  - Original tree reference (if forked)
  - Last used date
  - Quick actions (edit, share, delete)
- **Tree Forking:**
  - Fork from any tree user has access to
  - Fork from another user's shared tree (fork of fork)
  - Maintain lineage tracking
- **Sharing Options:**
  - Private (only me)
  - Share via link (anyone with link)
  - Share with team
  - Make public (community)
- **Version Awareness:**
  - Notification when original tree is updated
  - Diff view showing changes
  - Option to merge updates into fork
  - Option to ignore updates

**My Trees UI:**
```
┌─────────────────────────────────────────────────────────────┐
│ MY CUSTOM TREES                           [+ Create New]    │
├─────────────────────────────────────────────────────────────┤
│                                                             │
│ ┌─────────────────────────────────────────────────────────┐│
│ │ 🌲 Citrix VDA - Warner Robins Specific                  ││
│ │    Forked from: Citrix VDA Not Registering (Official)   ││
│ │    Modified: 3 custom steps added                       ││
│ │    Last used: 2 days ago • Used 8 times                 ││
│ │    Sharing: 🔒 Private                                  ││
│ │                                                         ││
│ │    [▶ Start Session]  [✏️ Edit]  [🔗 Share]  [🗑️]      ││
│ │                                                         ││
│ │    ⚠️ Original tree updated 1 day ago [View Changes]    ││
│ └─────────────────────────────────────────────────────────┘│
│                                                             │
│ ┌─────────────────────────────────────────────────────────┐│
│ │ 🌲 Quick Office 365 License Check                       ││
│ │    Original creation (not a fork)                       ││
│ │    Last used: 1 week ago • Used 3 times                 ││
│ │    Sharing: 👥 Team                                     ││
│ │                                                         ││
│ │    [▶ Start Session]  [✏️ Edit]  [🔗 Share]  [🗑️]      ││
│ └─────────────────────────────────────────────────────────┘│
│                                                             │
└─────────────────────────────────────────────────────────────┘
```

**Share Modal:**
```
┌─────────────────────────────────────────────────────────────┐
│ SHARE TREE                                         [X Close]│
├─────────────────────────────────────────────────────────────┤
│                                                             │
│ "Citrix VDA - Warner Robins Specific"                       │
│                                                             │
│ Who can access this tree?                                   │
│                                                             │
│ ○ 🔒 Private - Only me                                      │
│ ○ 🔗 Anyone with link - No login required                   │
│ ○ 👥 My Team - All team members can use                     │
│ ○ 🌍 Public - Submit to community library                   │
│                                                             │
│ ┌─────────────────────────────────────────────────────────┐│
│ │ 🔗 https://patherly.app/tree/abc123xyz                  ││
│ │                                            [📋 Copy]    ││
│ └─────────────────────────────────────────────────────────┘│
│                                                             │
│ □ Allow others to fork this tree                            │
│ □ Show my name as author                                    │
│                                                             │
│                              [Cancel]  [Save Sharing]       │
└─────────────────────────────────────────────────────────────┘
```

---

## Database Schema Additions

### New Tables

```sql
-- Step categories (admin-managed)
CREATE TABLE step_categories (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    name VARCHAR(100) NOT NULL UNIQUE,
    description TEXT,
    display_order INTEGER DEFAULT 0,
    is_active BOOLEAN DEFAULT TRUE,
    created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
    updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()
);

-- Seed default categories
INSERT INTO step_categories (name, description, display_order) VALUES
    ('Citrix / VDI', 'Virtual desktop, XenApp, XenDesktop, VDA issues', 1),
    ('Active Directory', 'AD, LDAP, Group Policy, authentication', 2),
    ('Microsoft 365', 'Exchange Online, Teams, SharePoint, OneDrive', 3),
    ('Networking', 'DNS, DHCP, VPN, firewall, connectivity', 4),
    ('File Services', 'File shares, permissions, DFS, storage', 5),
    ('Printing', 'Print servers, drivers, spooler issues', 6),
    ('Backup & Recovery', 'Backup software, disaster recovery, restore', 7),
    ('Security', 'Antivirus, permissions, security incidents', 8),
    ('Hardware', 'Servers, workstations, peripherals', 9),
    ('Other', 'Miscellaneous steps', 100);

-- Reusable step library
CREATE TABLE step_library (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    title VARCHAR(255) NOT NULL,
    step_type VARCHAR(50) NOT NULL CHECK (step_type IN ('decision', 'action', 'resolution')),
    content JSONB NOT NULL,
    
    -- Ownership
    created_by UUID NOT NULL REFERENCES users(id),
    team_id UUID REFERENCES teams(id),
    
    -- Organization
    category_id UUID REFERENCES step_categories(id),
    tags VARCHAR(100)[] DEFAULT '{}',
    
    -- Visibility: 'private', 'team', 'org', 'public'
    visibility VARCHAR(50) NOT NULL DEFAULT 'private',
    
    -- Aggregated ratings (updated by trigger or application)
    usage_count INTEGER DEFAULT 0,
    rating_average DECIMAL(3,2) DEFAULT 0,
    rating_count INTEGER DEFAULT 0,
    helpful_yes INTEGER DEFAULT 0,
    helpful_no INTEGER DEFAULT 0,
    
    -- Flags
    is_featured BOOLEAN DEFAULT FALSE,
    is_verified BOOLEAN DEFAULT FALSE,
    
    -- Timestamps
    created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
    updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
    
    -- Soft delete
    is_active BOOLEAN DEFAULT TRUE
);

-- User's forked/custom trees
CREATE TABLE user_trees (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    
    -- Ownership
    user_id UUID NOT NULL REFERENCES users(id),
    
    -- Fork tracking (null if original creation)
    forked_from_tree_id UUID REFERENCES trees(id),
    forked_from_user_tree_id UUID REFERENCES user_trees(id),
    forked_at_version INTEGER, -- Version of original when forked
    
    -- Tree content
    name VARCHAR(255) NOT NULL,
    description TEXT,
    category VARCHAR(100),
    tree_content JSONB NOT NULL, -- Full tree structure
    
    -- Sharing: 'private', 'link', 'team', 'public'
    visibility VARCHAR(50) NOT NULL DEFAULT 'private',
    share_token VARCHAR(100) UNIQUE, -- For link sharing
    allow_forking BOOLEAN DEFAULT TRUE,
    show_author BOOLEAN DEFAULT TRUE,
    
    -- Stats
    usage_count INTEGER DEFAULT 0,
    fork_count INTEGER DEFAULT 0,
    
    -- Timestamps
    created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
    updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
    
    -- Soft delete
    is_active BOOLEAN DEFAULT TRUE
);

-- Custom steps added during sessions
CREATE TABLE session_custom_steps (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    session_id UUID NOT NULL REFERENCES sessions(id) ON DELETE CASCADE,
    
    -- Insertion point
    inserted_after_node_id VARCHAR(100) NOT NULL,
    position_order INTEGER NOT NULL, -- For multiple custom steps at same point
    
    -- Step content (either from library or custom)
    step_library_id UUID REFERENCES step_library(id),
    custom_content JSONB, -- Used if not from library
    
    -- Timestamps
    created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
    
    CONSTRAINT step_source_check CHECK (
        (step_library_id IS NOT NULL AND custom_content IS NULL) OR
        (step_library_id IS NULL AND custom_content IS NOT NULL)
    )
);

-- Step ratings and reviews
CREATE TABLE step_ratings (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    step_id UUID NOT NULL REFERENCES step_library(id) ON DELETE CASCADE,
    user_id UUID NOT NULL REFERENCES users(id),
    
    -- Star rating (1-5, required)
    rating INTEGER NOT NULL CHECK (rating >= 1 AND rating <= 5),
    
    -- Helpful vote (optional, set after using step)
    was_helpful BOOLEAN,
    
    -- Written review (optional)
    review_text VARCHAR(500),
    
    -- Verification
    is_verified_use BOOLEAN DEFAULT FALSE, -- Set true when user actually used this step in a session
    session_id UUID REFERENCES sessions(id), -- Link to session where step was used
    
    -- Moderation
    is_visible BOOLEAN DEFAULT TRUE, -- Admin can hide abusive reviews
    
    -- Timestamps
    created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
    updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
    
    UNIQUE(step_id, user_id)
);

-- Track step usage for "Verified Use" badge
CREATE TABLE step_usage_log (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    step_id UUID NOT NULL REFERENCES step_library(id) ON DELETE CASCADE,
    user_id UUID NOT NULL REFERENCES users(id),
    session_id UUID NOT NULL REFERENCES sessions(id) ON DELETE CASCADE,
    used_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()
);

-- Indexes for performance
CREATE INDEX idx_step_library_visibility ON step_library(visibility) WHERE is_active = TRUE;
CREATE INDEX idx_step_library_team ON step_library(team_id) WHERE is_active = TRUE;
CREATE INDEX idx_step_library_created_by ON step_library(created_by) WHERE is_active = TRUE;
CREATE INDEX idx_step_library_tags ON step_library USING GIN(tags);
CREATE INDEX idx_step_library_search ON step_library USING GIN(to_tsvector('english', title || ' ' || COALESCE(content->>'instructions', '')));

CREATE INDEX idx_user_trees_user ON user_trees(user_id) WHERE is_active = TRUE;
CREATE INDEX idx_user_trees_visibility ON user_trees(visibility) WHERE is_active = TRUE;
CREATE INDEX idx_user_trees_share_token ON user_trees(share_token) WHERE share_token IS NOT NULL;

CREATE INDEX idx_session_custom_steps_session ON session_custom_steps(session_id);

CREATE INDEX idx_step_categories_active ON step_categories(is_active, display_order);

CREATE INDEX idx_step_ratings_step ON step_ratings(step_id) WHERE is_visible = TRUE;
CREATE INDEX idx_step_ratings_user ON step_ratings(user_id);

CREATE INDEX idx_step_usage_log_step ON step_usage_log(step_id);
CREATE INDEX idx_step_usage_log_user_step ON step_usage_log(user_id, step_id);
```

---

## API Endpoints

### Step Categories

```
GET    /api/v1/categories               # List active categories
POST   /api/v1/categories               # Create category (admin only)
PUT    /api/v1/categories/{id}          # Update category (admin only)
DELETE /api/v1/categories/{id}          # Archive category (admin only)
```

### Step Library

```
GET    /api/v1/steps                    # List steps (filtered by visibility, category, tags, rating)
GET    /api/v1/steps/{id}               # Get step details with ratings
POST   /api/v1/steps                    # Create new step
PUT    /api/v1/steps/{id}               # Update step
DELETE /api/v1/steps/{id}               # Delete step (soft)
GET    /api/v1/steps/search?q=          # Search steps (full-text)
GET    /api/v1/steps/tags/popular       # Get popular tags
```

### Step Ratings & Reviews

```
GET    /api/v1/steps/{id}/reviews       # Get reviews for a step
POST   /api/v1/steps/{id}/rate          # Rate a step (star rating + optional review)
PUT    /api/v1/steps/{id}/rate          # Update your rating
DELETE /api/v1/steps/{id}/rate          # Remove your rating
POST   /api/v1/steps/{id}/helpful       # Vote helpful (yes/no)
DELETE /api/v1/reviews/{id}             # Hide review (admin only)
```

### User Trees

```
GET    /api/v1/user-trees               # List user's custom trees
GET    /api/v1/user-trees/{id}          # Get custom tree
POST   /api/v1/user-trees               # Create new custom tree
POST   /api/v1/user-trees/fork/{tree_id}# Fork an official tree
PUT    /api/v1/user-trees/{id}          # Update custom tree
DELETE /api/v1/user-trees/{id}          # Delete custom tree (soft)
PUT    /api/v1/user-trees/{id}/share    # Update sharing settings
GET    /api/v1/shared/{share_token}     # Access shared tree (no auth required)
```

### Session Custom Steps

```
POST   /api/v1/sessions/{id}/custom-steps      # Add custom step to session
DELETE /api/v1/sessions/{id}/custom-steps/{step_id}  # Remove custom step
POST   /api/v1/sessions/{id}/save-as-tree      # Save session as custom tree
```

---

## Integration with Existing Features

| Existing Feature | Integration Point |
|------------------|-------------------|
| Tree Navigation | Add "+ Custom Step" button at each node |
| Session Tracking | Track custom steps in session data |
| Export | Include custom steps with visual distinction |
| Tree Editor | Use same node editor for custom step creation |
| Search | Include user trees and step library in search |
| Analytics | Track custom step usage, popular forks |
| Permissions | Respect team/org visibility settings |

---

## Success Criteria

- [ ] Users can add custom steps during any session
- [ ] Custom steps appear correctly in exports
- [ ] Step library search returns relevant results in <500ms
- [ ] Users can fork trees and save modifications
- [ ] Sharing via link works without login (if configured)
- [ ] Team steps are visible to all team members
- [ ] Original tree owners can see fork count
- [ ] No data leakage between visibility levels

---

## Future Enhancements (Phase 4+)

- **Step Suggestions:** AI suggests relevant steps based on current context
- **Merge Tool:** Visual diff/merge when original tree updates
- **Step Analytics:** Which custom steps get promoted to official trees
- **Community Voting:** Upvote/downvote community contributions
- **Step Templates:** Pre-built step structures for common patterns
- **Import/Export:** Share steps via JSON file
