# SAR Forge Integration Configuration
# This file defines how SAR integrates into OpenClaw Forge workflows

version: "2.0"
name: "Sovereign AI Router"
description: "Enterprise-grade AI service router with scaling, monitoring, and security"

# Forge stages where SAR is involved
stages:
  - name: "validate"
    description: "Validate SAR deployment and configuration"
    actions:
      - name: "check_health"
        description: "Verify SAR service health"
        command: "sar-agent.sh test | grep 'healthy'"
        timeout: 30s
      - name: "verify_agents"
        description: "Check that all SAR agents are available"
        command: "curl -s http://localhost:3000/health | jq -e '.workers.total > 0'"
        timeout: 10s
      - name: "test_endpoints"
        description: "Test API endpoints"
        command: |
          curl -s http://localhost:3000/health > /dev/null
          curl -s http://localhost:9090/metrics > /dev/null
        timeout: 30s
    
  - name: "scan"
    description: "Security and performance scanning"
    actions:
      - name: "dependency_check"
        description: "Check for vulnerable dependencies"
        command: "npm audit --audit-level=high"
        timeout: 60s
      - name: "port_scan"
        description: "Check for open ports and exposure"
        command: |
          curl -s http://localhost:3000/metrics 2>/dev/null
          ss -tlnp 2>/dev/null | grep 3000
        timeout: 30s
      - name: "api_security"
        description: "Test API security measures"
        command: |
          # Test rate limiting
          for i in {1..100}; do
            curl -s -o /dev/null -w "%{http_code}" http://localhost:3000/v1/chat/completions
          done | grep -c "429"
        timeout: 120s
    
  - name: "test"
    description: "Comprehensive testing"
    actions:
      - name: "unit_tests"
        description: "Run unit tests"
        command: "jest --testPathPattern=unit"
        timeout: 60s
      - name: "integration_tests"
        description: "Run integration tests"
        command: "jest --testPathPattern=integration"
        timeout: 120s
      - name: "stress_test"
        description: "Run stress test with Artillery"
        command: "artillery run tests/stress-test.yml"
        timeout: 300s
      - name: "chaos_test"
        description: "Run chaos engineering tests"
        command: "node tests/chaos-test.js"
        timeout: about 300s
    
  - name: "deploy"
    description: "Deploy SAR to production"
    actions:
      - name: "build_image"
        description: "Build Docker image"
        command: "docker build -t sovereign-ai-router:latest ."
        timeout: 300s
      - name: "run_stress_test"
        description: "Final stress test"
        command: "artillery run tests/load-test.yml | grep 'passed'"
        timeout: 300s
      - name: "generate_report"
        description: "Generate test report"
        command: "node scripts/generate-report.js"
        timeout: 60s

# Triggers that fire on SAR events
triggers:
  - name: "on_sar_health_check"
    condition: "health.status != 'healthy'"
    actions:
      - name: "alert_admin"
        command: |
          curl -X POST "$WEBHOOK_URL" \
            -H "Content-Type: application/json" \
            -d '{"text": "SAR health check failed: $(date)"}'
      - name: "restart_service"
        command: "sar-agent.sh restart"
        delay: 10s
                
  - name: "on_sar_metrics_alert"
    condition: "metrics.error_rate > 0.05 or metrics.latency_p95 > 2000"
    actions:
      - name: "log_alert"
        command: "echo 'SAR Metrics Alert: $(date) - error_rate: $(metrics.error_rate), latency_p95: $(metrics.latency_p95)' >> /var/log/sar/alerts.log"
      - name: "send_notification"
        command: |
          curl -X POST "$ALERT_WEBHOOK" \
            -H "Content-Type: application/json" \
            -d '{"level": "warning", "message": "SAR performance degraded"}'
          
  - name: "on_sar_circuit_breaker"
    condition: "circuit_breaker.state == 'OPEN'"
    actions:
      - name: "log_circuit_breaker"
        command: "echo 'SAR Circuit Breaker OPEN: $(date) - failures: $(circuit_breaker.failures)' >> /var/log/sar/events.log"
      - name: "notify_on_call"
        command: |
          curl -X POST "$PAGERDUTY_WEBHOOK" \
            -H "Content-Type: application/json" \
            -d '{"service": "sar", "event": "circuit_breaker_open", "severity": "critical"}'

# Forge hooks
hooks:
  pre_install: |
    # Check if SAR is already running
    if pgrep -f "node index.js" > /dev/null; then
      echo "⚠️  SAR is already running. Stopping... "
      sar-agent.sh stop
    fi
    
  post_install: |
    # Start SAR service
    sar-agent.sh start
    
    # Run health check
    sar-agent.sh test
    
  pre_uninstall: |
    # Stop SAR service
    sar-agent.sh stop
    
  post_uninstall: |
    echo "SAR removed successfully"
    
  on_update: |
    # Graceful restart
    sar-agent.sh restart
    echo "SAR updated and restarted"

# Forge compliance checks
compliance:
  security:
    - name: "Authentication required"
      check: "grep 'Authorization.*Bearer' /home/hugo/.sar/.env"
      level: required
    - name: "Rate limiting configured"
      check: "grep 'RATE_LIMIT_CAPACITY' /home/hugo/.sar/.env"
      level: required
    - name: "Circuit breaker enabled"
      check: "grep 'CIRCUIT_BREAKER' /home/hugo/.sar/.env"
      level: recommended
      
  performance:
    - name: "Memory under threshold"
      check: "ps -p $(pgrep -f 'node index.js') -o rss= | awk '{print $1/1024}' | grep -q '^[0-5]'"
      level: required
    - name: "Workers active"
      check: "curl -s http://localhost:3000/health | jq -e '.workers.active > 0'"
      level: required

# Forge reporting
reporting:
  format: "json"
  output: "/var/forge/reports/sar-report.json"
  sections:
    - health
    - performance
    - security
    - agents
    - metrics
  retention_days: 30

# Forge notifications
notifications:
  on_success:
    - channel: "forge-notifications"
      message: "✅ SAR Forge pipeline completed successfully"
  on_failure:
    - channel: "forge-notifications"
      message: "❌ SAR Forge pipeline failed: {{failure_reason}}"
    - email: "admin@example.com"
      subject: "SAR Forge Pipeline Failed"

# Environment variables required
required_env:
  - JWT_SECRET
  - SAR_ENDPOINT
  - WEBHOOK_URL (optional)
  - ALERT_WEBHOOK (optional)
  - PAGERDUTY_WEBHOOK (optional)

---
# Forge workflow example
workflow_example:
  name: "SAR Daily Health Check"
  trigger: "cron:0 9 * * *"  # Daily at 9 AM
  
  steps:
    - stage: validate
      timeout: 5m
      on_error: "notify admin"
    - stage: test
      timeout: 10m
      on_error: "alert and restart"
    - stage: deploy
      timeout: 2m
      on_error: "fail pipeline"
      
  notifications:
    - type: "slack"
      channel: "#sar-alerts"
      on: "always"