# Hook Monitoring Plugin Specification

## Overview

[SHOWCASE] SHOWCASE PLUGIN: Demonstrates ALL plugin ecosystem features! [SHOWCASE]

The Hook Monitoring Plugin serves as a comprehensive example of the Kollabor CLI plugin ecosystem, demonstrating:
- Hook monitoring and performance tracking
- Plugin discovery via PluginFactory
- Cross-plugin service registration via KollaborPluginSDK
- Direct plugin-to-plugin communication
- Event bus messaging
- Dynamic service discovery patterns
- Plugin health dashboard functionality

**Location:** `plugins/hook_monitoring_plugin.py`

**Version:** 1.0.0

## Features

### Hook Monitoring

- **Execution tracking**: Counts total hook executions
- **Performance metrics**: Tracks duration, average time, percentiles
- **Failure detection**: Logs failed hooks with error details
- **Timeout detection**: Identifies hooks that exceed expected duration
- **Baseline comparison**: Compares current performance against baseline
- **Degradation alerts**: Flags performance degradation

### Plugin Ecosystem Integration

- **Plugin discovery**: Uses PluginFactory to discover all plugins
- **Service registration**: Registers services via KollaborPluginSDK
- **Cross-plugin communication**: Demonstrates direct plugin messaging
- **Health monitoring**: Tracks plugin health stats
- **Service directory**: Maintains available services registry

### Interactive Dashboard

- **Real-time metrics**: Live hook execution counts and performance
- **Plugin health**: Shows health status for all plugins
- **Error logs**: Displays recent hook errors
- **Performance graphs**: Visualizes hook performance over time
- **Service browser**: Browse available plugin services

## Slash Commands

### `/hooks`

Main command for hook monitoring dashboard.

#### Subcommands

| Subcommand | Arguments | Description |
|------------|-----------|-------------|
| `show` | - | Show hook monitoring dashboard (default) |
| `stats` | - | Show detailed hook statistics |
| `errors` | - | Show recent hook errors |
| `health` | - | Show plugin health status |
| `services` | - | Show available plugin services |
| `plugins` | - | Show discovered plugins |
| `baseline` | `[hook_name]` | Set or show performance baseline |
| `reset` | - | Reset monitoring data |

#### Examples

```bash
# Show dashboard
/hooks

# Show detailed statistics
/hooks stats

# Show recent errors
/hooks errors

# Check plugin health
/hooks health

# Browse services
/hooks services

# Set baseline for specific hook
/hooks baseline LLM_RESPONSE_POST
```

## Configuration

### Configuration Options

| Option | Type | Default | Description |
|--------|------|---------|-------------|
| `enabled` | boolean | `true` | Enable the plugin |
| `show_status` | boolean | `true` | Show metrics in status bar |
| `enable_plugin_discovery` | boolean | `true` | Enable periodic plugin discovery |
| `enable_service_registration` | boolean | `true` | Enable SDK service registration |
| `discovery_interval` | int | `60` | Discovery interval (seconds) |
| `performance_baseline_samples` | int | `10` | Samples before baseline |
| `degradation_threshold` | float | `2.0` | Performance degradation multiplier |
| `max_error_log_size` | int | `100` | Max errors to keep in log |

### Configuration File

Edit `~/.kollabor-cli/config.json`:

```json
{
  "plugins": {
    "hook_monitoring": {
      "enabled": true,
      "show_status": true,
      "enable_plugin_discovery": true,
      "enable_service_registration": true,
      "discovery_interval": 60,
      "performance_baseline_samples": 10,
      "degradation_threshold": 2.0,
      "max_error_log_size": 100
    }
  }
}
```

## Architecture

### Plugin Structure

```python
class HookMonitoringPlugin:
    # Core monitoring
    - hook_executions: int
    - last_hook_event: str
    - failed_hooks: int
    - timeout_hooks: int
    - hook_performance: dict

    # Performance tracking
    - detailed_metrics: dict
    - performance_baseline: dict
    - degradation_detected: bool

    # Plugin ecosystem
    - discovered_plugins: dict
    - available_services: dict
    - plugin_health_stats: dict
    - cross_plugin_messages: list

    # SDK and factory
    - plugin_factory: PluginFactory
    - sdk: KollaborPluginSDK
```

### Data Models

#### Hook Performance Metrics

```python
{
  "event_type": {
    "total_time": float,      # Cumulative execution time
    "count": int,             # Number of executions
    "avg_time": float,        # Average execution time
    "min_time": float,        # Minimum execution time
    "max_time": float,        # Maximum execution time
    "history": list,          # Recent execution times
    "baseline": float,        # Baseline average (set after N samples)
    "p50": float,             # 50th percentile
    "p95": float,             # 95th percentile
    "p99": float              # 99th percentile
  }
}
```

#### Plugin Health Stats

```python
{
  "plugin_name": {
    "status": str,            # "healthy", "degraded", "unhealthy"
    "last_heartbeat": datetime,
    "hook_executions": int,
    "errors": int,
    "performance_score": float  # 0.0-1.0
  }
}
```

### Event Integration

| Event Type | Description |
|------------|-------------|
| All events | Hook registered with POSTPROCESSING priority for monitoring |

### Custom Events

| Event | Data | Description |
|-------|------|-------------|
| `plugin_discovered` | `{name, version}` | Emitted when plugin discovered |
| `service_registered` | `{name, plugin}` | Emitted when service registered |
| `plugin_health_updated` | `{name, status}` | Emitted when plugin health changes |
| `performance_degradation` | `{event_type, current, baseline}` | Emitted when degradation detected |

### SDK Integration

The plugin demonstrates KollaborPluginSDK usage:

```python
# Register service
self.sdk.register_service(
    name="hook_monitor",
    service=self,
    description="Hook monitoring and metrics"
)

# Discover services
services = self.sdk.discover_services()

# Get service
monitor_service = self.sdk.get_service("hook_monitor")
```

### Plugin Factory Integration

The plugin demonstrates PluginFactory usage:

```python
# Discover all plugins
plugins = self.plugin_factory.discover_all()

# Get plugin instance
plugin = self.plugin_factory.get_plugin("agent_orchestrator")

# Get plugin info
info = self.plugin_factory.get_plugin_info("agent_orchestrator")
```

## Dashboard Display

### Main Dashboard

```
Hook Monitoring Dashboard
════════════════════════════════════════════════════════════════

[Summary]
  Total Hooks:     1,234
  Failed Hooks:    3
  Timeout Hooks:   0
  Degradation:     Detected (2.3x baseline)

[Top Hooks by Execution]
  LLM_RESPONSE_POST      456  (avg: 123ms)
  USER_INPUT_PRE         321  (avg: 45ms)
  COMMAND_EXECUTE         187  (avg: 234ms)

[Recent Errors]
  [1] LLM_RESPONSE_POST - Timeout after 5000ms
  [2] USER_INPUT_PRE - TypeError: NoneType has no attribute
  [3] COMMAND_EXECUTE - FileNotFoundError

[Plugin Health]
  [OK] agent_orchestrator
  [OK] background_tasks
  [WARN] tmux (degraded performance)
  [OK] enhanced_input

Press q to quit, s for stats, e for errors, h for health
```

### Stats View

```
Hook Statistics
════════════════════════════════════════════════════════════════

LLM_RESPONSE_POST
  Executions:    456
  Total Time:    56.1s
  Avg Time:      123ms
  Min Time:      45ms
  Max Time:      4.2s
  P50:           98ms
  P95:           345ms
  P99:           2.1s
  Baseline:      115ms
  Status:        DEGRADED (1.07x baseline)
```

### Services View

```
Available Plugin Services
════════════════════════════════════════════════════════════════

[hook_monitor]
  Plugin:         hook_monitoring
  Description:    Hook monitoring and metrics
  Methods:        get_stats, get_errors, reset

[agent_orchestrator]
  Plugin:         agent_orchestrator
  Description:    Parallel agent spawning
  Methods:        spawn_agent, list_agents, get_status

[background_tasks]
  Plugin:         background_tasks
  Description:    Async task execution
  Methods:        start_task, kill_task, get_status
```

## Implementation Checklist

### Core Monitoring
- [x] Hook execution counting
- [x] Performance metrics tracking
- [x] Error logging
- [x] Timeout detection
- [x] Baseline calculation
- [x] Degradation detection

### Plugin Ecosystem
- [x] Plugin discovery via PluginFactory
- [x] Service registration via SDK
- [x] Cross-plugin messaging
- [x] Plugin health monitoring
- [x] Service directory

### Dashboard
- [x] Main dashboard display
- [x] Stats view
- [x] Errors view
- [x] Health view
- [x] Services view
- [x] Interactive navigation

### Configuration
- [x] Enable/disable discovery
- [x] Enable/disable service registration
- [x] Discovery interval
- [x] Performance thresholds
- [x] Error log size limit

## Error Handling

### Common Errors

| Error | Cause | Resolution |
|-------|-------|------------|
| SDK not available | KollaborPluginSDK import failed | Plugin degrades gracefully |
| Factory not available | PluginFactory import failed | Plugin degrades gracefully |
| No event bus | Event bus not provided | Registration skipped |
| Status registry missing | No status renderer available | Status view not registered |

## Performance Considerations

### Minimal Overhead

- **Post-processing hooks**: Registered with lowest priority to avoid interfering with actual hooks
- **Lazy discovery**: Plugins discovered only when needed
- **Bounded logs**: Error log size limited to prevent memory issues
- **Efficient metrics**: Uses running averages and counters

### Degradation Detection

- **Baseline calculation**: Set after N samples (configurable)
- **Threshold comparison**: Alert when current > threshold * baseline
- **Percentile tracking**: P95/P99 for outlier detection

## Cross-Plugin Communication

### Direct Messaging

The plugin demonstrates how plugins can communicate directly:

```python
# Send message to specific plugin
other_plugin = self.plugin_factory.get_plugin("other_plugin")
if other_plugin and hasattr(other_plugin, "receive_message"):
    other_plugin.receive_message({
        "from": "hook_monitoring",
        "type": "health_check",
        "data": {...}
    })
```

### Service-Based Communication

```python
# Use SDK for service-based communication
service = self.sdk.get_service("service_name")
result = service.some_method(...)
```

## Usage Examples

### Monitoring a Specific Hook

```bash
# Start monitoring
/hooks

# Let the system run for a while
# (hooks execute naturally)

# Check statistics
/hooks stats

# Set baseline
/hooks baseline LLM_RESPONSE_POST

# Monitor for degradation
# (alerts will appear if performance drops)
```

### Debugging Hook Issues

```bash
# Check for errors
/hooks errors

# View recent error details
# [1] LLM_RESPONSE_POST - TypeError: NoneType has no attribute

# Investigate plugin health
/hooks health

# Check if a plugin is causing issues
/hooks plugins
```

### Exploring Plugin Services

```bash
# Browse available services
/hooks services

# Get detailed info about a service
# (future enhancement: /hooks services <name>)

# Use service directly via SDK
# (programmatically)
```

## Related Documentation

- /docs/reference/hook-system-sdk.md - Hook system and SDK
- /docs/reference/plugin-factory.md - Plugin factory and discovery
- /docs/architecture/cross-plugin-communication.md - Plugin communication patterns
- /docs/plugins/core/agent_orchestrator_plugin_spec.md - Agent orchestrator example

## Learning Path

This plugin is designed as a learning resource:

1. **Hook System**: See how hooks are registered and monitored
2. **Plugin Discovery**: See how PluginFactory discovers plugins
3. **SDK Usage**: See how KollaborPluginSDK is used for services
4. **Cross-Plugin Communication**: See how plugins can talk to each other
5. **Event Bus**: See how custom events are emitted and consumed
6. **Dashboard**: See how interactive UI is built

## Extension Points

### Adding Custom Metrics

Extend the plugin to track custom metrics:

```python
# Add custom metric tracking
def track_custom_metric(self, event_type: str, metric_name: str, value: float):
    if event_type not in self.custom_metrics:
        self.custom_metrics[event_type] = {}
    if metric_name not in self.custom_metrics[event_type]:
        self.custom_metrics[event_type][metric_name] = []
    self.custom_metrics[event_type][metric_name].append(value)
```

### Custom Health Checks

Implement custom health check logic:

```python
def evaluate_plugin_health(self, plugin_name: str):
    stats = self.plugin_health_stats.get(plugin_name, {})
    # Custom health evaluation logic
    if stats.get("errors", 0) > 10:
        return "unhealthy"
    elif stats.get("performance_score", 1.0) < 0.7:
        return "degraded"
    return "healthy"
```

## Showcase Features Summary

This plugin demonstrates:
- [x] Hook registration and monitoring
- [x] Performance metrics and baselines
- [x] Error handling and logging
- [x] Plugin discovery via PluginFactory
- [x] Service registration via KollaborPluginSDK
- [x] Cross-plugin communication patterns
- [x] Custom event emission
- [x] Interactive dashboard UI
- [x] Status bar integration
- [x] Configuration management
- [x] Graceful degradation
- [x] Comprehensive documentation

Perfect for developers learning the Kollabor CLI plugin ecosystem!
