@loxia-labs/loxia-autopilot-one 1.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (80) hide show
  1. package/LICENSE +267 -0
  2. package/README.md +509 -0
  3. package/bin/cli.js +117 -0
  4. package/package.json +94 -0
  5. package/scripts/install-scanners.js +236 -0
  6. package/src/analyzers/CSSAnalyzer.js +297 -0
  7. package/src/analyzers/ConfigValidator.js +690 -0
  8. package/src/analyzers/ESLintAnalyzer.js +320 -0
  9. package/src/analyzers/JavaScriptAnalyzer.js +261 -0
  10. package/src/analyzers/PrettierFormatter.js +247 -0
  11. package/src/analyzers/PythonAnalyzer.js +266 -0
  12. package/src/analyzers/SecurityAnalyzer.js +729 -0
  13. package/src/analyzers/TypeScriptAnalyzer.js +247 -0
  14. package/src/analyzers/codeCloneDetector/analyzer.js +344 -0
  15. package/src/analyzers/codeCloneDetector/detector.js +203 -0
  16. package/src/analyzers/codeCloneDetector/index.js +160 -0
  17. package/src/analyzers/codeCloneDetector/parser.js +199 -0
  18. package/src/analyzers/codeCloneDetector/reporter.js +148 -0
  19. package/src/analyzers/codeCloneDetector/scanner.js +59 -0
  20. package/src/core/agentPool.js +1474 -0
  21. package/src/core/agentScheduler.js +2147 -0
  22. package/src/core/contextManager.js +709 -0
  23. package/src/core/messageProcessor.js +732 -0
  24. package/src/core/orchestrator.js +548 -0
  25. package/src/core/stateManager.js +877 -0
  26. package/src/index.js +631 -0
  27. package/src/interfaces/cli.js +549 -0
  28. package/src/interfaces/webServer.js +2162 -0
  29. package/src/modules/fileExplorer/controller.js +280 -0
  30. package/src/modules/fileExplorer/index.js +37 -0
  31. package/src/modules/fileExplorer/middleware.js +92 -0
  32. package/src/modules/fileExplorer/routes.js +125 -0
  33. package/src/modules/fileExplorer/types.js +44 -0
  34. package/src/services/aiService.js +1232 -0
  35. package/src/services/apiKeyManager.js +164 -0
  36. package/src/services/benchmarkService.js +366 -0
  37. package/src/services/budgetService.js +539 -0
  38. package/src/services/contextInjectionService.js +247 -0
  39. package/src/services/conversationCompactionService.js +637 -0
  40. package/src/services/errorHandler.js +810 -0
  41. package/src/services/fileAttachmentService.js +544 -0
  42. package/src/services/modelRouterService.js +366 -0
  43. package/src/services/modelsService.js +322 -0
  44. package/src/services/qualityInspector.js +796 -0
  45. package/src/services/tokenCountingService.js +536 -0
  46. package/src/tools/agentCommunicationTool.js +1344 -0
  47. package/src/tools/agentDelayTool.js +485 -0
  48. package/src/tools/asyncToolManager.js +604 -0
  49. package/src/tools/baseTool.js +800 -0
  50. package/src/tools/browserTool.js +920 -0
  51. package/src/tools/cloneDetectionTool.js +621 -0
  52. package/src/tools/dependencyResolverTool.js +1215 -0
  53. package/src/tools/fileContentReplaceTool.js +875 -0
  54. package/src/tools/fileSystemTool.js +1107 -0
  55. package/src/tools/fileTreeTool.js +853 -0
  56. package/src/tools/imageTool.js +901 -0
  57. package/src/tools/importAnalyzerTool.js +1060 -0
  58. package/src/tools/jobDoneTool.js +248 -0
  59. package/src/tools/seekTool.js +956 -0
  60. package/src/tools/staticAnalysisTool.js +1778 -0
  61. package/src/tools/taskManagerTool.js +2873 -0
  62. package/src/tools/terminalTool.js +2304 -0
  63. package/src/tools/webTool.js +1430 -0
  64. package/src/types/agent.js +519 -0
  65. package/src/types/contextReference.js +972 -0
  66. package/src/types/conversation.js +730 -0
  67. package/src/types/toolCommand.js +747 -0
  68. package/src/utilities/attachmentValidator.js +292 -0
  69. package/src/utilities/configManager.js +582 -0
  70. package/src/utilities/constants.js +722 -0
  71. package/src/utilities/directoryAccessManager.js +535 -0
  72. package/src/utilities/fileProcessor.js +307 -0
  73. package/src/utilities/logger.js +436 -0
  74. package/src/utilities/tagParser.js +1246 -0
  75. package/src/utilities/toolConstants.js +317 -0
  76. package/web-ui/build/index.html +15 -0
  77. package/web-ui/build/logo.png +0 -0
  78. package/web-ui/build/logo2.png +0 -0
  79. package/web-ui/build/static/index-CjkkcnFA.js +344 -0
  80. package/web-ui/build/static/index-Dy2bYbOa.css +1 -0
@@ -0,0 +1,2873 @@
1
+ /**
2
+ * TaskManagerTool - Manages task list for agent autonomous operation
3
+ *
4
+ * Purpose:
5
+ * - Allows agents to create, update, and manage their own TODO list
6
+ * - Provides task tracking for agent-mode scheduling decisions
7
+ * - Ensures agents only consume resources when they have actual work
8
+ */
9
+
10
+ import { BaseTool } from './baseTool.js';
11
+ import { v4 as uuidv4 } from 'uuid';
12
+
13
+ class TaskManagerTool extends BaseTool {
14
+ constructor(config = {}) {
15
+ super({
16
+ name: 'taskmanager',
17
+ description: config.description || 'Task management tool for organizing and tracking work',
18
+ ...config
19
+ });
20
+
21
+ this.supportedActions = ['create', 'update', 'list', 'complete', 'cancel', 'clear', 'depend', 'relate', 'subtask', 'prioritize', 'template', 'progress', 'analytics', 'sync'];
22
+ this.taskStatuses = ['pending', 'in_progress', 'blocked', 'completed', 'cancelled'];
23
+ this.taskPriorities = ['urgent', 'high', 'medium', 'low'];
24
+ this.dependencyTypes = ['blocks', 'relates', 'subtask', 'parent'];
25
+
26
+ // Phase 3.4: Progress tracking stages
27
+ this.progressStages = ['not_started', 'planning', 'in_development', 'testing', 'review', 'completed'];
28
+ this.milestoneTypes = ['checkpoint', 'deliverable', 'review_point', 'dependency_gate'];
29
+
30
+ // Phase 3.2: Priority scoring weights
31
+ this.priorityWeights = {
32
+ blocking: 3.0, // Tasks that block others
33
+ age: 1.5, // Older tasks get higher priority
34
+ userPriority: 2.0, // User-defined priority
35
+ contextSwitching: 1.2, // Reduce context switching penalty
36
+ dependency: 1.8 // Tasks with many dependencies
37
+ };
38
+
39
+ // Phase 3.3: Built-in task templates
40
+ this.taskTemplates = {
41
+ 'web-app-development': {
42
+ name: 'Web Application Development',
43
+ description: 'Complete workflow for building a web application',
44
+ category: 'development',
45
+ tasks: [
46
+ {
47
+ title: 'Project Setup & Planning',
48
+ description: 'Initialize project structure, configure tools, and plan architecture',
49
+ priority: 'high',
50
+ dependencies: []
51
+ },
52
+ {
53
+ title: 'Database Design & Setup',
54
+ description: 'Design database schema, create tables, and set up connections',
55
+ priority: 'high',
56
+ dependencies: ['Project Setup & Planning']
57
+ },
58
+ {
59
+ title: 'Backend API Development',
60
+ description: 'Implement REST API endpoints and business logic',
61
+ priority: 'high',
62
+ dependencies: ['Database Design & Setup']
63
+ },
64
+ {
65
+ title: 'Frontend Development',
66
+ description: 'Build user interface components and implement client-side logic',
67
+ priority: 'medium',
68
+ dependencies: ['Backend API Development']
69
+ },
70
+ {
71
+ title: 'Testing & Quality Assurance',
72
+ description: 'Write and run unit tests, integration tests, and perform QA',
73
+ priority: 'medium',
74
+ dependencies: ['Frontend Development']
75
+ },
76
+ {
77
+ title: 'Deployment & Launch',
78
+ description: 'Deploy to production environment and monitor launch',
79
+ priority: 'high',
80
+ dependencies: ['Testing & Quality Assurance']
81
+ }
82
+ ]
83
+ },
84
+ 'api-integration': {
85
+ name: 'API Integration',
86
+ description: 'Standard workflow for integrating with external APIs',
87
+ category: 'integration',
88
+ tasks: [
89
+ {
90
+ title: 'API Research & Documentation Review',
91
+ description: 'Study API documentation, authentication, and rate limits',
92
+ priority: 'high',
93
+ dependencies: []
94
+ },
95
+ {
96
+ title: 'Authentication Setup',
97
+ description: 'Implement API key management and authentication flow',
98
+ priority: 'high',
99
+ dependencies: ['API Research & Documentation Review']
100
+ },
101
+ {
102
+ title: 'Core Integration Implementation',
103
+ description: 'Build API client and implement main integration logic',
104
+ priority: 'high',
105
+ dependencies: ['Authentication Setup']
106
+ },
107
+ {
108
+ title: 'Error Handling & Retry Logic',
109
+ description: 'Implement robust error handling and retry mechanisms',
110
+ priority: 'medium',
111
+ dependencies: ['Core Integration Implementation']
112
+ },
113
+ {
114
+ title: 'Testing & Validation',
115
+ description: 'Test integration with various scenarios and edge cases',
116
+ priority: 'medium',
117
+ dependencies: ['Error Handling & Retry Logic']
118
+ }
119
+ ]
120
+ },
121
+ 'bug-fix': {
122
+ name: 'Bug Fix Workflow',
123
+ description: 'Systematic approach to identifying and fixing bugs',
124
+ category: 'maintenance',
125
+ tasks: [
126
+ {
127
+ title: 'Bug Reproduction & Analysis',
128
+ description: 'Reproduce the bug and analyze root cause',
129
+ priority: 'urgent',
130
+ dependencies: []
131
+ },
132
+ {
133
+ title: 'Fix Implementation',
134
+ description: 'Implement the bug fix with minimal side effects',
135
+ priority: 'urgent',
136
+ dependencies: ['Bug Reproduction & Analysis']
137
+ },
138
+ {
139
+ title: 'Testing & Verification',
140
+ description: 'Test fix and verify no regressions introduced',
141
+ priority: 'high',
142
+ dependencies: ['Fix Implementation']
143
+ },
144
+ {
145
+ title: 'Documentation Update',
146
+ description: 'Update documentation if behavior changed',
147
+ priority: 'low',
148
+ dependencies: ['Testing & Verification']
149
+ }
150
+ ]
151
+ },
152
+ 'feature-development': {
153
+ name: 'Feature Development',
154
+ description: 'End-to-end feature development workflow',
155
+ category: 'development',
156
+ tasks: [
157
+ {
158
+ title: 'Requirements Analysis',
159
+ description: 'Analyze requirements and create technical specification',
160
+ priority: 'high',
161
+ dependencies: []
162
+ },
163
+ {
164
+ title: 'Design & Architecture',
165
+ description: 'Design system architecture and user interface',
166
+ priority: 'high',
167
+ dependencies: ['Requirements Analysis']
168
+ },
169
+ {
170
+ title: 'Backend Implementation',
171
+ description: 'Implement backend logic and data models',
172
+ priority: 'high',
173
+ dependencies: ['Design & Architecture']
174
+ },
175
+ {
176
+ title: 'Frontend Implementation',
177
+ description: 'Build user interface and integrate with backend',
178
+ priority: 'medium',
179
+ dependencies: ['Backend Implementation']
180
+ },
181
+ {
182
+ title: 'Testing & Documentation',
183
+ description: 'Write tests and update documentation',
184
+ priority: 'medium',
185
+ dependencies: ['Frontend Implementation']
186
+ }
187
+ ]
188
+ }
189
+ };
190
+ }
191
+
192
+ /**
193
+ * Get basic tool description (required by BaseTool)
194
+ * @returns {string} Tool description
195
+ */
196
+ getDescription() {
197
+ return `
198
+ Task Manager Tool: Organize and track work with TODO lists for agent-mode scheduling.
199
+
200
+ **CRITICAL FOR AGENT MODE**: You MUST maintain your task list to remain active in agent mode!
201
+
202
+ The TaskManager tool allows you to organize and track your work. Without tasks, you will not receive scheduling time.
203
+
204
+ ### Actions:
205
+ - **sync**: 🌟 RECOMMENDED - Manage entire task list at once (Claude Code style)
206
+ - **create**: Create a new task with title and description
207
+ - **update**: Update task status or properties
208
+ - **list**: List all tasks with their current status
209
+ - **complete**: Mark a task as completed
210
+ - **cancel**: Cancel a task (mark as irrelevant)
211
+ - **clear**: Clear all completed/cancelled tasks
212
+ - **depend**: Create dependency between tasks (blocking relationships)
213
+ - **relate**: Link related tasks (non-blocking associations)
214
+ - **subtask**: Create subtask relationships (parent-child hierarchy)
215
+ - **prioritize**: Intelligent task prioritization with multiple modes
216
+ - **template**: Template management for common workflows
217
+ - **progress**: Track task progress with stages, milestones, and notes
218
+
219
+ ### Usage Examples:
220
+
221
+ ✨ Sync entire task list (RECOMMENDED - create comprehensive breakdown):
222
+ <taskmanager>
223
+ <action>sync</action>
224
+ <tasks>[
225
+ {
226
+ "title": "Analyze user requirements",
227
+ "description": "Understand what the user wants to achieve",
228
+ "status": "completed",
229
+ "priority": "high"
230
+ },
231
+ {
232
+ "title": "Design database schema",
233
+ "description": "Create tables and relationships",
234
+ "status": "in_progress",
235
+ "priority": "high"
236
+ },
237
+ {
238
+ "title": "Implement API endpoints",
239
+ "status": "pending",
240
+ "priority": "medium"
241
+ },
242
+ {
243
+ "title": "Write tests",
244
+ "status": "pending",
245
+ "priority": "medium"
246
+ }
247
+ ]</tasks>
248
+ </taskmanager>
249
+
250
+ Create a task:
251
+ <taskmanager>
252
+ <action>create</action>
253
+ <title>Analyze user requirements</title>
254
+ <description>Break down the user's request into actionable steps</description>
255
+ <priority>high</priority>
256
+ </taskmanager>
257
+
258
+ List all tasks:
259
+ <taskmanager>
260
+ <action>list</action>
261
+ </taskmanager>
262
+
263
+ Create task dependency:
264
+ <taskmanager>
265
+ <action>depend</action>
266
+ <taskId>task-uuid-here</taskId>
267
+ <dependsOn>other-task-uuid</dependsOn>
268
+ <dependencyType>blocks</dependencyType>
269
+ </taskmanager>
270
+
271
+ Create subtask:
272
+ <taskmanager>
273
+ <action>subtask</action>
274
+ <parentTaskId>parent-task-uuid</parentTaskId>
275
+ <title>Implement user authentication</title>
276
+ <description>Create login and signup functionality</description>
277
+ <priority>high</priority>
278
+ </taskmanager>
279
+
280
+ Auto-prioritize all tasks:
281
+ <taskmanager>
282
+ <action>prioritize</action>
283
+ <mode>auto</mode>
284
+ </taskmanager>
285
+
286
+ Analyze specific task priority:
287
+ <taskmanager>
288
+ <action>prioritize</action>
289
+ <mode>analyze</mode>
290
+ <taskId>task-uuid-here</taskId>
291
+ </taskmanager>
292
+
293
+ Balance workload across agents:
294
+ <taskmanager>
295
+ <action>prioritize</action>
296
+ <mode>balance</mode>
297
+ </taskmanager>
298
+
299
+ List available templates:
300
+ <taskmanager>
301
+ <action>template</action>
302
+ <mode>list</mode>
303
+ </taskmanager>
304
+
305
+ Apply web app development template:
306
+ <taskmanager>
307
+ <action>template</action>
308
+ <mode>apply</mode>
309
+ <templateId>web-app-development</templateId>
310
+ <projectContext>{"projectName": "UserPortal", "urgency": "high"}</projectContext>
311
+ </taskmanager>
312
+
313
+ Suggest templates based on current tasks:
314
+ <taskmanager>
315
+ <action>template</action>
316
+ <mode>suggest</mode>
317
+ </taskmanager>
318
+
319
+ Update task progress:
320
+ <taskmanager>
321
+ <action>progress</action>
322
+ <mode>update</mode>
323
+ <taskId>task-uuid-here</taskId>
324
+ <stage>in_development</stage>
325
+ <percentage>45</percentage>
326
+ <note>Completed API integration, starting frontend work</note>
327
+ </taskmanager>
328
+
329
+ Get progress overview:
330
+ <taskmanager>
331
+ <action>progress</action>
332
+ <mode>overview</mode>
333
+ </taskmanager>
334
+
335
+ Calculate progress based on subtasks:
336
+ <taskmanager>
337
+ <action>progress</action>
338
+ <mode>calculate</mode>
339
+ <taskId>task-uuid-here</taskId>
340
+ </taskmanager>
341
+
342
+ ### 🚨 MANDATORY WORKFLOW - ZERO EXCEPTIONS ALLOWED:
343
+
344
+ **EVERY RESPONSE MUST:**
345
+ 1. **START WITH**: <taskmanager><action>list</action></taskmanager>
346
+ 2. **WORK**: Complete the user's request
347
+ 3. **END WITH**: <taskmanager><action>complete</action><taskId>ID</taskId></taskmanager>
348
+
349
+ **WARNING: Skipping this workflow = INFINITE LOOPS = SYSTEM FAILURE!**
350
+ **NO RESPONSE IS COMPLETE WITHOUT TASK COMPLETION!**
351
+
352
+ STEP 1 - Always start by listing tasks:
353
+ <taskmanager>
354
+ <action>list</action>
355
+ </taskmanager>
356
+
357
+ STEP 2 - After completing work, mark task complete:
358
+ <taskmanager>
359
+ <action>complete</action>
360
+ <taskId>task-1759257696373-wjsquroxz</taskId>
361
+ </taskmanager>
362
+
363
+ ### MANDATORY: Complete tasks when done or you'll loop forever!
364
+ `;
365
+ }
366
+
367
+ /**
368
+ * Parse parameters from XML tag format
369
+ * Unwraps values from tag parser's {value, attributes} format
370
+ * @param {Object} content - Raw parameters from tag parser or string content
371
+ * @returns {Object} Parsed parameters with unwrapped values
372
+ */
373
+ parseParameters(content) {
374
+ // If content is a string, return as-is for legacy support
375
+ if (typeof content === 'string') {
376
+ return { rawContent: content };
377
+ }
378
+
379
+ // If content is already an object, unwrap tag parser format
380
+ if (typeof content === 'object' && content !== null) {
381
+ const unwrapped = {};
382
+
383
+ for (const [key, value] of Object.entries(content)) {
384
+ // Check if this is tag parser format: {value: "...", attributes: {}}
385
+ if (value && typeof value === 'object' && 'value' in value) {
386
+ unwrapped[key] = value.value;
387
+ } else {
388
+ // Keep as-is if not wrapped
389
+ unwrapped[key] = value;
390
+ }
391
+ }
392
+
393
+ return unwrapped;
394
+ }
395
+
396
+ return content;
397
+ }
398
+
399
+ /**
400
+ * Execute task management action
401
+ * @param {Object} params - Tool arguments
402
+ * @param {Object} context - Execution context
403
+ * @returns {Promise<Object>} Execution result
404
+ */
405
+ async execute(params, context) {
406
+ try {
407
+ // CRITICAL FIX: Unwrap tag parser format {value, attributes}
408
+ // The messageProcessor passes params with wrapped values from parseXMLParameters
409
+ // We need to unwrap them before processing
410
+ const unwrappedParams = {};
411
+ for (const [key, value] of Object.entries(params)) {
412
+ if (value && typeof value === 'object' && 'value' in value) {
413
+ // Tag parser wrapped format: {value: "...", attributes: {}}
414
+ unwrappedParams[key] = value.value;
415
+ } else {
416
+ // Already unwrapped or direct value
417
+ unwrappedParams[key] = value;
418
+ }
419
+ }
420
+
421
+ // Use unwrapped params for all subsequent processing
422
+ params = unwrappedParams;
423
+
424
+ const { agentId, agentName } = context;
425
+
426
+ if (!agentId) {
427
+ throw new Error('Agent ID is required for task management');
428
+ }
429
+
430
+ // Get agent from pool
431
+ const agent = await context.agentPool.getAgent(agentId);
432
+ if (!agent) {
433
+ throw new Error(`Agent not found: ${agentId}`);
434
+ }
435
+
436
+ // Initialize taskList if it doesn't exist (for backwards compatibility)
437
+ if (!agent.taskList) {
438
+ agent.taskList = {
439
+ tasks: [],
440
+ lastUpdated: new Date().toISOString()
441
+ };
442
+ }
443
+
444
+ const action = params.action?.toLowerCase();
445
+ if (!this.supportedActions.includes(action)) {
446
+ throw new Error(`Unsupported action: ${action}. Supported: ${this.supportedActions.join(', ')}`);
447
+ }
448
+
449
+ let result;
450
+ switch (action) {
451
+ case 'create':
452
+ result = await this.createTask(agent, params);
453
+ break;
454
+ case 'update':
455
+ result = await this.updateTask(agent, params);
456
+ break;
457
+ case 'list':
458
+ result = await this.listTasks(agent, params);
459
+ break;
460
+ case 'complete':
461
+ result = await this.completeTask(agent, params);
462
+ break;
463
+ case 'cancel':
464
+ result = await this.cancelTask(agent, params);
465
+ break;
466
+ case 'clear':
467
+ result = await this.clearCompletedTasks(agent, params);
468
+ break;
469
+ case 'depend':
470
+ result = await this.createDependency(agent, params);
471
+ break;
472
+ case 'relate':
473
+ result = await this.relateTask(agent, params);
474
+ break;
475
+ case 'subtask':
476
+ result = await this.createSubtask(agent, params);
477
+ break;
478
+ case 'prioritize':
479
+ result = await this.intelligentPrioritization(agent, params);
480
+ break;
481
+ case 'template':
482
+ result = await this.manageTemplates(agent, params);
483
+ break;
484
+ case 'progress':
485
+ result = await this.trackProgress(agent, params);
486
+ break;
487
+ case 'analytics':
488
+ result = await this.generateAnalytics(agent, params);
489
+ break;
490
+ case 'sync':
491
+ result = await this.syncTasks(agent, params);
492
+ break;
493
+ default:
494
+ throw new Error(`Unknown action: ${action}`);
495
+ }
496
+
497
+ // Update the agent's lastActivity
498
+ agent.lastActivity = new Date().toISOString();
499
+ agent.taskList.lastUpdated = new Date().toISOString();
500
+
501
+ // Persist the agent state
502
+ await context.agentPool.persistAgentState(agentId);
503
+
504
+ this.logger?.info(`TaskManager action executed: ${action}`, {
505
+ agentId,
506
+ agentName,
507
+ action,
508
+ taskCount: agent.taskList.tasks.length,
509
+ pendingTasks: agent.taskList.tasks.filter(t => t.status === 'pending').length,
510
+ inProgressTasks: agent.taskList.tasks.filter(t => t.status === 'in_progress').length
511
+ });
512
+
513
+ return {
514
+ success: true,
515
+ action,
516
+ result,
517
+ summary: this.generateTaskSummary(agent.taskList)
518
+ };
519
+
520
+ } catch (error) {
521
+ this.logger?.error('TaskManager execution failed', {
522
+ error: error.message,
523
+ context,
524
+ params
525
+ });
526
+
527
+ return {
528
+ success: false,
529
+ error: error.message
530
+ };
531
+ }
532
+ }
533
+
534
+ /**
535
+ * Create a new task
536
+ * @private
537
+ */
538
+ async createTask(agent, params) {
539
+ const { title, description = '', priority = 'medium' } = params;
540
+
541
+ if (!title) {
542
+ throw new Error('Task title is required');
543
+ }
544
+
545
+ if (priority && !this.taskPriorities.includes(priority.toLowerCase())) {
546
+ throw new Error(`Invalid priority: ${priority}. Must be: ${this.taskPriorities.join(', ')}`);
547
+ }
548
+
549
+ const task = {
550
+ id: `task-${uuidv4()}`,
551
+ title,
552
+ description,
553
+ status: 'pending',
554
+ priority: priority.toLowerCase(),
555
+ createdAt: new Date().toISOString(),
556
+ updatedAt: new Date().toISOString()
557
+ };
558
+
559
+ agent.taskList.tasks.push(task);
560
+
561
+ return {
562
+ message: 'Task created successfully',
563
+ task
564
+ };
565
+ }
566
+
567
+ /**
568
+ * Sync entire task list (Claude Code style batch management)
569
+ * @private
570
+ */
571
+ async syncTasks(agent, params) {
572
+ let { tasks } = params;
573
+
574
+ // Parse tasks if provided as JSON string
575
+ if (typeof tasks === 'string') {
576
+ try {
577
+ tasks = JSON.parse(tasks);
578
+ } catch (error) {
579
+ throw new Error(`Invalid tasks JSON: ${error.message}`);
580
+ }
581
+ }
582
+
583
+ if (!Array.isArray(tasks)) {
584
+ throw new Error('Tasks must be an array');
585
+ }
586
+
587
+ if (tasks.length === 0) {
588
+ throw new Error('Tasks array cannot be empty');
589
+ }
590
+
591
+ const timestamp = new Date().toISOString();
592
+ const existingTasks = agent.taskList.tasks || [];
593
+ const updatedTasks = [];
594
+ const createdTasks = [];
595
+ const matchedIds = new Set();
596
+
597
+ // Helper: fuzzy match task by title
598
+ const findExistingTask = (title) => {
599
+ const normalizedTitle = title.toLowerCase().trim();
600
+ return existingTasks.find(t =>
601
+ t.title.toLowerCase().trim() === normalizedTitle &&
602
+ !matchedIds.has(t.id)
603
+ );
604
+ };
605
+
606
+ // Validate and process each task
607
+ for (const taskData of tasks) {
608
+ if (!taskData.title) {
609
+ throw new Error('Each task must have a title');
610
+ }
611
+
612
+ const status = (taskData.status || 'pending').toLowerCase();
613
+ const priority = (taskData.priority || 'medium').toLowerCase();
614
+
615
+ // Validate status
616
+ if (!this.taskStatuses.includes(status)) {
617
+ throw new Error(`Invalid status "${status}" for task "${taskData.title}". Must be: ${this.taskStatuses.join(', ')}`);
618
+ }
619
+
620
+ // Validate priority
621
+ if (!this.taskPriorities.includes(priority)) {
622
+ throw new Error(`Invalid priority "${priority}" for task "${taskData.title}". Must be: ${this.taskPriorities.join(', ')}`);
623
+ }
624
+
625
+ // Try to match with existing task
626
+ const existingTask = findExistingTask(taskData.title);
627
+
628
+ if (existingTask) {
629
+ // Update existing task
630
+ existingTask.status = status;
631
+ existingTask.priority = priority;
632
+ if (taskData.description !== undefined) {
633
+ existingTask.description = taskData.description;
634
+ }
635
+ existingTask.updatedAt = timestamp;
636
+
637
+ updatedTasks.push(existingTask);
638
+ matchedIds.add(existingTask.id);
639
+ } else {
640
+ // Create new task
641
+ const newTask = {
642
+ id: `task-${uuidv4()}`,
643
+ title: taskData.title,
644
+ description: taskData.description || '',
645
+ status: status,
646
+ priority: priority,
647
+ createdAt: timestamp,
648
+ updatedAt: timestamp,
649
+ source: 'sync'
650
+ };
651
+
652
+ createdTasks.push(newTask);
653
+ }
654
+ }
655
+
656
+ // Replace task list with synced tasks
657
+ agent.taskList.tasks = [...updatedTasks, ...createdTasks];
658
+
659
+ // Ensure only one task is in_progress
660
+ const inProgressTasks = agent.taskList.tasks.filter(t => t.status === 'in_progress');
661
+ if (inProgressTasks.length > 1) {
662
+ // Keep only the first in_progress task, set others to pending
663
+ for (let i = 1; i < inProgressTasks.length; i++) {
664
+ inProgressTasks[i].status = 'pending';
665
+ }
666
+ }
667
+
668
+ // Auto-set first pending task to in_progress if no task is in_progress
669
+ if (inProgressTasks.length === 0) {
670
+ const firstPending = agent.taskList.tasks.find(t => t.status === 'pending');
671
+ if (firstPending) {
672
+ firstPending.status = 'in_progress';
673
+ firstPending.updatedAt = timestamp;
674
+ }
675
+ }
676
+
677
+ agent.taskList.lastUpdated = timestamp;
678
+
679
+ return {
680
+ message: 'Task list synchronized successfully',
681
+ summary: {
682
+ total: agent.taskList.tasks.length,
683
+ created: createdTasks.length,
684
+ updated: updatedTasks.length,
685
+ removed: existingTasks.length - matchedIds.size,
686
+ pending: agent.taskList.tasks.filter(t => t.status === 'pending').length,
687
+ inProgress: agent.taskList.tasks.filter(t => t.status === 'in_progress').length,
688
+ completed: agent.taskList.tasks.filter(t => t.status === 'completed').length,
689
+ cancelled: agent.taskList.tasks.filter(t => t.status === 'cancelled').length
690
+ },
691
+ tasks: agent.taskList.tasks.map(t => ({
692
+ id: t.id,
693
+ title: t.title,
694
+ status: t.status,
695
+ priority: t.priority
696
+ }))
697
+ };
698
+ }
699
+
700
+ /**
701
+ * Update an existing task
702
+ * @private
703
+ */
704
+ async updateTask(agent, params) {
705
+ const { taskId, status, priority, title, description } = params;
706
+
707
+ if (!taskId) {
708
+ throw new Error('Task ID is required for update');
709
+ }
710
+
711
+ const task = agent.taskList.tasks.find(t => t.id === taskId);
712
+ if (!task) {
713
+ throw new Error(`Task not found: ${taskId}`);
714
+ }
715
+
716
+ if (status) {
717
+ if (!this.taskStatuses.includes(status.toLowerCase())) {
718
+ throw new Error(`Invalid status: ${status}. Must be: ${this.taskStatuses.join(', ')}`);
719
+ }
720
+ task.status = status.toLowerCase();
721
+ }
722
+
723
+ if (priority) {
724
+ if (!this.taskPriorities.includes(priority.toLowerCase())) {
725
+ throw new Error(`Invalid priority: ${priority}. Must be: ${this.taskPriorities.join(', ')}`);
726
+ }
727
+ task.priority = priority.toLowerCase();
728
+ }
729
+
730
+ if (title !== undefined) task.title = title;
731
+ if (description !== undefined) task.description = description;
732
+
733
+ task.updatedAt = new Date().toISOString();
734
+
735
+ return {
736
+ message: 'Task updated successfully',
737
+ task
738
+ };
739
+ }
740
+
741
+ /**
742
+ * List all tasks
743
+ * @private
744
+ */
745
+ async listTasks(agent, params) {
746
+ const { status, priority } = params;
747
+ let tasks = [...agent.taskList.tasks];
748
+
749
+ // Filter by status if specified
750
+ if (status) {
751
+ if (!this.taskStatuses.includes(status.toLowerCase())) {
752
+ throw new Error(`Invalid status filter: ${status}`);
753
+ }
754
+ tasks = tasks.filter(t => t.status === status.toLowerCase());
755
+ }
756
+
757
+ // Filter by priority if specified
758
+ if (priority) {
759
+ if (!this.taskPriorities.includes(priority.toLowerCase())) {
760
+ throw new Error(`Invalid priority filter: ${priority}`);
761
+ }
762
+ tasks = tasks.filter(t => t.priority === priority.toLowerCase());
763
+ }
764
+
765
+ // Sort by priority (high first) then by creation date
766
+ const priorityOrder = { high: 0, medium: 1, low: 2 };
767
+ tasks.sort((a, b) => {
768
+ const priorityDiff = priorityOrder[a.priority] - priorityOrder[b.priority];
769
+ if (priorityDiff !== 0) return priorityDiff;
770
+ return new Date(a.createdAt) - new Date(b.createdAt);
771
+ });
772
+
773
+ return {
774
+ totalTasks: tasks.length,
775
+ tasks,
776
+ summary: {
777
+ pending: tasks.filter(t => t.status === 'pending').length,
778
+ in_progress: tasks.filter(t => t.status === 'in_progress').length,
779
+ completed: tasks.filter(t => t.status === 'completed').length,
780
+ cancelled: tasks.filter(t => t.status === 'cancelled').length
781
+ }
782
+ };
783
+ }
784
+
785
+ /**
786
+ * Complete a task
787
+ * @private
788
+ */
789
+ async completeTask(agent, params) {
790
+ let { taskId } = params;
791
+
792
+ // If no taskId provided, auto-complete the first in-progress task
793
+ if (!taskId) {
794
+ const inProgressTask = agent.taskList.tasks.find(t => t.status === 'in_progress' || t.status === 'pending');
795
+ if (inProgressTask) {
796
+ taskId = inProgressTask.id;
797
+ this.logger?.info(`Auto-completing current task: ${taskId}`, {
798
+ agentId: agent.id,
799
+ taskTitle: inProgressTask.title
800
+ });
801
+ } else {
802
+ throw new Error('No task ID provided and no in-progress tasks found to complete');
803
+ }
804
+ }
805
+
806
+ const task = agent.taskList.tasks.find(t => t.id === taskId);
807
+ if (!task) {
808
+ throw new Error(`Task not found: ${taskId}`);
809
+ }
810
+
811
+ if (task.status === 'completed') {
812
+ return {
813
+ message: 'Task already completed',
814
+ task
815
+ };
816
+ }
817
+
818
+ task.status = 'completed';
819
+ task.completedAt = new Date().toISOString();
820
+ task.updatedAt = new Date().toISOString();
821
+
822
+ // Phase 3: Trigger dependency updates when task is completed
823
+ if (this.scheduler && typeof this.scheduler.updateDependentTasks === 'function') {
824
+ try {
825
+ await this.scheduler.updateDependentTasks(agent, taskId);
826
+ this.logger?.info(`Triggered dependency update for completed task`, {
827
+ taskId,
828
+ title: task.title
829
+ });
830
+ } catch (error) {
831
+ this.logger?.warn(`Failed to update dependent tasks`, {
832
+ taskId,
833
+ error: error.message
834
+ });
835
+ }
836
+ }
837
+
838
+ return {
839
+ message: 'Task completed successfully',
840
+ task,
841
+ dependenciesUpdated: !!this.scheduler
842
+ };
843
+ }
844
+
845
+ /**
846
+ * Cancel a task
847
+ * @private
848
+ */
849
+ async cancelTask(agent, params) {
850
+ const { taskId, reason = '' } = params;
851
+
852
+ if (!taskId) {
853
+ throw new Error('Task ID is required');
854
+ }
855
+
856
+ const task = agent.taskList.tasks.find(t => t.id === taskId);
857
+ if (!task) {
858
+ throw new Error(`Task not found: ${taskId}`);
859
+ }
860
+
861
+ task.status = 'cancelled';
862
+ task.cancelledAt = new Date().toISOString();
863
+ task.cancellationReason = reason;
864
+ task.updatedAt = new Date().toISOString();
865
+
866
+ return {
867
+ message: 'Task cancelled successfully',
868
+ task
869
+ };
870
+ }
871
+
872
+ /**
873
+ * Clear completed and cancelled tasks
874
+ * @private
875
+ */
876
+ async clearCompletedTasks(agent, params) {
877
+ const originalCount = agent.taskList.tasks.length;
878
+
879
+ // Keep only pending and in_progress tasks
880
+ agent.taskList.tasks = agent.taskList.tasks.filter(
881
+ t => t.status === 'pending' || t.status === 'in_progress'
882
+ );
883
+
884
+ const removedCount = originalCount - agent.taskList.tasks.length;
885
+
886
+ return {
887
+ message: `Cleared ${removedCount} completed/cancelled tasks`,
888
+ remainingTasks: agent.taskList.tasks.length,
889
+ removed: removedCount
890
+ };
891
+ }
892
+
893
+ /**
894
+ * Create dependency between tasks (Phase 3)
895
+ * @private
896
+ */
897
+ async createDependency(agent, params) {
898
+ const { taskId, dependsOn, dependencyType = 'blocks' } = params;
899
+
900
+ if (!taskId || !dependsOn) {
901
+ throw new Error('Both taskId and dependsOn are required for creating dependencies');
902
+ }
903
+
904
+ if (!this.dependencyTypes.includes(dependencyType)) {
905
+ throw new Error(`Invalid dependency type: ${dependencyType}. Must be: ${this.dependencyTypes.join(', ')}`);
906
+ }
907
+
908
+ const task = agent.taskList.tasks.find(t => t.id === taskId);
909
+ const dependencyTask = agent.taskList.tasks.find(t => t.id === dependsOn);
910
+
911
+ if (!task) {
912
+ throw new Error(`Task not found: ${taskId}`);
913
+ }
914
+
915
+ if (!dependencyTask) {
916
+ throw new Error(`Dependency task not found: ${dependsOn}`);
917
+ }
918
+
919
+ // Initialize dependencies array if not exists
920
+ if (!task.dependencies) {
921
+ task.dependencies = [];
922
+ }
923
+
924
+ // Check if dependency already exists
925
+ const existingDep = task.dependencies.find(d => d.taskId === dependsOn);
926
+ if (existingDep) {
927
+ return {
928
+ message: 'Dependency already exists',
929
+ dependency: existingDep
930
+ };
931
+ }
932
+
933
+ // Create dependency
934
+ const dependency = {
935
+ taskId: dependsOn,
936
+ type: dependencyType,
937
+ createdAt: new Date().toISOString()
938
+ };
939
+
940
+ task.dependencies.push(dependency);
941
+ task.updatedAt = new Date().toISOString();
942
+
943
+ // If this is a blocking dependency, check if task should be blocked
944
+ if (dependencyType === 'blocks' && dependencyTask.status !== 'completed') {
945
+ task.status = 'blocked';
946
+ }
947
+
948
+ return {
949
+ message: 'Dependency created successfully',
950
+ dependency,
951
+ task
952
+ };
953
+ }
954
+
955
+ /**
956
+ * Create relationship between tasks (non-blocking)
957
+ * @private
958
+ */
959
+ async relateTask(agent, params) {
960
+ return await this.createDependency(agent, { ...params, dependencyType: 'relates' });
961
+ }
962
+
963
+ /**
964
+ * Create subtask relationship
965
+ * @private
966
+ */
967
+ async createSubtask(agent, params) {
968
+ const { parentTaskId, title, description = '', priority = 'medium' } = params;
969
+
970
+ if (!parentTaskId || !title) {
971
+ throw new Error('Parent task ID and title are required for creating subtasks');
972
+ }
973
+
974
+ const parentTask = agent.taskList.tasks.find(t => t.id === parentTaskId);
975
+ if (!parentTask) {
976
+ throw new Error(`Parent task not found: ${parentTaskId}`);
977
+ }
978
+
979
+ // Create the subtask
980
+ const subtask = {
981
+ id: `task-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`,
982
+ title,
983
+ description,
984
+ status: 'pending',
985
+ priority: priority.toLowerCase(),
986
+ createdAt: new Date().toISOString(),
987
+ updatedAt: new Date().toISOString(),
988
+ parentTaskId: parentTaskId,
989
+ isSubtask: true,
990
+ source: 'user-created'
991
+ };
992
+
993
+ agent.taskList.tasks.push(subtask);
994
+
995
+ // Initialize subtasks array on parent if not exists
996
+ if (!parentTask.subtasks) {
997
+ parentTask.subtasks = [];
998
+ }
999
+
1000
+ parentTask.subtasks.push(subtask.id);
1001
+ parentTask.updatedAt = new Date().toISOString();
1002
+
1003
+ return {
1004
+ message: 'Subtask created successfully',
1005
+ subtask,
1006
+ parentTask
1007
+ };
1008
+ }
1009
+
1010
+ /**
1011
+ * Template management (Phase 3.3)
1012
+ * @private
1013
+ */
1014
+ async manageTemplates(agent, params) {
1015
+ const { mode = 'list', templateId, customTemplate, projectContext } = params;
1016
+
1017
+ let results = {};
1018
+
1019
+ if (mode === 'list') {
1020
+ // List available templates
1021
+ results = await this.listAvailableTemplates(agent);
1022
+ } else if (mode === 'apply' && templateId) {
1023
+ // Apply a template to create tasks
1024
+ results = await this.applyTemplate(agent, templateId, projectContext);
1025
+ } else if (mode === 'create' && customTemplate) {
1026
+ // Create custom template
1027
+ results = await this.createCustomTemplate(agent, customTemplate);
1028
+ } else if (mode === 'suggest') {
1029
+ // Suggest templates based on existing tasks
1030
+ results = await this.suggestTemplates(agent);
1031
+ } else {
1032
+ throw new Error('Invalid template mode. Use: list, apply, create, or suggest');
1033
+ }
1034
+
1035
+ return {
1036
+ message: `Template management completed (${mode})`,
1037
+ mode,
1038
+ ...results
1039
+ };
1040
+ }
1041
+
1042
+ /**
1043
+ * List available task templates
1044
+ * @private
1045
+ */
1046
+ async listAvailableTemplates(agent) {
1047
+ const builtInTemplates = Object.entries(this.taskTemplates).map(([id, template]) => ({
1048
+ id,
1049
+ name: template.name,
1050
+ description: template.description,
1051
+ category: template.category,
1052
+ taskCount: template.tasks.length,
1053
+ type: 'built-in'
1054
+ }));
1055
+
1056
+ // Get custom templates from agent's storage
1057
+ const customTemplates = agent.customTemplates || [];
1058
+ const formattedCustom = customTemplates.map(template => ({
1059
+ ...template,
1060
+ type: 'custom'
1061
+ }));
1062
+
1063
+ return {
1064
+ builtInTemplates,
1065
+ customTemplates: formattedCustom,
1066
+ totalTemplates: builtInTemplates.length + formattedCustom.length,
1067
+ categories: [...new Set(builtInTemplates.map(t => t.category))]
1068
+ };
1069
+ }
1070
+
1071
+ /**
1072
+ * Apply a template to create structured tasks
1073
+ * @private
1074
+ */
1075
+ async applyTemplate(agent, templateId, projectContext = {}) {
1076
+ const template = this.taskTemplates[templateId] ||
1077
+ (agent.customTemplates || []).find(t => t.id === templateId);
1078
+
1079
+ if (!template) {
1080
+ throw new Error(`Template not found: ${templateId}`);
1081
+ }
1082
+
1083
+ const createdTasks = [];
1084
+ const taskMapping = new Map(); // Map template task titles to actual task IDs
1085
+
1086
+ // Apply project context to customize template
1087
+ const contextualizedTasks = this.applyProjectContext(template.tasks, projectContext);
1088
+
1089
+ // Create all tasks first
1090
+ for (const templateTask of contextualizedTasks) {
1091
+ const task = {
1092
+ id: `task-${uuidv4()}`,
1093
+ title: templateTask.title,
1094
+ description: templateTask.description,
1095
+ status: 'pending',
1096
+ priority: templateTask.priority,
1097
+ createdAt: new Date().toISOString(),
1098
+ updatedAt: new Date().toISOString(),
1099
+ templateId: templateId,
1100
+ templateOrigin: template.type || 'built-in',
1101
+ source: 'template-generated'
1102
+ };
1103
+
1104
+ agent.taskList.tasks.push(task);
1105
+ createdTasks.push(task);
1106
+ taskMapping.set(templateTask.title, task.id);
1107
+ }
1108
+
1109
+ // Create dependencies after all tasks exist
1110
+ for (let i = 0; i < contextualizedTasks.length; i++) {
1111
+ const templateTask = contextualizedTasks[i];
1112
+ const actualTask = createdTasks[i];
1113
+
1114
+ if (templateTask.dependencies && templateTask.dependencies.length > 0) {
1115
+ actualTask.dependencies = [];
1116
+
1117
+ for (const depTitle of templateTask.dependencies) {
1118
+ const depTaskId = taskMapping.get(depTitle);
1119
+ if (depTaskId) {
1120
+ actualTask.dependencies.push({
1121
+ taskId: depTaskId,
1122
+ type: 'blocks',
1123
+ createdAt: new Date().toISOString()
1124
+ });
1125
+
1126
+ // Set task as blocked if dependency isn't completed
1127
+ actualTask.status = 'blocked';
1128
+ }
1129
+ }
1130
+ }
1131
+ }
1132
+
1133
+ // Auto-prioritize the newly created tasks
1134
+ await this.autoPrioritizeAllTasks(agent);
1135
+
1136
+ return {
1137
+ template: {
1138
+ id: templateId,
1139
+ name: template.name,
1140
+ description: template.description
1141
+ },
1142
+ tasksCreated: createdTasks.length,
1143
+ tasks: createdTasks.map(task => ({
1144
+ id: task.id,
1145
+ title: task.title,
1146
+ priority: task.priority,
1147
+ status: task.status,
1148
+ dependencies: task.dependencies ? task.dependencies.length : 0
1149
+ })),
1150
+ workflowStructure: this.generateWorkflowVisualization(createdTasks)
1151
+ };
1152
+ }
1153
+
1154
+ /**
1155
+ * Apply project context to customize template tasks
1156
+ * @private
1157
+ */
1158
+ applyProjectContext(templateTasks, context) {
1159
+ return templateTasks.map(task => {
1160
+ let customizedTask = { ...task };
1161
+
1162
+ // Apply context-specific customizations
1163
+ if (context.projectName) {
1164
+ customizedTask.title = customizedTask.title.replace(/\[PROJECT\]/g, context.projectName);
1165
+ customizedTask.description = customizedTask.description.replace(/\[PROJECT\]/g, context.projectName);
1166
+ }
1167
+
1168
+ if (context.technology) {
1169
+ customizedTask.title = customizedTask.title.replace(/\[TECH\]/g, context.technology);
1170
+ customizedTask.description = customizedTask.description.replace(/\[TECH\]/g, context.technology);
1171
+ }
1172
+
1173
+ if (context.urgency === 'high') {
1174
+ customizedTask.priority = customizedTask.priority === 'low' ? 'medium' :
1175
+ customizedTask.priority === 'medium' ? 'high' : 'urgent';
1176
+ }
1177
+
1178
+ // Team size can affect priority rather than time estimates
1179
+ if (context.team === 'small' && customizedTask.priority === 'medium') {
1180
+ customizedTask.priority = 'high'; // Small teams need focused priorities
1181
+ }
1182
+
1183
+ return customizedTask;
1184
+ });
1185
+ }
1186
+
1187
+ /**
1188
+ * Create custom template from existing tasks or specification
1189
+ * @private
1190
+ */
1191
+ async createCustomTemplate(agent, customTemplate) {
1192
+ const { name, description, category, tasks } = customTemplate;
1193
+
1194
+ if (!name || !tasks || tasks.length === 0) {
1195
+ throw new Error('Custom template requires name and at least one task');
1196
+ }
1197
+
1198
+ const template = {
1199
+ id: `custom-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`,
1200
+ name,
1201
+ description: description || `Custom template: ${name}`,
1202
+ category: category || 'custom',
1203
+ tasks: tasks.map(task => ({
1204
+ title: task.title,
1205
+ description: task.description || '',
1206
+ priority: task.priority || 'medium',
1207
+ dependencies: task.dependencies || []
1208
+ })),
1209
+ createdAt: new Date().toISOString(),
1210
+ type: 'custom'
1211
+ };
1212
+
1213
+ // Initialize custom templates array if not exists
1214
+ if (!agent.customTemplates) {
1215
+ agent.customTemplates = [];
1216
+ }
1217
+
1218
+ agent.customTemplates.push(template);
1219
+
1220
+ return {
1221
+ template: {
1222
+ id: template.id,
1223
+ name: template.name,
1224
+ description: template.description,
1225
+ category: template.category,
1226
+ taskCount: template.tasks.length
1227
+ },
1228
+ message: 'Custom template created successfully'
1229
+ };
1230
+ }
1231
+
1232
+ /**
1233
+ * Suggest templates based on existing tasks and patterns
1234
+ * @private
1235
+ */
1236
+ async suggestTemplates(agent) {
1237
+ const existingTasks = agent.taskList.tasks;
1238
+ const suggestions = [];
1239
+
1240
+ // Analyze existing task patterns
1241
+ const taskTitles = existingTasks.map(t => t.title.toLowerCase());
1242
+ const priorities = existingTasks.map(t => t.priority);
1243
+
1244
+ // Pattern-based suggestions
1245
+ if (taskTitles.some(title => title.includes('api') || title.includes('endpoint'))) {
1246
+ suggestions.push({
1247
+ templateId: 'api-integration',
1248
+ reason: 'Detected API-related tasks',
1249
+ confidence: 0.8
1250
+ });
1251
+ }
1252
+
1253
+ if (taskTitles.some(title => title.includes('bug') || title.includes('fix') || title.includes('error'))) {
1254
+ suggestions.push({
1255
+ templateId: 'bug-fix',
1256
+ reason: 'Detected bug fix tasks',
1257
+ confidence: 0.9
1258
+ });
1259
+ }
1260
+
1261
+ if (taskTitles.some(title => title.includes('feature') || title.includes('implement'))) {
1262
+ suggestions.push({
1263
+ templateId: 'feature-development',
1264
+ reason: 'Detected feature development tasks',
1265
+ confidence: 0.7
1266
+ });
1267
+ }
1268
+
1269
+ if (existingTasks.length >= 5 && priorities.includes('high') && priorities.includes('medium')) {
1270
+ suggestions.push({
1271
+ templateId: 'web-app-development',
1272
+ reason: 'Large project with mixed priorities suggests web app development',
1273
+ confidence: 0.6
1274
+ });
1275
+ }
1276
+
1277
+ // Enhance suggestions with template details
1278
+ const detailedSuggestions = suggestions.map(suggestion => {
1279
+ const template = this.taskTemplates[suggestion.templateId];
1280
+ return {
1281
+ ...suggestion,
1282
+ templateName: template.name,
1283
+ templateDescription: template.description,
1284
+ taskCount: template.tasks.length
1285
+ };
1286
+ });
1287
+
1288
+ return {
1289
+ suggestions: detailedSuggestions,
1290
+ analysisResults: {
1291
+ existingTaskCount: existingTasks.length,
1292
+ dominantPriority: this.getMostCommonPriority(priorities),
1293
+ detectedPatterns: suggestions.map(s => s.reason)
1294
+ }
1295
+ };
1296
+ }
1297
+
1298
+ /**
1299
+ * Generate workflow visualization for created tasks
1300
+ * @private
1301
+ */
1302
+ generateWorkflowVisualization(tasks) {
1303
+ const workflow = {
1304
+ phases: [],
1305
+ criticalPath: [],
1306
+ parallelTasks: []
1307
+ };
1308
+
1309
+ // Group tasks by their dependency level
1310
+ const levels = new Map();
1311
+ const processedTasks = new Set();
1312
+
1313
+ // Find root tasks (no dependencies)
1314
+ const rootTasks = tasks.filter(task => !task.dependencies || task.dependencies.length === 0);
1315
+ rootTasks.forEach(task => {
1316
+ levels.set(0, (levels.get(0) || []).concat([task]));
1317
+ processedTasks.add(task.id);
1318
+ });
1319
+
1320
+ // Build dependency levels
1321
+ let currentLevel = 0;
1322
+ while (processedTasks.size < tasks.length && currentLevel < 10) {
1323
+ currentLevel++;
1324
+ const currentLevelTasks = [];
1325
+
1326
+ for (const task of tasks) {
1327
+ if (processedTasks.has(task.id)) continue;
1328
+
1329
+ if (task.dependencies && task.dependencies.every(dep => processedTasks.has(dep.taskId))) {
1330
+ currentLevelTasks.push(task);
1331
+ processedTasks.add(task.id);
1332
+ }
1333
+ }
1334
+
1335
+ if (currentLevelTasks.length > 0) {
1336
+ levels.set(currentLevel, currentLevelTasks);
1337
+ }
1338
+ }
1339
+
1340
+ // Convert levels to phases
1341
+ for (const [level, levelTasks] of levels.entries()) {
1342
+ workflow.phases.push({
1343
+ phase: level + 1,
1344
+ tasks: levelTasks.map(task => ({
1345
+ id: task.id,
1346
+ title: task.title,
1347
+ priority: task.priority
1348
+ })),
1349
+ taskCount: levelTasks.length,
1350
+ canRunInParallel: levelTasks.length > 1
1351
+ });
1352
+ }
1353
+
1354
+ return workflow;
1355
+ }
1356
+
1357
+ /**
1358
+ * Get most common priority from array
1359
+ * @private
1360
+ */
1361
+ getMostCommonPriority(priorities) {
1362
+ if (priorities.length === 0) return 'medium';
1363
+
1364
+ const counts = priorities.reduce((acc, priority) => {
1365
+ acc[priority] = (acc[priority] || 0) + 1;
1366
+ return acc;
1367
+ }, {});
1368
+
1369
+ return Object.keys(counts).reduce((a, b) => counts[a] > counts[b] ? a : b);
1370
+ }
1371
+
1372
+ /**
1373
+ * Progress tracking management (Phase 3.4)
1374
+ * @private
1375
+ */
1376
+ async trackProgress(agent, params) {
1377
+ const { mode = 'update', taskId, stage, milestone, note, percentage } = params;
1378
+
1379
+ let results = {};
1380
+
1381
+ if (mode === 'update' && taskId) {
1382
+ // Update progress for specific task
1383
+ results = await this.updateTaskProgress(agent, taskId, { stage, milestone, note, percentage });
1384
+ } else if (mode === 'overview') {
1385
+ // Get progress overview for all tasks
1386
+ results = await this.getProgressOverview(agent);
1387
+ } else if (mode === 'milestones' && taskId) {
1388
+ // Manage milestones for specific task
1389
+ results = await this.manageMilestones(agent, taskId, params);
1390
+ } else if (mode === 'calculate') {
1391
+ // Calculate progress based on subtasks and dependencies
1392
+ results = await this.calculateTaskProgress(agent, taskId);
1393
+ } else {
1394
+ throw new Error('Invalid progress mode. Use: update, overview, milestones, or calculate');
1395
+ }
1396
+
1397
+ return {
1398
+ message: `Progress tracking completed (${mode})`,
1399
+ mode,
1400
+ ...results
1401
+ };
1402
+ }
1403
+
1404
+ /**
1405
+ * Update progress for a specific task
1406
+ * @private
1407
+ */
1408
+ async updateTaskProgress(agent, taskId, progressData) {
1409
+ const task = agent.taskList.tasks.find(t => t.id === taskId);
1410
+ if (!task) {
1411
+ throw new Error(`Task not found: ${taskId}`);
1412
+ }
1413
+
1414
+ // Initialize progress tracking if not exists
1415
+ if (!task.progress) {
1416
+ task.progress = {
1417
+ stage: 'not_started',
1418
+ percentage: 0,
1419
+ milestones: [],
1420
+ notes: [],
1421
+ stageHistory: []
1422
+ };
1423
+ }
1424
+
1425
+ const oldStage = task.progress.stage;
1426
+
1427
+ // Update stage if provided
1428
+ if (progressData.stage) {
1429
+ if (!this.progressStages.includes(progressData.stage)) {
1430
+ throw new Error(`Invalid progress stage: ${progressData.stage}. Must be: ${this.progressStages.join(', ')}`);
1431
+ }
1432
+
1433
+ task.progress.stage = progressData.stage;
1434
+
1435
+ // Track stage changes
1436
+ task.progress.stageHistory.push({
1437
+ from: oldStage,
1438
+ to: progressData.stage,
1439
+ timestamp: new Date().toISOString()
1440
+ });
1441
+
1442
+ // Auto-update task status based on stage
1443
+ if (progressData.stage === 'not_started' && task.status === 'in_progress') {
1444
+ task.status = 'pending';
1445
+ } else if (['planning', 'in_development', 'testing', 'review'].includes(progressData.stage) && task.status === 'pending') {
1446
+ task.status = 'in_progress';
1447
+ } else if (progressData.stage === 'completed' && task.status !== 'completed') {
1448
+ task.status = 'completed';
1449
+ task.completedAt = new Date().toISOString();
1450
+ }
1451
+ }
1452
+
1453
+ // Update percentage if provided
1454
+ if (progressData.percentage !== undefined) {
1455
+ const percent = Math.max(0, Math.min(100, parseInt(progressData.percentage)));
1456
+ task.progress.percentage = percent;
1457
+
1458
+ // Auto-update stage based on percentage
1459
+ if (percent === 0 && task.progress.stage !== 'not_started') {
1460
+ task.progress.stage = 'not_started';
1461
+ } else if (percent > 0 && percent < 25 && task.progress.stage === 'not_started') {
1462
+ task.progress.stage = 'planning';
1463
+ } else if (percent >= 25 && percent < 75 && ['not_started', 'planning'].includes(task.progress.stage)) {
1464
+ task.progress.stage = 'in_development';
1465
+ } else if (percent >= 75 && percent < 95 && task.progress.stage !== 'testing') {
1466
+ task.progress.stage = 'testing';
1467
+ } else if (percent >= 95 && percent < 100 && task.progress.stage !== 'review') {
1468
+ task.progress.stage = 'review';
1469
+ } else if (percent === 100) {
1470
+ task.progress.stage = 'completed';
1471
+ task.status = 'completed';
1472
+ task.completedAt = new Date().toISOString();
1473
+ }
1474
+ }
1475
+
1476
+ // Add milestone if provided
1477
+ if (progressData.milestone) {
1478
+ const milestone = {
1479
+ id: `milestone-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`,
1480
+ type: progressData.milestone.type || 'checkpoint',
1481
+ title: progressData.milestone.title || 'Progress Milestone',
1482
+ description: progressData.milestone.description || '',
1483
+ achievedAt: new Date().toISOString(),
1484
+ stage: task.progress.stage
1485
+ };
1486
+
1487
+ task.progress.milestones.push(milestone);
1488
+ }
1489
+
1490
+ // Add progress note if provided
1491
+ if (progressData.note) {
1492
+ task.progress.notes.push({
1493
+ id: `note-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`,
1494
+ content: progressData.note,
1495
+ timestamp: new Date().toISOString(),
1496
+ stage: task.progress.stage
1497
+ });
1498
+ }
1499
+
1500
+ task.updatedAt = new Date().toISOString();
1501
+
1502
+ // Calculate progress for parent task if this is a subtask
1503
+ if (task.parentTaskId) {
1504
+ await this.calculateTaskProgress(agent, task.parentTaskId);
1505
+ }
1506
+
1507
+ return {
1508
+ task: {
1509
+ id: task.id,
1510
+ title: task.title,
1511
+ status: task.status,
1512
+ progress: task.progress
1513
+ },
1514
+ changes: {
1515
+ stageChanged: oldStage !== task.progress.stage,
1516
+ oldStage,
1517
+ newStage: task.progress.stage,
1518
+ milestoneAdded: !!progressData.milestone,
1519
+ noteAdded: !!progressData.note
1520
+ }
1521
+ };
1522
+ }
1523
+
1524
+ /**
1525
+ * Get progress overview for all tasks
1526
+ * @private
1527
+ */
1528
+ async getProgressOverview(agent) {
1529
+ const tasks = agent.taskList.tasks;
1530
+ const taskProgress = tasks.map(task => {
1531
+ const progress = task.progress || { stage: 'not_started', percentage: 0, milestones: [], notes: [] };
1532
+
1533
+ return {
1534
+ id: task.id,
1535
+ title: task.title,
1536
+ status: task.status,
1537
+ priority: task.priority,
1538
+ stage: progress.stage,
1539
+ percentage: progress.percentage,
1540
+ milestoneCount: progress.milestones ? progress.milestones.length : 0,
1541
+ isBlocked: task.status === 'blocked',
1542
+ hasSubtasks: !!(task.subtasks && task.subtasks.length > 0),
1543
+ parentTaskId: task.parentTaskId
1544
+ };
1545
+ });
1546
+
1547
+ // Calculate overall statistics
1548
+ const stats = {
1549
+ totalTasks: tasks.length,
1550
+ byStage: {},
1551
+ byStatus: {},
1552
+ averageProgress: 0,
1553
+ blockedTasks: 0,
1554
+ completedTasks: 0
1555
+ };
1556
+
1557
+ this.progressStages.forEach(stage => {
1558
+ stats.byStage[stage] = taskProgress.filter(t => t.stage === stage).length;
1559
+ });
1560
+
1561
+ this.taskStatuses.forEach(status => {
1562
+ stats.byStatus[status] = taskProgress.filter(t => t.status === status).length;
1563
+ });
1564
+
1565
+ stats.averageProgress = tasks.length > 0 ?
1566
+ Math.round(taskProgress.reduce((sum, t) => sum + t.percentage, 0) / tasks.length) : 0;
1567
+
1568
+ stats.blockedTasks = stats.byStatus.blocked || 0;
1569
+ stats.completedTasks = stats.byStatus.completed || 0;
1570
+
1571
+ // Find critical path and bottlenecks
1572
+ const criticalTasks = taskProgress.filter(t =>
1573
+ t.priority === 'urgent' && t.status !== 'completed'
1574
+ );
1575
+
1576
+ const bottlenecks = taskProgress.filter(t =>
1577
+ t.isBlocked && this.findTasksBlockedBy(t.id, tasks).length > 0
1578
+ );
1579
+
1580
+ return {
1581
+ overview: stats,
1582
+ tasks: taskProgress,
1583
+ criticalTasks,
1584
+ bottlenecks: bottlenecks.map(t => ({
1585
+ taskId: t.id,
1586
+ title: t.title,
1587
+ blockedTasksCount: this.findTasksBlockedBy(t.id, tasks).length
1588
+ })),
1589
+ recommendations: this.generateProgressRecommendations(taskProgress, stats)
1590
+ };
1591
+ }
1592
+
1593
+ /**
1594
+ * Calculate task progress based on subtasks and dependencies
1595
+ * @private
1596
+ */
1597
+ async calculateTaskProgress(agent, taskId) {
1598
+ const task = agent.taskList.tasks.find(t => t.id === taskId);
1599
+ if (!task) {
1600
+ throw new Error(`Task not found: ${taskId}`);
1601
+ }
1602
+
1603
+ // Initialize progress if not exists
1604
+ if (!task.progress) {
1605
+ task.progress = {
1606
+ stage: 'not_started',
1607
+ percentage: 0,
1608
+ milestones: [],
1609
+ notes: [],
1610
+ stageHistory: []
1611
+ };
1612
+ }
1613
+
1614
+ let calculatedPercentage = 0;
1615
+ let calculationMethod = 'manual';
1616
+
1617
+ // Calculate based on subtasks if they exist
1618
+ if (task.subtasks && task.subtasks.length > 0) {
1619
+ const subtasks = task.subtasks.map(subtaskId =>
1620
+ agent.taskList.tasks.find(t => t.id === subtaskId)
1621
+ ).filter(Boolean);
1622
+
1623
+ if (subtasks.length > 0) {
1624
+ const subtaskProgress = subtasks.map(subtask => {
1625
+ if (subtask.status === 'completed') return 100;
1626
+ if (subtask.progress && subtask.progress.percentage !== undefined) {
1627
+ return subtask.progress.percentage;
1628
+ }
1629
+ return subtask.status === 'in_progress' ? 25 : 0;
1630
+ });
1631
+
1632
+ calculatedPercentage = Math.round(
1633
+ subtaskProgress.reduce((sum, p) => sum + p, 0) / subtasks.length
1634
+ );
1635
+ calculationMethod = 'subtasks';
1636
+ }
1637
+ }
1638
+
1639
+ // If no subtasks, calculate based on dependencies completion
1640
+ else if (task.dependencies && task.dependencies.length > 0) {
1641
+ const completedDeps = task.dependencies.filter(dep => {
1642
+ const depTask = agent.taskList.tasks.find(t => t.id === dep.taskId);
1643
+ return depTask && depTask.status === 'completed';
1644
+ }).length;
1645
+
1646
+ const depProgress = (completedDeps / task.dependencies.length) * 30; // Dependencies contribute 30%
1647
+ const ownProgress = task.status === 'completed' ? 70 :
1648
+ task.status === 'in_progress' ? 35 : 0; // Own progress contributes 70%
1649
+
1650
+ calculatedPercentage = Math.round(depProgress + ownProgress);
1651
+ calculationMethod = 'dependencies';
1652
+ }
1653
+
1654
+ // Fallback to status-based calculation
1655
+ else {
1656
+ if (task.status === 'completed') calculatedPercentage = 100;
1657
+ else if (task.status === 'in_progress') calculatedPercentage = task.progress.percentage || 50;
1658
+ else if (task.status === 'pending') calculatedPercentage = 0;
1659
+ else if (task.status === 'blocked') calculatedPercentage = task.progress.percentage || 0;
1660
+
1661
+ calculationMethod = 'status';
1662
+ }
1663
+
1664
+ // Update the task's calculated progress
1665
+ task.progress.calculatedPercentage = calculatedPercentage;
1666
+ task.progress.calculationMethod = calculationMethod;
1667
+ task.progress.lastCalculated = new Date().toISOString();
1668
+
1669
+ // Auto-update stage based on calculated percentage if no manual stage set recently
1670
+ const recentStageUpdate = task.progress.stageHistory.length > 0 &&
1671
+ (Date.now() - new Date(task.progress.stageHistory[task.progress.stageHistory.length - 1].timestamp).getTime()) < 300000; // 5 minutes
1672
+
1673
+ if (!recentStageUpdate) {
1674
+ const autoStage = this.getStageFromPercentage(calculatedPercentage);
1675
+ if (autoStage !== task.progress.stage) {
1676
+ task.progress.stage = autoStage;
1677
+ task.progress.stageHistory.push({
1678
+ from: task.progress.stage,
1679
+ to: autoStage,
1680
+ timestamp: new Date().toISOString(),
1681
+ automatic: true
1682
+ });
1683
+ }
1684
+ }
1685
+
1686
+ task.updatedAt = new Date().toISOString();
1687
+
1688
+ return {
1689
+ taskId: task.id,
1690
+ title: task.title,
1691
+ calculatedPercentage,
1692
+ calculationMethod,
1693
+ manualPercentage: task.progress.percentage,
1694
+ stage: task.progress.stage,
1695
+ subtaskCount: task.subtasks ? task.subtasks.length : 0,
1696
+ dependencyCount: task.dependencies ? task.dependencies.length : 0
1697
+ };
1698
+ }
1699
+
1700
+ /**
1701
+ * Generate progress recommendations
1702
+ * @private
1703
+ */
1704
+ generateProgressRecommendations(taskProgress, stats) {
1705
+ const recommendations = [];
1706
+
1707
+ // Blocked task recommendations
1708
+ if (stats.blockedTasks > 0) {
1709
+ recommendations.push({
1710
+ type: 'urgent',
1711
+ category: 'blocked_tasks',
1712
+ message: `${stats.blockedTasks} tasks are blocked. Review dependencies to unblock progress.`,
1713
+ actionable: true
1714
+ });
1715
+ }
1716
+
1717
+ // Stalled task recommendations
1718
+ const stalledTasks = taskProgress.filter(t =>
1719
+ t.status === 'in_progress' && t.percentage < 25
1720
+ );
1721
+
1722
+ if (stalledTasks.length > 0) {
1723
+ recommendations.push({
1724
+ type: 'warning',
1725
+ category: 'stalled_progress',
1726
+ message: `${stalledTasks.length} tasks are in progress but showing low progress. Consider breaking them into smaller subtasks.`,
1727
+ actionable: true
1728
+ });
1729
+ }
1730
+
1731
+ // High progress tasks ready for completion
1732
+ const nearCompletionTasks = taskProgress.filter(t =>
1733
+ t.percentage >= 90 && t.status !== 'completed'
1734
+ );
1735
+
1736
+ if (nearCompletionTasks.length > 0) {
1737
+ recommendations.push({
1738
+ type: 'success',
1739
+ category: 'near_completion',
1740
+ message: `${nearCompletionTasks.length} tasks are near completion. Focus on finishing these for quick wins.`,
1741
+ actionable: true
1742
+ });
1743
+ }
1744
+
1745
+ // Overall progress recommendations
1746
+ if (stats.averageProgress < 25) {
1747
+ recommendations.push({
1748
+ type: 'info',
1749
+ category: 'overall_progress',
1750
+ message: 'Overall progress is low. Consider prioritizing and focusing on fewer tasks.',
1751
+ actionable: false
1752
+ });
1753
+ }
1754
+
1755
+ return recommendations;
1756
+ }
1757
+
1758
+ /**
1759
+ * Get stage from percentage
1760
+ * @private
1761
+ */
1762
+ getStageFromPercentage(percentage) {
1763
+ if (percentage === 0) return 'not_started';
1764
+ if (percentage < 25) return 'planning';
1765
+ if (percentage < 75) return 'in_development';
1766
+ if (percentage < 95) return 'testing';
1767
+ if (percentage < 100) return 'review';
1768
+ return 'completed';
1769
+ }
1770
+
1771
+ /**
1772
+ * Set scheduler reference for dependency management (Phase 3)
1773
+ * @param {Object} scheduler - AgentScheduler instance
1774
+ */
1775
+ setScheduler(scheduler) {
1776
+ this.scheduler = scheduler;
1777
+ this.logger?.info('TaskManagerTool: Scheduler dependency injected');
1778
+ }
1779
+
1780
+ /**
1781
+ * Intelligent task prioritization (Phase 3.2)
1782
+ * @private
1783
+ */
1784
+ async intelligentPrioritization(agent, params) {
1785
+ const { mode = 'auto', taskId } = params;
1786
+
1787
+ let results = {};
1788
+
1789
+ if (mode === 'auto') {
1790
+ // Auto-prioritize all tasks
1791
+ results = await this.autoPrioritizeAllTasks(agent);
1792
+ } else if (mode === 'analyze' && taskId) {
1793
+ // Analyze specific task priority
1794
+ results = await this.analyzeTaskPriority(agent, taskId);
1795
+ } else if (mode === 'balance') {
1796
+ // Balance priorities across all agents
1797
+ results = await this.balanceCrossAgentPriorities(agent);
1798
+ } else {
1799
+ throw new Error('Invalid prioritization mode. Use: auto, analyze, or balance');
1800
+ }
1801
+
1802
+ return {
1803
+ message: `Intelligent prioritization completed (${mode})`,
1804
+ mode,
1805
+ ...results
1806
+ };
1807
+ }
1808
+
1809
+ /**
1810
+ * Auto-prioritize all tasks using intelligent scoring
1811
+ * @private
1812
+ */
1813
+ async autoPrioritizeAllTasks(agent) {
1814
+ const tasks = agent.taskList.tasks.filter(t =>
1815
+ t.status === 'pending' || t.status === 'in_progress'
1816
+ );
1817
+
1818
+ if (tasks.length === 0) {
1819
+ return { message: 'No active tasks to prioritize' };
1820
+ }
1821
+
1822
+ // Calculate priority scores for all tasks
1823
+ const tasksWithScores = tasks.map(task => ({
1824
+ ...task,
1825
+ priorityScore: this.calculatePriorityScore(task, agent.taskList.tasks),
1826
+ originalPriority: task.priority
1827
+ }));
1828
+
1829
+ // Sort by priority score (higher = more important)
1830
+ tasksWithScores.sort((a, b) => b.priorityScore - a.priorityScore);
1831
+
1832
+ // Assign new priorities based on scores
1833
+ const priorityMapping = ['urgent', 'high', 'medium', 'low'];
1834
+ const updatedTasks = [];
1835
+
1836
+ tasksWithScores.forEach((task, index) => {
1837
+ const newPriorityIndex = Math.min(
1838
+ Math.floor(index / Math.max(1, tasks.length / 4)),
1839
+ priorityMapping.length - 1
1840
+ );
1841
+ const newPriority = priorityMapping[newPriorityIndex];
1842
+
1843
+ if (task.originalPriority !== newPriority) {
1844
+ const originalTask = agent.taskList.tasks.find(t => t.id === task.id);
1845
+ originalTask.priority = newPriority;
1846
+ originalTask.updatedAt = new Date().toISOString();
1847
+ originalTask.priorityScore = task.priorityScore;
1848
+ originalTask.priorityReason = this.generatePriorityReason(task);
1849
+
1850
+ updatedTasks.push({
1851
+ id: task.id,
1852
+ title: task.title,
1853
+ oldPriority: task.originalPriority,
1854
+ newPriority: newPriority,
1855
+ score: task.priorityScore.toFixed(2),
1856
+ reason: originalTask.priorityReason
1857
+ });
1858
+ }
1859
+ });
1860
+
1861
+ return {
1862
+ totalTasks: tasks.length,
1863
+ updatedTasks: updatedTasks.length,
1864
+ changes: updatedTasks
1865
+ };
1866
+ }
1867
+
1868
+ /**
1869
+ * Calculate intelligent priority score for a task
1870
+ * @private
1871
+ */
1872
+ calculatePriorityScore(task, allTasks) {
1873
+ let score = 0;
1874
+
1875
+ // Base user priority score
1876
+ const priorityScores = { urgent: 4, high: 3, medium: 2, low: 1 };
1877
+ score += priorityScores[task.priority] * this.priorityWeights.userPriority;
1878
+
1879
+ // Age factor (older tasks get higher priority)
1880
+ const ageHours = (Date.now() - new Date(task.createdAt).getTime()) / (1000 * 60 * 60);
1881
+ score += Math.min(ageHours / 24, 3) * this.priorityWeights.age;
1882
+
1883
+ // Blocking factor (tasks that block others get higher priority)
1884
+ const blockedTasks = this.findTasksBlockedBy(task.id, allTasks);
1885
+ score += blockedTasks.length * this.priorityWeights.blocking;
1886
+
1887
+ // Dependency complexity factor
1888
+ const dependencyCount = (task.dependencies || []).length;
1889
+ score += Math.min(dependencyCount, 3) * this.priorityWeights.dependency;
1890
+
1891
+ // Subtask factor (parent tasks with many subtasks get higher priority)
1892
+ const subtaskCount = (task.subtasks || []).length;
1893
+ score += Math.min(subtaskCount, 2) * this.priorityWeights.dependency;
1894
+
1895
+ return score;
1896
+ }
1897
+
1898
+ /**
1899
+ * Find tasks that are blocked by the given task
1900
+ * @private
1901
+ */
1902
+ findTasksBlockedBy(taskId, allTasks) {
1903
+ return allTasks.filter(task => {
1904
+ if (!task.dependencies) return false;
1905
+ return task.dependencies.some(dep =>
1906
+ dep.taskId === taskId && dep.type === 'blocks'
1907
+ );
1908
+ });
1909
+ }
1910
+
1911
+ /**
1912
+ * Generate human-readable priority reason
1913
+ * @private
1914
+ */
1915
+ generatePriorityReason(task) {
1916
+ const reasons = [];
1917
+
1918
+ if (task.priorityScore > 8) {
1919
+ reasons.push('high overall impact');
1920
+ }
1921
+
1922
+ const ageHours = (Date.now() - new Date(task.createdAt).getTime()) / (1000 * 60 * 60);
1923
+ if (ageHours > 24) {
1924
+ reasons.push('overdue task');
1925
+ }
1926
+
1927
+ if (task.priority === 'urgent') {
1928
+ reasons.push('user-marked urgent');
1929
+ }
1930
+
1931
+ if ((task.subtasks || []).length > 0) {
1932
+ reasons.push('has subtasks');
1933
+ }
1934
+
1935
+ return reasons.length > 0 ? reasons.join(', ') : 'standard prioritization';
1936
+ }
1937
+
1938
+ /**
1939
+ * Analyze priority of a specific task
1940
+ * @private
1941
+ */
1942
+ async analyzeTaskPriority(agent, taskId) {
1943
+ const task = agent.taskList.tasks.find(t => t.id === taskId);
1944
+ if (!task) {
1945
+ throw new Error(`Task not found: ${taskId}`);
1946
+ }
1947
+
1948
+ const score = this.calculatePriorityScore(task, agent.taskList.tasks);
1949
+ const blockedTasks = this.findTasksBlockedBy(taskId, agent.taskList.tasks);
1950
+ const reason = this.generatePriorityReason({ ...task, priorityScore: score });
1951
+
1952
+ return {
1953
+ task: {
1954
+ id: task.id,
1955
+ title: task.title,
1956
+ currentPriority: task.priority,
1957
+ priorityScore: score.toFixed(2),
1958
+ reason
1959
+ },
1960
+ analysis: {
1961
+ blocksOtherTasks: blockedTasks.length,
1962
+ ageInHours: ((Date.now() - new Date(task.createdAt).getTime()) / (1000 * 60 * 60)).toFixed(1),
1963
+ dependencyCount: (task.dependencies || []).length,
1964
+ subtaskCount: (task.subtasks || []).length
1965
+ },
1966
+ blockedTasks: blockedTasks.map(t => ({ id: t.id, title: t.title }))
1967
+ };
1968
+ }
1969
+
1970
+ /**
1971
+ * Balance priorities across all agents (requires scheduler)
1972
+ * @private
1973
+ */
1974
+ async balanceCrossAgentPriorities(agent) {
1975
+ if (!this.scheduler || typeof this.scheduler.getAllAgents !== 'function') {
1976
+ return { message: 'Cross-agent balancing requires scheduler integration' };
1977
+ }
1978
+
1979
+ try {
1980
+ const allAgents = await this.scheduler.getAllAgents();
1981
+ const agentWorkloads = [];
1982
+
1983
+ allAgents.forEach(ag => {
1984
+ if (ag.taskList && ag.taskList.tasks) {
1985
+ const activeTasks = ag.taskList.tasks.filter(t =>
1986
+ t.status === 'pending' || t.status === 'in_progress'
1987
+ );
1988
+ const urgentTasks = activeTasks.filter(t => t.priority === 'urgent').length;
1989
+ const highTasks = activeTasks.filter(t => t.priority === 'high').length;
1990
+
1991
+ agentWorkloads.push({
1992
+ agentId: ag.id,
1993
+ agentName: ag.name,
1994
+ totalActive: activeTasks.length,
1995
+ urgent: urgentTasks,
1996
+ high: highTasks,
1997
+ workloadScore: urgentTasks * 3 + highTasks * 2 + activeTasks.length
1998
+ });
1999
+ }
2000
+ });
2001
+
2002
+ // Sort by workload (lowest first)
2003
+ agentWorkloads.sort((a, b) => a.workloadScore - b.workloadScore);
2004
+
2005
+ return {
2006
+ currentAgent: {
2007
+ agentId: agent.id,
2008
+ rank: agentWorkloads.findIndex(a => a.agentId === agent.id) + 1,
2009
+ totalAgents: agentWorkloads.length
2010
+ },
2011
+ workloadDistribution: agentWorkloads,
2012
+ recommendation: this.generateBalancingRecommendation(agent, agentWorkloads)
2013
+ };
2014
+ } catch (error) {
2015
+ return {
2016
+ error: `Cross-agent balancing failed: ${error.message}`,
2017
+ fallback: 'Using single-agent prioritization'
2018
+ };
2019
+ }
2020
+ }
2021
+
2022
+ /**
2023
+ * Generate workload balancing recommendation
2024
+ * @private
2025
+ */
2026
+ generateBalancingRecommendation(currentAgent, workloads) {
2027
+ const current = workloads.find(w => w.agentId === currentAgent.id);
2028
+ if (!current) return 'No recommendation available';
2029
+
2030
+ const avgWorkload = workloads.reduce((sum, w) => sum + w.workloadScore, 0) / workloads.length;
2031
+
2032
+ if (current.workloadScore > avgWorkload * 1.5) {
2033
+ return 'Consider delegating some tasks to less busy agents';
2034
+ } else if (current.workloadScore < avgWorkload * 0.5) {
2035
+ return 'Agent has capacity for additional high-priority tasks';
2036
+ } else {
2037
+ return 'Workload is well balanced';
2038
+ }
2039
+ }
2040
+
2041
+ /**
2042
+ * Generate task summary
2043
+ * @private
2044
+ */
2045
+ generateTaskSummary(taskList) {
2046
+ const tasks = taskList.tasks;
2047
+ return {
2048
+ total: tasks.length,
2049
+ pending: tasks.filter(t => t.status === 'pending').length,
2050
+ in_progress: tasks.filter(t => t.status === 'in_progress').length,
2051
+ completed: tasks.filter(t => t.status === 'completed').length,
2052
+ cancelled: tasks.filter(t => t.status === 'cancelled').length,
2053
+ high_priority: tasks.filter(t => t.priority === 'high' && (t.status === 'pending' || t.status === 'in_progress')).length
2054
+ };
2055
+ }
2056
+
2057
+ /**
2058
+ * Phase 3.5: Generate task analytics and reporting
2059
+ * @private
2060
+ */
2061
+ async generateAnalytics(agent, params) {
2062
+ const { mode = 'summary', timeframe = '30', reportType = 'comprehensive', agentId } = params;
2063
+
2064
+ let results = {};
2065
+
2066
+ switch (mode) {
2067
+ case 'summary':
2068
+ results = await this.getAnalyticsSummary(agent, timeframe);
2069
+ break;
2070
+ case 'performance':
2071
+ results = await this.getPerformanceMetrics(agent, timeframe);
2072
+ break;
2073
+ case 'trends':
2074
+ results = await this.getTrendAnalysis(agent, timeframe);
2075
+ break;
2076
+ case 'team':
2077
+ results = await this.getTeamAnalytics(timeframe);
2078
+ break;
2079
+ case 'export':
2080
+ results = await this.exportAnalytics(agent, params);
2081
+ break;
2082
+ case 'insights':
2083
+ results = await this.generateInsights(agent, timeframe);
2084
+ break;
2085
+ default:
2086
+ throw new Error('Invalid analytics mode. Use: summary, performance, trends, team, export, or insights');
2087
+ }
2088
+
2089
+ return {
2090
+ message: `Analytics report generated (${mode})`,
2091
+ mode,
2092
+ timeframe,
2093
+ generatedAt: new Date().toISOString(),
2094
+ ...results
2095
+ };
2096
+ }
2097
+
2098
+ /**
2099
+ * Get comprehensive analytics summary
2100
+ * @private
2101
+ */
2102
+ async getAnalyticsSummary(agent, timeframe) {
2103
+ const tasks = agent.taskList.tasks;
2104
+ const cutoffDate = new Date(Date.now() - parseInt(timeframe) * 24 * 60 * 60 * 1000);
2105
+
2106
+ // Filter tasks within timeframe
2107
+ const timeframeTasks = tasks.filter(t => new Date(t.createdAt) >= cutoffDate);
2108
+
2109
+ const summary = {
2110
+ overview: {
2111
+ totalTasks: timeframeTasks.length,
2112
+ completed: timeframeTasks.filter(t => t.status === 'completed').length,
2113
+ inProgress: timeframeTasks.filter(t => t.status === 'in_progress').length,
2114
+ pending: timeframeTasks.filter(t => t.status === 'pending').length,
2115
+ cancelled: timeframeTasks.filter(t => t.status === 'cancelled').length,
2116
+ blocked: timeframeTasks.filter(t => t.status === 'blocked').length
2117
+ },
2118
+ priorityBreakdown: {
2119
+ urgent: timeframeTasks.filter(t => t.priority === 'urgent').length,
2120
+ high: timeframeTasks.filter(t => t.priority === 'high').length,
2121
+ medium: timeframeTasks.filter(t => t.priority === 'medium').length,
2122
+ low: timeframeTasks.filter(t => t.priority === 'low').length
2123
+ },
2124
+ progressMetrics: this.calculateProgressMetrics(timeframeTasks),
2125
+ dependencyMetrics: this.calculateDependencyMetrics(timeframeTasks),
2126
+ templateUsage: this.calculateTemplateUsage(timeframeTasks)
2127
+ };
2128
+
2129
+ // Calculate completion rate
2130
+ summary.completionRate = summary.overview.totalTasks > 0
2131
+ ? Math.round((summary.overview.completed / summary.overview.totalTasks) * 100)
2132
+ : 0;
2133
+
2134
+ // Calculate average task age
2135
+ const activeTasks = timeframeTasks.filter(t => t.status !== 'completed' && t.status !== 'cancelled');
2136
+ summary.averageTaskAge = activeTasks.length > 0
2137
+ ? Math.round(activeTasks.reduce((sum, task) => {
2138
+ return sum + (Date.now() - new Date(task.createdAt).getTime()) / (1000 * 60 * 60 * 24);
2139
+ }, 0) / activeTasks.length)
2140
+ : 0;
2141
+
2142
+ return {
2143
+ summary,
2144
+ insights: this.generateSummaryInsights(summary)
2145
+ };
2146
+ }
2147
+
2148
+ /**
2149
+ * Get performance metrics
2150
+ * @private
2151
+ */
2152
+ async getPerformanceMetrics(agent, timeframe) {
2153
+ const tasks = agent.taskList.tasks;
2154
+ const cutoffDate = new Date(Date.now() - parseInt(timeframe) * 24 * 60 * 60 * 1000);
2155
+ const completedTasks = tasks.filter(t =>
2156
+ t.status === 'completed' &&
2157
+ t.completedAt &&
2158
+ new Date(t.completedAt) >= cutoffDate
2159
+ );
2160
+
2161
+ const metrics = {
2162
+ productivity: {
2163
+ tasksCompleted: completedTasks.length,
2164
+ completionRate: this.calculateCompletionRate(tasks, timeframe),
2165
+ averageCompletionTime: this.calculateAverageCompletionTime(completedTasks),
2166
+ velocityTrend: this.calculateVelocityTrend(tasks, timeframe)
2167
+ },
2168
+ quality: {
2169
+ blockedTasksRate: this.calculateBlockedTasksRate(tasks),
2170
+ cancelledTasksRate: this.calculateCancelledTasksRate(tasks, timeframe),
2171
+ reworkRate: this.calculateReworkRate(tasks, timeframe)
2172
+ },
2173
+ efficiency: {
2174
+ priorityAccuracy: this.calculatePriorityAccuracy(completedTasks),
2175
+ dependencyHandling: this.calculateDependencyEfficiency(tasks),
2176
+ progressConsistency: this.calculateProgressConsistency(tasks)
2177
+ }
2178
+ };
2179
+
2180
+ return {
2181
+ metrics,
2182
+ recommendations: this.generatePerformanceRecommendations(metrics)
2183
+ };
2184
+ }
2185
+
2186
+ /**
2187
+ * Get trend analysis
2188
+ * @private
2189
+ */
2190
+ async getTrendAnalysis(agent, timeframe) {
2191
+ const tasks = agent.taskList.tasks;
2192
+ const days = parseInt(timeframe);
2193
+ const trends = {
2194
+ daily: this.calculateDailyTrends(tasks, days),
2195
+ weekly: this.calculateWeeklyTrends(tasks, days),
2196
+ priorityTrends: this.calculatePriorityTrends(tasks, days),
2197
+ progressTrends: this.calculateProgressTrends(tasks, days)
2198
+ };
2199
+
2200
+ return {
2201
+ trends,
2202
+ forecasts: this.generateForecasts(trends),
2203
+ patterns: this.identifyPatterns(trends)
2204
+ };
2205
+ }
2206
+
2207
+ /**
2208
+ * Get team-wide analytics (across all agents)
2209
+ * @private
2210
+ */
2211
+ async getTeamAnalytics(timeframe) {
2212
+ if (!this.scheduler || !this.scheduler.getAllAgents) {
2213
+ throw new Error('Team analytics requires scheduler with getAllAgents method');
2214
+ }
2215
+
2216
+ const allAgents = await this.scheduler.getAllAgents();
2217
+ const cutoffDate = new Date(Date.now() - parseInt(timeframe) * 24 * 60 * 60 * 1000);
2218
+
2219
+ const teamData = {
2220
+ agents: [],
2221
+ aggregatedMetrics: {
2222
+ totalTasks: 0,
2223
+ totalCompleted: 0,
2224
+ averageWorkload: 0,
2225
+ topPerformers: [],
2226
+ bottlenecks: []
2227
+ }
2228
+ };
2229
+
2230
+ // Analyze each agent
2231
+ for (const agent of allAgents) {
2232
+ if (!agent.taskList || !agent.taskList.tasks) continue;
2233
+
2234
+ const tasks = agent.taskList.tasks;
2235
+ const timeframeTasks = tasks.filter(t => new Date(t.createdAt) >= cutoffDate);
2236
+
2237
+ const agentMetrics = {
2238
+ agentId: agent.id,
2239
+ agentName: agent.name,
2240
+ totalTasks: timeframeTasks.length,
2241
+ completed: timeframeTasks.filter(t => t.status === 'completed').length,
2242
+ pending: timeframeTasks.filter(t => t.status === 'pending').length,
2243
+ inProgress: timeframeTasks.filter(t => t.status === 'in_progress').length,
2244
+ workloadScore: this.calculateWorkloadScore(tasks),
2245
+ completionRate: timeframeTasks.length > 0
2246
+ ? Math.round((timeframeTasks.filter(t => t.status === 'completed').length / timeframeTasks.length) * 100)
2247
+ : 0
2248
+ };
2249
+
2250
+ teamData.agents.push(agentMetrics);
2251
+ teamData.aggregatedMetrics.totalTasks += agentMetrics.totalTasks;
2252
+ teamData.aggregatedMetrics.totalCompleted += agentMetrics.completed;
2253
+ }
2254
+
2255
+ // Calculate team-level metrics
2256
+ teamData.aggregatedMetrics.teamCompletionRate = teamData.aggregatedMetrics.totalTasks > 0
2257
+ ? Math.round((teamData.aggregatedMetrics.totalCompleted / teamData.aggregatedMetrics.totalTasks) * 100)
2258
+ : 0;
2259
+
2260
+ teamData.aggregatedMetrics.averageWorkload = teamData.agents.length > 0
2261
+ ? Math.round(teamData.agents.reduce((sum, a) => sum + a.workloadScore, 0) / teamData.agents.length)
2262
+ : 0;
2263
+
2264
+ // Identify top performers and bottlenecks
2265
+ teamData.aggregatedMetrics.topPerformers = teamData.agents
2266
+ .filter(a => a.completionRate >= 80)
2267
+ .sort((a, b) => b.completionRate - a.completionRate)
2268
+ .slice(0, 3);
2269
+
2270
+ teamData.aggregatedMetrics.bottlenecks = teamData.agents
2271
+ .filter(a => a.workloadScore > teamData.aggregatedMetrics.averageWorkload * 1.5)
2272
+ .sort((a, b) => b.workloadScore - a.workloadScore);
2273
+
2274
+ return {
2275
+ teamAnalytics: teamData,
2276
+ workloadDistribution: this.analyzeWorkloadDistribution(teamData.agents),
2277
+ collaborationMetrics: this.analyzeCollaborationMetrics(allAgents)
2278
+ };
2279
+ }
2280
+
2281
+ /**
2282
+ * Export analytics data
2283
+ * @private
2284
+ */
2285
+ async exportAnalytics(agent, params) {
2286
+ const { format = 'json', includeRawData = false, timeframe = '30' } = params;
2287
+
2288
+ const analyticsData = {
2289
+ metadata: {
2290
+ agentId: agent.id,
2291
+ agentName: agent.name,
2292
+ exportedAt: new Date().toISOString(),
2293
+ timeframe: `${timeframe} days`,
2294
+ format
2295
+ },
2296
+ summary: await this.getAnalyticsSummary(agent, timeframe),
2297
+ performance: await this.getPerformanceMetrics(agent, timeframe),
2298
+ trends: await this.getTrendAnalysis(agent, timeframe)
2299
+ };
2300
+
2301
+ if (includeRawData) {
2302
+ const cutoffDate = new Date(Date.now() - parseInt(timeframe) * 24 * 60 * 60 * 1000);
2303
+ analyticsData.rawData = {
2304
+ tasks: agent.taskList.tasks.filter(t => new Date(t.createdAt) >= cutoffDate)
2305
+ };
2306
+ }
2307
+
2308
+ let exportedData;
2309
+ switch (format.toLowerCase()) {
2310
+ case 'json':
2311
+ exportedData = JSON.stringify(analyticsData, null, 2);
2312
+ break;
2313
+ case 'csv':
2314
+ exportedData = this.convertToCSV(analyticsData);
2315
+ break;
2316
+ case 'summary':
2317
+ exportedData = this.generateTextSummary(analyticsData);
2318
+ break;
2319
+ default:
2320
+ throw new Error('Invalid export format. Use: json, csv, or summary');
2321
+ }
2322
+
2323
+ return {
2324
+ exportData: exportedData,
2325
+ format,
2326
+ size: exportedData.length,
2327
+ records: analyticsData.rawData ? analyticsData.rawData.tasks.length : 0
2328
+ };
2329
+ }
2330
+
2331
+ /**
2332
+ * Generate actionable insights
2333
+ * @private
2334
+ */
2335
+ async generateInsights(agent, timeframe) {
2336
+ const summary = await this.getAnalyticsSummary(agent, timeframe);
2337
+ const performance = await this.getPerformanceMetrics(agent, timeframe);
2338
+ const trends = await this.getTrendAnalysis(agent, timeframe);
2339
+
2340
+ const insights = {
2341
+ productivity: this.generateProductivityInsights(summary, performance, trends),
2342
+ workflow: this.generateWorkflowInsights(summary, performance, trends),
2343
+ optimization: this.generateOptimizationInsights(summary, performance, trends),
2344
+ predictions: this.generatePredictions(trends)
2345
+ };
2346
+
2347
+ return {
2348
+ insights,
2349
+ actionItems: this.generateActionItems(insights),
2350
+ priorities: this.generatePriorityRecommendations(insights)
2351
+ };
2352
+ }
2353
+
2354
+ // Helper methods for analytics calculations
2355
+
2356
+ calculateProgressMetrics(tasks) {
2357
+ const tasksWithProgress = tasks.filter(t => t.progress);
2358
+ if (tasksWithProgress.length === 0) return { averageProgress: 0, stageDistribution: {} };
2359
+
2360
+ const averageProgress = Math.round(
2361
+ tasksWithProgress.reduce((sum, t) => sum + (t.progress.percentage || 0), 0) / tasksWithProgress.length
2362
+ );
2363
+
2364
+ const stageDistribution = {};
2365
+ this.progressStages.forEach(stage => {
2366
+ stageDistribution[stage] = tasksWithProgress.filter(t => t.progress.stage === stage).length;
2367
+ });
2368
+
2369
+ return { averageProgress, stageDistribution };
2370
+ }
2371
+
2372
+ calculateDependencyMetrics(tasks) {
2373
+ const tasksWithDeps = tasks.filter(t => t.dependencies && t.dependencies.length > 0);
2374
+ const blockedTasks = tasks.filter(t => t.status === 'blocked').length;
2375
+
2376
+ return {
2377
+ tasksWithDependencies: tasksWithDeps.length,
2378
+ averageDependencies: tasksWithDeps.length > 0
2379
+ ? Math.round(tasksWithDeps.reduce((sum, t) => sum + t.dependencies.length, 0) / tasksWithDeps.length)
2380
+ : 0,
2381
+ blockedTasks,
2382
+ dependencyChainLength: this.calculateMaxDependencyChain(tasks)
2383
+ };
2384
+ }
2385
+
2386
+ calculateTemplateUsage(tasks) {
2387
+ const templateTasks = tasks.filter(t => t.source === 'template-generated');
2388
+ const templateDistribution = {};
2389
+
2390
+ templateTasks.forEach(t => {
2391
+ const templateId = t.templateId || 'unknown';
2392
+ templateDistribution[templateId] = (templateDistribution[templateId] || 0) + 1;
2393
+ });
2394
+
2395
+ return {
2396
+ totalTemplateGenerated: templateTasks.length,
2397
+ templateDistribution,
2398
+ templateEfficiency: this.calculateTemplateEfficiency(templateTasks)
2399
+ };
2400
+ }
2401
+
2402
+ calculateCompletionRate(tasks, timeframe) {
2403
+ const cutoffDate = new Date(Date.now() - parseInt(timeframe) * 24 * 60 * 60 * 1000);
2404
+ const timeframeTasks = tasks.filter(t => new Date(t.createdAt) >= cutoffDate);
2405
+
2406
+ return timeframeTasks.length > 0
2407
+ ? Math.round((timeframeTasks.filter(t => t.status === 'completed').length / timeframeTasks.length) * 100)
2408
+ : 0;
2409
+ }
2410
+
2411
+ calculateAverageCompletionTime(completedTasks) {
2412
+ if (completedTasks.length === 0) return 0;
2413
+
2414
+ const completionTimes = completedTasks.map(task => {
2415
+ const created = new Date(task.createdAt);
2416
+ const completed = new Date(task.completedAt);
2417
+ return (completed - created) / (1000 * 60 * 60 * 24); // days
2418
+ });
2419
+
2420
+ return Math.round(completionTimes.reduce((sum, time) => sum + time, 0) / completionTimes.length * 10) / 10;
2421
+ }
2422
+
2423
+ generateSummaryInsights(summary) {
2424
+ const insights = [];
2425
+
2426
+ if (summary.completionRate < 50) {
2427
+ insights.push('Completion rate is below 50%. Consider reviewing task prioritization and blocking issues.');
2428
+ }
2429
+
2430
+ if (summary.averageTaskAge > 7) {
2431
+ insights.push(`Tasks are aging (avg: ${summary.averageTaskAge} days). Focus on completing older tasks.`);
2432
+ }
2433
+
2434
+ if (summary.priorityBreakdown.urgent > summary.overview.totalTasks * 0.3) {
2435
+ insights.push('High proportion of urgent tasks. Consider better planning and early issue identification.');
2436
+ }
2437
+
2438
+ return insights;
2439
+ }
2440
+
2441
+ generatePerformanceRecommendations(metrics) {
2442
+ const recommendations = [];
2443
+
2444
+ if (metrics.productivity.completionRate < 70) {
2445
+ recommendations.push('Focus on improving task completion rate through better time management');
2446
+ }
2447
+
2448
+ if (metrics.quality.blockedTasksRate > 20) {
2449
+ recommendations.push('High blocked task rate - review dependency management and resource allocation');
2450
+ }
2451
+
2452
+ if (metrics.efficiency.priorityAccuracy < 60) {
2453
+ recommendations.push('Improve priority setting accuracy by reviewing completed task outcomes');
2454
+ }
2455
+
2456
+ return recommendations;
2457
+ }
2458
+
2459
+ // Additional helper methods for complex calculations
2460
+ calculateWorkloadScore(tasks) {
2461
+ const activeTasks = tasks.filter(t => t.status === 'pending' || t.status === 'in_progress');
2462
+ const urgentCount = activeTasks.filter(t => t.priority === 'urgent').length;
2463
+ const highCount = activeTasks.filter(t => t.priority === 'high').length;
2464
+
2465
+ return urgentCount * 3 + highCount * 2 + activeTasks.length;
2466
+ }
2467
+
2468
+ calculateMaxDependencyChain(tasks) {
2469
+ // Simple implementation - returns the maximum number of dependencies for any task
2470
+ return Math.max(0, ...tasks.map(t => (t.dependencies ? t.dependencies.length : 0)));
2471
+ }
2472
+
2473
+ calculateTemplateEfficiency(templateTasks) {
2474
+ if (templateTasks.length === 0) return 100;
2475
+ const completedTemplateProps = templateTasks.filter(t => t.status === 'completed').length;
2476
+ return Math.round((completedTemplateProps / templateTasks.length) * 100);
2477
+ }
2478
+
2479
+ calculateVelocityTrend(tasks, timeframe) {
2480
+ // Simple velocity calculation based on completed tasks in timeframe
2481
+ const cutoffDate = new Date(Date.now() - parseInt(timeframe) * 24 * 60 * 60 * 1000);
2482
+ const completedInTimeframe = tasks.filter(t =>
2483
+ t.status === 'completed' &&
2484
+ t.completedAt &&
2485
+ new Date(t.completedAt) >= cutoffDate
2486
+ ).length;
2487
+
2488
+ return Math.round((completedInTimeframe / parseInt(timeframe)) * 7); // tasks per week
2489
+ }
2490
+
2491
+ calculateBlockedTasksRate(tasks) {
2492
+ const activeTasks = tasks.filter(t => t.status !== 'completed' && t.status !== 'cancelled');
2493
+ if (activeTasks.length === 0) return 0;
2494
+ const blockedTasks = tasks.filter(t => t.status === 'blocked').length;
2495
+ return Math.round((blockedTasks / activeTasks.length) * 100);
2496
+ }
2497
+
2498
+ calculateCancelledTasksRate(tasks, timeframe) {
2499
+ const cutoffDate = new Date(Date.now() - parseInt(timeframe) * 24 * 60 * 60 * 1000);
2500
+ const timeframeTasks = tasks.filter(t => new Date(t.createdAt) >= cutoffDate);
2501
+ if (timeframeTasks.length === 0) return 0;
2502
+ const cancelledTasks = timeframeTasks.filter(t => t.status === 'cancelled').length;
2503
+ return Math.round((cancelledTasks / timeframeTasks.length) * 100);
2504
+ }
2505
+
2506
+ calculateReworkRate(tasks, timeframe) {
2507
+ // Simple implementation - tasks that moved back to earlier progress stages
2508
+ const cutoffDate = new Date(Date.now() - parseInt(timeframe) * 24 * 60 * 60 * 1000);
2509
+ const timeframeTasks = tasks.filter(t => new Date(t.createdAt) >= cutoffDate);
2510
+ const tasksWithRework = timeframeTasks.filter(t =>
2511
+ t.progress &&
2512
+ t.progress.stageHistory &&
2513
+ t.progress.stageHistory.some(h =>
2514
+ this.progressStages.indexOf(h.to) < this.progressStages.indexOf(h.from)
2515
+ )
2516
+ ).length;
2517
+
2518
+ return timeframeTasks.length > 0 ? Math.round((tasksWithRework / timeframeTasks.length) * 100) : 0;
2519
+ }
2520
+
2521
+ calculatePriorityAccuracy(completedTasks) {
2522
+ if (completedTasks.length === 0) return 100;
2523
+ // Simple heuristic: assume urgent/high priority tasks completed faster were accurate
2524
+ const fastCompletedUrgentHigh = completedTasks.filter(t => {
2525
+ if (!['urgent', 'high'].includes(t.priority)) return false;
2526
+ const created = new Date(t.createdAt);
2527
+ const completed = new Date(t.completedAt);
2528
+ const daysToComplete = (completed - created) / (1000 * 60 * 60 * 24);
2529
+ return daysToComplete <= 3; // completed within 3 days
2530
+ }).length;
2531
+
2532
+ const totalUrgentHigh = completedTasks.filter(t => ['urgent', 'high'].includes(t.priority)).length;
2533
+ return totalUrgentHigh > 0 ? Math.round((fastCompletedUrgentHigh / totalUrgentHigh) * 100) : 100;
2534
+ }
2535
+
2536
+ calculateDependencyEfficiency(tasks) {
2537
+ const tasksWithDeps = tasks.filter(t => t.dependencies && t.dependencies.length > 0);
2538
+ if (tasksWithDeps.length === 0) return 100;
2539
+
2540
+ const efficientTasks = tasksWithDeps.filter(t => t.status !== 'blocked').length;
2541
+ return Math.round((efficientTasks / tasksWithDeps.length) * 100);
2542
+ }
2543
+
2544
+ calculateProgressConsistency(tasks) {
2545
+ const tasksWithProgress = tasks.filter(t => t.progress && t.progress.percentage !== undefined);
2546
+ if (tasksWithProgress.length === 0) return 100;
2547
+
2548
+ // Simple heuristic: tasks with progress matching their stage
2549
+ const consistentTasks = tasksWithProgress.filter(t => {
2550
+ const stage = t.progress.stage;
2551
+ const percentage = t.progress.percentage;
2552
+
2553
+ if (stage === 'not_started' && percentage === 0) return true;
2554
+ if (stage === 'planning' && percentage > 0 && percentage < 25) return true;
2555
+ if (stage === 'in_development' && percentage >= 25 && percentage < 75) return true;
2556
+ if (stage === 'testing' && percentage >= 75 && percentage < 95) return true;
2557
+ if (stage === 'review' && percentage >= 95 && percentage < 100) return true;
2558
+ if (stage === 'completed' && percentage === 100) return true;
2559
+
2560
+ return false;
2561
+ }).length;
2562
+
2563
+ return Math.round((consistentTasks / tasksWithProgress.length) * 100);
2564
+ }
2565
+
2566
+ calculateDailyTrends(tasks, days) {
2567
+ const trends = [];
2568
+ for (let i = 0; i < days; i++) {
2569
+ const date = new Date(Date.now() - i * 24 * 60 * 60 * 1000);
2570
+ const dayStart = new Date(date.getFullYear(), date.getMonth(), date.getDate());
2571
+ const dayEnd = new Date(dayStart.getTime() + 24 * 60 * 60 * 1000);
2572
+
2573
+ const dayTasks = tasks.filter(t => {
2574
+ const created = new Date(t.createdAt);
2575
+ return created >= dayStart && created < dayEnd;
2576
+ });
2577
+
2578
+ trends.unshift({
2579
+ date: dayStart.toISOString().split('T')[0],
2580
+ created: dayTasks.length,
2581
+ completed: dayTasks.filter(t => t.status === 'completed').length
2582
+ });
2583
+ }
2584
+ return trends;
2585
+ }
2586
+
2587
+ calculateWeeklyTrends(tasks, days) {
2588
+ const weeks = Math.ceil(days / 7);
2589
+ const trends = [];
2590
+
2591
+ for (let i = 0; i < weeks; i++) {
2592
+ const weekStart = new Date(Date.now() - (i + 1) * 7 * 24 * 60 * 60 * 1000);
2593
+ const weekEnd = new Date(Date.now() - i * 7 * 24 * 60 * 60 * 1000);
2594
+
2595
+ const weekTasks = tasks.filter(t => {
2596
+ const created = new Date(t.createdAt);
2597
+ return created >= weekStart && created < weekEnd;
2598
+ });
2599
+
2600
+ trends.unshift({
2601
+ week: `Week ${weeks - i}`,
2602
+ created: weekTasks.length,
2603
+ completed: weekTasks.filter(t => t.status === 'completed').length
2604
+ });
2605
+ }
2606
+ return trends;
2607
+ }
2608
+
2609
+ calculatePriorityTrends(tasks, days) {
2610
+ const cutoffDate = new Date(Date.now() - days * 24 * 60 * 60 * 1000);
2611
+ const timeframeTasks = tasks.filter(t => new Date(t.createdAt) >= cutoffDate);
2612
+
2613
+ return {
2614
+ urgent: timeframeTasks.filter(t => t.priority === 'urgent').length,
2615
+ high: timeframeTasks.filter(t => t.priority === 'high').length,
2616
+ medium: timeframeTasks.filter(t => t.priority === 'medium').length,
2617
+ low: timeframeTasks.filter(t => t.priority === 'low').length
2618
+ };
2619
+ }
2620
+
2621
+ calculateProgressTrends(tasks, days) {
2622
+ const cutoffDate = new Date(Date.now() - days * 24 * 60 * 60 * 1000);
2623
+ const timeframeTasks = tasks.filter(t => new Date(t.createdAt) >= cutoffDate);
2624
+ const tasksWithProgress = timeframeTasks.filter(t => t.progress);
2625
+
2626
+ const stageTrends = {};
2627
+ this.progressStages.forEach(stage => {
2628
+ stageTrends[stage] = tasksWithProgress.filter(t => t.progress.stage === stage).length;
2629
+ });
2630
+
2631
+ return stageTrends;
2632
+ }
2633
+
2634
+ generateForecasts(trends) {
2635
+ return {
2636
+ predictedCompletions: this.predictFutureCompletions(trends.daily),
2637
+ workloadForecast: this.predictWorkloadTrend(trends.weekly),
2638
+ priorityShift: this.predictPriorityShift(trends.priorityTrends)
2639
+ };
2640
+ }
2641
+
2642
+ identifyPatterns(trends) {
2643
+ return {
2644
+ peakDays: this.identifyPeakActivityDays(trends.daily),
2645
+ cyclicalPatterns: this.identifyCyclicalPatterns(trends.weekly),
2646
+ priorityPatterns: this.identifyPriorityPatterns(trends.priorityTrends)
2647
+ };
2648
+ }
2649
+
2650
+ // Simplified implementations for missing complex methods
2651
+ predictFutureCompletions(dailyTrends) {
2652
+ if (dailyTrends.length < 7) return 'Insufficient data';
2653
+ const recentAvg = dailyTrends.slice(-7).reduce((sum, day) => sum + day.completed, 0) / 7;
2654
+ return `${Math.round(recentAvg)} tasks/day predicted`;
2655
+ }
2656
+
2657
+ predictWorkloadTrend(weeklyTrends) {
2658
+ if (weeklyTrends.length < 2) return 'Stable';
2659
+ const recent = weeklyTrends[weeklyTrends.length - 1].created;
2660
+ const previous = weeklyTrends[weeklyTrends.length - 2].created;
2661
+ const change = ((recent - previous) / previous) * 100;
2662
+
2663
+ if (change > 20) return 'Increasing workload';
2664
+ if (change < -20) return 'Decreasing workload';
2665
+ return 'Stable workload';
2666
+ }
2667
+
2668
+ predictPriorityShift(priorityTrends) {
2669
+ const total = Object.values(priorityTrends).reduce((sum, count) => sum + count, 0);
2670
+ if (total === 0) return 'No priority data';
2671
+
2672
+ const urgentPercent = (priorityTrends.urgent / total) * 100;
2673
+ if (urgentPercent > 30) return 'High urgent task ratio - plan for capacity';
2674
+ return 'Balanced priority distribution';
2675
+ }
2676
+
2677
+ identifyPeakActivityDays(dailyTrends) {
2678
+ const maxCreated = Math.max(...dailyTrends.map(d => d.created));
2679
+ return dailyTrends.filter(d => d.created === maxCreated).map(d => d.date);
2680
+ }
2681
+
2682
+ identifyCyclicalPatterns(weeklyTrends) {
2683
+ if (weeklyTrends.length < 4) return 'Insufficient data for pattern analysis';
2684
+ return 'Weekly patterns detected - further analysis available';
2685
+ }
2686
+
2687
+ identifyPriorityPatterns(priorityTrends) {
2688
+ const total = Object.values(priorityTrends).reduce((sum, count) => sum + count, 0);
2689
+ if (total === 0) return 'No priority patterns';
2690
+
2691
+ const dominant = Object.entries(priorityTrends).reduce((max, [priority, count]) =>
2692
+ count > max.count ? { priority, count } : max, { priority: '', count: 0 }
2693
+ );
2694
+
2695
+ return `${dominant.priority} priority tasks dominate (${Math.round((dominant.count / total) * 100)}%)`;
2696
+ }
2697
+
2698
+ generateProductivityInsights(summary, performance, trends) {
2699
+ const insights = [];
2700
+
2701
+ if (performance.metrics.productivity.completionRate > 80) {
2702
+ insights.push('High productivity - excellent task completion rate');
2703
+ } else if (performance.metrics.productivity.completionRate < 50) {
2704
+ insights.push('Low productivity - focus on task completion strategies');
2705
+ }
2706
+
2707
+ if (summary.summary.averageTaskAge > 10) {
2708
+ insights.push('Tasks are aging significantly - prioritize older tasks');
2709
+ }
2710
+
2711
+ return insights;
2712
+ }
2713
+
2714
+ generateWorkflowInsights(summary, performance, trends) {
2715
+ const insights = [];
2716
+
2717
+ if (summary.summary.dependencyMetrics.blockedTasks > 3) {
2718
+ insights.push('Multiple blocked tasks - review dependency management');
2719
+ }
2720
+
2721
+ if (summary.summary.templateUsage.totalTemplateGenerated > summary.summary.overview.totalTasks * 0.5) {
2722
+ insights.push('Heavy template usage - consider workflow optimization');
2723
+ }
2724
+
2725
+ return insights;
2726
+ }
2727
+
2728
+ generateOptimizationInsights(summary, performance, trends) {
2729
+ const insights = [];
2730
+
2731
+ if (performance.metrics.efficiency.priorityAccuracy < 70) {
2732
+ insights.push('Priority setting needs improvement - review task urgency assessment');
2733
+ }
2734
+
2735
+ if (performance.metrics.quality.blockedTasksRate > 15) {
2736
+ insights.push('High blocked task rate - optimize dependency planning');
2737
+ }
2738
+
2739
+ return insights;
2740
+ }
2741
+
2742
+ generatePredictions(trends) {
2743
+ return [
2744
+ trends.forecasts.predictedCompletions,
2745
+ trends.forecasts.workloadForecast,
2746
+ trends.forecasts.priorityShift
2747
+ ];
2748
+ }
2749
+
2750
+ generateActionItems(insights) {
2751
+ const allInsights = [
2752
+ ...insights.productivity,
2753
+ ...insights.workflow,
2754
+ ...insights.optimization
2755
+ ];
2756
+
2757
+ return allInsights.map((insight, index) => ({
2758
+ id: `action-${index + 1}`,
2759
+ description: insight,
2760
+ priority: insight.includes('urgent') || insight.includes('critical') ? 'high' : 'medium',
2761
+ category: insight.includes('productivity') ? 'productivity' :
2762
+ insight.includes('workflow') ? 'workflow' : 'optimization'
2763
+ }));
2764
+ }
2765
+
2766
+ generatePriorityRecommendations(insights) {
2767
+ const recommendations = [];
2768
+
2769
+ if (insights.productivity.some(i => i.includes('Low productivity'))) {
2770
+ recommendations.push({
2771
+ priority: 'urgent',
2772
+ action: 'Focus on task completion strategies',
2773
+ impact: 'high'
2774
+ });
2775
+ }
2776
+
2777
+ if (insights.workflow.some(i => i.includes('blocked tasks'))) {
2778
+ recommendations.push({
2779
+ priority: 'high',
2780
+ action: 'Review and resolve task dependencies',
2781
+ impact: 'medium'
2782
+ });
2783
+ }
2784
+
2785
+ return recommendations;
2786
+ }
2787
+
2788
+ analyzeWorkloadDistribution(agents) {
2789
+ if (agents.length === 0) return { balance: 'No agents', distribution: [] };
2790
+
2791
+ const workloads = agents.map(a => a.workloadScore);
2792
+ const avg = workloads.reduce((sum, w) => sum + w, 0) / workloads.length;
2793
+ const maxDeviation = Math.max(...workloads.map(w => Math.abs(w - avg)));
2794
+
2795
+ return {
2796
+ balance: maxDeviation > avg * 0.5 ? 'Unbalanced' : 'Balanced',
2797
+ distribution: agents.map(a => ({
2798
+ agent: a.agentName,
2799
+ workload: a.workloadScore,
2800
+ deviation: Math.round(((a.workloadScore - avg) / avg) * 100)
2801
+ }))
2802
+ };
2803
+ }
2804
+
2805
+ analyzeCollaborationMetrics(allAgents) {
2806
+ return {
2807
+ totalAgents: allAgents.length,
2808
+ activeAgents: allAgents.filter(a => a.taskList && a.taskList.tasks.length > 0).length,
2809
+ collaborationScore: Math.round(Math.random() * 100) // Simplified - would analyze shared dependencies
2810
+ };
2811
+ }
2812
+
2813
+ convertToCSV(analyticsData) {
2814
+ // Simplified CSV export
2815
+ const headers = ['Metric', 'Value'];
2816
+ const rows = [
2817
+ ['Total Tasks', analyticsData.summary.summary.overview.totalTasks],
2818
+ ['Completed Tasks', analyticsData.summary.summary.overview.completed],
2819
+ ['Completion Rate', `${analyticsData.summary.summary.completionRate}%`],
2820
+ ['Average Task Age', `${analyticsData.summary.summary.averageTaskAge} days`]
2821
+ ];
2822
+
2823
+ return [headers, ...rows].map(row => row.join(',')).join('\n');
2824
+ }
2825
+
2826
+ generateTextSummary(analyticsData) {
2827
+ const summary = analyticsData.summary.summary;
2828
+ return `
2829
+ Analytics Summary
2830
+ ================
2831
+ Total Tasks: ${summary.overview.totalTasks}
2832
+ Completed: ${summary.overview.completed} (${summary.completionRate}%)
2833
+ In Progress: ${summary.overview.inProgress}
2834
+ Pending: ${summary.overview.pending}
2835
+ Average Task Age: ${summary.averageTaskAge} days
2836
+
2837
+ Key Insights:
2838
+ ${analyticsData.summary.insights.map(insight => `- ${insight}`).join('\n')}
2839
+ `.trim();
2840
+ }
2841
+
2842
+ /**
2843
+ * Format tool result for display
2844
+ * @param {Object} result - Tool execution result
2845
+ * @returns {string} Formatted result
2846
+ */
2847
+ formatResult(result) {
2848
+ if (!result.success) {
2849
+ return `TaskManager Error: ${result.error}`;
2850
+ }
2851
+
2852
+ const lines = [`TaskManager: ${result.action} completed`];
2853
+
2854
+ if (result.result.task) {
2855
+ lines.push(`Task: [${result.result.task.status}] ${result.result.task.title} (${result.result.task.id})`);
2856
+ }
2857
+
2858
+ if (result.result.tasks) {
2859
+ lines.push(`Found ${result.result.tasks.length} tasks:`);
2860
+ result.result.tasks.forEach(task => {
2861
+ lines.push(` - [${task.status}] ${task.title} (Priority: ${task.priority})`);
2862
+ });
2863
+ }
2864
+
2865
+ if (result.summary) {
2866
+ lines.push(`Summary: ${result.summary.pending} pending, ${result.summary.in_progress} in progress, ${result.summary.completed} completed`);
2867
+ }
2868
+
2869
+ return lines.join('\n');
2870
+ }
2871
+ }
2872
+
2873
+ export default TaskManagerTool;