/ scripts / add-agent-error-handling.js
add-agent-error-handling.js
 1  #!/usr/bin/env node
 2  
 3  /**
 4   * Add error handling to all agent processTask methods
 5   */
 6  
 7  import fs from 'fs';
 8  import path from 'path';
 9  
10  const agentFiles = [
11    'src/agents/architect.js',
12    'src/agents/security.js',
13    'src/agents/monitor.js',
14    'src/agents/triage.js',
15  ];
16  
17  for (const filePath of agentFiles) {
18    const fullPath = path.join(process.cwd(), filePath);
19    let content = fs.readFileSync(fullPath, 'utf8');
20  
21    // Pattern to match processTask method
22    const processTaskPattern = /(\s+async processTask\(task\) \{)\s+(switch \(task\.task_type\) \{)/s;
23  
24    // Replacement with error handling wrapper
25    const replacement = `$1
26      try {
27        // Parse context_json if needed
28        const context =
29          task.context_json && typeof task.context_json === 'string'
30            ? JSON.parse(task.context_json)
31            : task.context_json || {};
32  
33        // Ensure context is attached to task for handlers
34        task.context_json = context;
35  
36        $2`;
37  
38    content = content.replace(processTaskPattern, replacement);
39  
40    // Find closing brace of processTask and add catch block
41    // Look for the pattern: multiple closing braces near end of processTask
42    const catchBlock = `    } catch (error) {
43        await this.log('error', \`\${this.agentName.charAt(0).toUpperCase() + this.agentName.slice(1)} task \${task.id} failed: \${error.message}\`, {
44          task_id: task.id,
45          task_type: task.task_type,
46          error: error.message,
47          stack: error.stack,
48        });
49        throw error; // Re-throw so task manager can handle
50      }
51    }`;
52  
53    // Replace the final closing brace of processTask
54    const closingPattern = /^(\s+)\}$/gm;
55    const matches = [...content.matchAll(closingPattern)];
56  
57    // Find the correct closing brace by looking for processTask function boundaries
58    const processTaskStartIndex = content.indexOf('async processTask(task)');
59    const nextMethodIndex = content.indexOf('\n  async ', processTaskStartIndex + 50);
60  
61    let closingIndex = -1;
62    for (let i = matches.length - 1; i >= 0; i--) {
63      const match = matches[i];
64      if (
65        match.index > processTaskStartIndex &&
66        (nextMethodIndex === -1 || match.index < nextMethodIndex)
67      ) {
68        closingIndex = match.index;
69        break;
70      }
71    }
72  
73    if (closingIndex !== -1) {
74      content = content.slice(0, closingIndex) + catchBlock + content.slice(closingIndex + 4);
75    }
76  
77    fs.writeFileSync(fullPath, content);
78    console.log(`Updated ${filePath}`);
79  }
80  
81  console.log('All agent files updated with error handling');