{
  "workflow": {
    "name": "Bzzz Chat-to-Code Testing Pipeline",
    "description": "Chat-triggered workflow that sends tasks to Bzzz agents for sandbox execution and returns results",
    "version": "1.0",
    "trigger_type": "chat",
    "nodes": [
      {
        "id": "chat_trigger",
        "type": "Chat Trigger",
        "name": "Chat Input",
        "settings": {
          "webhookId": "bzzz-chat-test",
          "options": {
            "respondImmediately": false,
            "respondWithLastNode": true
          }
        },
        "position": [250, 300]
      },
      {
        "id": "parse_request",
        "type": "Code",
        "name": "Parse Chat Request",
        "parameters": {
          "jsCode": "// Parse incoming chat message for task details\nconst chatMessage = $input.first().json.chatInput || $input.first().json.body?.message || $input.first().json.message;\nconst userId = $input.first().json.userId || 'test-user';\n\n// Extract task information from chat message\nconst taskMatch = chatMessage.match(/task:\\s*(.+?)(?:\\n|$)/i);\nconst repoMatch = chatMessage.match(/repo:\\s*(.+?)(?:\\n|$)/i);\nconst langMatch = chatMessage.match(/lang(?:uage)?:\\s*(.+?)(?:\\n|$)/i);\n\n// Default values\nconst taskDescription = taskMatch ? taskMatch[1].trim() : chatMessage;\nconst repository = repoMatch ? repoMatch[1].trim() : 'https://github.com/test/sandbox-repo.git';\nconst language = langMatch ? langMatch[1].trim() : 'auto-detect';\n\n// Generate unique task ID\nconst taskId = Math.floor(Math.random() * 10000) + 1000;\n\nconst bzzzTask = {\n  task_id: taskId,\n  title: `Chat Task #${taskId}`,\n  description: taskDescription,\n  repository: repository,\n  language: language,\n  priority: 'medium',\n  requesting_user: userId,\n  chat_session: $input.first().json.sessionId || 'default',\n  created_at: new Date().toISOString(),\n  task_type: 'development',\n  requirements: {\n    sandbox: true,\n    execution_timeout: '10m',\n    max_iterations: 5\n  }\n};\n\nreturn { json: bzzzTask };"
        },
        "position": [450, 300]
      },
      {
        "id": "validate_task",
        "type": "HTTP Request",
        "name": "Validate Task with LLM",
        "parameters": {
          "method": "POST",
          "url": "http://192.168.1.27:11434/api/generate",
          "headers": {
            "Content-Type": "application/json"
          },
          "body": {
            "model": "phi4",
            "prompt": "Validate and enhance this development task for execution:\n\nTask: {{$json.description}}\nRepository: {{$json.repository}}\nLanguage: {{$json.language}}\n\nAnalyze:\n1. Is this a valid development task?\n2. Are there any security concerns?\n3. What specific steps would be needed?\n4. Estimated complexity (1-10)\n5. Recommended approach\n\nProvide validation result and enhanced task description.",
            "stream": false
          },
          "options": {
            "timeout": 30000
          }
        },
        "position": [650, 300]
      },
      {
        "id": "create_bzzz_request",
        "type": "Code",
        "name": "Create Bzzz API Request",
        "parameters": {
          "jsCode": "const originalTask = $input.all()[0].json;\nconst validation = JSON.parse($input.all()[1].json.response);\n\n// Enhanced task with LLM validation\nconst enhancedTask = {\n  ...originalTask,\n  enhanced_description: validation.enhanced_description || originalTask.description,\n  complexity_score: validation.complexity || 5,\n  security_validated: validation.security_ok !== false,\n  recommended_approach: validation.approach || 'iterative_development',\n  estimated_duration: validation.estimated_minutes || 10\n};\n\n// Bzzz API request format\nconst bzzzRequest = {\n  method: 'execute_task_in_sandbox',\n  task: enhancedTask,\n  execution_options: {\n    sandbox_image: 'registry.home.deepblack.cloud/tony/bzzz-sandbox:latest',\n    timeout: '600s',\n    max_iterations: 10,\n    return_full_log: true,\n    cleanup_on_complete: true\n  },\n  callback: {\n    webhook_url: `https://n8n.home.deepblack.cloud/webhook/bzzz-chat-result/${originalTask.task_id}`,\n    include_artifacts: true\n  }\n};\n\nreturn { json: bzzzRequest };"
        },
        "position": [850, 300]
      },
      {
        "id": "submit_to_bzzz",
        "type": "HTTP Request",
        "name": "Submit to Bzzz Agent",
        "parameters": {
          "method": "POST",
          "url": "http://localhost:8080/bzzz/api/execute-task",
          "headers": {
            "Content-Type": "application/json",
            "Authorization": "Bearer bzzz-test-token"
          },
          "body": "={{$json}}",
          "options": {
            "timeout": 60000
          }
        },
        "position": [1050, 300]
      },
      {
        "id": "send_confirmation",
        "type": "Respond to Webhook",
        "name": "Send Chat Confirmation",
        "parameters": {
          "respondBody": "🚀 **Task Submitted to Bzzz Agent**\\n\\n**Task ID:** {{$json.task.task_id}}\\n**Description:** {{$json.task.enhanced_description}}\\n**Complexity:** {{$json.task.complexity_score}}/10\\n**Estimated Duration:** {{$json.task.estimated_duration}} minutes\\n\\n⏳ Executing in sandbox... I'll notify you when complete!",
          "respondHeaders": {
            "Content-Type": "application/json"
          },
          "responseCode": 200
        },
        "position": [1250, 300]
      },
      {
        "id": "result_webhook",
        "type": "Webhook",
        "name": "Receive Bzzz Results",
        "parameters": {
          "path": "bzzz-chat-result",
          "method": "POST",
          "options": {
            "noResponseBody": false
          }
        },
        "position": [250, 600]
      },
      {
        "id": "process_results",
        "type": "Code",
        "name": "Process Execution Results",
        "parameters": {
          "jsCode": "const bzzzResult = $json;\nconst taskId = bzzzResult.task_id;\nconst executionStatus = bzzzResult.status;\nconst artifacts = bzzzResult.artifacts || {};\nconst executionLog = bzzzResult.execution_log || [];\nconst errors = bzzzResult.errors || [];\n\n// Format results for chat response\nlet resultMessage = `🎯 **Task #${taskId} Complete**\\n\\n`;\n\nif (executionStatus === 'success') {\n  resultMessage += `✅ **Status:** Successful\\n`;\n  resultMessage += `⏱️ **Duration:** ${bzzzResult.execution_time || 'Unknown'}\\n`;\n  \n  if (artifacts.files_created) {\n    resultMessage += `📁 **Files Created:** ${artifacts.files_created.length}\\n`;\n    artifacts.files_created.forEach(file => {\n      resultMessage += `   • ${file.name} (${file.size} bytes)\\n`;\n    });\n  }\n  \n  if (artifacts.code_generated) {\n    resultMessage += `\\n💻 **Generated Code:**\\n\\`\\`\\`${artifacts.language || 'text'}\\n${artifacts.code_generated.substring(0, 500)}${artifacts.code_generated.length > 500 ? '...' : ''}\\n\\`\\`\\`\\n`;\n  }\n  \n  if (bzzzResult.git_branch) {\n    resultMessage += `🌿 **Git Branch:** ${bzzzResult.git_branch}\\n`;\n  }\n  \n  if (bzzzResult.pr_url) {\n    resultMessage += `🔗 **Pull Request:** ${bzzzResult.pr_url}\\n`;\n  }\n  \n} else {\n  resultMessage += `❌ **Status:** Failed\\n`;\n  resultMessage += `⚠️ **Error:** ${errors[0]?.message || 'Unknown error'}\\n`;\n}\n\n// Add execution summary\nif (executionLog.length > 0) {\n  resultMessage += `\\n📋 **Execution Summary:**\\n`;\n  executionLog.slice(-3).forEach((log, i) => {\n    resultMessage += `${i + 1}. ${log.action}: ${log.result.substring(0, 100)}${log.result.length > 100 ? '...' : ''}\\n`;\n  });\n}\n\nconst processedResult = {\n  task_id: taskId,\n  status: executionStatus,\n  message: resultMessage,\n  original_request: bzzzResult.original_request,\n  execution_details: {\n    duration: bzzzResult.execution_time,\n    iterations: executionLog.length,\n    files_created: artifacts.files_created?.length || 0,\n    success: executionStatus === 'success'\n  },\n  raw_result: bzzzResult\n};\n\nreturn { json: processedResult };"
        },
        "position": [450, 600]
      },
      {
        "id": "notify_chat",
        "type": "HTTP Request",
        "name": "Send Result to Chat",
        "parameters": {
          "method": "POST",
          "url": "https://n8n.home.deepblack.cloud/webhook/bzzz-chat-notification",
          "headers": {
            "Content-Type": "application/json"
          },
          "body": {
            "chatSessionId": "{{$json.original_request.chat_session}}",
            "userId": "{{$json.original_request.requesting_user}}",
            "message": "{{$json.message}}",
            "taskId": "{{$json.task_id}}",
            "success": "{{$json.execution_details.success}}",
            "attachments": {
              "execution_log": "{{$json.raw_result.execution_log}}",
              "artifacts": "{{$json.raw_result.artifacts}}"
            }
          }
        },
        "position": [650, 600]
      },
      {
        "id": "log_execution",
        "type": "HTTP Request",
        "name": "Log to Audit System",
        "parameters": {
          "method": "POST",
          "url": "http://localhost:8080/bzzz/audit/chat-execution",
          "headers": {
            "Content-Type": "application/json"
          },
          "body": {
            "task_id": "{{$json.task_id}}",
            "user_id": "{{$json.original_request.requesting_user}}",
            "execution_status": "{{$json.status}}",
            "duration": "{{$json.execution_details.duration}}",
            "files_created": "{{$json.execution_details.files_created}}",
            "timestamp": "{{new Date().toISOString()}}",
            "source": "chat-integration"
          }
        },
        "position": [850, 600]
      }
    ],
    "connections": {
      "chat_trigger": {
        "main": [
          [
            {
              "node": "parse_request",
              "type": "main",
              "index": 0
            }
          ]
        ]
      },
      "parse_request": {
        "main": [
          [
            {
              "node": "validate_task",
              "type": "main",
              "index": 0
            }
          ]
        ]
      },
      "validate_task": {
        "main": [
          [
            {
              "node": "create_bzzz_request",
              "type": "main",
              "index": 0
            }
          ]
        ]
      },
      "create_bzzz_request": {
        "main": [
          [
            {
              "node": "submit_to_bzzz",
              "type": "main",
              "index": 0
            }
          ]
        ]
      },
      "submit_to_bzzz": {
        "main": [
          [
            {
              "node": "send_confirmation",
              "type": "main",
              "index": 0
            }
          ]
        ]
      },
      "result_webhook": {
        "main": [
          [
            {
              "node": "process_results",
              "type": "main",
              "index": 0
            }
          ]
        ]
      },
      "process_results": {
        "main": [
          [
            {
              "node": "notify_chat",
              "type": "main",
              "index": 0
            },
            {
              "node": "log_execution",
              "type": "main",
              "index": 0
            }
          ]
        ]
      }
    }
  },
  "chat_interface_examples": {
    "simple_request": "Create a simple 'Hello World' function in Python",
    "specific_task": "Task: Implement a REST API endpoint for user authentication\\nRepo: https://github.com/myorg/api-server.git\\nLanguage: Python",
    "complex_request": "Build a React component that displays a todo list with add/remove functionality. Include proper TypeScript types and basic styling.",
    "bug_fix": "Fix the memory leak in the user session handler - it's not properly cleaning up expired sessions"
  }
}