/** * Workflow Optimizer (GAP-004) * * Analyzes multi-step workflows to find optimization opportunities: * 1. Detects when later steps contain API endpoints that can replace earlier steps * 2. Identifies data sufficiency - when API response has all needed data * 3. Suggests shortcut paths that bypass browser rendering * 4. Tracks optimization metrics for A/B testing * * Example: 4-step form wizard -> single API call to final endpoint * Result: 10-100x speedup by eliminating browser renders */ import type { NetworkRequest } from '../types/index.js'; import type { Workflow } from '../types/workflow.js'; /** * Detected optimization opportunity in a workflow */ export interface WorkflowOptimization { /** Unique ID for this optimization */ id: string; /** Workflow this optimization applies to */ workflowId: string; /** Type of optimization detected */ type: 'api_shortcut' | 'data_sufficiency' | 'step_merge'; /** Original steps that can be bypassed */ bypassedSteps: number[]; /** The step containing the shortcut (API endpoint) */ shortcutStep: number; /** The API endpoint that provides the shortcut */ shortcutEndpoint: ShortcutEndpoint; /** Estimated speedup factor (e.g., 10x, 50x) */ estimatedSpeedupFactor: number; /** Confidence in this optimization (0-1) */ confidence: number; /** Data fields available via the shortcut */ dataFieldsCovered: string[]; /** Parameters needed to call the shortcut directly */ requiredParameters: string[]; /** Metrics tracking optimization success */ metrics: OptimizationMetrics; /** When this optimization was discovered */ discoveredAt: number; /** Whether this optimization is promoted for use */ isPromoted: boolean; } /** * API endpoint that provides a workflow shortcut */ export interface ShortcutEndpoint { url: string; method: string; contentType: string; /** Parameter placeholders in the URL (e.g., {id}, {page}) */ urlParameters: string[]; /** Query parameters */ queryParameters: Record; /** Required headers */ headers: Record; /** Response structure info */ responseStructure?: { dataPath?: string; fields: string[]; }; } /** * Metrics for tracking optimization effectiveness */ export interface OptimizationMetrics { /** Times the optimized path was used */ timesUsed: number; /** Times it succeeded */ successCount: number; /** Times it failed */ failureCount: number; /** Average duration using optimized path (ms) */ avgOptimizedDuration: number; /** Average duration using original path (ms) */ avgOriginalDuration: number; /** Last time metrics were updated */ lastUpdated: number; } /** * Result of workflow analysis */ export interface WorkflowAnalysisResult { workflowId: string; workflowName: string; totalSteps: number; totalDuration: number; optimizations: WorkflowOptimization[]; analysisTimestamp: number; } /** * Captured network data for a workflow step */ export interface StepNetworkData { stepNumber: number; stepUrl: string; requests: NetworkRequest[]; apiRequests: NetworkRequest[]; duration: number; } export declare class WorkflowOptimizer { private optimizations; private optimizationsByWorkflow; /** * Analyze a workflow to find optimization opportunities */ analyzeWorkflow(workflow: Workflow, stepNetworkData: StepNetworkData[]): Promise; /** * Find API shortcuts - later steps that have API endpoints containing all needed data */ private findApiShortcuts; /** * Find data sufficiency patterns - where one step's extracted data * contains all fields from earlier steps */ private findDataSufficiency; /** * Filter requests to only include API-like requests */ private filterApiRequests; /** * Analyze if an API request could serve as a shortcut */ private analyzeApiForShortcut; /** * Extract field names from an object (recursive, limited depth) */ private extractFieldNames; /** * Extract URL parameters and query params */ private extractUrlParameters; /** * Extract endpoint info from a network request */ private extractEndpointInfo; /** * Analyze response structure to understand data layout */ private analyzeResponseStructure; /** * Find the best API request from a list (most data, most relevant) */ private findBestApiRequest; /** * Calculate speedup factor */ private calculateSpeedup; /** * Create empty metrics object */ private createEmptyMetrics; /** * Generate unique optimization ID */ private generateOptimizationId; /** * Get optimization by ID */ getOptimization(id: string): WorkflowOptimization | undefined; /** * Get all optimizations for a workflow */ getWorkflowOptimizations(workflowId: string): WorkflowOptimization[]; /** * Get promoted optimization for a workflow (if any) */ getPromotedOptimization(workflowId: string): WorkflowOptimization | undefined; /** * Record optimization usage result */ recordOptimizationResult(optimizationId: string, success: boolean, duration: number): void; /** * Record original workflow duration (for comparison) */ recordOriginalDuration(workflowId: string, duration: number): void; /** * Check if optimization should be auto-promoted */ private checkAutoPromotion; /** * Manually promote an optimization */ promoteOptimization(optimizationId: string): boolean; /** * Demote an optimization */ demoteOptimization(optimizationId: string): boolean; /** * Update running average calculation */ private updateRunningAverage; /** * Get optimization statistics */ getStatistics(): { totalOptimizations: number; promotedOptimizations: number; byType: Record; avgSpeedup: number; avgConfidence: number; }; /** * Clear all optimizations */ clear(): void; } /** Default workflow optimizer instance */ export declare const workflowOptimizer: WorkflowOptimizer; //# sourceMappingURL=workflow-optimizer.d.ts.map