File size: 5,024 Bytes
3a92230
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
const AGENTS = [
  { id: 'pm', name: 'Product Manager', icon: 'πŸ“‹', color: 'blue' },
  { id: 'architect', name: 'Architect', icon: 'πŸ—οΈ', color: 'purple' },
  { id: 'planner', name: 'Task Planner', icon: 'πŸ“', color: 'indigo' },
  { id: 'backend', name: 'Backend Dev', icon: 'βš™οΈ', color: 'green' },
  { id: 'frontend', name: 'Frontend Dev', icon: '🎨', color: 'pink' },
  { id: 'devops', name: 'DevOps', icon: 'πŸš€', color: 'orange' },
  { id: 'qa', name: 'QA Agent', icon: 'πŸ§ͺ', color: 'yellow' },
  { id: 'reviewer', name: 'Code Review', icon: 'πŸ”', color: 'cyan' },
  { id: 'security', name: 'Security', icon: 'πŸ”', color: 'red' },
  { id: 'docs', name: 'Documentation', icon: 'πŸ“–', color: 'teal' },
  { id: 'knowledge', name: 'Knowledge Mgr', icon: '🧠', color: 'violet' },
];

const WORKFLOW_STEPS = [
  { phase: 'Planning', agents: ['pm', 'architect', 'planner'], description: 'Define requirements and architecture' },
  { phase: 'Execution', agents: ['backend', 'frontend', 'devops'], description: 'Implement and deploy' },
  { phase: 'Validation', agents: ['qa', 'security', 'reviewer'], description: 'Test, secure, and review' },
  { phase: 'Documentation', agents: ['docs'], description: 'Update all documentation' },
  { phase: 'Learning', agents: ['knowledge'], description: 'Extract and store learnings' },
];

const SAMPLE_TASKS = [
  'Build a REST API for user management',
  'Create a real-time chat feature',
  'Implement authentication with OAuth2',
  'Build a dashboard analytics module',
  'Create a file upload service',
  'Implement search functionality with Elasticsearch',
];

const KNOWLEDGE_ENTRIES = [
  {
    task: 'JWT Authentication Implementation',
    error: 'Token expiration not validated on server side',
    root_cause: 'Missing expiration check in middleware',
    fix: 'Added exp claim validation in auth middleware',
    prevention_rule: 'IF using JWT THEN validate expiration config BECAUSE misconfiguration causes auth issues',
    success_score: 0.85,
    tags: ['auth', 'jwt', 'security'],
  },
  {
    task: 'Database Migration',
    error: 'Data loss during column rename',
    root_cause: 'Direct column rename without backup',
    fix: 'Added backup step and incremental migration',
    prevention_rule: 'IF modifying schema THEN create backup first BECAUSE direct changes can cause data loss',
    success_score: 0.72,
    tags: ['database', 'migration', 'data'],
  },
  {
    task: 'API Rate Limiting',
    error: 'Legitimate users blocked',
    root_cause: 'Rate limit too aggressive for normal usage',
    fix: 'Adjusted limits based on traffic analysis',
    prevention_rule: 'IF implementing rate limits THEN analyze traffic patterns first BECAUSE aggressive limits block valid users',
    success_score: 0.91,
    tags: ['api', 'rate-limiting', 'performance'],
  },
];

function generateCommunication(agentId, step, task) {
  const agent = AGENTS.find(a => a.id === agentId);
  const statuses = ['pending', 'in_progress', 'done'];
  const status = statuses[Math.floor(Math.random() * 2) + 1];
  
  const outputs = {
    pm: `Requirements defined for: ${task}`,
    architect: `System design completed for: ${task}`,
    planner: `Task decomposed into 5 subtasks`,
    backend: `API endpoints implemented`,
    frontend: `UI components built and integrated`,
    devops: `CI/CD pipeline configured`,
    qa: `12 tests written, all passing`,
    reviewer: `Code reviewed, 3 improvements suggested`,
    security: `No critical vulnerabilities found`,
    docs: `Documentation updated`,
    knowledge: `Experience logged to knowledge base`,
  };

  return {
    agent: agent.name,
    task: step.description,
    input: task,
    output: outputs[agentId] || 'Task completed',
    issues: status === 'in_progress' ? ['Awaiting dependency'] : [],
    status,
    next_step: status === 'done' ? 'Proceed to next phase' : 'Continue current work',
    timestamp: new Date().toISOString(),
  };
}

export default function handler(req, res) {
  if (req.method !== 'POST') {
    return res.status(405).json({ error: 'Method not allowed' });
  }

  const { task, mode = 'safe' } = req.body;
  const selectedTask = task || SAMPLE_TASKS[Math.floor(Math.random() * SAMPLE_TASKS.length)];

  const simulation = {
    task: selectedTask,
    mode,
    startedAt: new Date().toISOString(),
    phases: WORKFLOW_STEPS.map((step, phaseIndex) => {
      const communications = step.agents.map(agentId => 
        generateCommunication(agentId, step, selectedTask)
      );
      return {
        phase: step.phase,
        description: step.description,
        order: phaseIndex + 1,
        communications,
        status: 'done',
      };
    }),
    knowledge: KNOWLEDGE_ENTRIES,
    definitionOfDone: {
      code_compiles: true,
      tests_pass: true,
      security_checks: mode !== 'fast',
      code_reviewed: mode !== 'fast',
      docs_updated: mode === 'safe',
    },
    completedAt: new Date().toISOString(),
  };

  res.status(200).json(simulation);
}