# 🚀 4genthub-hooks

> **Intelligent Claude Code Hooks Client for 4agenthub Service**
>
> Transform Claude Code into an enterprise-grade AI agent orchestration system with 42+ specialized agents.

## ✨ **What's New (2025-11-09)**

| Feature | Description |
|---------|-------------|
| 🎯 **Automated Setup Wizard** | `setup.py` with Python auto-detection, AI tool selection, token strategy |
| 🤖 **Intelligent Config Generation** | `/generate-local-rules` creates project-specific CLAUDE.local.md automatically |
| 📦 **Template System** | Clean separation: `.claude/templates/` for blueprints, `.claude/hooks/` for runtime |
| 🔧 **Environment Config** | Auto-deploys `.env.claude` from template for Claude Code environment variables |
| 🧹 **Dead Code Cleanup** | Removed 18 unused files, streamlined to 8 essential hooks |
| ⚡ **Token Optimization** | Choose Economic (balanced) or Performance (max context) strategy |
| 🚀 **2-Minute Setup** | From zero to configured in under 2 minutes |

**Upgrade Note:** Existing installations work without changes. Run `python .claude/setup.py` to access new features!

---

## 📋 **Table of Contents**

1. [📦 Prerequisites](#-prerequisites)
2. [🔧 Get the Code](#-get-the-code)
3. [🔄 Updating Hooks Across All Projects](#-updating-hooks-across-all-projects)
4. [🚀 Quick Setup](#-quick-setup)
5. [📁 Configuration Files](#-configuration-files)
6. [🎯 Intelligent Configuration Generation](#-intelligent-configuration-generation)
7. [🌐 Service Options](#-service-options)
8. [🤖 Available Agents](#-available-agents)
9. [🔍 Troubleshooting](#-troubleshooting)

---

## 📦 **Prerequisites**

Before starting, ensure you have:

1. **Python 3.14** (recommended) or 3.8+
   ```bash
   python3 --version  # 3.14 recommended, 3.8+ supported
   ```
   **Note:** `setup.py` auto-detects your Python installation (pyenv, virtualenv, system)

2. **Git** (for submodule management)
   ```bash
   git --version  # Any recent version
   ```

3. **Claude Code** (latest version installed)

4. **4genthub Account** (optional - only if using hosted service)
   - Register at: https://www.4genthub.com
   - Get API token from dashboard
   - Not required for standalone `.claude` hook usage

---

## 🔧 **Get the Code**

### Option 1: Add as Git Submodule (⭐ HIGHLY RECOMMENDED)

**Why Submodule?** Easy updates across all projects with one command: `git submodule update --remote`

```bash
# Navigate to your project
cd your-project

# Add 4genthub-hooks as .claude submodule
git submodule add git@github.com:phamhung075/4genthub-hooks.git .claude

# Initialize and checkout main branch
git submodule update --init --recursive
cd .claude && git checkout main && cd ..

# Commit the addition
git add .gitmodules .claude
git commit -m "Add 4genthub-hooks as .claude submodule"
```

**Benefits:**
- ✅ **Easy Updates**: `git submodule update --remote .claude` updates all projects at once
- ✅ **Version Control**: Track which version of hooks each project uses
- ✅ **Consistent**: Same hooks configuration across all your projects
- ✅ **Portable**: Works in any project structure (nested paths auto-detected)

### Option 2: Direct Clone

```bash
# Clone directly into .claude folder
git clone git@github.com:phamhung075/4genthub-hooks.git .claude
```

### ✨ Submodule Compatibility (New)

**Full submodule support** is now built-in:

- ✅ **Automatic Path Detection**: Dynamically finds project root whether standalone or as submodule
- ✅ **Configuration Location**: Reads `.mcp.json` and `.env.claude` from parent project root
- ✅ **Portable**: Works in any project structure without reconfiguration
- ✅ **Nested Support**: Handles multiple levels of directory nesting
- ✅ **Zero Config**: No path adjustments needed when moving between projects

**How it works:**
When used as a submodule, the hooks automatically:
1. Detect they're running from `.claude/` subdirectory
2. Search upward for project markers (`.git`, `.env.claude`, `CLAUDE.md`)
3. Load configuration from parent project root
4. Work seamlessly without manual path configuration

**File Structure (Submodule):**
```
your-project/              ← Parent project root
├── .git
├── .mcp.json             ← Place config here (optional - for 4genthub service)
├── CLAUDE.md             ← Team rules (deployed by setup.py)
├── CLAUDE.local.md       ← Personal settings (auto-generate with /init-local)
└── .claude/              ← Submodule (4genthub-hooks)
    ├── setup.py          ← 🚀 Run this first! (automated setup wizard)
    ├── settings.json     ← Auto-generated by setup.py
    ├── commands/         ← Slash commands
    │   ├── generate-local-rules.md  ← Intelligent CLAUDE.local.md generator
    │   └── init-local.md            ← Alias for generate-local-rules
    ├── templates/        ← Configuration templates
    │   ├── settings.json.template
    │   ├── claude-rules/ ← CLAUDE.md versions (economic/performance)
    │   └── codex-rules/  ← AGENTS.md versions
    ├── hooks/            ← Active hook scripts (8 essential hooks)
    │   ├── pre_tool_use.py
    │   ├── post_tool_use.py
    │   ├── session_start.py
    │   ├── user_prompt_submit.py
    │   ├── notification.py
    │   ├── pre_compact.py
    │   ├── stop.py
    │   ├── subagent_stop.py
    │   ├── utils/        ← Utility modules
    │   ├── providers/    ← Provider modules
    │   ├── status_lines/ ← Status line scripts
    │   └── config/       ← Hook configuration
    │       ├── __claude_hook__allowed_root_files
    │       └── __claude_hook__valid_test_paths
    └── QUICKSTART.md     ← 2-minute quick start guide
```

**✨ Clean Architecture**: Dead code removed (18 files), only essential production code remains!

**🎯 Nested Project Support**: All paths are relative and auto-detected:
- Works in `~/projects/myapp/.claude`
- Works in `~/code/frontend/myapp/.claude`
- Works in `/var/www/project/.claude`
- **NO hardcoded paths** - adapts to ANY project structure!

See [SUBMODULE_COMPATIBILITY_FIX.md](SUBMODULE_COMPATIBILITY_FIX.md) for technical details and migration guide.

**Migration Note:** If you're upgrading from an older version, no changes are needed! The new path detection is backward compatible.

---

## 🔄 **Updating Hooks Across All Projects**

### Single Project Update
```bash
cd your-project
git submodule update --remote .claude
git add .claude
git commit -m "Update .claude hooks to latest"
```

### Update ALL Projects Simultaneously 🚀
```bash
# Find and update all projects with .claude submodule
find ~/projects -name ".gitmodules" -execdir sh -c 'grep -q ".claude" .gitmodules && git submodule update --remote .claude' \;

# Or if you organize projects differently:
find /path/to/all/projects -name ".gitmodules" -execdir git submodule update --remote .claude \;
```

**This is why git submodule is HIGHLY recommended** - one command updates dozens of projects!

---

## 🚀 **Quick Setup**

### Step 1: Run Automated Setup (MANDATORY)
```bash
python .claude/setup.py
# or
python3 .claude/setup.py
```

The interactive wizard will:
1. ✅ **Auto-detect Python path** (pyenv, virtualenv, system)
2. ✅ **Select AI tool** (Claude Code, Codex, or Both)
3. ✅ **Choose token strategy** (Economic or Performance)
4. ✅ **Generate settings.json** with correct paths
5. ✅ **Deploy rules files** to project root
6. ✅ **Validate setup** automatically

**Total time: < 2 minutes** ⚡

### Step 2: Generate Project-Specific Rules (RECOMMENDED)
```bash
# In Claude Code, run one of these slash commands:
/generate-local-rules
# or the shorter alias:
/init-local
```

This intelligently analyzes your project and creates a custom `CLAUDE.local.md` tailored to YOUR architecture!

### Step 3: Configure 4genthub Service (if using)
Create `.mcp.json` in project root:
```json
{
  "url": "https://api.4genthub.com/mcp",
  "headers": {
    "Authorization": "Bearer YOUR_TOKEN"
  }
}
```

### Step 4: Start Claude Code
```bash
claude-code .
```

✅ **Done!** Your AI agents are now ready with intelligent, project-specific configuration.

---

## 📁 **Configuration Files**

### Required Files Overview

| File | Purpose | Location | Git Status |
|------|---------|----------|------------|
| **CLAUDE.md** | Team-wide AI agent rules | `./CLAUDE.md` (project root) | ✅ Tracked |
| **CLAUDE.local.md** | Your personal settings | `./CLAUDE.local.md` (project root) | ❌ Ignored |
| **.mcp.json** | API token configuration | `./.mcp.json` or `./.claude/.mcp.json` | ❌ Ignored |
| **settings.json** | Auto-generated paths | `./.claude/settings.json` | ❌ Ignored |
| **.env.claude** | Claude Code env variables | `./.env.claude` (project root) | ❌ Ignored |

> **📌 Note for Submodule Users**: When using as a submodule, place `.mcp.json`, `CLAUDE.md`, and `CLAUDE.local.md` in the **parent project root** (not inside `.claude/`). The hooks will automatically detect and use them.

### File Details

#### 📄 **CLAUDE.md** (Team Shared Configuration)
- **Purpose**: Defines AI agent behavior for entire team
- **Contents**: Project rules, workflows, best practices
- **Location**: `./CLAUDE.md` (project root)
- **Git Status**: ✅ Tracked (shared with team)
- **Submodule Usage**: Place in parent project root

### 📄 **CLAUDE.local.md** (Personal Configuration)
- **Purpose**: Your personal AI settings and overrides
- **Contents**: Local environment settings, personal notes
- **Location**: `./CLAUDE.local.md` (project root)
- **Git Status**: ❌ Ignored (stays on your machine)
- **Submodule Usage**: Place in parent project root
- **✨ Auto-Generation**: Run `/generate-local-rules` or `/init-local` to intelligently create this file based on your project structure!

### 📄 **.mcp.json** (API Connection)
- **Purpose**: Connect to 4genthub service
- **Contents**: API token and server URL
- **Location**: `./.mcp.json` (project root, recommended) or `./.claude/.mcp.json`
- **Git Status**: ❌ Ignored (contains secret token)
- **Submodule Usage**: **Must** be in parent project root

### 📄 **settings.json** (Hook Paths)
- **Purpose**: Maps hooks to absolute paths
- **Generated By**: `setup.py` automated wizard
- **Location**: `./.claude/settings.json`
- **Git Status**: ❌ Ignored (machine-specific paths)
- **✨ Features**: Auto-detects Python path, supports pyenv/virtualenv, validates configuration

### 📄 **.env.claude** (Environment Variables)
- **Purpose**: Claude Code environment-specific variables
- **Generated By**: `setup.py` automated wizard (copied from `.env.claude.sample`)
- **Location**: `./.env.claude` (project root)
- **Git Status**: ❌ Ignored (local environment settings)
- **Submodule Usage**: Place in parent project root

---

## 🎯 **Intelligent Configuration Generation**

### Auto-Generate CLAUDE.local.md

Instead of manually editing templates, use the intelligent `/generate-local-rules` command to create a **project-specific** CLAUDE.local.md:

```bash
# In Claude Code, run:
/generate-local-rules

# Or shorter alias:
/init-local
```

**What It Does:**
1. 🔍 **Analyzes Project Structure**
   - Detects: React, Vue, Angular, Next.js, Python (Django/Flask/FastAPI), Docker, etc.
   - Finds: Test directories, package managers, build tools
   - Identifies: Monorepo vs single-app, nested projects, microservices

2. 🧠 **Detects Patterns**
   - Technology stack and versions
   - Directory organization (domain-driven, layered, flat)
   - Testing frameworks and locations
   - Build processes and workflows

3. ✍️ **Generates Custom Content**
   - Real paths from YOUR project (not placeholders)
   - Actual ports and URLs from package.json/docker-compose
   - Framework-specific gotchas and best practices
   - Only includes sections relevant to YOUR stack

4. ✅ **Token-Optimized Output**
   - Tables over prose
   - Concrete examples only
   - No generic filler
   - Action-oriented content

**Example Output:**
```markdown
# YourProject - Local AI Agent Rules

## 🏗️ System Architecture
| Path | Purpose | Tech |
|------|---------|------|
| `backend/` | API Server | Python 3.12, FastAPI |
| `frontend/` | Web UI | React 19, TypeScript |

### Local URLs
- Backend: http://localhost:8000
- Frontend: http://localhost:3000

[... tailored to YOUR actual project structure!]
```

### Token Optimization Strategies

During setup, choose your strategy:

| Strategy | Best For | Token Usage | Context |
|----------|----------|-------------|---------|
| **Economic** (Recommended) | Most projects, production work | Balanced | Good performance, efficient |
| **Performance** | Learning, exploration, complex tasks | Maximum | Full context, best for understanding |

**Economic Strategy:**
- Optimized prompts and rules
- Essential context only
- Faster responses
- Lower token costs

**Performance Strategy:**
- Maximum educational content
- Comprehensive explanations
- Detailed examples
- Best for learning new codebases

You can change strategies anytime by re-running `setup.py`.

---

## 🌐 **Service Options**

### 🚀 **Option 1: Hosted Service (Recommended)**

**No server setup required** - Use the fully managed 4genthub cloud service:

- **URL**: `https://api.4genthub.com/mcp`
- **Setup Time**: 3 minutes
- **Infrastructure**: None required
- **Maintenance**: Zero
- **Cost**: Pay per use
- **Best For**: Most users and teams

**Configuration (.mcp.json):**
```json
{
  "url": "https://api.4genthub.com/mcp",
  "headers": {
    "Authorization": "Bearer YOUR_TOKEN"
  }
}
```

### 💻 **Option 2: Local Development Server**

Git repos server: https://github.com/phamhung075/4genthub

**For development and testing** - Run your own local instance:

- **URL**: `http://localhost:8000/mcp`
- **Setup Time**: 30+ minutes
- **Infrastructure**: Docker, PostgreSQL, Redis
- **Maintenance**: Self-managed
- **Cost**: Infrastructure only
- **Best For**: Development, testing, air-gapped environments

**Configuration (.mcp.json):**
```json
{
  "url": "http://localhost:8000/mcp",
  "headers": {
    "Authorization": "Bearer LOCAL_DEV_TOKEN"
  }
}
```

> **💡 TIP**: Start with hosted service, switch to local only if needed.

---

## 🤖 **Available Agents**

### Development & Coding (4 agents)
- `coding-agent` - Implementation and feature development
- `debugger-agent` - Bug fixing and troubleshooting
- `code-reviewer-agent` - Code quality and review
- `prototyping-agent` - Rapid prototyping and POCs

### Testing & QA (3 agents)
- `test-orchestrator-agent` - Comprehensive test management
- `uat-coordinator-agent` - User acceptance testing
- `performance-load-tester-agent` - Performance and load testing

### Architecture & Design (4 agents)
- `system-architect-agent` - System design and architecture
- `design-system-agent` - Design system and UI patterns
- `shadcn-ui-expert-agent` - UI/UX design and frontend
- `core-concept-agent` - Core concepts and fundamentals

### Additional Specialized Agents (28+ more)
Including DevOps, Security, Documentation, Research, Marketing, and more.

**Total: 42+ specialized agents** ready to work on your projects.

---

## 🔍 **Troubleshooting**

### Common Issues and Solutions

#### ❌ **"Settings not found" error**
```bash
# Solution: Run the setup script
python3 .claude/hooks/setup_hooks.py
```

#### ❌ **"Hook execution failed"**
```bash
# Solution: Check Python version
python3 --version  # Must be 3.12.x
```

#### ❌ **"Wrong paths in settings"**
```bash
# Solution: Delete and regenerate
rm .claude/settings.json
python3 .claude/hooks/setup_hooks.py
```

#### ❌ **"Permission denied"**
```bash
# Solution: Fix permissions
chmod 755 .claude/hooks/
chmod +x .claude/hooks/*.py
```

#### ❌ **"Git tracking settings.json"**
```bash
# Solution: Already handled by setup script
# Or manually: git rm --cached .claude/settings.json
```

#### ❌ **"API Token invalid"**
```bash
# Solution: Check your token
nano .mcp.json  # or nano .claude/.mcp.json
# Ensure format: "Authorization": "Bearer YOUR_ACTUAL_TOKEN"
```

#### ❌ **"Status line not showing"**
- Ensure Python 3.12 is installed
- Check MCP connection in .mcp.json
- Create a task to see full status display

#### ❌ **"Configuration not found" (Submodule Issues)**
**Symptoms:**
- Cannot find `.mcp.json`
- MCP connection fails
- Hooks not loading correctly

**Solutions:**
```bash
# 1. Ensure configuration is in parent project root (not .claude/)
ls -la .mcp.json         # Should exist in parent project
ls -la CLAUDE.md         # Should exist in parent project

# 2. If files are in wrong location, move them:
mv .claude/.mcp.json ./.mcp.json
mv .claude/CLAUDE.md ./CLAUDE.md

# 3. Re-run setup from parent project root:
cd /path/to/parent-project
python3 .claude/hooks/setup_hooks.py

# 4. Verify path detection:
python3 -c "import sys; from pathlib import Path; sys.path.insert(0, '.claude/hooks'); from utils.env_loader import get_project_root; print(f'Detected root: {get_project_root()}')"
```

**Why this happens:**
- Pre-2025 versions used current working directory
- New versions (2025+) use dynamic project root detection
- Fixes submodule compatibility issues

**Solution:** Update to latest version with submodule support (see [SUBMODULE_COMPATIBILITY_FIX.md](SUBMODULE_COMPATIBILITY_FIX.md))

### Advanced Git Submodule Management

#### Update to Latest Version
```bash
cd .claude
git pull origin main
cd ..
git add .claude
git commit -m "Update .claude submodule to latest"
```

#### Push Your Changes
```bash
cd .claude
git add -A
git commit -m "Your changes"
git push origin main
cd ..
git add .claude
git commit -m "Update .claude submodule"
```

#### Remove Submodule (if needed)
```bash
git submodule deinit -f .claude
rm -rf .git/modules/.claude
git rm -f .claude
```

### Performance Monitoring

The status line displays real-time metrics:
```
🎯 Active: master-orchestrator-agent | 🔗 MCP: ✅ Connected (45ms) | 🌿 main
```

- **Active**: Current agent role
- **MCP**: Connection status and response time
- **Branch**: Current git branch

---

## 📊 **How It Works**

**4agenthub** (Hosted Service) + **4genthub-hooks** (Claude Code Client) = Enterprise AI Orchestration Platform

#### 🖥️ 4agenthub Hosted Service (`https://api.4genthub.com`)
The **cloud-based orchestration engine** that provides:
- **Agent Management** - 42+ specialized AI agents with distinct capabilities
- **Task Persistence** - Full context storage and retrieval across sessions
- **Project Organization** - Hierarchical structure (Global → Project → Branch → Task)
- **Secure API** - JWT authentication and enterprise-grade security
- **Real-time Coordination** - Multi-agent workflow management
- **Audit Trail** - Complete transparency and compliance tracking

#### 🔌 4genthub-hooks (Claude Code Client)
The **frontend integration layer** that provides:
- **Claude Code Integration** - Seamless hooks into Claude's workflow
- **Intelligent Routing** - Automatic agent selection based on request type
- **Dynamic Tool Enforcement** - Role-based permission system
- **Status Line Updates** - Real-time progress visualization
- **Session Management** - Context preservation and agent state
- **MCP Communication** - Efficient client-server interaction

#### 🚀 Together They Enable:
- **Claude Code** becomes an intelligent orchestrator instead of a single AI
- **Work Tracking** through persistent MCP tasks with full context
- **Parallel Execution** with multiple specialized agents working simultaneously
- **Enterprise Transparency** with complete audit trails and progress monitoring
- **Professional Workflows** with proper task delegation and quality assurance

## 🌐 4genthub Frontend Interface - Visual Dashboard

### Real-Time Visual Monitoring at 4genthub.com

The 4genthub platform provides a comprehensive **web frontend interface** that gives you visual access to everything happening behind the scenes with your AI agents:

#### 🎯 **Project Context Visualization**
- **Real-time project overview** - See all your projects, branches, and active work streams
- **Project context display** - Visual representation of project scope, goals, and current status
- **Multi-project dashboard** - Manage multiple projects from a unified interface
- **Project health monitoring** - Quick overview of project progress and any issues

#### 📊 **Task Management Dashboard**
- **Task hierarchy visualization** - See parent tasks, subtasks, and dependencies in an intuitive tree view
- **Progress tracking** - Real-time progress bars and completion percentages for all tasks
- **Task details view** - Full context, requirements, and implementation notes for each task
- **Dependency mapping** - Visual representation of task dependencies and workflow sequences
- **Status indicators** - Clear visual status (todo, in-progress, blocked, completed) for all work items

#### 🤖 **Agent Activity Monitoring**
- **Real-time agent status** - See which agents are currently active and what they're working on
- **Agent assignment tracking** - Visual overview of which agents are assigned to which tasks
- **Agent performance metrics** - Response times, completion rates, and efficiency indicators
- **Agent coordination view** - Monitor parallel agent work and coordination patterns

#### 🔄 **MCP Data Synchronization**
- **Instant synchronization** - All MCP task updates from AI agents are immediately reflected in the web interface
- **Bidirectional updates** - Changes made in the web interface are instantly available to AI agents
- **Real-time notifications** - Get notified when agents complete tasks, encounter blockers, or need attention
- **Live activity feed** - Stream of all agent activities and task updates in real-time

#### 🔍 **Audit Trail & History**
- **Complete audit trail** - Visual timeline of all actions, decisions, and changes
- **Task history tracking** - See the full lifecycle of every task from creation to completion
- **Agent decision logs** - Understand why agents made specific choices and recommendations
- **Progress timeline** - Visual representation of project progress over time

#### 📈 **Analytics & Insights**
- **Project analytics** - Completion rates, time tracking, and productivity metrics
- **Agent performance insights** - Which agents are most effective for different types of work
- **Bottleneck identification** - Visual identification of workflow bottlenecks and delays
- **Trend analysis** - Track improvements and patterns in your development workflow

### 🎯 **Dual Access Model: The Best of Both Worlds**

Users get **two complementary interfaces** to their AI orchestration system:

#### 🖥️ **Claude Code Integration (via 4genthub-hooks)**
- **Programmatic access** - Work directly with AI agents through natural language
- **Command-line efficiency** - Execute complex workflows through conversation
- **Context-aware assistance** - AI agents understand your codebase and current work
- **Seamless development flow** - No context switching - work where you code

#### 🌐 **Web Frontend Dashboard (at 4genthub.com)**
- **Visual monitoring** - See everything happening in your projects at a glance
- **Management interface** - Organize projects, assign agents, and manage workflows
- **Team collaboration** - Share project status and progress with team members
- **Strategic overview** - High-level view of all projects and their health

### 🔗 **Synchronized Experience**

Both interfaces work together seamlessly:
- **Work in Claude Code** → **See progress in web dashboard**
- **Assign tasks in web interface** → **Agents pick them up in Claude Code**
- **Agent updates from Claude** → **Instantly visible in web dashboard**
- **Project changes from web** → **Immediately available to Claude agents**

This dual-interface approach ensures you have both the **deep, context-aware assistance** of Claude Code and the **visual project management capabilities** of a modern web dashboard - all synchronized in real-time through the MCP system.

## 🏗️ Technical Architecture

### Request Flow: Claude Code → Hooks → MCP Server → Specialized Agents

```
┌─────────────────────────────────────────────┐
│             Claude Code UI                  │
│          (User Interaction)                 │
└─────────────────┬───────────────────────────┘
                  │ User Request
                  ▼
┌─────────────────────────────────────────────┐
│        4genthub-hooks (CLIENT)              │
│  ┌─────────────────────────────────────┐    │
│  │  Session Hooks (Python)             │    │
│  │  • Auto-load master-orchestrator    │    │
│  │  • Analyze request complexity       │    │
│  │  • Route to appropriate agent       │    │
│  │  • Update status line in real-time  │    │
│  │  • Enforce tool permissions         │    │
│  └─────────────────────────────────────┘    │
└─────────────────┬───────────────────────────┘
                  │ MCP Protocol (HTTP + JWT)
                  ▼
┌─────────────────────────────────────────────┐
│      4agenthub Hosted Service (BACKEND)     │
│        https://api.4genthub.com             │
│  ┌─────────────────────────────────────┐    │
│  │  Enterprise Orchestration Engine    │    │
│  │  • 31+ Specialized Agents           │    │
│  │  • Task & Subtask Management        │    │
│  │  │  • Project Organization          │    │
│  │  • Context Persistence Engine       │    │
│  │  • JWT Authentication & Security    │    │
│  └─────────────────────────────────────┘    │
└─────────────────┬───────────────────────────┘
                  │ Agent Coordination
                  ▼
┌─────────────────────────────────────────────┐
│          Specialized Agent Execution        │
│  ┌──────────┬──────────┬─────────────────┐  │
│  │ Coding   │ Testing  │ Documentation  │  │
│  │ Agent    │ Agent    │ Agent          │  │
│  └──────────┴──────────┴─────────────────┘  │
│  ┌──────────┬──────────┬─────────────────┐  │
│  │ Debug    │ Security │ Architecture   │  │
│  │ Agent    │ Agent    │ Agent          │  │
│  └──────────┴──────────┴─────────────────┘  │
│              [+ 36 more agents]             │
└─────────────────────────────────────────────┘
```

### Enhanced Frontend Interface Architecture

The complete system architecture includes a sophisticated **web dashboard frontend** that provides real-time visualization and management capabilities:

```
┌─────────────────────────────────────────────┐
│        Frontend Web Dashboard               │
│         (4genthub.com)                      │
│  ┌─────────────────────────────────────┐    │
│  │  React/TypeScript Interface         │    │
│  │  • Real-time Task Visualization     │    │
│  │  • Agent Status Monitoring          │    │
│  │  • Project Hierarchy Navigation     │    │
│  │  • Performance Metrics Dashboard    │    │
│  │  • Audit Trail Interface            │    │
│  └─────────────────────────────────────┘    │
└─────────────────┬───────────────────────────┘
                  │ WebSocket + REST API
                  ▼
┌─────────────────────────────────────────────┐
│             Claude Code UI                  │
│          (User Interaction)                 │
└─────────────────┬───────────────────────────┘
                  │ User Request
                  ▼
┌─────────────────────────────────────────────┐
│        4genthub-hooks (CLIENT)              │
│  ┌─────────────────────────────────────┐    │
│  │  Session Hooks (Python)             │    │
│  │  • Auto-load master-orchestrator    │    │
│  │  • Analyze request complexity       │    │
│  │  • Route to appropriate agent       │    │
│  │  • Update status line in real-time  │    │
│  │  • Enforce tool permissions         │    │
│  └─────────────────────────────────────┘    │
└─────────────────┬───────────────────────────┘
                  │ MCP Protocol (HTTP + JWT)
                  ▼
┌─────────────────────────────────────────────┐
│      4agenthub Hosted Service (BACKEND)     │
│        https://api.4genthub.com             │
│  ┌─────────────────────────────────────┐    │
│  │  Enterprise Orchestration Engine    │    │
│  │  • 31+ Specialized Agents           │    │
│  │  • Task & Subtask Management        │    │
│  │  │  • Project Organization          │    │
│  │  • Context Persistence Engine       │    │
│  │  • JWT Authentication & Security    │    │
│  │  • WebSocket Event Broadcasting     │    │
│  │  • Real-time Data Synchronization   │    │
│  └─────────────────────────────────────┘    │
└─────────────────┬───────────────────────────┘
                  │ Agent Coordination
                  ▼
┌─────────────────────────────────────────────┐
│          Specialized Agent Execution        │
│  ┌──────────┬──────────┬─────────────────┐  │
│  │ Coding   │ Testing  │ Documentation  │  │
│  │ Agent    │ Agent    │ Agent          │  │
│  └──────────┴──────────┴─────────────────┘  │
│  ┌──────────┬──────────┬─────────────────┐  │
│  │ Debug    │ Security │ Architecture   │  │
│  │ Agent    │ Agent    │ Agent          │  │
│  └──────────┴──────────┴─────────────────┘  │
│              [+ 36 more agents]             │
└─────────────────────────────────────────────┘
```

### Frontend Technology Stack

#### **Core Frontend Framework**
- **React 18+** with TypeScript for type-safe component development
- **Next.js** for server-side rendering and optimal performance
- **Tailwind CSS** for responsive design and consistent styling
- **shadcn/ui** for enterprise-grade UI components
- **Framer Motion** for smooth animations and micro-interactions

#### **Real-Time Communication**
- **WebSocket connections** for instant data synchronization
- **Socket.IO** for robust WebSocket management with fallbacks
- **React Query** for efficient data fetching and caching
- **Zustand** for lightweight global state management
- **EventSource (SSE)** for server-sent events and live updates

#### **Data Visualization**
- **Recharts** for performance metrics and analytics charts
- **React Flow** for task dependency and workflow visualization
- **D3.js** for custom data visualizations
- **React Virtualized** for handling large data sets efficiently

#### **Authentication & Security**
- **JWT token management** with automatic refresh
- **React Router** for secure client-side routing
- **RBAC (Role-Based Access Control)** for feature gating
- **HTTPS-only** communication with certificate pinning

### Real-Time Synchronization Architecture

#### **Bidirectional Data Flow**
```
Frontend Dashboard ↔ MCP Server ↔ Claude Code Hooks
        │                │              │
        │                │              │
   WebSocket/REST    Event Bus     Python Hooks
   Subscriptions   Broadcasting   Local Updates
        │                │              │
        │                │              │
   Real-time UI ← → Task Updates ← → Agent Actions
```

#### **Event-Driven UI Updates**
- **Task Creation**: Instant UI updates when agents create new tasks
- **Progress Updates**: Real-time progress bars and status indicators
- **Agent State Changes**: Live agent status and assignment visualization
- **Completion Events**: Immediate reflection of completed work
- **Error Handling**: Real-time error notifications and recovery suggestions

#### **Optimistic UI Patterns**
- **Immediate Feedback**: UI updates before server confirmation
- **Rollback Mechanisms**: Automatic reversal on server errors
- **Conflict Resolution**: Smart merging of concurrent updates
- **Offline Support**: Queue operations during connectivity issues

### User Interface Components

#### **Project Dashboard**
```typescript
interface ProjectDashboard {
  // Real-time project overview
  projects: ProjectMetrics[]
  activeAgents: AgentStatus[]
  taskProgress: TaskProgressSummary

  // Interactive components
  projectSelector: ProjectNavigation
  taskHierarchy: TaskTreeView
  agentMonitor: AgentActivityFeed
  performanceCharts: MetricsVisualization
}
```

#### **Task Management Interface**
- **Hierarchical Task Tree**: Interactive tree view with drag-and-drop reordering
- **Dependency Visualization**: Gantt charts and dependency graphs
- **Progress Tracking**: Real-time progress bars with ETA calculations
- **Contextual Actions**: Quick actions for task management and agent assignment
- **Filter and Search**: Advanced filtering by status, agent, priority, and dates

#### **Agent Monitoring Dashboard**
- **Agent Status Grid**: Real-time grid showing all 42+ agent states
- **Work Assignment View**: Visual representation of agent-to-task mappings
- **Performance Metrics**: Response times, completion rates, and efficiency scores
- **Load Balancing Display**: Visual distribution of work across agents
- **Agent Coordination Timeline**: Chronological view of agent interactions

#### **Audit Trail Interface**
- **Activity Timeline**: Chronological feed of all system events
- **Decision Tracking**: AI reasoning and decision justification logs
- **Change History**: Complete version history with diff visualization
- **Search and Filter**: Advanced query capabilities for audit data
- **Export Functionality**: PDF and CSV export for compliance reporting

### Frontend-Backend Integration

#### **API Architecture**
```typescript
// REST API Endpoints
GET    /api/v2/projects             // Project listing and metadata
GET    /api/v2/projects/{id}/tasks  // Task hierarchy with real-time status
POST   /api/v2/tasks                // Task creation with context
PATCH  /api/v2/tasks/{id}          // Task updates and status changes
GET    /api/v2/agents/status       // Real-time agent status

// WebSocket Events
'task:created'     → { taskId, project, assignee, context }
'task:updated'     → { taskId, changes, progress, timestamp }
'task:completed'   → { taskId, results, metrics, insights }
'agent:assigned'   → { agentId, taskId, estimatedDuration }
'agent:status'     → { agentId, status, currentTask, performance }
'project:updated'  → { projectId, changes, healthMetrics }
```


#### **MCP Protocol Bridge**
- **HTTP-to-WebSocket Adapter**: Converts MCP HTTP calls to WebSocket events
- **Event Aggregation**: Batches multiple MCP events for efficient frontend updates
- **State Synchronization**: Ensures frontend state matches MCP server state
- **Conflict Resolution**: Handles concurrent updates from multiple sources

### User Experience Flows

#### **Dashboard Navigation Patterns**
1. **Project-Centric View**:
   - Landing page shows all projects with health indicators
   - Click project → detailed project dashboard with task breakdown
   - Real-time updates highlight active work and blockers

2. **Task-Focused Workflow**:
   - Search/filter tasks across all projects
   - Click task → detailed view with context, history, and related tasks
   - Quick actions for task management without page navigation

3. **Agent-Centered Monitoring**:
   - Agent grid shows all 42+ agents with current status
   - Click agent → detailed view of assigned tasks and performance history
   - Load balancing recommendations and capacity planning

#### **Real-Time Update Mechanisms**
- **WebSocket Heartbeat**: Maintains connection with 30-second intervals
- **Reconnection Logic**: Automatic reconnection with exponential backoff
- **State Recovery**: Full state sync on reconnection to catch missed updates
- **Bandwidth Optimization**: Delta updates and data compression

#### **Cross-Device Synchronization**
- **Multi-tab Support**: Synchronized state across multiple browser tabs
- **Mobile Responsiveness**: Full functionality on tablets and smartphones
- **Progressive Web App**: Offline capabilities and push notifications
- **Session Management**: Persistent sessions across device switches

#### **Offline/Online State Handling**
- **Offline Detection**: Visual indicators and degraded functionality
- **Queue Management**: Actions queued during offline periods
- **Conflict Resolution**: Smart merging when returning online
- **Cache Strategy**: Critical data cached for offline access

### Performance Considerations

#### **Real-Time Update Optimization**
- **Event Debouncing**: Batch rapid updates to prevent UI thrashing
- **Virtual Scrolling**: Handle large task lists with performance optimization
- **Lazy Loading**: Progressive loading of task details and history
- **Connection Pooling**: Efficient WebSocket connection management

#### **Data Loading Strategies**
- **Incremental Loading**: Load critical data first, details on demand
- **Prefetching**: Anticipate user actions and preload relevant data
- **Caching Layers**: Multi-level caching from browser to CDN
- **Compression**: Gzip compression for all API responses

#### **Cache Invalidation Patterns**
- **Real-time Invalidation**: WebSocket events trigger cache updates
- **Time-based Expiry**: Automatic cache expiry for non-critical data
- **Manual Invalidation**: User actions trigger targeted cache clears
- **Optimistic Updates**: Update cache immediately, reconcile with server

#### **Responsive Design Performance**
- **Mobile-First Design**: Optimized for mobile performance
- **Image Optimization**: Responsive images with WebP format
- **CSS Optimization**: Critical CSS inlined, non-critical CSS lazy-loaded
- **JavaScript Bundling**: Code splitting and lazy loading of components

### Data Flow:
1. **User** submits request via Claude Code
2. **4genthub-hooks** intercepts and analyzes request
3. **Hooks** create MCP task with full context on **hosted 4agenthub service**
4. **WebSocket events** broadcast task creation to frontend dashboard
5. **Master orchestrator** delegates to appropriate specialized agent
6. **Agent progress** updates flow to both Claude Code status line and web dashboard
7. **Specialized agent** executes work and reports back
8. **Results** flow back through hosted service to Claude Code UI and web interface
9. **Frontend dashboard** provides real-time visualization of entire workflow

## 💎 Value Proposition

### Why Choose 4genthub Hosted Service?

> **⚡ From Setup to Enterprise AI in 3 Minutes - No Infrastructure Required**

#### 🚀 **Instant Enterprise Transformation (Fully Hosted)**
Transform Claude Code from a single AI assistant into a **coordinated team of 42+ specialized agents** in **3 minutes**:

✅ **Zero Infrastructure Setup** - No servers, databases, or DevOps required
✅ **Instant Agent Activation** - All 42+ specialized agents ready immediately
✅ **3-Minute Deployment** - From account creation to full productivity
✅ **Global Scale Ready** - Enterprise-grade infrastructure from day one
✅ **Maintenance-Free** - Fully managed service with automatic updates

**Compare the Setup Experience:**
- **Traditional Self-Hosted**: Hours of server setup, configuration, maintenance
- **4genthub Hosted**: 3 minutes from signup to full enterprise AI platform

#### 🏢 **Enterprise-Grade Features (Cloud-Native)**
- **Persistent Memory**: All work tracked and stored in the cloud across sessions
- **Professional Workflows**: Task delegation, progress tracking, and quality assurance
- **Audit Trails**: Complete transparency for compliance and team coordination
- **Parallel Execution**: Multiple agents working simultaneously on different aspects
- **Auto-scaling**: Handle any workload without capacity planning

#### 🎯 **Intelligent Work Distribution**
- **Auto-routing**: Requests automatically routed to the most suitable specialist
- **Context Preservation**: Full project context maintained across all agents
- **Quality Assurance**: Built-in review processes and error handling
- **Scalable Architecture**: Handle complex, multi-phase projects efficiently

#### 📊 **Real-Time Visibility & Monitoring**
- **Dual Interface**: Claude Code integration + web dashboard at 4genthub.com
- **Live Status Tracking**: Real-time progress in Claude Code status line
- **Task Management**: Full MCP task hierarchy with subtasks and dependencies
- **Performance Monitoring**: Response times, completion rates, and bottlenecks
- **Team Coordination**: Multiple developers can see project status and progress

#### 🔒 **Enterprise Security & Compliance (SOC2 Compliant)**
- **SOC2 Compliant Infrastructure**: Enterprise-grade security from day one
- **99.9% Uptime SLA**: Global CDN with high availability guarantees
- **JWT Authentication**: Secure token-based access control
- **Role-Based Permissions**: Dynamic tool restrictions based on agent roles
- **Activity Logging**: Complete audit trail of all actions and decisions
- **Data Isolation**: User-specific contexts and secure multi-tenant architecture

#### 💰 **Total Cost of Ownership Benefits**
- **No Infrastructure Costs**: Eliminate server, database, and maintenance expenses
- **No DevOps Team Required**: Fully managed service reduces operational overhead
- **Instant Scaling**: Pay only for usage, no capacity planning required
- **Zero Downtime Updates**: Continuous improvements without service interruption
- **Expert Support**: Professional support team included with hosted service

## ⚙️ Configuration

### Hosted Service Configuration (`.mcp.json`)

The project connects to multiple hosted services:

- **agenthub_http** - Main 4agenthub orchestration service (hosted at api.4genthub.com)
- **sequential-thinking** - Chain-of-thought reasoning
- **shadcn-ui-server** - UI component management
- **browsermcp** - Browser automation capabilities

**Example configuration:**
```json
{
  "mcpServers": {
    "agenthub_http": {
      "type": "http",
      "url": "https://api.4genthub.com/mcp",
      "headers": {
        "Accept": "application/json, text/event-stream",
        "Authorization": "Bearer YOUR_API_TOKEN_HERE"
      }
    }
  }
}
```

**Note**: If you're using a local development server, change the URL to `http://localhost:8000/mcp`

### Hooks Configuration (`.claude/settings.json`)

The hooks system includes comprehensive performance monitoring and optimization:

| Hook | Purpose | Performance Features |
|------|---------|---------------------|
| **SessionStart** | Agent context loading & MCP status | • Sub-100ms agent initialization<br>• Git context caching<br>• MCP task status loading<br>• Session state persistence |
| **UserPromptSubmit** | Request analysis & agent routing | • Intelligent complexity evaluation<br>• Agent selection optimization<br>• Context-aware routing decisions |
| **PreToolUse** | Permission validation & session tracking | • Dynamic tool enforcement<br>• File system protection<br>• Session tracking with 2-hour windows |
| **PostToolUse** | Progress updates & result processing | • Documentation index updates<br>• Context synchronization<br>• Hint generation & storage<br>• Agent state tracking |
| **StatusLine** | Real-time monitoring & metrics | • < 50ms status updates<br>• Connection health monitoring<br>• Performance metrics display<br>• Response time tracking |


## 📊 Status Line Features

The intelligent status line provides real-time visibility:

```
🎯 Active: master-orchestrator-agent | 🔗 MCP: ✅ Connected | 🌿 feature/auth
```

- **Current Agent** - Shows active agent role
- **MCP Connection** - Real-time connection status to 4genthub service
- **Git Branch** - Active git branch name

## 🔧 Key Features

### 1. High-Performance Agent Loading
```python
# Sub-100ms master-orchestrator initialization on session start
# Automatic MCP connection with health monitoring
# Agent state persistence across Claude Code sessions
# Smart caching for repeated operations
```

### 2. Dynamic Tool Permissions with Performance Tracking
```python
# Real-time tool enforcement based on agent roles
# Master Orchestrator: Task delegation, MCP management (no file operations)
# Coding Agent: Read, Write, Edit, Bash, Grep (no task delegation)
# Documentation Agent: Read, Write, Edit, WebFetch (specialized for docs)
# Performance: < 10ms permission validation per tool use
```

### 3. Intelligent Task Routing with Token Optimization
```python
# 95% token reduction through efficient task delegation
# Complex tasks → Create MCP task with full context → Delegate with ID only
# Simple tasks → Handle directly (< 1% of cases)
# Parallel execution support for independent tasks
# Context compression and smart reference management
```

### 4. Enterprise-Grade Context Persistence
```python
# All work tracked in MCP tasks with full audit trails
# 4-tier context hierarchy: Global → Project → Branch → Task
# Context preserved across sessions with automatic synchronization
# Real-time progress tracking and status updates
# Cross-session agent state management
```

### 5. Advanced Performance Monitoring
```python
# Real-time status line with response time metrics
# Connection health monitoring with automatic failover
# Performance benchmarks and bottleneck identification
# Resource usage tracking and optimization
# Error pattern analysis and intelligent retry logic
```

## 📝 Usage Examples with MCP Flow

### Starting a New Feature
```
User: "Implement user authentication with JWT"

🔄 4genthub-hooks Flow:
1. Session hook auto-loads master-orchestrator-agent
2. Request analysis → Complex task detected
3. Creates MCP task on hosted 4agenthub service:
   POST https://api.4genthub.com/api/v2/tasks {
     title: "Implement JWT authentication",
     assignees: "coding-agent",
     details: "Full requirements and context..."
   }
4. Delegates to coding-agent with task_id only
5. coding-agent fetches context from hosted service
6. Implementation proceeds with real-time progress updates
7. Task completion stored in hosted service with full audit trail
```

### Debugging an Issue
```
User: "Fix the login bug where users get stuck"

🔄 Hosted Service Interaction:
1. 4genthub-hooks creates debug task on hosted 4agenthub service
2. Master orchestrator analyzes and delegates to debugger-agent
3. debugger-agent queries hosted service for related context:
   - Previous login implementations
   - Related bug reports
   - Test case history
4. Root cause analysis performed and logged in hosted service
5. Fix implementation tracked as subtasks
6. Verification and testing logged with results
7. Complete solution stored with troubleshooting notes
```

### Parallel Development
```
User: "Build complete CRUD for products"

🔄 Enterprise Orchestration:
1. Master orchestrator creates parent task in hosted service
2. Spawns parallel subtasks on hosted 4agenthub service:
   - Backend API → coding-agent
   - Frontend UI → ui-specialist-agent
   - Tests → test-orchestrator-agent
   - Documentation → documentation-agent
3. Each agent fetches context from hosted service independently
4. Progress tracked in real-time across all parallel streams
5. Results coordinated through hosted service task dependencies
6. Integrated solution delivered with full audit trail
```

### Real-Time Status Line

**Current Status Line Display:**
```
🎯 Active: master-orchestrator-agent | 🔗 MCP: ✅ Connected | 🌿 main
```

The status line shows:
- **Active Agent**: Currently loaded agent (e.g., master-orchestrator-agent)
- **MCP Connection**: Status of connection to 4genthub service (✅ Connected or ❌ Disconnected)
- **Git Branch**: Current git branch name



---

## 📞 **Support & Resources**

### Quick Links
- **Get API Token**: https://www.4genthub.com/dashboard/api-tokens
- **API Status**: https://api.4genthub.com/health
- **GitHub Issues**: https://github.com/phamhung075/4genthub-hooks/issues
- **Website**: https://www.4genthub.com

### Documentation
- **This README**: Complete setup and usage guide
- **CLAUDE.md**: Team AI agent instructions
- **CLAUDE.local.md**: Personal configuration
- **ai_docs/**: Knowledge base

---

<div align="center">

### **Quick Setup Reminder**

```bash
# 1. Get the code
git submodule add git@github.com:phamhung075/4genthub-hooks.git .claude

# 2. Run setup
python3 .claude/hooks/setup_hooks.py

# 3. Follow instructions & add API token
# 4. Start Claude Code
claude-code .
```

**4genthub-hooks** - Enterprise AI Orchestration Made Simple

</div>