{
  "name": "Central Knowledge Management Orchestrator",
  "nodes": [
    {
      "parameters": {
        "pollTimes": {
          "item": [
            {
              "mode": "everyMinute"
            }
          ]
        },
        "triggerOn": "everyMinute",
        "options": {}
      },
      "id": "orchestrator-cron-trigger",
      "name": "Orchestrator Cron Trigger",
      "type": "n8n-nodes-base.cron",
      "typeVersion": 1,
      "position": [
        200,
        400
      ]
    },
    {
      "parameters": {
        "httpMethod": "POST",
        "path": "knowledge-orchestrator",
        "responseMode": "responseNode",
        "options": {}
      },
      "id": "orchestrator-webhook",
      "name": "Orchestrator Webhook",
      "type": "n8n-nodes-base.webhook",
      "typeVersion": 2,
      "position": [
        200,
        600
      ]
    },
    {
      "parameters": {
        "assignments": {
          "assignments": [
            {
              "id": "orchestration-mode",
              "name": "mode",
              "value": "={{ $json.body?.mode || 'auto' }}",
              "type": "string"
            },
            {
              "id": "target-systems",
              "name": "targetSystems",
              "value": "={{ $json.body?.targetSystems || ['appflowy', 'affine', 'google_drive'] }}",
              "type": "array"
            },
            {
              "id": "orchestration-timestamp",
              "name": "timestamp",
              "value": "={{ $now }}",
              "type": "string"
            },
            {
              "id": "force-full-sync",
              "name": "forceFullSync",
              "value": "={{ $json.body?.forceFullSync || false }}",
              "type": "boolean"
            },
            {
              "id": "enable-ai-analysis",
              "name": "enableAIAnalysis",
              "value": "={{ $json.body?.enableAIAnalysis || true }}",
              "type": "boolean"
            }
          ]
        },
        "options": {}
      },
      "id": "process-orchestration-request",
      "name": "Process Orchestration Request",
      "type": "n8n-nodes-base.set",
      "typeVersion": 3.4,
      "position": [
        450,
        500
      ]
    },
    {
      "parameters": {
        "operation": "executeQuery",
        "query": "SELECT \n  source_system,\n  COUNT(*) as total_documents,\n  MAX(sync_timestamp) as last_sync,\n  COUNT(CASE WHEN status = 'error' THEN 1 END) as error_count\nFROM knowledge_sync_log \nWHERE sync_timestamp > NOW() - INTERVAL '24 hours'\nGROUP BY source_system",
        "options": {}
      },
      "id": "analyze-system-health",
      "name": "Analyze System Health",
      "type": "n8n-nodes-base.postgres",
      "typeVersion": 2.5,
      "position": [
        700,
        300
      ],
      "credentials": {
        "postgres": {
          "name": "<your credential>"
        }
      }
    },
    {
      "parameters": {
        "operation": "executeQuery",
        "query": "SELECT \n  document_id,\n  source_system,\n  content_hash,\n  sync_timestamp,\n  metadata\nFROM knowledge_sync_log \nWHERE status = 'synced' \n  AND sync_timestamp > NOW() - INTERVAL '1 hour'\nORDER BY sync_timestamp DESC",
        "options": {}
      },
      "id": "get-recent-activity",
      "name": "Get Recent Activity",
      "type": "n8n-nodes-base.postgres",
      "typeVersion": 2.5,
      "position": [
        700,
        400
      ],
      "credentials": {
        "postgres": {
          "name": "<your credential>"
        }
      }
    },
    {
      "parameters": {
        "operation": "executeQuery",
        "query": "SELECT \n  sm.source_system,\n  sm.target_system,\n  sm.mapping_type,\n  COUNT(*) as mapping_count,\n  COUNT(CASE WHEN sm.status = 'active' THEN 1 END) as active_mappings,\n  COUNT(CASE WHEN sm.status = 'error' THEN 1 END) as error_mappings\nFROM knowledge_sync_mapping sm\nGROUP BY sm.source_system, sm.target_system, sm.mapping_type",
        "options": {}
      },
      "id": "check-sync-mappings",
      "name": "Check Sync Mappings",
      "type": "n8n-nodes-base.postgres",
      "typeVersion": 2.5,
      "position": [
        700,
        500
      ],
      "credentials": {
        "postgres": {
          "name": "<your credential>"
        }
      }
    },
    {
      "parameters": {
        "assignments": {
          "assignments": [
            {
              "id": "system-health-summary",
              "name": "systemHealth",
              "value": "={{ $('Analyze System Health').all().reduce((acc, item) => { acc[item.source_system] = { totalDocs: item.total_documents, lastSync: item.last_sync, errorCount: item.error_count, status: item.error_count > 0 ? 'warning' : 'healthy' }; return acc; }, {}) }}",
              "type": "object"
            },
            {
              "id": "recent-activity-count",
              "name": "recentActivityCount",
              "value": "={{ $('Get Recent Activity').all().length }}",
              "type": "number"
            },
            {
              "id": "sync-mappings-summary",
              "name": "syncMappings",
              "value": "={{ $('Check Sync Mappings').all() }}",
              "type": "array"
            },
            {
              "id": "needs-maintenance",
              "name": "needsMaintenance",
              "value": "={{ Object.values($json.systemHealth).some(system => system.status === 'warning') }}",
              "type": "boolean"
            },
            {
              "id": "needs-sync",
              "name": "needsSync",
              "value": "={{ $json.recentActivityCount > 0 || $('Process Orchestration Request').item.json.forceFullSync }}",
              "type": "boolean"
            }
          ]
        },
        "options": {}
      },
      "id": "evaluate-orchestration-needs",
      "name": "Evaluate Orchestration Needs",
      "type": "n8n-nodes-base.set",
      "typeVersion": 3.4,
      "position": [
        950,
        400
      ]
    },
    {
      "parameters": {
        "conditions": {
          "options": {
            "caseSensitive": true,
            "leftValue": "",
            "typeValidation": "strict"
          },
          "conditions": [
            {
              "id": "maintenance-needed",
              "leftValue": "={{ $json.needsMaintenance }}",
              "rightValue": true,
              "operator": {
                "type": "boolean",
                "operation": "true",
                "singleValue": true
              }
            }
          ],
          "combinator": "and"
        },
        "options": {}
      },
      "id": "check-maintenance-needed",
      "name": "Check Maintenance Needed",
      "type": "n8n-nodes-base.if",
      "typeVersion": 2,
      "position": [
        1200,
        300
      ]
    },
    {
      "parameters": {
        "conditions": {
          "options": {
            "caseSensitive": true,
            "leftValue": "",
            "typeValidation": "strict"
          },
          "conditions": [
            {
              "id": "sync-needed",
              "leftValue": "={{ $json.needsSync }}",
              "rightValue": true,
              "operator": {
                "type": "boolean",
                "operation": "true",
                "singleValue": true
              }
            }
          ],
          "combinator": "and"
        },
        "options": {}
      },
      "id": "check-sync-needed",
      "name": "Check Sync Needed",
      "type": "n8n-nodes-base.if",
      "typeVersion": 2,
      "position": [
        1200,
        500
      ]
    },
    {
      "parameters": {
        "url": "https://n8n.{{ $vars.domain_name }}/webhook/trigger-knowledge-sync",
        "options": {
          "timeout": 120000
        },
        "sendBody": true,
        "contentType": "json",
        "body": {
          "source": "all",
          "direction": "bidirectional",
          "forceSync": "={{ $('Process Orchestration Request').item.json.forceFullSync }}",
          "orchestrationSession": "={{ $('Process Orchestration Request').item.json.timestamp }}"
        }
      },
      "id": "trigger-bidirectional-sync",
      "name": "Trigger Bidirectional Sync",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        1450,
        400
      ]
    },
    {
      "parameters": {
        "url": "https://n8n.{{ $vars.domain_name }}/webhook/enhanced-rag-agent",
        "options": {
          "timeout": 60000
        },
        "sendBody": true,
        "contentType": "json",
        "body": {
          "chatInput": "Please analyze the recent knowledge management activity and provide insights about content patterns, frequently updated topics, and potential knowledge gaps.",
          "sessionId": "orchestrator-analysis-{{ $('Process Orchestration Request').item.json.timestamp }}",
          "enableAnalysis": "={{ $('Process Orchestration Request').item.json.enableAIAnalysis }}"
        }
      },
      "id": "trigger-ai-analysis",
      "name": "Trigger AI Analysis",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        1450,
        600
      ]
    },
    {
      "parameters": {
        "operation": "executeQuery",
        "query": "UPDATE knowledge_sync_log \nSET status = 'resolved'\nWHERE status = 'error' \n  AND sync_timestamp < NOW() - INTERVAL '1 hour'",
        "options": {}
      },
      "id": "cleanup-old-errors",
      "name": "Cleanup Old Errors",
      "type": "n8n-nodes-base.postgres",
      "typeVersion": 2.5,
      "position": [
        1450,
        200
      ],
      "credentials": {
        "postgres": {
          "name": "<your credential>"
        }
      }
    },
    {
      "parameters": {
        "url": "http://qdrant:6333/collections/knowledge_base/cluster/status",
        "options": {
          "timeout": 10000
        },
        "sendHeaders": true,
        "headerParameters": {
          "parameters": [
            {
              "name": "api-key",
              "value": "{{ $vars.qdrant_api_key }}"
            }
          ]
        }
      },
      "id": "check-vector-db-health",
      "name": "Check Vector DB Health",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        1450,
        100
      ]
    },
    {
      "parameters": {
        "assignments": {
          "assignments": [
            {
              "id": "orchestration-summary",
              "name": "orchestrationSummary",
              "value": "={{ { timestamp: $('Process Orchestration Request').item.json.timestamp, systemHealth: $('Evaluate Orchestration Needs').item.json.systemHealth, maintenancePerformed: $('Evaluate Orchestration Needs').item.json.needsMaintenance, syncTriggered: $('Evaluate Orchestration Needs').item.json.needsSync, recentActivity: $('Evaluate Orchestration Needs').item.json.recentActivityCount, vectorDbStatus: $('Check Vector DB Health').item.json.status || 'unknown', aiAnalysisEnabled: $('Process Orchestration Request').item.json.enableAIAnalysis } }}",
              "type": "object"
            }
          ]
        },
        "options": {}
      },
      "id": "compile-orchestration-report",
      "name": "Compile Orchestration Report",
      "type": "n8n-nodes-base.set",
      "typeVersion": 3.4,
      "position": [
        1700,
        400
      ]
    },
    {
      "parameters": {
        "operation": "insert",
        "table": {
          "__rl": true,
          "value": "orchestration_log",
          "mode": "list"
        },
        "data": {
          "insert": [
            {
              "column": "session_id",
              "value": "={{ $('Process Orchestration Request').item.json.timestamp }}"
            },
            {
              "column": "mode",
              "value": "={{ $('Process Orchestration Request').item.json.mode }}"
            },
            {
              "column": "target_systems",
              "value": "={{ $('Process Orchestration Request').item.json.targetSystems }}"
            },
            {
              "column": "maintenance_performed",
              "value": "={{ $('Evaluate Orchestration Needs').item.json.needsMaintenance }}"
            },
            {
              "column": "sync_triggered",
              "value": "={{ $('Evaluate Orchestration Needs').item.json.needsSync }}"
            },
            {
              "column": "system_health",
              "value": "={{ $('Evaluate Orchestration Needs').item.json.systemHealth }}"
            },
            {
              "column": "orchestration_summary",
              "value": "={{ $json.orchestrationSummary }}"
            },
            {
              "column": "created_at",
              "value": "={{ $now }}"
            }
          ]
        },
        "options": {}
      },
      "id": "log-orchestration-session",
      "name": "Log Orchestration Session",
      "type": "n8n-nodes-base.postgres",
      "typeVersion": 2.5,
      "position": [
        1950,
        400
      ],
      "credentials": {
        "postgres": {
          "name": "<your credential>"
        }
      }
    },
    {
      "parameters": {
        "conditions": {
          "options": {
            "caseSensitive": true,
            "leftValue": "",
            "typeValidation": "strict"
          },
          "conditions": [
            {
              "id": "webhook-trigger-check",
              "leftValue": "={{ $('Orchestrator Webhook').item }}",
              "rightValue": "",
              "operator": {
                "type": "object",
                "operation": "notEmpty"
              }
            }
          ],
          "combinator": "and"
        },
        "options": {}
      },
      "id": "check-webhook-response-needed",
      "name": "Check Webhook Response Needed",
      "type": "n8n-nodes-base.if",
      "typeVersion": 2,
      "position": [
        2200,
        400
      ]
    },
    {
      "parameters": {
        "options": {}
      },
      "id": "respond-to-orchestrator-webhook",
      "name": "Respond to Orchestrator Webhook",
      "type": "n8n-nodes-base.respondToWebhook",
      "typeVersion": 1.1,
      "position": [
        2450,
        300
      ]
    },
    {
      "parameters": {
        "pollTimes": {
          "item": [
            {
              "mode": "everyHour"
            }
          ]
        },
        "triggerOn": "everyHour",
        "options": {}
      },
      "id": "deep-analysis-trigger",
      "name": "Deep Analysis Trigger",
      "type": "n8n-nodes-base.cron",
      "typeVersion": 1,
      "position": [
        200,
        800
      ]
    },
    {
      "parameters": {
        "assignments": {
          "assignments": [
            {
              "id": "deep-analysis-mode",
              "name": "mode",
              "value": "deep_analysis",
              "type": "string"
            },
            {
              "id": "analysis-timestamp",
              "name": "timestamp",
              "value": "={{ $now }}",
              "type": "string"
            },
            {
              "id": "enable-full-ai",
              "name": "enableAIAnalysis",
              "value": true,
              "type": "boolean"
            }
          ]
        },
        "options": {}
      },
      "id": "prepare-deep-analysis",
      "name": "Prepare Deep Analysis",
      "type": "n8n-nodes-base.set",
      "typeVersion": 3.4,
      "position": [
        450,
        800
      ]
    },
    {
      "parameters": {
        "url": "https://n8n.{{ $vars.domain_name }}/webhook/enhanced-rag-agent",
        "options": {
          "timeout": 180000
        },
        "sendBody": true,
        "contentType": "json",
        "body": {
          "chatInput": "Perform a comprehensive analysis of the knowledge management system: 1) Identify content clusters and themes across all platforms, 2) Detect knowledge gaps and outdated information, 3) Suggest content consolidation opportunities, 4) Analyze user interaction patterns, 5) Recommend system optimizations.",
          "sessionId": "deep-analysis-{{ $json.timestamp }}",
          "enableAnalysis": true
        }
      },
      "id": "perform-deep-analysis",
      "name": "Perform Deep Analysis",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        700,
        800
      ]
    },
    {
      "parameters": {
        "operation": "insert",
        "table": {
          "__rl": true,
          "value": "deep_analysis_reports",
          "mode": "list"
        },
        "data": {
          "insert": [
            {
              "column": "analysis_timestamp",
              "value": "={{ $('Prepare Deep Analysis').item.json.timestamp }}"
            },
            {
              "column": "analysis_type",
              "value": "comprehensive_knowledge_audit"
            },
            {
              "column": "findings",
              "value": "={{ $json.output || $json.response || 'Analysis completed' }}"
            },
            {
              "column": "recommendations",
              "value": "{{ [] }}"
            },
            {
              "column": "created_at",
              "value": "={{ $now }}"
            }
          ]
        },
        "options": {}
      },
      "id": "store-deep-analysis-report",
      "name": "Store Deep Analysis Report",
      "type": "n8n-nodes-base.postgres",
      "typeVersion": 2.5,
      "position": [
        950,
        800
      ],
      "credentials": {
        "postgres": {
          "name": "<your credential>"
        }
      }
    },
    {
      "parameters": {
        "content": "## Central Knowledge Management Orchestrator\n\n**Purpose:** Master controller for the entire knowledge management ecosystem, coordinating all sync processes, health monitoring, and AI-driven insights.\n\n**Core Functions:**\n- **Health Monitoring**: Continuous system health checks across all platforms\n- **Sync Orchestration**: Coordinates bidirectional sync processes\n- **AI Analysis**: Triggers intelligent content analysis and recommendations  \n- **Maintenance**: Automated cleanup and optimization tasks\n- **Reporting**: Comprehensive logging and analytics\n- **Deep Analysis**: Periodic comprehensive knowledge audits\n\n**Triggers:**\n- Cron: Every minute for routine checks\n- Webhook: On-demand orchestration\n- Hourly: Deep analysis and comprehensive audits\n\n**Integrations:**\n- AppFlowy Content Sync\n- Affine Content Sync  \n- Bidirectional Knowledge Sync\n- Enhanced RAG AI Agent\n- Vector Database Health Checks\n- PostgreSQL Analytics\n\n**API Endpoints:**\n- POST /webhook/knowledge-orchestrator\n- Supports: mode, targetSystems, forceFullSync, enableAIAnalysis parameters",
        "height": 700,
        "width": 900,
        "color": 1
      },
      "id": "orchestrator-documentation",
      "name": "Orchestrator Documentation",
      "type": "n8n-nodes-base.stickyNote",
      "typeVersion": 1,
      "position": [
        2600,
        50
      ]
    }
  ],
  "connections": {
    "Orchestrator Cron Trigger": {
      "main": [
        [
          {
            "node": "Process Orchestration Request",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Orchestrator Webhook": {
      "main": [
        [
          {
            "node": "Process Orchestration Request",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Process Orchestration Request": {
      "main": [
        [
          {
            "node": "Analyze System Health",
            "type": "main",
            "index": 0
          },
          {
            "node": "Get Recent Activity",
            "type": "main",
            "index": 0
          },
          {
            "node": "Check Sync Mappings",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Get Recent Activity": {
      "main": [
        [
          {
            "node": "Evaluate Orchestration Needs",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Evaluate Orchestration Needs": {
      "main": [
        [
          {
            "node": "Check Maintenance Needed",
            "type": "main",
            "index": 0
          },
          {
            "node": "Check Sync Needed",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Check Maintenance Needed": {
      "main": [
        [
          {
            "node": "Cleanup Old Errors",
            "type": "main",
            "index": 0
          },
          {
            "node": "Check Vector DB Health",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Check Sync Needed": {
      "main": [
        [
          {
            "node": "Trigger Bidirectional Sync",
            "type": "main",
            "index": 0
          },
          {
            "node": "Trigger AI Analysis",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Trigger Bidirectional Sync": {
      "main": [
        [
          {
            "node": "Compile Orchestration Report",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Check Vector DB Health": {
      "main": [
        [
          {
            "node": "Compile Orchestration Report",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Compile Orchestration Report": {
      "main": [
        [
          {
            "node": "Log Orchestration Session",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Log Orchestration Session": {
      "main": [
        [
          {
            "node": "Check Webhook Response Needed",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Check Webhook Response Needed": {
      "main": [
        [
          {
            "node": "Respond to Orchestrator Webhook",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Deep Analysis Trigger": {
      "main": [
        [
          {
            "node": "Prepare Deep Analysis",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Prepare Deep Analysis": {
      "main": [
        [
          {
            "node": "Perform Deep Analysis",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Perform Deep Analysis": {
      "main": [
        [
          {
            "node": "Store Deep Analysis Report",
            "type": "main",
            "index": 0
          }
        ]
      ]
    }
  },
  "active": true,
  "settings": {
    "executionOrder": "v1"
  },
  "versionId": "orchestrator-v1",
  "meta": {
    "templateCredsSetupCompleted": true
  },
  "id": "KnowledgeOrchestrator",
  "tags": [
    "orchestrator",
    "knowledge-management",
    "automation",
    "monitoring",
    "ai-analysis"
  ]
}