All files / src/hooks task-hooks.ts

0% Statements 0/513
0% Branches 0/1
0% Functions 0/1
0% Lines 0/513

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   
/**
 * V3 Task Lifecycle Hooks
 *
 * Provides pre-task and post-task hooks for task execution lifecycle.
 * Integrates with ReasoningBank for learning and pattern recognition.
 *
 * @module v3/shared/hooks/task-hooks
 */

import {
  HookEvent,
  HookContext,
  HookResult,
  HookPriority,
  TaskInfo,
} from './types.js';
import { HookRegistry } from './registry.js';

/**
 * Pre-task hook result with agent suggestions
 */
export interface PreTaskHookResult extends HookResult {
  /** Suggested agents for the task */
  suggestedAgents?: AgentSuggestion[];
  /** Task complexity estimation */
  complexity?: 'low' | 'medium' | 'high';
  /** Estimated duration in milliseconds */
  estimatedDuration?: number;
  /** Related patterns from ReasoningBank */
  patterns?: TaskPattern[];
  /** Potential risks */
  risks?: string[];
  /** Recommendations */
  recommendations?: string[];
}

/**
 * Post-task hook result with learning data
 */
export interface PostTaskHookResult extends HookResult {
  /** Task outcome */
  outcome?: TaskOutcome;
  /** Learning updates applied */
  learningUpdates?: LearningUpdate;
  /** Pattern ID if a new pattern was created */
  patternId?: string;
  /** Trajectory ID for ReasoningBank */
  trajectoryId?: string;
}

/**
 * Agent suggestion for task routing
 */
export interface AgentSuggestion {
  /** Agent type */
  type: string;
  /** Confidence score (0-1) */
  confidence: number;
  /** Reason for suggestion */
  reason: string;
  /** Capabilities relevant to this task */
  capabilities?: string[];
}

/**
 * Task pattern from ReasoningBank
 */
export interface TaskPattern {
  /** Pattern identifier */
  id: string;
  /** Pattern description */
  description: string;
  /** Match score (0-1) */
  matchScore: number;
  /** Historical success rate */
  successRate: number;
  /** Average duration in ms */
  avgDuration: number;
  /** Recommended strategies */
  strategies?: string[];
}

/**
 * Task outcome for learning
 */
export interface TaskOutcome {
  /** Whether the task succeeded */
  success: boolean;
  /** Duration in milliseconds */
  duration: number;
  /** Quality score (0-1) */
  quality?: number;
  /** Error details if failed */
  error?: string;
  /** Output artifacts */
  artifacts?: string[];
  /** Agent that executed the task */
  agent?: string;
}

/**
 * Learning update result
 */
export interface LearningUpdate {
  /** Number of patterns updated */
  patternsUpdated: number;
  /** Number of new patterns created */
  newPatterns: number;
  /** Confidence adjustments made */
  confidenceAdjusted: number;
  /** Trajectories recorded */
  trajectoriesRecorded: number;
}

/**
 * Task store for tracking active tasks
 */
interface TaskStore {
  taskId: string;
  description: string;
  startTime: number;
  metadata?: Record<string, unknown>;
  suggestedAgents?: AgentSuggestion[];
}

/**
 * Task Hooks Manager
 *
 * Manages pre-task and post-task hooks with ReasoningBank integration.
 */
export class TaskHooksManager {
  private registry: HookRegistry;
  private activeTasks: Map<string, TaskStore> = new Map();
  private taskPatterns: Map<string, TaskPattern[]> = new Map();

  constructor(registry: HookRegistry) {
    this.registry = registry;
    this.registerDefaultHooks();
  }

  /**
   * Register default task hooks
   */
  private registerDefaultHooks(): void {
    // Pre-task hook for agent suggestion
    this.registry.register(
      HookEvent.PreTaskExecute,
      this.handlePreTask.bind(this),
      HookPriority.Normal,
      { name: 'task-hooks:pre-task' }
    );

    // Post-task hook for learning
    this.registry.register(
      HookEvent.PostTaskExecute,
      this.handlePostTask.bind(this),
      HookPriority.Normal,
      { name: 'task-hooks:post-task' }
    );
  }

  /**
   * Handle pre-task execution
   */
  async handlePreTask(context: HookContext): Promise<PreTaskHookResult> {
    const task = context.task;
    if (!task) {
      return { success: false, error: new Error('No task in context') };
    }

    // Store task for tracking
    const taskStore: TaskStore = {
      taskId: task.id,
      description: task.description,
      startTime: Date.now(),
      metadata: task.metadata,
    };

    // Analyze task and suggest agents
    const analysis = await this.analyzeTask(task);

    taskStore.suggestedAgents = analysis.suggestedAgents;
    this.activeTasks.set(task.id, taskStore);

    // Store patterns for this task
    if (analysis.patterns.length > 0) {
      this.taskPatterns.set(task.id, analysis.patterns);
    }

    return {
      success: true,
      suggestedAgents: analysis.suggestedAgents,
      complexity: analysis.complexity,
      estimatedDuration: analysis.estimatedDuration,
      patterns: analysis.patterns,
      risks: analysis.risks,
      recommendations: analysis.recommendations,
      data: {
        task: {
          ...task,
          metadata: {
            ...task.metadata,
            suggestedAgents: analysis.suggestedAgents.map(a => a.type),
            complexity: analysis.complexity,
          },
        },
      },
    };
  }

  /**
   * Handle post-task execution
   */
  async handlePostTask(context: HookContext): Promise<PostTaskHookResult> {
    const task = context.task;
    if (!task) {
      return { success: false, error: new Error('No task in context') };
    }

    const taskStore = this.activeTasks.get(task.id);
    const patterns = this.taskPatterns.get(task.id);

    // Calculate duration
    const duration = taskStore ? Date.now() - taskStore.startTime : 0;

    // Extract outcome from context metadata
    const success = context.metadata?.success !== false;
    const quality = context.metadata?.quality as number | undefined;
    const error = context.metadata?.error as string | undefined;
    const agent = context.metadata?.agent as string | undefined;

    const outcome: TaskOutcome = {
      success,
      duration,
      quality,
      error,
      agent,
      artifacts: context.metadata?.artifacts as string[] | undefined,
    };

    // Record learning trajectory
    const learningUpdates = await this.recordLearning(task, outcome, patterns);

    // Clean up
    this.activeTasks.delete(task.id);
    this.taskPatterns.delete(task.id);

    return {
      success: true,
      outcome,
      learningUpdates,
      patternId: learningUpdates.newPatterns > 0 ? `pattern-${task.id}` : undefined,
      trajectoryId: `trajectory-${task.id}-${Date.now()}`,
    };
  }

  /**
   * Analyze task for agent suggestions and patterns
   */
  private async analyzeTask(task: TaskInfo): Promise<{
    suggestedAgents: AgentSuggestion[];
    complexity: 'low' | 'medium' | 'high';
    estimatedDuration: number;
    patterns: TaskPattern[];
    risks: string[];
    recommendations: string[];
  }> {
    const description = task.description.toLowerCase();

    // Pattern-based agent suggestion
    const suggestedAgents: AgentSuggestion[] = [];
    const patterns: TaskPattern[] = [];
    const risks: string[] = [];
    const recommendations: string[] = [];

    // Analyze task keywords for agent routing
    const agentPatterns: Array<{
      keywords: string[];
      agent: string;
      capabilities: string[];
    }> = [
      {
        keywords: ['implement', 'code', 'create', 'build', 'develop', 'write'],
        agent: 'coder',
        capabilities: ['code-generation', 'implementation', 'debugging'],
      },
      {
        keywords: ['test', 'spec', 'coverage', 'unit', 'integration'],
        agent: 'tester',
        capabilities: ['unit-testing', 'integration-testing', 'coverage-analysis'],
      },
      {
        keywords: ['review', 'check', 'audit', 'analyze'],
        agent: 'reviewer',
        capabilities: ['code-review', 'quality-analysis', 'best-practices'],
      },
      {
        keywords: ['research', 'investigate', 'explore', 'study'],
        agent: 'researcher',
        capabilities: ['research', 'analysis', 'documentation'],
      },
      {
        keywords: ['security', 'vulnerability', 'cve', 'threat'],
        agent: 'security-architect',
        capabilities: ['security-analysis', 'vulnerability-detection', 'threat-modeling'],
      },
      {
        keywords: ['performance', 'optimize', 'speed', 'memory'],
        agent: 'performance-engineer',
        capabilities: ['performance-optimization', 'profiling', 'benchmarking'],
      },
      {
        keywords: ['architect', 'design', 'structure', 'pattern'],
        agent: 'core-architect',
        capabilities: ['architecture-design', 'pattern-application', 'system-design'],
      },
      {
        keywords: ['memory', 'storage', 'database', 'cache'],
        agent: 'memory-specialist',
        capabilities: ['memory-management', 'data-persistence', 'caching'],
      },
      {
        keywords: ['swarm', 'coordinate', 'orchestrate', 'agent'],
        agent: 'swarm-specialist',
        capabilities: ['swarm-coordination', 'agent-orchestration', 'distributed-systems'],
      },
    ];

    // Score each agent based on keyword matches
    for (const pattern of agentPatterns) {
      let matchCount = 0;
      for (const keyword of pattern.keywords) {
        if (description.includes(keyword)) {
          matchCount++;
        }
      }

      if (matchCount > 0) {
        const confidence = Math.min(0.3 + matchCount * 0.2, 0.95);
        suggestedAgents.push({
          type: pattern.agent,
          confidence,
          reason: `Matched keywords: ${pattern.keywords.filter(k => description.includes(k)).join(', ')}`,
          capabilities: pattern.capabilities,
        });
      }
    }

    // Sort by confidence
    suggestedAgents.sort((a, b) => b.confidence - a.confidence);

    // If no matches, default to coder
    if (suggestedAgents.length === 0) {
      suggestedAgents.push({
        type: 'coder',
        confidence: 0.5,
        reason: 'Default agent for unclassified tasks',
        capabilities: ['code-generation', 'implementation'],
      });
    }

    // Estimate complexity based on description length and keywords
    let complexity: 'low' | 'medium' | 'high' = 'medium';
    const complexityKeywords = ['complex', 'large', 'multiple', 'refactor', 'redesign', 'critical'];
    const simpleKeywords = ['simple', 'small', 'quick', 'fix', 'minor', 'typo'];

    const hasComplexKeywords = complexityKeywords.some(k => description.includes(k));
    const hasSimpleKeywords = simpleKeywords.some(k => description.includes(k));

    if (hasComplexKeywords) {
      complexity = 'high';
    } else if (hasSimpleKeywords) {
      complexity = 'low';
    } else if (description.length > 200) {
      complexity = 'high';
    } else if (description.length < 50) {
      complexity = 'low';
    }

    // Estimate duration based on complexity
    const durationMap = {
      low: 5 * 60 * 1000,      // 5 minutes
      medium: 30 * 60 * 1000,  // 30 minutes
      high: 2 * 60 * 60 * 1000, // 2 hours
    };
    const estimatedDuration = durationMap[complexity];

    // Detect risks
    if (description.includes('production') || description.includes('live')) {
      risks.push('Task involves production environment');
    }
    if (description.includes('delete') || description.includes('remove')) {
      risks.push('Task involves destructive operations');
    }
    if (description.includes('security') || description.includes('auth')) {
      risks.push('Task involves security-sensitive operations');
    }
    if (description.includes('database') || description.includes('migration')) {
      risks.push('Task involves database changes');
    }

    // Add recommendations
    if (complexity === 'high') {
      recommendations.push('Consider breaking this task into smaller subtasks');
    }
    if (suggestedAgents.length > 1) {
      recommendations.push('Consider using multiple agents for better coverage');
    }
    if (risks.length > 0) {
      recommendations.push('Review risks before proceeding');
    }

    return {
      suggestedAgents,
      complexity,
      estimatedDuration,
      patterns,
      risks,
      recommendations,
    };
  }

  /**
   * Record learning trajectory
   */
  private async recordLearning(
    task: TaskInfo,
    outcome: TaskOutcome,
    patterns?: TaskPattern[]
  ): Promise<LearningUpdate> {
    // In a real implementation, this would integrate with ReasoningBank
    // For now, we track basic statistics

    const learningUpdate: LearningUpdate = {
      patternsUpdated: patterns?.length || 0,
      newPatterns: outcome.success ? 1 : 0,
      confidenceAdjusted: patterns?.length || 0,
      trajectoriesRecorded: 1,
    };

    return learningUpdate;
  }

  /**
   * Execute pre-task hook manually
   */
  async executePreTask(
    taskId: string,
    description: string,
    metadata?: Record<string, unknown>
  ): Promise<PreTaskHookResult> {
    const context: HookContext = {
      event: HookEvent.PreTaskExecute,
      timestamp: new Date(),
      task: {
        id: taskId,
        description,
        metadata,
      },
    };

    return this.handlePreTask(context);
  }

  /**
   * Execute post-task hook manually
   */
  async executePostTask(
    taskId: string,
    success: boolean,
    metadata?: Record<string, unknown>
  ): Promise<PostTaskHookResult> {
    const taskStore = this.activeTasks.get(taskId);

    const context: HookContext = {
      event: HookEvent.PostTaskExecute,
      timestamp: new Date(),
      task: {
        id: taskId,
        description: taskStore?.description || 'Unknown task',
        metadata: taskStore?.metadata,
      },
      metadata: {
        ...metadata,
        success,
      },
    };

    return this.handlePostTask(context);
  }

  /**
   * Get active tasks
   */
  getActiveTasks(): Map<string, TaskStore> {
    return new Map(this.activeTasks);
  }

  /**
   * Clear all active tasks
   */
  clearActiveTasks(): void {
    this.activeTasks.clear();
    this.taskPatterns.clear();
  }
}

/**
 * Create task hooks manager
 */
export function createTaskHooksManager(registry: HookRegistry): TaskHooksManager {
  return new TaskHooksManager(registry);
}