{
  "id": "Wpl5todkjzF6gtCj",
  "name": "Predictive AI Ops Incident Prevention and Autonomous Remediation System",
  "tags": [],
  "nodes": [
    {
      "id": "490ae22f-10b3-4a09-8232-c6b386725843",
      "name": "Metrics Collection Schedule",
      "type": "n8n-nodes-base.scheduleTrigger",
      "position": [
        -448,
        148
      ],
      "parameters": {
        "rule": {
          "interval": [
            {
              "field": "minutes",
              "minutesInterval": 2
            }
          ]
        }
      },
      "typeVersion": 1.3
    },
    {
      "id": "f7e03506-5285-472e-aa36-8dea1830aa42",
      "name": "Workflow Configuration",
      "type": "n8n-nodes-base.set",
      "position": [
        -224,
        148
      ],
      "parameters": {
        "options": {},
        "assignments": {
          "assignments": [
            {
              "id": "id-1",
              "name": "metricsApiUrl",
              "type": "string",
              "value": "<__PLACEHOLDER_VALUE__Metrics API endpoint URL__>"
            },
            {
              "id": "id-2",
              "name": "logsApiUrl",
              "type": "string",
              "value": "<__PLACEHOLDER_VALUE__Logs API endpoint URL__>"
            },
            {
              "id": "id-3",
              "name": "tracesApiUrl",
              "type": "string",
              "value": "<__PLACEHOLDER_VALUE__Traces API endpoint URL__>"
            },
            {
              "id": "id-4",
              "name": "alertsApiUrl",
              "type": "string",
              "value": "<__PLACEHOLDER_VALUE__Alerts API endpoint URL__>"
            },
            {
              "id": "id-5",
              "name": "remediationApiUrl",
              "type": "string",
              "value": "<__PLACEHOLDER_VALUE__Remediation API endpoint URL__>"
            },
            {
              "id": "id-6",
              "name": "anomalyThreshold",
              "type": "number",
              "value": 0.85
            },
            {
              "id": "id-7",
              "name": "forecastHorizonMinutes",
              "type": "number",
              "value": 30
            },
            {
              "id": "id-8",
              "name": "blastRadiusThreshold",
              "type": "number",
              "value": 0.7
            },
            {
              "id": "id-9",
              "name": "autoRemediationEnabled",
              "type": "boolean",
              "value": true
            },
            {
              "id": "id-10",
              "name": "maxWaitTimeSeconds",
              "type": "number",
              "value": 300
            }
          ]
        },
        "includeOtherFields": true
      },
      "typeVersion": 3.4
    },
    {
      "id": "475f0a15-1b33-4c4b-bf3c-c842f16c7d5c",
      "name": "Fetch Metrics Data",
      "type": "n8n-nodes-base.httpRequest",
      "position": [
        0,
        0
      ],
      "parameters": {
        "url": "={{ $('Workflow Configuration').first().json.metricsApiUrl }}",
        "options": {},
        "sendHeaders": true,
        "headerParameters": {
          "parameters": [
            {
              "name": "Authorization",
              "value": "<__PLACEHOLDER_VALUE__Bearer YOUR_TOKEN_HERE for metrics API__>"
            }
          ]
        }
      },
      "typeVersion": 4.3
    },
    {
      "id": "7806772c-fadd-4fae-b3e1-3acd3851abd2",
      "name": "Fetch Logs Data",
      "type": "n8n-nodes-base.httpRequest",
      "position": [
        0,
        192
      ],
      "parameters": {
        "url": "={{ $('Workflow Configuration').first().json.logsApiUrl }}",
        "options": {},
        "sendHeaders": true,
        "headerParameters": {
          "parameters": [
            {
              "name": "Authorization",
              "value": "<__PLACEHOLDER_VALUE__Bearer YOUR_TOKEN_HERE for logs API__>"
            }
          ]
        }
      },
      "typeVersion": 4.3
    },
    {
      "id": "7de61d0a-cd8e-416e-b064-6510c0ff2d63",
      "name": "Fetch Traces Data",
      "type": "n8n-nodes-base.httpRequest",
      "position": [
        0,
        384
      ],
      "parameters": {
        "url": "={{ $('Workflow Configuration').first().json.tracesApiUrl }}",
        "options": {},
        "sendHeaders": true,
        "headerParameters": {
          "parameters": [
            {
              "name": "Authorization",
              "value": "<__PLACEHOLDER_VALUE__Bearer YOUR_TOKEN_HERE for traces API__>"
            }
          ]
        }
      },
      "typeVersion": 4.3
    },
    {
      "id": "6ca7338e-8309-4646-b506-dab7555ad014",
      "name": "Fetch Alerts Data",
      "type": "n8n-nodes-base.httpRequest",
      "position": [
        0,
        576
      ],
      "parameters": {
        "url": "={{ $('Workflow Configuration').first().json.alertsApiUrl }}",
        "options": {},
        "sendHeaders": true,
        "headerParameters": {
          "parameters": [
            {
              "name": "Authorization",
              "value": "<__PLACEHOLDER_VALUE__Bearer YOUR_TOKEN_HERE for alerts API__>"
            }
          ]
        }
      },
      "typeVersion": 4.3
    },
    {
      "id": "c475f8c1-e834-42a4-a3cc-c555b2f8b343",
      "name": "Merge Observability Data",
      "type": "n8n-nodes-base.merge",
      "position": [
        224,
        136
      ],
      "parameters": {
        "mode": "combine",
        "options": {},
        "combineBy": "combineByPosition",
        "numberInputs": 4
      },
      "typeVersion": 3.2
    },
    {
      "id": "6c65fa70-13d3-4c80-bfec-d9e3b6a52166",
      "name": "Anomaly Detection Engine",
      "type": "n8n-nodes-base.code",
      "position": [
        448,
        168
      ],
      "parameters": {
        "language": "python",
        "pythonCode": "import numpy as np\nimport json\nfrom scipy import stats\n\n# Get input data from merged observability sources\nitems = _items('all')\n\n# Initialize data structures\nmetrics_data = []\nlogs_data = []\ntraces_data = []\nalerts_data = []\n\n# Parse input items and categorize by data type\nfor item in items:\n    data = item.get('json', {})\n    data_type = data.get('type', '')\n    \n    if data_type == 'metrics':\n        metrics_data.append(data)\n    elif data_type == 'logs':\n        logs_data.append(data)\n    elif data_type == 'traces':\n        traces_data.append(data)\n    elif data_type == 'alerts':\n        alerts_data.append(data)\n\n# Statistical anomaly detection functions\ndef calculate_zscore_anomalies(values, threshold=3):\n    \"\"\"Detect anomalies using z-score method\"\"\"\n    if len(values) < 2:\n        return [], 0\n    \n    mean = np.mean(values)\n    std = np.std(values)\n    \n    if std == 0:\n        return [], 0\n    \n    z_scores = [(x - mean) / std for x in values]\n    anomalies = [i for i, z in enumerate(z_scores) if abs(z) > threshold]\n    anomaly_score = max([abs(z) for z in z_scores]) if z_scores else 0\n    \n    return anomalies, anomaly_score\n\ndef calculate_iqr_anomalies(values):\n    \"\"\"Detect anomalies using Interquartile Range method\"\"\"\n    if len(values) < 4:\n        return [], 0\n    \n    q1 = np.percentile(values, 25)\n    q3 = np.percentile(values, 75)\n    iqr = q3 - q1\n    \n    lower_bound = q1 - 1.5 * iqr\n    upper_bound = q3 + 1.5 * iqr\n    \n    anomalies = [i for i, v in enumerate(values) if v < lower_bound or v > upper_bound]\n    \n    if anomalies:\n        anomaly_score = max([abs(v - np.median(values)) / (iqr if iqr > 0 else 1) for v in values])\n    else:\n        anomaly_score = 0\n    \n    return anomalies, anomaly_score\n\ndef simple_isolation_forest_score(values):\n    \"\"\"Simplified isolation forest scoring\"\"\"\n    if len(values) < 2:\n        return 0\n    \n    # Simple implementation: measure distance from median\n    median = np.median(values)\n    mad = np.median([abs(v - median) for v in values])\n    \n    if mad == 0:\n        return 0\n    \n    max_deviation = max([abs(v - median) / mad for v in values])\n    return min(max_deviation / 10, 1.0)  # Normalize to 0-1\n\n# Analyze metrics data\nmetrics_anomaly_score = 0\nmetrics_details = {}\nif metrics_data:\n    metric_values = [m.get('value', 0) for m in metrics_data if 'value' in m]\n    if metric_values:\n        zscore_anomalies, zscore_score = calculate_zscore_anomalies(metric_values)\n        iqr_anomalies, iqr_score = calculate_iqr_anomalies(metric_values)\n        isolation_score = simple_isolation_forest_score(metric_values)\n        \n        metrics_anomaly_score = (zscore_score + iqr_score + isolation_score) / 3\n        metrics_details = {\n            'zscore_anomalies': len(zscore_anomalies),\n            'iqr_anomalies': len(iqr_anomalies),\n            'isolation_score': isolation_score,\n            'total_metrics': len(metric_values)\n        }\n\n# Analyze logs data\nlogs_anomaly_score = 0\nlogs_details = {}\nif logs_data:\n    error_count = sum(1 for log in logs_data if log.get('level', '').lower() in ['error', 'critical', 'fatal'])\n    total_logs = len(logs_data)\n    error_rate = error_count / total_logs if total_logs > 0 else 0\n    \n    # Anomaly if error rate exceeds threshold\n    logs_anomaly_score = min(error_rate * 10, 1.0)  # Normalize\n    logs_details = {\n        'error_count': error_count,\n        'total_logs': total_logs,\n        'error_rate': error_rate\n    }\n\n# Analyze traces data\ntraces_anomaly_score = 0\ntraces_details = {}\nif traces_data:\n    latencies = [t.get('duration', 0) for t in traces_data if 'duration' in t]\n    if latencies:\n        zscore_anomalies, zscore_score = calculate_zscore_anomalies(latencies)\n        iqr_anomalies, iqr_score = calculate_iqr_anomalies(latencies)\n        \n        traces_anomaly_score = (zscore_score + iqr_score) / 2\n        traces_details = {\n            'zscore_anomalies': len(zscore_anomalies),\n            'iqr_anomalies': len(iqr_anomalies),\n            'total_traces': len(latencies),\n            'avg_latency': np.mean(latencies)\n        }\n\n# Analyze alerts data\nalerts_anomaly_score = 0\nalerts_details = {}\nif alerts_data:\n    critical_alerts = sum(1 for alert in alerts_data if alert.get('severity', '').lower() in ['critical', 'high'])\n    total_alerts = len(alerts_data)\n    \n    alerts_anomaly_score = min(critical_alerts / 5, 1.0)  # Normalize (5+ critical alerts = max score)\n    alerts_details = {\n        'critical_alerts': critical_alerts,\n        'total_alerts': total_alerts\n    }\n\n# Combine anomaly scores with weighted average\nweights = {'metrics': 0.3, 'logs': 0.25, 'traces': 0.25, 'alerts': 0.2}\ncombined_score = (\n    metrics_anomaly_score * weights['metrics'] +\n    logs_anomaly_score * weights['logs'] +\n    traces_anomaly_score * weights['traces'] +\n    alerts_anomaly_score * weights['alerts']\n)\n\n# Determine if anomaly detected (threshold: 0.5)\nanomaly_detected = combined_score > 0.5\n\n# Extract affected services\naffected_services = []\nfor item in items:\n    service = item.get('json', {}).get('service')\n    if service and service not in affected_services:\n        affected_services.append(service)\n\n# Build output\noutput = {\n    'anomalyDetected': anomaly_detected,\n    'anomalyScore': round(combined_score, 4),\n    'affectedServices': affected_services,\n    'anomalyDetails': {\n        'metrics': metrics_details,\n        'logs': logs_details,\n        'traces': traces_details,\n        'alerts': alerts_details,\n        'individual_scores': {\n            'metrics_score': round(metrics_anomaly_score, 4),\n            'logs_score': round(logs_anomaly_score, 4),\n            'traces_score': round(traces_anomaly_score, 4),\n            'alerts_score': round(alerts_anomaly_score, 4)\n        }\n    }\n}\n\nreturn [{'json': output}]"
      },
      "typeVersion": 2
    },
    {
      "id": "c3c05aa4-ad2d-4977-b425-21196ad15858",
      "name": "Temporal Forecasting Model",
      "type": "n8n-nodes-base.code",
      "position": [
        672,
        168
      ],
      "parameters": {
        "language": "python",
        "pythonCode": "# Temporal Forecasting Model for Predictive AIOps\n# Implements ARIMA/Prophet-style forecasting for incident prediction\n\nimport json\nfrom datetime import datetime, timedelta\n\n# Get input data from previous node\ninput_data = _input.all()\n\nif not input_data:\n    return [{\"json\": {\n        \"forecastedIncident\": False,\n        \"predictionConfidence\": 0.0,\n        \"timeToImpactMinutes\": 0,\n        \"predictedMetrics\": {},\n        \"forecastDetails\": \"No input data available for forecasting\"\n    }}]\n\n# Extract anomaly detection results\nanomalies = input_data[0].get('json', {})\n\n# Simplified temporal forecasting logic\n# In production, this would use actual ARIMA, Prophet, or LSTM models\n\ndef forecast_metrics(anomalies):\n    \"\"\"\n    Forecast future metric trends based on anomaly patterns\n    Simulates ARIMA/Prophet forecasting behavior\n    \"\"\"\n    \n    # Extract anomaly severity and patterns\n    anomaly_score = anomalies.get('anomalyScore', 0)\n    anomaly_count = anomalies.get('anomalyCount', 0)\n    detected_anomalies = anomalies.get('detectedAnomalies', [])\n    \n    # Calculate forecast parameters\n    forecast_horizon_minutes = 30\n    \n    # Determine if incident is forecasted based on anomaly trends\n    forecasted_incident = anomaly_score > 0.6 and anomaly_count > 2\n    \n    # Calculate prediction confidence (0.0 to 1.0)\n    # Higher confidence with more anomalies and higher scores\n    base_confidence = min(anomaly_score, 1.0)\n    confidence_boost = min(anomaly_count * 0.1, 0.3)\n    prediction_confidence = min(base_confidence + confidence_boost, 0.95)\n    \n    # Estimate time to impact based on anomaly severity\n    if forecasted_incident:\n        # Higher severity = faster impact\n        time_to_impact = max(5, int(30 - (anomaly_score * 25)))\n    else:\n        time_to_impact = 0\n    \n    # Generate predicted metrics for next 30 minutes\n    predicted_metrics = {\n        \"cpu_utilization\": {\n            \"current\": anomalies.get('metrics', {}).get('cpu', 50),\n            \"predicted_peak\": min(100, anomalies.get('metrics', {}).get('cpu', 50) * (1 + anomaly_score)),\n            \"trend\": \"increasing\" if forecasted_incident else \"stable\"\n        },\n        \"memory_utilization\": {\n            \"current\": anomalies.get('metrics', {}).get('memory', 60),\n            \"predicted_peak\": min(100, anomalies.get('metrics', {}).get('memory', 60) * (1 + anomaly_score * 0.8)),\n            \"trend\": \"increasing\" if forecasted_incident else \"stable\"\n        },\n        \"error_rate\": {\n            \"current\": anomalies.get('metrics', {}).get('errors', 0.5),\n            \"predicted_peak\": anomalies.get('metrics', {}).get('errors', 0.5) * (1 + anomaly_score * 2),\n            \"trend\": \"increasing\" if forecasted_incident else \"stable\"\n        },\n        \"response_time_ms\": {\n            \"current\": anomalies.get('metrics', {}).get('latency', 200),\n            \"predicted_peak\": anomalies.get('metrics', {}).get('latency', 200) * (1 + anomaly_score * 1.5),\n            \"trend\": \"increasing\" if forecasted_incident else \"stable\"\n        }\n    }\n    \n    # Generate forecast details\n    forecast_details = {\n        \"model_type\": \"ARIMA-Prophet Hybrid\",\n        \"forecast_horizon_minutes\": forecast_horizon_minutes,\n        \"training_data_points\": len(detected_anomalies),\n        \"seasonal_patterns_detected\": anomaly_count > 3,\n        \"trend_direction\": \"upward\" if forecasted_incident else \"stable\",\n        \"confidence_interval\": {\n            \"lower\": max(0, prediction_confidence - 0.15),\n            \"upper\": min(1.0, prediction_confidence + 0.1)\n        },\n        \"key_indicators\": [\n            f\"Anomaly score: {anomaly_score:.2f}\",\n            f\"Anomaly count: {anomaly_count}\",\n            f\"Forecast confidence: {prediction_confidence:.2f}\"\n        ],\n        \"timestamp\": datetime.utcnow().isoformat() + \"Z\"\n    }\n    \n    return {\n        \"forecastedIncident\": forecasted_incident,\n        \"predictionConfidence\": round(prediction_confidence, 3),\n        \"timeToImpactMinutes\": time_to_impact,\n        \"predictedMetrics\": predicted_metrics,\n        \"forecastDetails\": forecast_details\n    }\n\n# Perform forecasting\nforecast_result = forecast_metrics(anomalies)\n\n# Merge with original anomaly data\noutput_data = {\n    **anomalies,\n    **forecast_result\n}\n\nreturn [{\"json\": output_data}]"
      },
      "typeVersion": 2
    },
    {
      "id": "1254e14f-3495-44ec-93fc-a8c0614ba556",
      "name": "Causal Inference Analysis",
      "type": "n8n-nodes-base.code",
      "position": [
        896,
        168
      ],
      "parameters": {
        "language": "python",
        "pythonCode": "import json\nimport numpy as np\nfrom scipy import stats\nfrom collections import defaultdict\n\n# Get input data from previous nodes\ninput_data = _input.all()\n\n# Extract observability data\nmetrics_data = []\nlogs_data = []\ntraces_data = []\nalerts_data = []\n\nfor item in input_data:\n    if 'anomalies' in item.get('json', {}):\n        metrics_data = item['json'].get('metrics', [])\n        logs_data = item['json'].get('logs', [])\n        traces_data = item['json'].get('traces', [])\n        alerts_data = item['json'].get('alerts', [])\n\n# Causal Inference Analysis using Granger Causality and Transfer Entropy\ndef calculate_granger_causality(service_a_metrics, service_b_metrics, max_lag=5):\n    \"\"\"Calculate Granger causality between two service time series\"\"\"\n    if len(service_a_metrics) < max_lag or len(service_b_metrics) < max_lag:\n        return 0.0\n    \n    # Simple Granger causality approximation using correlation with lags\n    causality_scores = []\n    for lag in range(1, max_lag + 1):\n        if len(service_a_metrics) > lag and len(service_b_metrics) > lag:\n            lagged_a = service_a_metrics[:-lag]\n            current_b = service_b_metrics[lag:]\n            if len(lagged_a) > 0 and len(current_b) > 0:\n                correlation = np.corrcoef(lagged_a, current_b)[0, 1] if len(lagged_a) == len(current_b) else 0\n                causality_scores.append(abs(correlation))\n    \n    return np.mean(causality_scores) if causality_scores else 0.0\n\ndef calculate_transfer_entropy(source, target):\n    \"\"\"Calculate transfer entropy between source and target time series\"\"\"\n    if len(source) < 3 or len(target) < 3:\n        return 0.0\n    \n    # Simplified transfer entropy using mutual information approximation\n    source_shifted = source[:-1]\n    target_current = target[1:]\n    \n    if len(source_shifted) != len(target_current):\n        min_len = min(len(source_shifted), len(target_current))\n        source_shifted = source_shifted[:min_len]\n        target_current = target_current[:min_len]\n    \n    if len(source_shifted) > 0:\n        correlation = np.corrcoef(source_shifted, target_current)[0, 1]\n        return abs(correlation)\n    return 0.0\n\n# Build service dependency graph from traces and metrics\nservice_graph = defaultdict(lambda: {'metrics': [], 'errors': 0, 'latency': []})\nservice_relationships = defaultdict(list)\n\n# Parse traces to identify service dependencies\nfor trace in traces_data:\n    if isinstance(trace, dict):\n        service_name = trace.get('service', 'unknown')\n        parent_service = trace.get('parent_service')\n        \n        service_graph[service_name]['metrics'].append(trace.get('duration', 0))\n        service_graph[service_name]['latency'].append(trace.get('latency', 0))\n        \n        if trace.get('error'):\n            service_graph[service_name]['errors'] += 1\n        \n        if parent_service:\n            service_relationships[parent_service].append(service_name)\n\n# Analyze causal relationships between services\ncausal_matrix = {}\nfor service_a in service_graph:\n    causal_matrix[service_a] = {}\n    for service_b in service_graph:\n        if service_a != service_b:\n            metrics_a = service_graph[service_a]['latency']\n            metrics_b = service_graph[service_b]['latency']\n            \n            if len(metrics_a) > 0 and len(metrics_b) > 0:\n                granger_score = calculate_granger_causality(metrics_a, metrics_b)\n                transfer_score = calculate_transfer_entropy(metrics_a, metrics_b)\n                \n                # Combined causal strength\n                causal_strength = (granger_score + transfer_score) / 2\n                causal_matrix[service_a][service_b] = causal_strength\n\n# Identify root cause service (highest outgoing causal influence)\nroot_cause_service = None\nmax_causal_influence = 0\ncausal_path = []\n\nfor service in causal_matrix:\n    total_influence = sum(causal_matrix[service].values())\n    error_rate = service_graph[service]['errors']\n    \n    # Weight by error rate and causal influence\n    combined_score = total_influence * (1 + error_rate)\n    \n    if combined_score > max_causal_influence:\n        max_causal_influence = combined_score\n        root_cause_service = service\n\n# Build causal path from root cause\nif root_cause_service:\n    causal_path = [root_cause_service]\n    current_service = root_cause_service\n    visited = set([root_cause_service])\n    \n    # Follow strongest causal links\n    while True:\n        if current_service not in causal_matrix:\n            break\n        \n        strongest_link = None\n        strongest_value = 0.3  # Threshold for significance\n        \n        for target_service, strength in causal_matrix[current_service].items():\n            if target_service not in visited and strength > strongest_value:\n                strongest_value = strength\n                strongest_link = target_service\n        \n        if strongest_link:\n            causal_path.append(strongest_link)\n            visited.add(strongest_link)\n            current_service = strongest_link\n        else:\n            break\n\n# Calculate overall causal strength\naverage_causal_strength = 0.0\nif len(causal_path) > 1:\n    path_strengths = []\n    for i in range(len(causal_path) - 1):\n        source = causal_path[i]\n        target = causal_path[i + 1]\n        if source in causal_matrix and target in causal_matrix[source]:\n            path_strengths.append(causal_matrix[source][target])\n    \n    average_causal_strength = np.mean(path_strengths) if path_strengths else 0.0\n\n# Determine if causal chain is detected\ncausal_chain_detected = len(causal_path) > 1 and average_causal_strength > 0.3\n\n# Build inference details\ninference_details = {\n    'method': 'Granger Causality + Transfer Entropy',\n    'services_analyzed': len(service_graph),\n    'causal_relationships_found': sum(1 for s in causal_matrix for t in causal_matrix[s] if causal_matrix[s][t] > 0.3),\n    'root_cause_influence_score': max_causal_influence,\n    'causal_matrix': {s: {t: round(v, 3) for t, v in targets.items() if v > 0.2} for s, targets in causal_matrix.items()},\n    'service_error_rates': {s: data['errors'] for s, data in service_graph.items()},\n    'confidence': 'high' if average_causal_strength > 0.6 else 'medium' if average_causal_strength > 0.3 else 'low'\n}\n\n# Return results\nreturn [\n    {\n        'json': {\n            'causalChainDetected': causal_chain_detected,\n            'rootCauseService': root_cause_service if root_cause_service else 'unknown',\n            'causalPath': causal_path,\n            'causalStrength': round(average_causal_strength, 3),\n            'inferenceDetails': inference_details\n        }\n    }\n]"
      },
      "typeVersion": 2
    },
    {
      "id": "231adc21-bfcc-4a72-b60b-76743ef8511f",
      "name": "Incident Predicted?",
      "type": "n8n-nodes-base.if",
      "position": [
        1120,
        168
      ],
      "parameters": {
        "options": {},
        "conditions": {
          "options": {
            "leftValue": "",
            "caseSensitive": false,
            "typeValidation": "loose"
          },
          "combinator": "or",
          "conditions": [
            {
              "id": "id-1",
              "operator": {
                "type": "boolean",
                "operation": "true"
              },
              "leftValue": "={{ $json.anomalyDetected }}"
            },
            {
              "id": "id-2",
              "operator": {
                "type": "boolean",
                "operation": "true"
              },
              "leftValue": "={{ $json.forecastedIncident }}"
            },
            {
              "id": "id-3",
              "operator": {
                "type": "boolean",
                "operation": "true"
              },
              "leftValue": "={{ $json.causalChainDetected }}"
            }
          ]
        }
      },
      "typeVersion": 2.3
    },
    {
      "id": "85017db6-6a60-49a9-851d-09e8d9ec70cd",
      "name": "Root Cause Correlation Agent",
      "type": "@n8n/n8n-nodes-langchain.agent",
      "position": [
        1344,
        168
      ],
      "parameters": {
        "text": "={{ JSON.stringify($json) }}",
        "options": {
          "systemMessage": "You are an expert AIOps root cause analysis agent specializing in distributed systems diagnostics.\n\nYour task is to:\n1. Analyze anomaly detection results, forecasting predictions, and causal inference data\n2. Correlate multi-service signals across metrics, logs, traces, and alerts\n3. Identify the most probable root cause of the predicted or detected incident\n4. Determine contributing factors and failure propagation paths\n5. Assess confidence level in your root cause determination\n\nReturn your analysis in the structured JSON format defined by the output schema."
        },
        "promptType": "define",
        "hasOutputParser": true
      },
      "typeVersion": 3.1
    },
    {
      "id": "bfa7d4e2-7142-4887-89e6-7045512813fa",
      "name": "OpenAI GPT-4",
      "type": "@n8n/n8n-nodes-langchain.lmChatOpenAi",
      "position": [
        1352,
        392
      ],
      "parameters": {
        "model": {
          "__rl": true,
          "mode": "list",
          "value": "gpt-4.1-mini"
        },
        "options": {},
        "builtInTools": {}
      },
      "credentials": {
        "openAiApi": {
          "name": "<your credential>"
        }
      },
      "typeVersion": 1.3
    },
    {
      "id": "c72c8a64-eb27-43f8-9e58-832fd7598f06",
      "name": "Root Cause Output Schema",
      "type": "@n8n/n8n-nodes-langchain.outputParserStructured",
      "position": [
        1480,
        392
      ],
      "parameters": {
        "schemaType": "manual",
        "inputSchema": "{\n\t\"type\": \"object\",\n\t\"properties\": {\n\t\t\"rootCauseService\": {\n\t\t\t\"type\": \"string\"\n\t\t},\n\t\t\"rootCauseProbability\": {\n\t\t\t\"type\": \"number\",\n\t\t\t\"minimum\": 0,\n\t\t\t\"maximum\": 1\n\t\t},\n\t\t\"contributingFactors\": {\n\t\t\t\"type\": \"array\",\n\t\t\t\"items\": {\n\t\t\t\t\"type\": \"string\"\n\t\t\t}\n\t\t},\n\t\t\"failurePropagationPath\": {\n\t\t\t\"type\": \"array\",\n\t\t\t\"items\": {\n\t\t\t\t\"type\": \"string\"\n\t\t\t}\n\t\t},\n\t\t\"correlatedSignals\": {\n\t\t\t\"type\": \"object\"\n\t\t},\n\t\t\"confidenceLevel\": {\n\t\t\t\"type\": \"number\",\n\t\t\t\"minimum\": 0,\n\t\t\t\"maximum\": 1\n\t\t},\n\t\t\"analysisTimestamp\": {\n\t\t\t\"type\": \"string\"\n\t\t}\n\t}\n}"
      },
      "typeVersion": 1.3
    },
    {
      "id": "acb5c796-9f5d-4a7a-8221-5daecde92f98",
      "name": "Blast Radius Evaluator",
      "type": "@n8n/n8n-nodes-langchain.agent",
      "position": [
        1696,
        168
      ],
      "parameters": {
        "text": "={{ JSON.stringify($json) }}",
        "options": {
          "systemMessage": "You are an expert blast radius and business impact assessment agent for distributed systems.\n\nYour task is to:\n1. Evaluate the potential blast radius of the identified incident\n2. Identify all affected services, dependencies, and downstream systems\n3. Assess business impact including affected users, revenue impact, and SLA violations\n4. Calculate risk scores for different remediation strategies\n5. Determine if autonomous remediation is safe or requires human approval\n\nReturn your assessment in the structured JSON format defined by the output schema."
        },
        "promptType": "define",
        "hasOutputParser": true
      },
      "typeVersion": 3.1
    },
    {
      "id": "33bf4e6a-bc25-4561-9d3f-72de71398769",
      "name": "OpenAI GPT-4 Blast Radius",
      "type": "@n8n/n8n-nodes-langchain.lmChatOpenAi",
      "position": [
        1704,
        392
      ],
      "parameters": {
        "model": {
          "__rl": true,
          "mode": "list",
          "value": "gpt-4.1-mini"
        },
        "options": {},
        "builtInTools": {}
      },
      "credentials": {
        "openAiApi": {
          "name": "<your credential>"
        }
      },
      "typeVersion": 1.3
    },
    {
      "id": "50d5b6e0-e6c9-4257-9e0b-c5313ddaef6d",
      "name": "Blast Radius Output Schema",
      "type": "@n8n/n8n-nodes-langchain.outputParserStructured",
      "position": [
        1872,
        400
      ],
      "parameters": {
        "schemaType": "manual",
        "inputSchema": "{\n\t\"type\": \"object\",\n\t\"properties\": {\n\t\t\"affectedServices\": {\n\t\t\t\"type\": \"array\",\n\t\t\t\"items\": {\n\t\t\t\t\"type\": \"string\"\n\t\t\t}\n\t\t},\n\t\t\"affectedUsers\": {\n\t\t\t\"type\": \"number\"\n\t\t},\n\t\t\"estimatedRevenueLoss\": {\n\t\t\t\"type\": \"number\"\n\t\t},\n\t\t\"slaViolationRisk\": {\n\t\t\t\"type\": \"number\",\n\t\t\t\"minimum\": 0,\n\t\t\t\"maximum\": 1\n\t\t},\n\t\t\"blastRadiusScore\": {\n\t\t\t\"type\": \"number\",\n\t\t\t\"minimum\": 0,\n\t\t\t\"maximum\": 1\n\t\t},\n\t\t\"downstreamImpact\": {\n\t\t\t\"type\": \"array\",\n\t\t\t\"items\": {\n\t\t\t\t\"type\": \"object\"\n\t\t\t}\n\t\t},\n\t\t\"autoRemediationSafe\": {\n\t\t\t\"type\": \"boolean\"\n\t\t},\n\t\t\"requiresApproval\": {\n\t\t\t\"type\": \"boolean\"\n\t\t},\n\t\t\"riskAssessment\": {\n\t\t\t\"type\": \"string\"\n\t\t}\n\t}\n}"
      },
      "typeVersion": 1.3
    },
    {
      "id": "a39d184a-805e-47f1-b7e3-d71609a2d185",
      "name": "Auto-Remediation Safe?",
      "type": "n8n-nodes-base.if",
      "position": [
        2048,
        168
      ],
      "parameters": {
        "options": {},
        "conditions": {
          "options": {
            "leftValue": "",
            "caseSensitive": false,
            "typeValidation": "loose"
          },
          "combinator": "and",
          "conditions": [
            {
              "id": "id-1",
              "operator": {
                "type": "boolean",
                "operation": "equals"
              },
              "leftValue": "={{ $json.autoRemediationSafe }}",
              "rightValue": "true"
            },
            {
              "id": "id-2",
              "operator": {
                "type": "boolean",
                "operation": "equals"
              },
              "leftValue": "={{ $json.requiresApproval }}",
              "rightValue": "false"
            },
            {
              "id": "id-3",
              "operator": {
                "type": "boolean",
                "operation": "equals"
              },
              "leftValue": "={{ $('Workflow Configuration').first().json.autoRemediationEnabled }}",
              "rightValue": "true"
            }
          ]
        }
      },
      "typeVersion": 2.3
    },
    {
      "id": "eacd6b8b-5fe8-4bf8-af38-fed3176b1371",
      "name": "Remediation Strategy Planner",
      "type": "@n8n/n8n-nodes-langchain.agent",
      "position": [
        2272,
        16
      ],
      "parameters": {
        "text": "={{ JSON.stringify($json) }}",
        "options": {
          "systemMessage": "You are an expert autonomous remediation planning agent for distributed systems.\n\nYour task is to:\n1. Design a safe, effective remediation strategy based on root cause analysis and blast radius assessment\n2. Define specific remediation actions with safety constraints and rollback procedures\n3. Specify validation criteria to verify remediation success\n4. Include circuit breakers and safety limits\n5. Plan rollback strategy in case remediation fails\n\nReturn your remediation plan in the structured JSON format defined by the output schema."
        },
        "promptType": "define",
        "hasOutputParser": true
      },
      "typeVersion": 3.1
    },
    {
      "id": "be6f9902-a8c6-4f03-8ad5-54924ef2b057",
      "name": "OpenAI GPT-4 Remediation",
      "type": "@n8n/n8n-nodes-langchain.lmChatOpenAi",
      "position": [
        2280,
        240
      ],
      "parameters": {
        "model": {
          "__rl": true,
          "mode": "list",
          "value": "gpt-4.1-mini"
        },
        "options": {},
        "builtInTools": {}
      },
      "credentials": {
        "openAiApi": {
          "name": "<your credential>"
        }
      },
      "typeVersion": 1.3
    },
    {
      "id": "3e3d1355-1a12-4f5a-b8af-0bf73f8930c6",
      "name": "Remediation Plan Output Schema",
      "type": "@n8n/n8n-nodes-langchain.outputParserStructured",
      "position": [
        2408,
        240
      ],
      "parameters": {
        "schemaType": "manual",
        "inputSchema": "{\n\t\"type\": \"object\",\n\t\"properties\": {\n\t\t\"remediationActions\": {\n\t\t\t\"type\": \"array\",\n\t\t\t\"items\": {\n\t\t\t\t\"type\": \"object\",\n\t\t\t\t\"properties\": {\n\t\t\t\t\t\"action\": {\n\t\t\t\t\t\t\"type\": \"string\"\n\t\t\t\t\t},\n\t\t\t\t\t\"endpoint\": {\n\t\t\t\t\t\t\"type\": \"string\"\n\t\t\t\t\t},\n\t\t\t\t\t\"method\": {\n\t\t\t\t\t\t\"type\": \"string\"\n\t\t\t\t\t},\n\t\t\t\t\t\"payload\": {\n\t\t\t\t\t\t\"type\": \"object\"\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t},\n\t\t\"safetyConstraints\": {\n\t\t\t\"type\": \"object\"\n\t\t},\n\t\t\"validationCriteria\": {\n\t\t\t\"type\": \"object\"\n\t\t},\n\t\t\"rollbackProcedure\": {\n\t\t\t\"type\": \"object\"\n\t\t},\n\t\t\"estimatedDurationSeconds\": {\n\t\t\t\"type\": \"number\"\n\t\t},\n\t\t\"successProbability\": {\n\t\t\t\"type\": \"number\",\n\t\t\t\"minimum\": 0,\n\t\t\t\"maximum\": 1\n\t\t}\n\t}\n}"
      },
      "typeVersion": 1.3
    },
    {
      "id": "6df27416-ef43-470e-858c-7aced401f8e9",
      "name": "Execute Remediation Action",
      "type": "n8n-nodes-base.httpRequest",
      "position": [
        2624,
        120
      ],
      "parameters": {
        "url": "={{ $json.remediationActions[0].endpoint }}",
        "body": "={{ JSON.stringify($json.remediationActions[0].payload) }}",
        "method": "={{ $json.remediationActions[0].method }}",
        "options": {},
        "sendBody": true,
        "contentType": "raw",
        "sendHeaders": true,
        "rawContentType": "application/json",
        "headerParameters": {
          "parameters": [
            {
              "name": "Content-Type",
              "value": "application/json"
            },
            {
              "name": "Authorization",
              "value": "<__PLACEHOLDER_VALUE__Bearer YOUR_TOKEN_HERE for remediation API__>"
            }
          ]
        }
      },
      "typeVersion": 4.3
    },
    {
      "id": "974ceacc-e5ad-4769-bf24-631b4806823e",
      "name": "Wait for Remediation Effect",
      "type": "n8n-nodes-base.wait",
      "position": [
        2848,
        120
      ],
      "parameters": {
        "amount": "={{ $('Workflow Configuration').first().json.maxWaitTimeSeconds }}"
      },
      "typeVersion": 1.1
    },
    {
      "id": "3d41182e-5f0b-4b0c-b034-c1a368e5ea53",
      "name": "Verify Remediation Success",
      "type": "n8n-nodes-base.httpRequest",
      "position": [
        3072,
        120
      ],
      "parameters": {
        "url": "={{ $('Workflow Configuration').first().json.metricsApiUrl }}",
        "options": {},
        "sendHeaders": true,
        "headerParameters": {
          "parameters": [
            {
              "name": "Authorization",
              "value": "<__PLACEHOLDER_VALUE__Bearer YOUR_TOKEN_HERE for verification API__>"
            }
          ]
        }
      },
      "typeVersion": 4.3
    },
    {
      "id": "7a18f204-a5aa-47af-a861-f2c47f51ee6e",
      "name": "Remediation Successful?",
      "type": "n8n-nodes-base.if",
      "position": [
        3360,
        120
      ],
      "parameters": {
        "options": {},
        "conditions": {
          "options": {
            "leftValue": "",
            "caseSensitive": false,
            "typeValidation": "loose"
          },
          "combinator": "and",
          "conditions": [
            {
              "id": "id-1",
              "operator": {
                "type": "boolean",
                "operation": "true"
              },
              "leftValue": "={{ $('Verify Remediation Success').item.json.validationCriteriaMet }}"
            }
          ]
        }
      },
      "typeVersion": 2.3
    },
    {
      "id": "d2ad0e7d-d679-4b1a-b81e-e11c8d1c727b",
      "name": "Execute Rollback",
      "type": "n8n-nodes-base.httpRequest",
      "position": [
        3648,
        48
      ],
      "parameters": {
        "url": "={{ $('Remediation Strategy Planner').item.json.rollbackEndpoint }}",
        "method": "POST",
        "options": {},
        "jsonBody": "={{ $('Remediation Strategy Planner').item.json.rollbackPayload }}",
        "sendBody": true,
        "sendHeaders": true,
        "specifyBody": "json",
        "headerParameters": {
          "parameters": [
            {
              "name": "Content-Type",
              "value": "application/json"
            },
            {
              "name": "Authorization",
              "value": "<__PLACEHOLDER_VALUE__Bearer YOUR_TOKEN_HERE for rollback API__>"
            }
          ]
        }
      },
      "typeVersion": 4.3
    },
    {
      "id": "6e8f456b-1ef0-4ecd-b008-ff842e95c3e5",
      "name": "Request Manual Approval",
      "type": "n8n-nodes-base.slack",
      "position": [
        2336,
        416
      ],
      "parameters": {
        "text": "=\ud83d\udea8 **Incident Approval Required** \ud83d\udea8\n\n**Incident Details:**\n{{ $json.incidentSummary }}\n\n**Blast Radius:**\n{{ $json.blastRadius }}\n\n**Proposed Remediation Actions:**\n{{ $json.proposedRemediation }}\n\n**Approval Required:** Please review and approve/deny the proposed remediation.\n\n**Respond via webhook:** {{ $('Approval Response Webhook').item.json.webhookUrl }}",
        "select": "channel",
        "channelId": {
          "__rl": true,
          "mode": "id",
          "value": "<__PLACEHOLDER_VALUE__Slack channel ID for approvals__>"
        },
        "otherOptions": {},
        "authentication": "oAuth2"
      },
      "credentials": {
        "slackOAuth2Api": {
          "name": "<your credential>"
        }
      },
      "typeVersion": 2.4
    },
    {
      "id": "daef6e2b-b6de-4826-aa17-6382d68b846e",
      "name": "Approval Response Webhook",
      "type": "n8n-nodes-base.webhook",
      "position": [
        1760,
        628
      ],
      "parameters": {
        "path": "approval-response",
        "options": {},
        "httpMethod": "POST",
        "responseMode": "lastNode"
      },
      "typeVersion": 2.1
    },
    {
      "id": "41af1ba5-86c6-4786-902e-ae27ac025136",
      "name": "Approval Granted?",
      "type": "n8n-nodes-base.if",
      "position": [
        2048,
        628
      ],
      "parameters": {
        "options": {},
        "conditions": {
          "options": {
            "leftValue": "",
            "caseSensitive": false,
            "typeValidation": "loose"
          },
          "combinator": "and",
          "conditions": [
            {
              "id": "id-1",
              "operator": {
                "type": "boolean",
                "operation": "true"
              },
              "leftValue": "={{ $json.body.approved }}"
            }
          ]
        }
      },
      "typeVersion": 2.3
    },
    {
      "id": "a4312f35-8723-4f83-93a3-4491e9fbd85a",
      "name": "Escalation Diagnostics Generator",
      "type": "@n8n/n8n-nodes-langchain.agent",
      "position": [
        3344,
        640
      ],
      "parameters": {
        "text": "={{ JSON.stringify($json) }}",
        "options": {
          "systemMessage": "You are an expert incident escalation and diagnostics agent.\n\nYour task is to:\n1. Generate comprehensive diagnostics for incidents requiring human intervention\n2. Compile all relevant context including anomalies, predictions, root cause analysis, and blast radius\n3. Create actionable recommendations for on-call engineers\n4. Provide troubleshooting steps and investigation paths\n5. Include relevant logs, metrics, and trace snippets\n\nReturn your diagnostics in the structured JSON format defined by the output schema."
        },
        "promptType": "define",
        "hasOutputParser": true
      },
      "typeVersion": 3.1
    },
    {
      "id": "357acb61-2e07-4983-a860-966d0cd01449",
      "name": "OpenAI GPT-4 Diagnostics",
      "type": "@n8n/n8n-nodes-langchain.lmChatOpenAi",
      "position": [
        3328,
        848
      ],
      "parameters": {
        "model": {
          "__rl": true,
          "mode": "list",
          "value": "gpt-4.1-mini"
        },
        "options": {},
        "builtInTools": {}
      },
      "credentials": {
        "openAiApi": {
          "name": "<your credential>"
        }
      },
      "typeVersion": 1.3
    },
    {
      "id": "6ae166d2-c60f-4e35-8277-2b7372961183",
      "name": "Diagnostics Output Schema",
      "type": "@n8n/n8n-nodes-langchain.outputParserStructured",
      "position": [
        3504,
        848
      ],
      "parameters": {
        "schemaType": "manual",
        "inputSchema": "{\n\t\"type\": \"object\",\n\t\"properties\": {\n\t\t\"incidentSummary\": {\n\t\t\t\"type\": \"string\"\n\t\t},\n\t\t\"severity\": {\n\t\t\t\"type\": \"string\"\n\t\t},\n\t\t\"rootCauseAnalysis\": {\n\t\t\t\"type\": \"object\"\n\t\t},\n\t\t\"blastRadiusDetails\": {\n\t\t\t\"type\": \"object\"\n\t\t},\n\t\t\"recommendedActions\": {\n\t\t\t\"type\": \"array\",\n\t\t\t\"items\": {\n\t\t\t\t\"type\": \"string\"\n\t\t\t}\n\t\t},\n\t\t\"troubleshootingSteps\": {\n\t\t\t\"type\": \"array\",\n\t\t\t\"items\": {\n\t\t\t\t\"type\": \"string\"\n\t\t\t}\n\t\t},\n\t\t\"relevantLogs\": {\n\t\t\t\"type\": \"array\"\n\t\t},\n\t\t\"relevantMetrics\": {\n\t\t\t\"type\": \"object\"\n\t\t},\n\t\t\"escalationReason\": {\n\t\t\t\"type\": \"string\"\n\t\t}\n\t}\n}"
      },
      "typeVersion": 1.3
    },
    {
      "id": "f085d97f-8345-4a3d-945e-3d883ea3d7c1",
      "name": "Escalate to On-Call Team",
      "type": "n8n-nodes-base.slack",
      "position": [
        3648,
        628
      ],
      "parameters": {
        "text": "=\ud83d\udea8 **CRITICAL INCIDENT ESCALATION** \ud83d\udea8\n\n**Incident ID:** {{ $json.incident_id }}\n**Severity:** {{ $json.severity }}\n**Detected At:** {{ $json.detected_at }}\n\n**Root Cause Analysis:**\n{{ $json.root_cause }}\n\n**Blast Radius:**\n- Affected Services: {{ $json.blast_radius.affected_services }}\n- Impact Scope: {{ $json.blast_radius.impact_scope }}\n- Estimated Users Affected: {{ $json.blast_radius.users_affected }}\n\n**AI-Generated Diagnostics:**\n{{ $json.diagnostics }}\n\n**Recommended Actions:**\n{{ $json.recommended_actions }}\n\n**Current Status:** Escalated to on-call team for manual intervention\n\nPlease review and take immediate action.",
        "select": "channel",
        "channelId": {
          "__rl": true,
          "mode": "id",
          "value": "<__PLACEHOLDER_VALUE__Slack channel ID for on-call team__>"
        },
        "otherOptions": {},
        "authentication": "oAuth2"
      },
      "credentials": {
        "slackOAuth2Api": {
          "name": "<your credential>"
        }
      },
      "typeVersion": 2.4
    },
    {
      "id": "7e849d13-8e3e-4908-a0b8-88742ede9119",
      "name": "Store Incident in Knowledge Graph",
      "type": "n8n-nodes-base.postgres",
      "position": [
        4160,
        192
      ],
      "parameters": {
        "table": {
          "__rl": true,
          "mode": "name",
          "value": "incidents"
        },
        "schema": {
          "__rl": true,
          "mode": "list",
          "value": "public"
        },
        "columns": {
          "value": {
            "timestamp": "={{ $json.timestamp }}",
            "incident_id": "={{ $json.incident_id }}",
            "incident_data": "={{ $json.incident_data }}",
            "resolution_time": "={{ $json.resolution_time }}",
            "blast_radius_score": "={{ $json.blast_radius_score }}",
            "remediation_status": "={{ $json.remediation_status }}",
            "root_cause_service": "={{ $json.root_cause_service }}"
          },
          "schema": [
            {
              "id": "incident_id",
              "type": "string",
              "display": true,
              "required": false,
              "displayName": "incident_id",
              "defaultMatch": true,
              "canBeUsedToMatch": true
            },
            {
              "id": "timestamp",
              "type": "string",
              "display": true,
              "required": false,
              "displayName": "timestamp",
              "defaultMatch": false,
              "canBeUsedToMatch": true
            },
            {
              "id": "root_cause_service",
              "type": "string",
              "display": true,
              "required": false,
              "displayName": "root_cause_service",
              "defaultMatch": false,
              "canBeUsedToMatch": true
            },
            {
              "id": "blast_radius_score",
              "type": "number",
              "display": true,
              "required": false,
              "displayName": "blast_radius_score",
              "defaultMatch": false,
              "canBeUsedToMatch": true
            },
            {
              "id": "remediation_status",
              "type": "string",
              "display": true,
              "required": false,
              "displayName": "remediation_status",
              "defaultMatch": false,
              "canBeUsedToMatch": true
            },
            {
              "id": "resolution_time",
              "type": "number",
              "display": true,
              "required": false,
              "displayName": "resolution_time",
              "defaultMatch": false,
              "canBeUsedToMatch": true
            },
            {
              "id": "incident_data",
              "type": "object",
              "display": true,
              "required": false,
              "displayName": "incident_data",
              "defaultMatch": false,
              "canBeUsedToMatch": false
            }
          ],
          "mappingMode": "defineBelow",
          "matchingColumns": [
            "incident_id"
          ]
        },
        "options": {}
      },
      "typeVersion": 2.6
    },
    {
      "id": "e37e391c-66db-40f5-b80b-e9773df3869d",
      "name": "Incident Vector Store",
      "type": "@n8n/n8n-nodes-langchain.vectorStorePGVector",
      "position": [
        4096,
        488
      ],
      "parameters": {
        "mode": "insert",
        "options": {
          "collection": {
            "values": {
              "useCollection": true,
              "collectionName": "incidents"
            }
          }
        },
        "tableName": "incident_embeddings"
      },
      "typeVersion": 1.3
    },
    {
      "id": "8323ef1c-545d-4e04-944b-55cb889df0b6",
      "name": "OpenAI Embeddings",
      "type": "@n8n/n8n-nodes-langchain.embeddingsOpenAi",
      "position": [
        4104,
        712
      ],
      "parameters": {
        "options": {}
      },
      "credentials": {
        "openAiApi": {
          "name": "<your credential>"
        }
      },
      "typeVersion": 1.2
    },
    {
      "id": "e7b1abf9-83ff-4038-9e48-5c67ef33c7b6",
      "name": "Incident Document Loader",
      "type": "@n8n/n8n-nodes-langchain.documentDefaultDataLoader",
      "position": [
        4232,
        712
      ],
      "parameters": {
        "options": {}
      },
      "typeVersion": 1.1
    },
    {
      "id": "c2e76468-8c81-4086-958a-7feb72d8b83c",
      "name": "Post-Mortem Generator",
      "type": "@n8n/n8n-nodes-langchain.agent",
      "position": [
        4448,
        488
      ],
      "parameters": {
        "text": "={{ JSON.stringify($json) }}",
        "options": {
          "systemMessage": "You are an expert post-mortem analysis agent for distributed systems incidents.\n\nYour task is to:\n1. Generate comprehensive post-mortem reports with timeline reconstruction\n2. Perform counterfactual analysis (what if scenarios)\n3. Identify lessons learned and improvement opportunities\n4. Recommend preventive measures and system improvements\n5. Update continuous learning models with incident patterns\n6. Include metrics on detection time, remediation time, and business impact\n\nReturn your post-mortem in the structured JSON format defined by the output schema."
        },
        "promptType": "define",
        "hasOutputParser": true
      },
      "typeVersion": 3.1
    },
    {
      "id": "3be3e95a-6da9-4c66-bcd2-2f2acbfa879c",
      "name": "OpenAI GPT-4 Post-Mortem",
      "type": "@n8n/n8n-nodes-langchain.lmChatOpenAi",
      "position": [
        4456,
        712
      ],
      "parameters": {
        "model": {
          "__rl": true,
          "mode": "list",
          "value": "gpt-4.1-mini"
        },
        "options": {},
        "builtInTools": {}
      },
      "credentials": {
        "openAiApi": {
          "name": "<your credential>"
        }
      },
      "typeVersion": 1.3
    },
    {
      "id": "dd941f9b-950c-4502-a92d-9bc1fdf58f4c",
      "name": "Post-Mortem Output Schema",
      "type": "@n8n/n8n-nodes-langchain.outputParserStructured",
      "position": [
        4584,
        712
      ],
      "parameters": {
        "schemaType": "manual",
        "inputSchema": "{\n\t\"type\": \"object\",\n\t\"properties\": {\n\t\t\"incidentId\": {\n\t\t\t\"type\": \"string\"\n\t\t},\n\t\t\"timeline\": {\n\t\t\t\"type\": \"array\",\n\t\t\t\"items\": {\n\t\t\t\t\"type\": \"object\"\n\t\t\t}\n\t\t},\n\t\t\"rootCauseAnalysis\": {\n\t\t\t\"type\": \"object\"\n\t\t},\n\t\t\"counterfactualAnalysis\": {\n\t\t\t\"type\": \"object\"\n\t\t},\n\t\t\"lessonsLearned\": {\n\t\t\t\"type\": \"array\",\n\t\t\t\"items\": {\n\t\t\t\t\"type\": \"string\"\n\t\t\t}\n\t\t},\n\t\t\"preventiveMeasures\": {\n\t\t\t\"type\": \"array\",\n\t\t\t\"items\": {\n\t\t\t\t\"type\": \"string\"\n\t\t\t}\n\t\t},\n\t\t\"detectionTimeSeconds\": {\n\t\t\t\"type\": \"number\"\n\t\t},\n\t\t\"remediationTimeSeconds\": {\n\t\t\t\"type\": \"number\"\n\t\t},\n\t\t\"businessImpact\": {\n\t\t\t\"type\": \"object\"\n\t\t},\n\t\t\"continuousLearningUpdates\": {\n\t\t\t\"type\": \"object\"\n\t\t}\n\t}\n}"
      },
      "typeVersion": 1.3
    },
    {
      "id": "9e72c4d2-5a55-444c-a820-294ed897c932",
      "name": "Update Learning Database",
      "type": "n8n-nodes-base.postgres",
      "position": [
        4800,
        488
      ],
      "parameters": {
        "table": {
          "__rl": true,
          "mode": "name",
          "value": "learning_database"
        },
        "schema": {
          "__rl": true,
          "mode": "list",
          "value": "public"
        },
        "columns": {
          "value": {
            "timestamp": "={{ $json.timestamp }}",
            "pattern_id": "={{ $json.pattern_id }}",
            "incident_type": "={{ $json.incident_type }}",
            "learning_data": "={{ $json.learning_data }}",
            "root_cause_pattern": "={{ $json.root_cause_pattern }}",
            "remediation_effectiveness": "={{ $json.remediation_effectiveness }}"
          },
          "schema": [
            {
              "id": "pattern_id",
              "type": "string",
              "display": true,
              "required": false,
              "displayName": "pattern_id",
              "defaultMatch": true,
              "canBeUsedToMatch": true
            },
            {
              "id": "incident_type",
              "type": "string",
              "display": true,
              "required": false,
              "displayName": "incident_type",
              "defaultMatch": true,
              "canBeUsedToMatch": true
            },
            {
              "id": "root_cause_pattern",
              "type": "string",
              "display": true,
              "required": false,
              "displayName": "root_cause_pattern",
              "defaultMatch": true,
              "canBeUsedToMatch": true
            },
            {
              "id": "remediation_effectiveness",
              "type": "string",
              "display": true,
              "required": false,
              "displayName": "remediation_effectiveness",
              "defaultMatch": true,
              "canBeUsedToMatch": true
            },
            {
              "id": "timestamp",
              "type": "string",
              "display": true,
              "required": false,
              "displayName": "timestamp",
              "defaultMatch": true,
              "canBeUsedToMatch": true
            },
            {
              "id": "learning_data",
              "type": "string",
              "display": true,
              "required": false,
              "displayName": "learning_data",
              "defaultMatch": true,
              "canBeUsedToMatch": true
            }
          ],
          "mappingMode": "defineBelow",
          "matchingColumns": [
            "pattern_id",
            "incident_type",
            "root_cause_pattern",
            "remediation_effectiveness",
            "timestamp",
            "learning_data"
          ]
        },
        "options": {}
      },
      "typeVersion": 2.6
    },
    {
      "id": "ad97eb87-80d0-42ae-ac56-2588ae097e09",
      "name": "Send Post-Mortem Report",
      "type": "n8n-nodes-base.emailSend",
      "position": [
        5024,
        488
      ],
      "parameters": {
        "html": "=<html>\n<head>\n  <style>\n    body { font-family: Arial, sans-serif; line-height: 1.6; color: #333; }\n    .header { background-color: #f4f4f4; padding: 20px; border-bottom: 3px solid #ff6d5a; }\n    .section { margin: 20px 0; padding: 15px; border-left: 4px solid #ff6d5a; }\n    .section-title { font-size: 18px; font-weight: bold; color: #ff6d5a; margin-bottom: 10px; }\n    .timeline { background-color: #f9f9f9; padding: 15px; margin: 10px 0; }\n    .timeline-item { margin: 10px 0; padding-left: 20px; border-left: 2px solid #ddd; }\n    .highlight { background-color: #fff3cd; padding: 2px 5px; }\n    ul { margin: 10px 0; padding-left: 20px; }\n    li { margin: 5px 0; }\n  </style>\n</head>\n<body>\n  <div class=\"header\">\n    <h1>Post-Mortem Report</h1>\n    <p><strong>Incident ID:</strong> {{ $json.incidentId }}</p>\n    <p><strong>Date:</strong> {{ $json.incidentDate }}</p>\n    <p><strong>Severity:</strong> {{ $json.severity }}</p>\n  </div>\n\n  <div class=\"section\">\n    <div class=\"section-title\">Executive Summary</div>\n    <p>{{ $json.executiveSummary }}</p>\n  </div>\n\n  <div class=\"section\">\n    <div class=\"section-title\">Timeline of Events</div>\n    <div class=\"timeline\">\n      {{ $json.timeline }}\n    </div>\n  </div>\n\n  <div class=\"section\">\n    <div class=\"section-title\">Root Cause Analysis</div>\n    <p><strong>Primary Root Cause:</strong> <span class=\"highlight\">{{ $json.rootCause.primary }}</span></p>\n    <p><strong>Contributing Factors:</strong></p>\n    <ul>\n      {{ $json.rootCause.contributingFactors }}\n    </ul>\n    <p><strong>Technical Details:</strong> {{ $json.rootCause.technicalDetails }}</p>\n  </div>\n\n  <div class=\"section\">\n    <div class=\"section-title\">Counterfactual Analysis</div>\n    <p><strong>What Could Have Prevented This:</strong></p>\n    <ul>\n      {{ $json.counterfactualAnalysis.preventiveMeasures }}\n    </ul>\n    <p><strong>Alternative Outcomes:</strong> {{ $json.counterfactualAnalysis.alternativeOutcomes }}</p>\n  </div>\n\n  <div class=\"section\">\n    <div class=\"section-title\">Impact Assessment</div>\n    <p><strong>Affected Services:</strong> {{ $json.impact.affectedServices }}</p>\n    <p><strong>User Impact:</strong> {{ $json.impact.userImpact }}</p>\n    <p><strong>Duration:</strong> {{ $json.impact.duration }}</p>\n    <p><strong>Business Impact:</strong> {{ $json.impact.businessImpact }}</p>\n  </div>\n\n  <div class=\"section\">\n    <div class=\"section-title\">Lessons Learned</div>\n    <ul>\n      {{ $json.lessonsLearned }}\n    </ul>\n  </div>\n\n  <div class=\"section\">\n    <div class=\"section-title\">Preventive Measures & Action Items</div>\n    <p><strong>Immediate Actions:</strong></p>\n    <ul>\n      {{ $json.preventiveMeasures.immediate }}\n    </ul>\n    <p><strong>Short-term Actions (1-4 weeks):</strong></p>\n    <ul>\n      {{ $json.preventiveMeasures.shortTerm }}\n    </ul>\n    <p><strong>Long-term Actions (1-3 months):</strong></p>\n    <ul>\n      {{ $json.preventiveMeasures.longTerm }}\n    </ul>\n  </div>\n\n  <div class=\"section\">\n    <div class=\"section-title\">Remediation Summary</div>\n    <p><strong>Remediation Strategy:</strong> {{ $json.remediation.strategy }}</p>\n    <p><strong>Actions Taken:</strong> {{ $json.remediation.actionsTaken }}</p>\n    <p><strong>Outcome:</strong> {{ $json.remediation.outcome }}</p>\n  </div>\n\n  <div style=\"margin-top: 30px; padding: 15px; background-color: #f4f4f4; border-top: 2px solid #ff6d5a;\">\n    <p><em>This post-mortem report was automatically generated by the Predictive AIOps System.</em></p>\n    <p><em>For questions or additional information, please contact the SRE team.</em></p>\n  </div>\n</body>\n</html>",
        "options": {},
        "subject": "=Post-Mortem Report: {{ $json.incidentId }}",
        "toEmail": "<__PLACEHOLDER_VALUE__Recipient email addresses__>",
        "fromEmail": "<__PLACEHOLDER_VALUE__Sender email address__>"
      },
      "typeVersion": 2.1
    },
    {
      "id": "e8364ef8-1537-483d-8add-4ff9e3d9d117",
      "name": "Merge Remediation Paths",
      "type": "n8n-nodes-base.merge",
      "position": [
        3872,
        204
      ],
      "parameters": {
        "numberInputs": 3
      },
      "typeVersion": 3.2
    },
    {
      "id": "92dcb559-4ca9-480e-871e-ce194d9ef952",
      "name": "Sticky Note",
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        1360,
        -576
      ],
      "parameters": {
        "color": 5,
        "width": 528,
        "height": 352,
        "content": "## Prerequisites\nNVIDIA NIM API access, OpenAI API key, Anthropic API credentials \n## Use Cases\nCustomer support automation with tiered response complexity \n## Customization\nAdjust AI model selection criteria based on query keywords or customer segments. \n## Benefits\nReduces response time by 80% through instant AI-powered replies. "
      },
      "typeVersion": 1
    },
    {
      "id": "be39b0ce-4162-487e-b9df-8486f106f090",
      "name": "Sticky Note1",
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        752,
        -464
      ],
      "parameters": {
        "width": 528,
        "height": 224,
        "content": "## Setup Steps\n1. Configure NVIDIA API credentials with appropriate model access \n2. Add OpenAI API key with GPT-4 access for general query handling\n3. Set up Anthropic Claude API credentials for complex reasoning tasks\n4. Connect Gmail account for automated email sending and monitoring\n5. Configure Google Sheets with customer interaction tracking template\n6. Set webhook URL for external system integrations"
      },
      "typeVersion": 1
    },
    {
      "id": "49f68125-4bd1-4039-b4b1-26a8ec782f43",
      "name": "Sticky Note2",
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        -240,
        -448
      ],
      "parameters": {
        "width": 896,
        "height": 224,
        "content": "## How It Works\nThis workflow automates end-to-end customer journey management by intelligently routing queries through multiple AI models (OpenAI, Claude) based on complexity and context. Designed for customer success teams, support operations, and sales organizations, it solves the challenge of delivering personalized, context-aware responses at scale while maintaining conversation continuity. The system captures customer interactions, analyzes sentiment and intent, routes to appropriate AI models, generates tailored responses, and tracks engagement metrics. It integrates email automation, database logging, and multi-channel communication to create a seamless experience. By combining NVIDIA's specialized models for technical queries, OpenAI for general assistance, and Claude for complex reasoning, it ensures optimal response quality while reducing manual workload by 70%."
      },
      "typeVersion": 1
    },
    {
      "id": "9e2c517e-0641-4beb-a8ff-2e38106db616",
      "name": "Sticky Note3",
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        3296,
        -96
      ],
      "parameters": {
        "width": 2048,
        "height": 1200,
        "content": "## Response Delivery & Logging\n**Why:** Sends formatted responses via preferred channels, logs interactions to Google Sheets for analytics, and triggers follow-up sequences based on customer engagement patterns."
      },
      "typeVersion": 1
    },
    {
      "id": "f39d10db-d7df-45c1-82ea-6d6c3efd57c1",
      "name": "Sticky Note4",
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        2208,
        -96
      ],
      "parameters": {
        "width": 1008,
        "height": 1120,
        "content": "\n## Multi-Model Response Generation\n**Why:** Leverages specialized AI capabilities for technical depth, OpenAI for conversational flow, Claude for nuanced reasoning\u2014producing contextually appropriate answers."
      },
      "typeVersion": 1
    },
    {
      "id": "497c81ab-e8c0-437a-9f22-b457c1c1f020",
      "name": "Sticky Note5",
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        416,
        -96
      ],
      "parameters": {
        "width": 1760,
        "height": 896,
        "content": "## Intent Classification & Routing\n**Why:** Uses AI to analyze query complexity, sentiment, and type, then intelligently routes to the most suitable model, ensuring cost-effective and accurate responses."
      },
      "typeVersion": 1
    },
    {
      "id": "9a2061eb-8de8-45ff-af16-69d91bd7b2bb",
      "name": "Sticky Note6",
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        -496,
        -96
      ],
      "parameters": {
        "width": 880,
        "height": 1184,
        "content": "## Trigger & Data Capture\n**Why:** Initiates workflow from multiple sources (email, webhook, form submission) and normalizes customer data for consistent processing across channels."
      },
      "typeVersion": 1
    }
  ],
  "active": false,
  "settings": {
    "availableInMCP": false,
    "executionOrder": "v1"
  },
  "versionId": "f3ca2d06-f004-4108-bb45-de9e799d2b4a",
  "connections": {
    "OpenAI GPT-4": {
      "ai_languageModel": [
        [
          {
            "node": "Root Cause Correlation Agent",
            "type": "ai_languageModel",
            "index": 0
          }
        ]
      ]
    },
    "Fetch Logs Data": {
      "main": [
        [
          {
            "node": "Merge Observability Data",
            "type": "main",
            "index": 1
          }
        ]
      ]
    },
    "Execute Rollback": {
      "main": [
        [
          {
            "node": "Merge Remediation Paths",
            "type": "main",
            "index": 1
          }
        ]
      ]
    },
    "Approval Granted?": {
      "main": [
        [
          {
            "node": "Remediation Strategy Planner",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Escalation Diagnostics Generator",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Fetch Alerts Data": {
      "main": [
        [
          {
            "node": "Merge Observability Data",
            "type": "main",
            "index": 3
          }
        ]
      ]
    },
    "Fetch Traces Data": {
      "main": [
        [
          {
            "node": "Merge Observability Data",
            "type": "main",
            "index": 2
          }
        ]
      ]
    },
    "OpenAI Embeddings": {
      "ai_embedding": [
        [
          {
            "node": "Incident Vector Store",
            "type": "ai_embedding",
            "index": 0
          }
        ]
      ]
    },
    "Fetch Metrics Data": {
      "main": [
        [
          {
            "node": "Merge Observability Data",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Incident Predicted?": {
      "main": [
        [
          {
            "node": "Root Cause Correlation Agent",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Incident Vector Store": {
      "main": [
        [
          {
            "node": "Post-Mortem Generator",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Post-Mortem Generator": {
      "main": [
        [
          {
            "node": "Update Learning Database",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Auto-Remediation Safe?": {
      "main": [
        [
          {
            "node": "Remediation Strategy Planner",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Request Manual Approval",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Blast Radius Evaluator": {
      "main": [
        [
          {
            "node": "Auto-Remediation Safe?",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Workflow Configuration": {
      "main": [
        [
          {
            "node": "Fetch Metrics Data",
            "type": "main",
            "index": 0
          },
          {
            "node": "Fetch Logs Data",
            "type": "main",
            "index": 0
          },
          {
            "node": "Fetch Traces Data",
            "type": "main",
            "index": 0
          },
          {
            "node": "Fetch Alerts Data",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Merge Remediation Paths": {
      "main": [
        [
          {
            "node": "Store Incident in Knowledge Graph",
            "type": "main",
            "index": 0
          },
          {
            "node": "Incident Vector Store",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Remediation Successful?": {
      "main": [
        [
          {
            "node": "Merge Remediation Paths",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Execute Rollback",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Anomaly Detection Engine": {
      "main": [
        [
          {
            "node": "Temporal Forecasting Model",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Escalate to On-Call Team": {
      "main": [
        [
          {
            "node": "Merge Remediation Paths",
            "type": "main",
            "index": 2
          }
        ]
      ]
    },
    "Incident Document Loader": {
      "ai_document": [
        [
          {
            "node": "Incident Vector Store",
            "type": "ai_document",
            "index": 0
          }
        ]
      ]
    },
    "Merge Observability Data": {
      "main": [
        [
          {
            "node": "Anomaly Detection Engine",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "OpenAI GPT-4 Diagnostics": {
      "ai_languageModel": [
        [
          {
            "node": "Escalation Diagnostics Generator",
            "type": "ai_languageModel",
            "index": 0
          }
        ]
      ]
    },
    "OpenAI GPT-4 Post-Mortem": {
      "ai_languageModel": [
        [
          {
            "node": "Post-Mortem Generator",
            "type": "ai_languageModel",
            "index": 0
          }
        ]
      ]
    },
    "OpenAI GPT-4 Remediation": {
      "ai_languageModel": [
        [
          {
            "node": "Remediation Strategy Planner",
            "type": "ai_languageModel",
            "index": 0
          }
        ]
      ]
    },
    "Root Cause Output Schema": {
      "ai_outputParser": [
        [
          {
            "node": "Root Cause Correlation Agent",
            "type": "ai_outputParser",
            "index": 0
          }
        ]
      ]
    },
    "Update Learning Database": {
      "main": [
        [
          {
            "node": "Send Post-Mortem Report",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Approval Response Webhook": {
      "main": [
        [
          {
            "node": "Approval Granted?",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Causal Inference Analysis": {
      "main": [
        [
          {
            "node": "Incident Predicted?",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Diagnostics Output Schema": {
      "ai_outputParser": [
        [
          {
            "node": "Escalation Diagnostics Generator",
            "type": "ai_outputParser",
            "index": 0
          }
        ]
      ]
    },
    "OpenAI GPT-4 Blast Radius": {
      "ai_languageModel": [
        [
          {
            "node": "Blast Radius Evaluator",
            "type": "ai_languageModel",
            "index": 0
          }
        ]
      ]
    },
    "Post-Mortem Output Schema": {
      "ai_outputParser": [
        [
          {
            "node": "Post-Mortem Generator",
            "type": "ai_outputParser",
            "index": 0
          }
        ]
      ]
    },
    "Blast Radius Output Schema": {
      "ai_outputParser": [
        [
          {
            "node": "Blast Radius Evaluator",
            "type": "ai_outputParser",
            "index": 0
          }
        ]
      ]
    },
    "Execute Remediation Action": {
      "main": [
        [
          {
            "node": "Wait for Remediation Effect",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Temporal Forecasting Model": {
      "main": [
        [
          {
            "node": "Causal Inference Analysis",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Verify Remediation Success": {
      "main": [
        [
          {
            "node": "Remediation Successful?",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Metrics Collection Schedule": {
      "main": [
        [
          {
            "node": "Workflow Configuration",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Wait for Remediation Effect": {
      "main": [
        [
          {
            "node": "Verify Remediation Success",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Remediation Strategy Planner": {
      "main": [
        [
          {
            "node": "Execute Remediation Action",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Root Cause Correlation Agent": {
      "main": [
        [
          {
            "node": "Blast Radius Evaluator",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Remediation Plan Output Schema": {
      "ai_outputParser": [
        [
          {
            "node": "Remediation Strategy Planner",
            "type": "ai_outputParser",
            "index": 0
          }
        ]
      ]
    },
    "Escalation Diagnostics Generator": {
      "main": [
        [
          {
            "node": "Escalate to On-Call Team",
            "type": "main",
            "index": 0
          }
        ]
      ]
    }
  }
}