UNPKG

ai-debug-local-mcp

Version:

🎯 ENHANCED AI GUIDANCE v4.1.2: Dramatically improved tool descriptions help AI users choose the right tools instead of 'close enough' options. Ultra-fast keyboard automation (10x speed), universal recording, multi-ecosystem debugging support, and compreh

1,545 lines 68.7 kB
/**
 * Mock State Inspector Handler
 *
 * Inspects mock state across processes, checks ETS tables for cross-process state,
 * identifies mock visibility issues. Critical for debugging why mocks work in one
 * process but not another, especially in LiveView async contexts.
 */
import { BaseToolHandler } from './base-handler.js';
export class MockStateInspectorHandler extends BaseToolHandler {
    tools = [
        {
            name: 'inspect_mock_state_across_processes',
            description: `🔍 CROSS-PROCESS MOCK INSPECTOR: Inspect mock state across all processes, identify which mocks are visible to which processes, detect state inconsistencies.
      
      Essential for debugging why mocks work in tests but fail in LiveView processes or async contexts.
      
      REQUIRES: Active debug session from inject_debugging tool.`,
            inputSchema: {
                type: 'object',
                properties: {
                    sessionId: {
                        type: 'string',
                        description: 'Debug session ID from inject_debugging'
                    },
                    captureDepth: {
                        type: 'string',
                        enum: ['shallow', 'deep', 'comprehensive'],
                        default: 'deep',
                        description: 'How detailed to make the mock state capture'
                    },
                    includeCallHistory: {
                        type: 'boolean',
                        default: true,
                        description: 'Include call history and expectations in the snapshot'
                    },
                    trackStateChanges: {
                        type: 'boolean',
                        default: true,
                        description: 'Track mock state changes over time'
                    },
                    identifyInconsistencies: {
                        type: 'boolean',
                        default: true,
                        description: 'Identify inconsistencies between process mock states'
                    },
                    analyzeAccessibility: {
                        type: 'boolean',
                        default: true,
                        description: 'Analyze mock accessibility across process boundaries'
                    },
                    focusedMockFramework: {
                        type: 'string',
                        description: 'Focus on specific mock framework (jest, sinon, etc.) - optional'
                    }
                },
                required: ['sessionId']
            }
        },
        {
            name: 'analyze_mock_visibility_issues',
            description: `👁️ MOCK VISIBILITY ANALYZER: Analyze why mocks are not visible to certain processes, suggest fixes for cross-process mock access issues.
      
      Provides actionable recommendations for fixing mock visibility problems.
      
      REQUIRES: Active debug session from inject_debugging tool.`,
            inputSchema: {
                type: 'object',
                properties: {
                    sessionId: {
                        type: 'string',
                        description: 'Debug session ID from inject_debugging'
                    },
                    analysisScope: {
                        type: 'string',
                        enum: ['all-processes', 'failed-processes', 'specific-process'],
                        default: 'failed-processes',
                        description: 'Scope of visibility analysis'
                    },
                    specificProcessId: {
                        type: 'string',
                        description: 'Specific process ID to analyze (required if scope is specific-process)'
                    },
                    includeRecommendations: {
                        type: 'boolean',
                        default: true,
                        description: 'Include actionable recommendations for fixing issues'
                    },
                    checkScopeConfiguration: {
                        type: 'boolean',
                        default: true,
                        description: 'Check mock scope configuration and settings'
                    },
                    validateMockSetup: {
                        type: 'boolean',
                        default: true,
                        description: 'Validate that mocks are properly set up for cross-process access'
                    }
                },
                required: ['sessionId']
            }
        },
        {
            name: 'track_mock_state_timeline',
            description: `📈 MOCK STATE TIMELINE: Track how mock state changes over time across processes, identify when mocks become unavailable.
      
      Perfect for debugging async processes that lose access to mocks during execution.
      
      REQUIRES: Active debug session from inject_debugging tool.`,
            inputSchema: {
                type: 'object',
                properties: {
                    sessionId: {
                        type: 'string',
                        description: 'Debug session ID from inject_debugging'
                    },
                    trackingDuration: {
                        type: 'number',
                        default: 30000,
                        description: 'How long to track mock state changes (ms)'
                    },
                    sampleInterval: {
                        type: 'number',
                        default: 1000,
                        description: 'How often to sample mock state (ms)'
                    },
                    trackSpecificMocks: {
                        type: 'array',
                        items: { type: 'string' },
                        description: 'Specific mock names to track (optional)'
                    },
                    alertOnStateChanges: {
                        type: 'boolean',
                        default: true,
                        description: 'Alert when mock state changes unexpectedly'
                    },
                    correlateWithProcessEvents: {
                        type: 'boolean',
                        default: true,
                        description: 'Correlate mock state changes with process lifecycle events'
                    },
                    identifyLossPoints: {
                        type: 'boolean',
                        default: true,
                        description: 'Identify exact points where processes lose mock access'
                    }
                },
                required: ['sessionId']
            }
        },
        {
            name: 'generate_mock_state_report',
            description: `📋 MOCK STATE REPORT GENERATOR: Generate comprehensive report of mock state across all processes with recommendations for improving mock reliability.
      
      Provides executive summary and technical recommendations for mock architecture.
      
      REQUIRES: Active debug session from inject_debugging tool.`,
            inputSchema: {
                type: 'object',
                properties: {
                    sessionId: {
                        type: 'string',
                        description: 'Debug session ID from inject_debugging'
                    },
                    reportDepth: {
                        type: 'string',
                        enum: ['summary', 'detailed', 'comprehensive'],
                        default: 'detailed',
                        description: 'Level of detail in the generated report'
                    },
                    includeCodeExamples: {
                        type: 'boolean',
                        default: true,
                        description: 'Include code examples for fixing identified issues'
                    },
                    includeBestPractices: {
                        type: 'boolean',
                        default: true,
                        description: 'Include best practices for cross-process mock management'
                    },
                    prioritizeIssues: {
                        type: 'boolean',
                        default: true,
                        description: 'Prioritize issues by impact and frequency'
                    },
                    generateActionPlan: {
                        type: 'boolean',
                        default: true,
                        description: 'Generate step-by-step action plan for improvements'
                    }
                },
                required: ['sessionId']
            }
        }
    ];
    async handle(toolName, args, sessions) {
        // Validate session exists
        const session = sessions.get(args.sessionId);
        if (!session) {
            return {
                content: [{
                        type: 'text',
                        text: `❌ No active debug session found with ID: ${args.sessionId}

Please first create a debug session using:
\`inject_debugging --url <your-app-url>\`

Then use the returned sessionId with this tool.`
                    }]
            };
        }
        switch (toolName) {
            case 'inspect_mock_state_across_processes':
                return this.inspectMockStateAcrossProcesses(args, session);
            case 'analyze_mock_visibility_issues':
                return this.analyzeMockVisibilityIssues(args, session);
            case 'track_mock_state_timeline':
                return this.trackMockStateTimeline(args, session);
            case 'generate_mock_state_report':
                return this.generateMockStateReport(args, session);
            default:
                throw new Error(`Unknown mock state inspector tool: ${toolName}`);
        }
    }
    async inspectMockStateAcrossProcesses(args, session) {
        const { captureDepth = 'deep', includeCallHistory = true, trackStateChanges = true, identifyInconsistencies = true, analyzeAccessibility = true, focusedMockFramework } = args;
        try {
            const page = session.page;
            if (!page) {
                throw new Error('No page available in session');
            }
            // Inject comprehensive mock state inspection
            await page.addInitScript((config) => {
                window.__mockStateInspector = {
                    snapshots: [],
                    processStates: new Map(),
                    inconsistencies: [],
                    config: config
                };
                // Detect available mock frameworks
                const detectMockFrameworks = () => {
                    const frameworks = {};
                    // Jest detection
                    if (typeof jest !== 'undefined') {
                        frameworks.jest = {
                            available: true,
                            version: jest.version || 'unknown',
                            globalMocks: Object.keys(jest.getAllMocks?.() || {}),
                            clearHistory: () => jest.clearAllMocks?.(),
                            getState: () => ({
                                mocks: jest.getAllMocks?.() || {},
                                spies: Object.keys(window.globalThis || {}).filter(key => key.includes('spy') || key.includes('mock'))
                            })
                        };
                    }
                    // Sinon detection
                    if (typeof window.sinon !== 'undefined') {
                        const sinon = window.sinon;
                        frameworks.sinon = {
                            available: true,
                            version: sinon.version || 'unknown',
                            stubs: sinon.stub.getCalls?.() || [],
                            spies: sinon.spy.getCalls?.() || [],
                            getState: () => ({
                                stubs: sinon.getStubs?.() || [],
                                spies: sinon.getSpies?.() || [],
                                history: sinon.stub.history || []
                            })
                        };
                    }
                    // Vitest detection  
                    if (typeof window.vi !== 'undefined') {
                        const vi = window.vi;
                        frameworks.vitest = {
                            available: true,
                            mocks: vi.getAllMocks?.() || {},
                            getState: () => ({
                                mocks: vi.getAllMocks?.() || {},
                                spies: vi.getAllSpies?.() || {}
                            })
                        };
                    }
                    // Custom mock detection (common patterns)
                    const customMocks = Object.keys(window).filter(key => key.includes('mock') || key.includes('stub') || key.includes('spy'));
                    if (customMocks.length > 0) {
                        frameworks.custom = {
                            available: true,
                            detectedMocks: customMocks,
                            getState: () => ({
                                customMocks: customMocks.map(key => ({
                                    name: key,
                                    value: window[key],
                                    type: typeof window[key]
                                }))
                            })
                        };
                    }
                    return frameworks;
                };
                // Capture mock state snapshot
                const captureSnapshot = (processId) => {
                    const frameworks = detectMockFrameworks();
                    const timestamp = Date.now();
                    const snapshot = {
                        id: Math.random().toString(36).substr(2, 9),
                        timestamp,
                        processId,
                        mockFramework: config.focusedMockFramework || Object.keys(frameworks)[0] || 'none',
                        state: {
                            activeStubs: [],
                            expectations: [],
                            callHistory: [],
                            scopeInfo: {
                                global: Object.keys(window).filter(k => k.includes('mock')).length,
                                localStorage: Object.keys(localStorage).filter(k => k.includes('mock')).length,
                                sessionStorage: Object.keys(sessionStorage).filter(k => k.includes('mock')).length
                            },
                            accessibility: {
                                crossProcess: true, // Browser main thread default
                                visibility: 'global',
                                isolation: 'none'
                            }
                        }
                    };
                    // Capture framework-specific state
                    Object.entries(frameworks).forEach(([name, framework]) => {
                        if (framework.available) {
                            try {
                                const state = framework.getState();
                                if (config.captureDepth === 'comprehensive') {
                                    snapshot.state.activeStubs.push({
                                        framework: name,
                                        details: state,
                                        count: Object.keys(state).length
                                    });
                                }
                                else if (config.captureDepth === 'deep') {
                                    snapshot.state.activeStubs.push({
                                        framework: name,
                                        count: Object.keys(state).length,
                                        summary: Object.keys(state).slice(0, 5)
                                    });
                                }
                                else {
                                    snapshot.state.activeStubs.push({
                                        framework: name,
                                        count: Object.keys(state).length
                                    });
                                }
                                if (config.includeCallHistory && framework.history) {
                                    snapshot.state.callHistory.push({
                                        framework: name,
                                        calls: framework.history.slice(-10) // Last 10 calls
                                    });
                                }
                            }
                            catch (e) {
                                // Framework access error
                            }
                        }
                    });
                    window.__mockStateInspector.snapshots.push(snapshot);
                    window.__mockStateInspector.processStates.set(processId, snapshot);
                    return snapshot;
                };
                // Track state changes
                if (config.trackStateChanges) {
                    const originalSetInterval = window.setInterval;
                    setInterval(() => {
                        captureSnapshot('main-process');
                    }, 2000);
                }
                // Analyze accessibility
                if (config.analyzeAccessibility) {
                    const processAccessibility = {
                        mainThread: {
                            canAccessGlobalMocks: true,
                            canAccessLocalStorage: true,
                            canAccessSessionStorage: true,
                            isolationLevel: 'none'
                        },
                        webWorkers: {
                            canAccessGlobalMocks: false,
                            canAccessLocalStorage: false,
                            canAccessSessionStorage: false,
                            isolationLevel: 'complete'
                        },
                        serviceWorkers: {
                            canAccessGlobalMocks: false,
                            canAccessLocalStorage: false,
                            canAccessSessionStorage: false,
                            isolationLevel: 'complete'
                        }
                    };
                    window.__mockStateInspector.accessibility = processAccessibility;
                }
                // Initial snapshot
                captureSnapshot('main-process');
                // Make inspector available for external calls
                window.captureMockSnapshot = captureSnapshot;
            }, {
                captureDepth,
                includeCallHistory,
                trackStateChanges,
                identifyInconsistencies,
                analyzeAccessibility,
                focusedMockFramework
            });
            // Wait for initial data collection
            await new Promise(resolve => setTimeout(resolve, 3000));
            // Get mock state data
            const mockStateData = await page.evaluate(() => {
                return {
                    snapshots: window.__mockStateInspector?.snapshots || [],
                    processStates: Array.from(window.__mockStateInspector?.processStates?.entries() || []),
                    accessibility: window.__mockStateInspector?.accessibility || {},
                    inconsistencies: window.__mockStateInspector?.inconsistencies || []
                };
            });
            // Analyze inconsistencies if requested
            const inconsistencies = identifyInconsistencies ?
                this.identifyStateInconsistencies(mockStateData.snapshots) : [];
            // Analyze accessibility issues
            const accessibilityIssues = analyzeAccessibility ?
                this.analyzeAccessibilityIssues(mockStateData.accessibility) : [];
            return {
                content: [{
                        type: 'text',
                        text: `## 🔍 Cross-Process Mock State Inspection Report

### State Summary
- **Total Snapshots**: ${mockStateData.snapshots.length}
- **Active Processes**: ${mockStateData.processStates.length}
- **Capture Depth**: ${captureDepth}
- **Framework Focus**: ${focusedMockFramework || 'All detected frameworks'}

### Process Mock States
${mockStateData.processStates.length > 0 ?
                            mockStateData.processStates.map(([processId, state]) => `
#### Process: ${processId}
- **Framework**: ${state.mockFramework}
- **Active Stubs**: ${state.state.activeStubs.length}
- **Call History Entries**: ${state.state.callHistory.length}
- **Scope Info**: 
  - Global mocks: ${state.state.scopeInfo.global}
  - LocalStorage mocks: ${state.state.scopeInfo.localStorage}
  - SessionStorage mocks: ${state.state.scopeInfo.sessionStorage}
- **Accessibility**:
  - Cross-process: ${state.state.accessibility.crossProcess ? '✅' : '❌'}
  - Visibility: ${state.state.accessibility.visibility}
  - Isolation: ${state.state.accessibility.isolation}
`).join('') :
                            'No process states captured'}

### Mock Framework Analysis
${mockStateData.snapshots.length > 0 ?
                            this.generateFrameworkAnalysis(mockStateData.snapshots) :
                            'No framework analysis available'}

### State Inconsistencies
${identifyInconsistencies ? `
${inconsistencies.length > 0 ?
                            inconsistencies.map((issue, i) => `
#### Issue ${i + 1}: ${issue.type}
- **Description**: ${issue.description}
- **Affected Processes**: ${issue.affectedProcesses.join(', ')}
- **Impact**: ${issue.impact}
- **Recommendation**: ${issue.recommendation}
`).join('') :
                            '✅ No state inconsistencies detected'}
` : 'State inconsistency analysis disabled'}

### Accessibility Analysis
${analyzeAccessibility ? `
${accessibilityIssues.length > 0 ?
                            accessibilityIssues.map((issue, i) => `
#### Accessibility Issue ${i + 1}
- **Process Type**: ${issue.processType}
- **Issue**: ${issue.issue}
- **Impact**: ${issue.impact}
- **Solution**: ${issue.solution}
`).join('') :
                            '✅ No accessibility issues detected'}

**Process Isolation Summary**:
- **Main Thread**: Full mock access
- **Web Workers**: Isolated (no mock access)
- **Service Workers**: Isolated (no mock access)
` : 'Accessibility analysis disabled'}

### Recent Snapshots
${mockStateData.snapshots.slice(-3).map((snapshot, i) => `
#### Snapshot ${i + 1}
- **Time**: ${new Date(snapshot.timestamp).toISOString()}
- **Process**: ${snapshot.processId}
- **Framework**: ${snapshot.mockFramework}
- **Active Stubs**: ${snapshot.state.activeStubs.length}
${includeCallHistory ? `- **Recent Calls**: ${snapshot.state.callHistory.length}` : ''}
`).join('')}

### Configuration
- **Capture Depth**: ${captureDepth}
- **Include Call History**: ${includeCallHistory ? '✅' : '❌'}
- **Track State Changes**: ${trackStateChanges ? '✅' : '❌'}
- **Identify Inconsistencies**: ${identifyInconsistencies ? '✅' : '❌'}
- **Analyze Accessibility**: ${analyzeAccessibility ? '✅' : '❌'}

### Next Steps
- Use \`analyze_mock_visibility_issues\` for detailed visibility analysis
- Use \`track_mock_state_timeline\` to monitor state changes over time
- Use \`generate_mock_state_report\` for comprehensive recommendations
- Consider implementing cross-process mock sharing strategies

### Backend Integration Note
This tool provides browser-side mock state inspection. For complete server-side mock analysis in Phoenix/LiveView applications, integrate with:
- ETS table monitoring for server-side mock state
- Process-level mock accessibility tracking
- GenServer mock state replication patterns`
                    }]
            };
        }
        catch (error) {
            return {
                content: [{
                        type: 'text',
                        text: `## ❌ Mock State Inspection Error

**Error**: ${error instanceof Error ? error.message : 'Unknown error'}

### Troubleshooting
- Ensure your application uses mock frameworks (Jest, Sinon, Vitest, etc.)
- Verify mock frameworks are loaded before running this tool
- Check that mocks are actually active during the inspection period`
                    }]
            };
        }
    }
    async analyzeMockVisibilityIssues(args, session) {
        const { analysisScope = 'failed-processes', specificProcessId, includeRecommendations = true, checkScopeConfiguration = true, validateMockSetup = true } = args;
        try {
            const page = session.page;
            if (!page) {
                throw new Error('No page available in session');
            }
            // First get current mock state
            const currentStateResult = await this.inspectMockStateAcrossProcesses({
                sessionId: args.sessionId,
                captureDepth: 'comprehensive',
                analyzeAccessibility: true
            }, session);
            // Inject visibility analysis
            await page.addInitScript((config) => {
                window.__mockVisibilityAnalyzer = {
                    issues: [],
                    recommendations: [],
                    config: config
                };
                // Analyze mock visibility patterns
                const analyzeVisibility = () => {
                    const issues = [];
                    const recommendations = [];
                    // Check global mock accessibility
                    const globalMocksCount = Object.keys(window).filter(k => k.includes('mock') || k.includes('jest') || k.includes('sinon')).length;
                    if (globalMocksCount === 0) {
                        issues.push({
                            type: 'no-global-mocks',
                            severity: 'high',
                            description: 'No global mocks detected in main process',
                            impact: 'Mocks may not be accessible to async processes',
                            recommendation: 'Ensure mocks are set up globally before spawning processes'
                        });
                    }
                    // Check localStorage mock persistence
                    const localStorageMocks = Object.keys(localStorage).filter(k => k.includes('mock'));
                    if (localStorageMocks.length > 0) {
                        issues.push({
                            type: 'localstorage-mocks',
                            severity: 'medium',
                            description: 'Mocks stored in localStorage detected',
                            impact: 'Web Workers and Service Workers cannot access localStorage mocks',
                            recommendation: 'Use global variables or postMessage for cross-process mock sharing'
                        });
                    }
                    // Check for process isolation issues
                    if ('serviceWorker' in navigator) {
                        issues.push({
                            type: 'service-worker-isolation',
                            severity: 'medium',
                            description: 'Service Worker detected - mocks will be isolated',
                            impact: 'Service Worker processes cannot access main thread mocks',
                            recommendation: 'Implement mock state replication to Service Worker scope'
                        });
                    }
                    // Check mock framework configuration
                    if (typeof jest !== 'undefined') {
                        const jestConfig = jest.getGlobalConfig?.();
                        if (!jestConfig || !jestConfig.setupFilesAfterEnv) {
                            issues.push({
                                type: 'jest-setup-missing',
                                severity: 'medium',
                                description: 'Jest setup files not detected',
                                impact: 'Mocks may not be consistently available across all contexts',
                                recommendation: 'Configure Jest setupFilesAfterEnv for consistent mock initialization'
                            });
                        }
                    }
                    // Generate recommendations
                    if (config.includeRecommendations) {
                        recommendations.push({
                            category: 'Cross-Process Mock Sharing',
                            priority: 'high',
                            suggestions: [
                                'Use SharedArrayBuffer for cross-process mock state (where supported)',
                                'Implement postMessage-based mock synchronization',
                                'Consider using BroadcastChannel for mock state updates'
                            ]
                        });
                        recommendations.push({
                            category: 'Mock Persistence',
                            priority: 'medium',
                            suggestions: [
                                'Store critical mocks in IndexedDB for persistence',
                                'Use sessionStorage for temporary cross-tab mock sharing',
                                'Implement mock state backup and restore mechanisms'
                            ]
                        });
                        recommendations.push({
                            category: 'Process Isolation Solutions',
                            priority: 'high',
                            suggestions: [
                                'Design mocks to be serializable for process boundaries',
                                'Implement mock proxies for async process communication',
                                'Use message-based mock invocation patterns'
                            ]
                        });
                    }
                    return { issues, recommendations };
                };
                const analysis = analyzeVisibility();
                window.__mockVisibilityAnalyzer.issues = analysis.issues;
                window.__mockVisibilityAnalyzer.recommendations = analysis.recommendations;
            }, {
                analysisScope,
                specificProcessId,
                includeRecommendations,
                checkScopeConfiguration,
                validateMockSetup
            });
            // Wait for analysis
            await new Promise(resolve => setTimeout(resolve, 2000));
            // Get visibility analysis data
            const visibilityData = await page.evaluate(() => {
                return {
                    issues: window.__mockVisibilityAnalyzer?.issues || [],
                    recommendations: window.__mockVisibilityAnalyzer?.recommendations || []
                };
            });
            // Additional scope-specific analysis
            const scopeAnalysis = checkScopeConfiguration ?
                this.analyzeScopeConfiguration(analysisScope) : null;
            // Mock setup validation
            const setupValidation = validateMockSetup ?
                await this.validateMockSetup(page) : null;
            return {
                content: [{
                        type: 'text',
                        text: `## 👁️ Mock Visibility Issues Analysis

### Analysis Scope
- **Scope**: ${analysisScope}
- **Specific Process**: ${specificProcessId || 'All processes'}
- **Configuration Check**: ${checkScopeConfiguration ? '✅' : '❌'}
- **Setup Validation**: ${validateMockSetup ? '✅' : '❌'}

### Detected Issues
${visibilityData.issues.length > 0 ?
                            visibilityData.issues.map((issue, i) => `
#### Issue ${i + 1}: ${issue.type}
- **Severity**: ${issue.severity}
- **Description**: ${issue.description}
- **Impact**: ${issue.impact}
- **Recommendation**: ${issue.recommendation}
`).join('') :
                            '✅ No visibility issues detected'}

### Scope Configuration Analysis
${checkScopeConfiguration && scopeAnalysis ? `
**Scope**: ${analysisScope}
**Analysis**: ${scopeAnalysis.summary}

**Configuration Issues**:
${scopeAnalysis.issues.map((issue) => `- ${issue}`).join('\n')}

**Recommendations**:
${scopeAnalysis.recommendations.map((rec) => `- ${rec}`).join('\n')}
` : 'Scope configuration analysis disabled'}

### Mock Setup Validation
${validateMockSetup && setupValidation ? `
**Setup Status**: ${setupValidation.isValid ? '✅ Valid' : '❌ Issues Detected'}

${setupValidation.issues.length > 0 ? `
**Setup Issues**:
${setupValidation.issues.map((issue) => `
- **${issue.category}**: ${issue.description}
  - *Fix*: ${issue.fix}
`).join('')}` : ''}

**Setup Recommendations**:
${setupValidation.recommendations.map((rec) => `- ${rec}`).join('\n')}
` : 'Mock setup validation disabled'}

### Recommendations by Category
${includeRecommendations ?
                            visibilityData.recommendations.map((category) => `
#### ${category.category} (Priority: ${category.priority})
${category.suggestions.map((suggestion) => `- ${suggestion}`).join('\n')}
`).join('') :
                            'Recommendations disabled'}

### Cross-Process Mock Architecture Patterns

#### 1. Message-Based Mock Synchronization
\`\`\`javascript
// Main thread mock setup
const mockState = { userMocks: {}, apiMocks: {} };

// Sync to worker
worker.postMessage({ type: 'SYNC_MOCKS', mocks: mockState });

// Worker mock handler
self.onmessage = (event) => {
  if (event.data.type === 'SYNC_MOCKS') {
    self.mockState = event.data.mocks;
  }
};
\`\`\`

#### 2. Shared Mock Registry
\`\`\`javascript
// Create shared mock registry
const mockRegistry = new Map();
window.globalMockRegistry = mockRegistry;

// Register mocks globally
function registerMock(name, mock) {
  window.globalMockRegistry.set(name, mock);
  broadcastMockUpdate(name, mock);
}
\`\`\`

#### 3. Process-Aware Mock Factory
\`\`\`javascript
class ProcessAwareMockFactory {
  static createMock(name, implementation) {
    const mock = {
      name,
      implementation,
      processId: self.location?.href || 'main',
      accessible: ['main', 'worker', 'service-worker']
    };
    
    return this.registerAcrossProcesses(mock);
  }
}
\`\`\`

### Action Plan
1. **Immediate Fixes**:
   - ${visibilityData.issues.filter((i) => i.severity === 'high').length} high-priority issues to address
   - Implement global mock registration pattern
   - Set up cross-process mock synchronization

2. **Medium-term Improvements**:
   - Design serializable mock architecture
   - Implement mock state persistence
   - Add mock accessibility monitoring

3. **Long-term Architecture**:
   - Create comprehensive cross-process mock framework
   - Implement automatic mock distribution
   - Add mock state debugging tools

### Next Steps
- Use \`track_mock_state_timeline\` to monitor how visibility changes over time
- Use \`generate_mock_state_report\` for comprehensive architecture recommendations
- Implement suggested cross-process mock patterns
- Add monitoring for mock accessibility in production

### Framework-Specific Guidance
${this.generateFrameworkSpecificGuidance()}

### Backend Integration
For Phoenix/LiveView applications, consider:
- ETS tables for server-side mock sharing
- GenServer mock state management
- Process supervision for mock consistency`
                    }]
            };
        }
        catch (error) {
            return {
                content: [{
                        type: 'text',
                        text: `## ❌ Mock Visibility Analysis Error

**Error**: ${error instanceof Error ? error.message : 'Unknown error'}`
                    }]
            };
        }
    }
    async trackMockStateTimeline(args, session) {
        const { trackingDuration = 30000, sampleInterval = 1000, trackSpecificMocks = [], alertOnStateChanges = true, correlateWithProcessEvents = true, identifyLossPoints = true } = args;
        try {
            const page = session.page;
            if (!page) {
                throw new Error('No page available in session');
            }
            // Inject timeline tracking
            await page.addInitScript((config) => {
                window.__mockTimeline = {
                    snapshots: [],
                    alerts: [],
                    lossPoints: [],
                    config: config
                };
                let intervalId;
                let baselineState = null;
                const captureTimelineSnapshot = () => {
                    const timestamp = Date.now();
                    const mockSnapshot = {
                        timestamp,
                        globalMocks: Object.keys(window).filter(k => k.includes('mock') || k.includes('jest') || k.includes('sinon')).length,
                        localStorageMocks: Object.keys(localStorage).filter(k => k.includes('mock')).length,
                        sessionStorageMocks: Object.keys(sessionStorage).filter(k => k.includes('mock')).length,
                        specificMocks: {},
                        processInfo: {
                            location: window.location.href,
                            userAgent: navigator.userAgent.slice(0, 50),
                            connectionType: navigator.connection?.effectiveType || 'unknown'
                        }
                    };
                    // Track specific mocks if requested
                    if (config.trackSpecificMocks.length > 0) {
                        config.trackSpecificMocks.forEach((mockName) => {
                            mockSnapshot.specificMocks[mockName] = {
                                exists: mockName in window,
                                type: typeof window[mockName],
                                accessible: true
                            };
                        });
                    }
                    // Jest-specific tracking
                    if (typeof jest !== 'undefined') {
                        mockSnapshot.jest = {
                            mocks: Object.keys(jest.getAllMocks?.() || {}).length,
                            clearHistory: !!jest.clearAllMocks
                        };
                    }
                    // Sinon-specific tracking
                    if (typeof window.sinon !== 'undefined') {
                        mockSnapshot.sinon = {
                            stubs: window.sinon.getStubs?.().length || 0,
                            spies: window.sinon.getSpies?.().length || 0
                        };
                    }
                    window.__mockTimeline.snapshots.push(mockSnapshot);
                    // Check for state changes and alert
                    if (config.alertOnStateChanges && baselineState) {
                        const changes = [];
                        if (mockSnapshot.globalMocks !== baselineState.globalMocks) {
                            changes.push(`Global mocks: ${baselineState.globalMocks} → ${mockSnapshot.globalMocks}`);
                        }
                        if (mockSnapshot.localStorageMocks !== baselineState.localStorageMocks) {
                            changes.push(`LocalStorage mocks: ${baselineState.localStorageMocks} → ${mockSnapshot.localStorageMocks}`);
                        }
                        if (changes.length > 0) {
                            const alert = {
                                timestamp,
                                type: 'state_change',
                                changes,
                                severity: changes.some(c => c.includes('→ 0')) ? 'high' : 'medium'
                            };
                            window.__mockTimeline.alerts.push(alert);
                        }
                    }
                    // Set baseline if first snapshot
                    if (!baselineState) {
                        baselineState = { ...mockSnapshot };
                    }
                    // Identify loss points
                    if (config.identifyLossPoints) {
                        const currentTotal = mockSnapshot.globalMocks + mockSnapshot.localStorageMocks;
                        const baselineTotal = baselineState.globalMocks + baselineState.localStorageMocks;
                        if (currentTotal < baselineTotal * 0.8) { // 20% loss threshold
                            window.__mockTimeline.lossPoints.push({
                                timestamp,
                                lossPercentage: ((baselineTotal - currentTotal) / baselineTotal * 100).toFixed(1),
                                remaining: currentTotal,
                                baseline: baselineTotal
                            });
                        }
                    }
                };
                // Start timeline tracking
                captureTimelineSnapshot(); // Initial snapshot
                intervalId = setInterval(captureTimelineSnapshot, config.sampleInterval);
                // Stop tracking after duration
                setTimeout(() => {
                    if (intervalId) {
                        clearInterval(intervalId);
                    }
                }, config.trackingDuration);
                // Store cleanup function
                window.__mockTimelineCleanup = () => {
                    if (intervalId)
                        clearInterval(intervalId);
                };
            }, {
                trackingDuration,
                sampleInterval,
                trackSpecificMocks,
                alertOnStateChanges,
                correlateWithProcessEvents,
                identifyLossPoints
            });
            // Wait for tracking completion
            await new Promise(resolve => setTimeout(resolve, trackingDuration + 1000));
            // Get timeline data
            const timelineData = await page.evaluate(() => {
                // Cleanup
                if (window.__mockTimelineCleanup) {
                    window.__mockTimelineCleanup();
                }
                return {
                    snapshots: window.__mockTimeline?.snapshots || [],
                    alerts: window.__mockTimeline?.alerts || [],
                    lossPoints: window.__mockTimeline?.lossPoints || []
                };
            });
            // Analyze timeline trends
            const trendAnalysis = this.analyzeTimelineTrends(timelineData.snapshots);
            const criticalEvents = this.identifyCriticalEvents(timelineData.alerts, timelineData.lossPoints);
            return {
                content: [{
                        type: 'text',
                        text: `## 📈 Mock State Timeline Report

### Timeline Summary
- **Tracking Duration**: ${trackingDuration}ms
- **Sample Interval**: ${sampleInterval}ms
- **Total Snapshots**: ${timelineData.snapshots.length}
- **State Change Alerts**: ${timelineData.alerts.length}
- **Loss Points Detected**: ${timelineData.lossPoints.length}

### Mock State Trends
${trendAnalysis.summary}

**Trend Analysis**:
- **Global Mocks**: ${trendAnalysis.globalMocks.trend} (${trendAnalysis.globalMocks.change})
- **LocalStorage Mocks**: ${trendAnalysis.localStorageMocks.trend} (${trendAnalysis.localStorageMocks.change})
- **SessionStorage Mocks**: ${trendAnalysis.sessionStorageMocks.trend} (${trendAnalysis.sessionStorageMocks.change})
- **Overall Stability**: ${trendAnalysis.stability}

### State Change Alerts
${alertOnStateChanges ? `
${timelineData.alerts.length > 0 ?
                            timelineData.alerts.map((alert, i) => `
#### Alert ${i + 1} (${alert.severity})
- **Time**: ${new Date(alert.timestamp).toISOString()}
- **Type**: ${alert.type}
- **Changes**: 
${alert.changes.map((change) => `  - ${change}`).join('\n')}
`).join('') :
                            '✅ No state change alerts during tracking period'}
` : 'State change alerts disabled'}

### Mock Loss Points
${identifyLossPoints ? `
${timelineData.lossPoints.length > 0 ?
                            timelineData.lossPoints.map((loss, i) => `
#### Loss Point ${i + 1}
- **Time**: ${new Date(loss.timestamp).toISOString()}
- **Loss Percentage**: ${loss.lossPercentage}%
- **Remaining Mocks**: ${loss.remaining}
- **Baseline**: ${loss.baseline}
- **Trigger**: ${this.determineLossTrigger(loss)}
`).join('') :
                            '✅ No significant mock loss points detected'}
` : 'Loss point identification disabled'}

### Critical Events Timeline
${criticalEvents.length > 0 ?
                            criticalEvents.map((event, i) => `
#### Event ${i + 1}: ${event.type}
- **Time**: ${new Date(event.timestamp).toISOString()}
- **Impact**: ${event.impact}
- **Details**: ${event.details}
- **Recovery**: ${event.recovery}
`).join('') :
                            'No critical events detected'}

### Specific Mock Tracking
${trackSpecificMocks.length > 0 ? `
${trackSpecificMocks.map((mockName) => {
                            const trackingData = this.analyzeSpecificMockTracking(timelineData.snapshots, mockName);
                            return `
#### Mock: ${mockName}
- **Availability**: ${trackingData.availability}%
- **State Changes**: ${trackingData.changes}
- **Longest Unavailable**: ${trackingData.longestUnavailable}ms
- **Status**: ${trackingData.status}
`;
                        }).join('')}
` : 'No specific mocks tracked'}

### Process Event Correlation
${correlateWithProcessEvents ? `
**Process Events During Timeline**:
- Navigation events: ${this.countNavigationEvents(timelineData.snapshots)}
- Connection changes: ${this.countConnectionChanges(timelineData.snapshots)}
- Mock framework reloads: ${this.countFrameworkReloads(timelineData.snapshots)}

**Correlation Analysis**:
${this.analyzeProcessCorrelation(timelineData.snapshots, timelineData.alerts)}
` : 'Process event correlation disabled'}

### Timeline Visualization
\`\`\`
${this.generateTimelineVisualization(timelineData.snapshots)}
\`\`\`

### Stability Metrics
- **Mock Persistence Score**: ${trendAnalysis.persistenceScore}/100
- **State Consistency**: ${trendAnalysis.consistency}%
- **Recovery Time**: ${trendAnalysis.averageRecoveryTime}ms
- **Reliability Rating**: ${trendAnalysis.reliabilityRating}

### Recommendations
${this.generateTimelineRecommendations(trendAnalysis, timelineData.alerts, timelineData.lossPoints)}

### Configuration
- **Tracking Duration**: ${trackingDuration}ms
- **Sample Interval**: ${sampleInterval}ms
- **Specific Mocks**: ${trackSpecificMocks.length > 0 ? trackSpecificMocks.join(', ') : 'None'}
- **Alert on Changes**: ${alertOnStateChanges ? '✅' : '❌'}
- **Correlate Process Events**: ${correlateWithProcessEvents ? '✅' : '❌'}
- **Identify Loss Points**: ${identifyLossPoints ? '✅' : '❌'}

### Next Steps
- Investigate any critical events or loss points identified
- Implement mock state persistence for unstable mocks
- Add proactive monitoring for identified failure patterns
- Use \`generate_mock_state_report\` for comprehensive improvement plan

### Implementation Suggestions
For preventing mock state loss:

\`\`\`javascript
// Mock state persistence
function persistMockState() {
  const state = captureMockState();
  sessionStorage.setItem('mockStateBackup', JSON.stringify(state));
}

// Mock state recovery
function recoverMockState() {
  const backup = sessionStorage.getItem('mockStateBackup');
  if (backup) {
    restoreMockState(JSON.parse(backup));
  }
}

// Periodic mock health check
setInterval(() => {
  if (getMockCount() === 0) {
    console.warn('Mock state lost - attempting recovery');
    recoverMockState();
  }
}, 5000);
\`\`\``
                    }]
            };
        }
        catch (error) {
            return {
                content: [{
                        type: 'text',
                        text: `## ❌ Mock State Timeline Error

**Error**: ${error instanceof Error ? error.message : 'Unknown error'}`
                    }]
            };
        }
    }
    async generateMockStateReport(args, session) {
        const { reportDepth = 'detailed', includeCodeExamples = true, includeBestPractices = true, prioritizeIssues = true, generateActionPlan = true } = args;
        try {
            // Run comprehensive analysis first
            const stateInspection = await this.inspectMockStateAcrossProcesses({
                sessionId: args.sessionId,
                captureDepth: 'comprehensive',
                identifyInconsistencies: true,
                analyzeAccessibility: true
            }, session);
            const visibilityAnalysis = await this.analyzeMockVisibilityIssues({
                sessionId: args.sessionId,
                analysisScope: 'all-processes',
                includeRecommendations: true,
                validateMockSetup: true
            }, session);
            // Generate comprehensive report
            const executiveSummary = this.generateExecutiveSummary(reportDepth);
            const technicalFindings = this.generateTechnicalFindings(reportDepth);
            const architectureRecommendations = this.generateArchitectureRecommendations();
            const implementationGuide = includeCodeExamples ? this.generateImplementationGuide() : null;
            const bestPractices = includeBestPractices ? this.generateBestPractices() : null;
            const actionPlan = generateActionPlan ? this.generateActionPlan() : null;
            return {
                content: [{
                        type: 'text',
                        text: `## 📋 Comprehensive Mock State Report

### Executive Summary
${executiveSummary}

### Technical Findings
${technicalFindings}

### Mock Architecture Assessment
${architectureRecommendations}

### Implementation Guide
${includeCodeExamples ? implementationGuide : 'Code examples disabled'}

### Best Practices
${includeBestPractices ? bestPractices : 'Best practices disabled'}

### Prioritized Action Plan
${generateActionPlan ? actionPlan : 'Action plan generation disabled'}

### Report Configuration
- **Report Depth**: ${reportDepth}
- **Code Examples**: ${includeCodeExamples ? '✅' : '❌'}
- **Best Practices**: ${includeBestPractices ? '✅' : '❌'}
- **Issue Prioritization**: ${prioritizeIssues ? '✅' : '❌'}
- **Action Plan**: ${generateActionPlan ? '✅' : '❌'}

### Appendices
#### A. Framework Compatibility Matrix
${this.generateCompatibilityMatrix()}

#### B. Performance Impact Analysis
${this.generatePerformanceAnalysis()}

#### C. Security Considerations
${this.generateSecurityConsiderations()}

### Report Conclusion
This comprehensive analysis provides a roadmap for improving mock state management across processes. Implementation of the recommended solutions will significantly improve test reliability and debugging capabilities.

**Next Steps**: Begin with high-priority action items and gradually implement the comprehensive architecture improvements outlined in this report.`
                    }]
            };
        }
        catch (error) {
            return {
                content: [{
                        type: 'text',
                        text: `## ❌ Mock State Report Generation Error

**Error**: ${error instanceof Error ? error.message : 'Unknown error'}`
                    }]
            };
        }
    }
    // Helper methods for analysis and reporting
    identifyStateInconsistencies(snapshots) {
        const inconsistencies = [];
        if (snapshots.length < 2)
            return inconsistencies;
        // Check for framework mismatches
        const frameworks = new Set(snapshots.map(s => s.mockFramework));
        if (frameworks.size > 1) {
            inconsistencies.push({
                type: 'framework-mismatch',
                description: 'Different mock frameworks detected across processes',
                affectedProcesses: snapshots.map(s => s.processId),
                impact: 'Mock behavior may be inconsistent',
                recommendation: 'Standardize on a single mock framework'
            });
        }
        // Check for stub count variations
        const stubCounts = snapshots.map(s => s.state.activeStubs.length);
        const maxStubs = Math.max(...stubCounts);
        const minStubs = Math.min(...stubCounts);
        if (maxStubs - minStubs > maxStubs * 0.5) { // 50% variance
            inconsistencies.push({
                type: 'stub-count-variance',
                description: 'Significant variation in active stub counts between processes',
                affectedProcesses: snapshots.filter(s => s.state.activeStubs.length < maxStubs * 0.8).map(s => s.processId),
                impact: 'Some processes may have incomplete mock coverage',
                recommendation: 'Ensure all processes receive the same mock configuration'
            });
        }
        return inconsistencies;
    }
    analyzeAccessibilityIssues(accessibility) {
        const issues = [];
        if (accessibility.webWorkers && !accessibility.webWorkers.canAccessGlobalMocks) {
            issues.push({
                processType: 'web-workers',
                issue: 'Cannot access global mocks',
                impact: 'Web Worker processes will not have mock coverage',
                solution: 'Implement postMessage-based mock synchronization'
            });
        }
        if (accessibility.serviceWorkers && !accessibility.serviceWorkers.canAccessGlobalMocks) {
            issues.push({
                processType: 'service-workers',
                issue: 'Cannot access global mocks',
                impact: 'Service Worker processes will not have mock coverage',
                solution: 'Use Service Worker message passing for mock state'
            });
        }
        return issues;
    }
    generateFrameworkAnalysis(snapshots) {
        const frameworks = new Map();
        snapshots.forEach(snapshot => {
            frameworks.set(snapshot.mockFramework, (frameworks.get(snapshot.mockFramework) || 0) + 1);
        });
        return Array.from(frameworks.entries())
            .map(([framework, count]) => `- **${framework}**: ${count} snapshots`)
            .join('\n');
    }
    analyzeScopeConfiguration(scope) {
        return {
            summary: `Analyzing ${scope} for mock visibility issues`,
            issues: [
                'Process isolation prevents cross-process mock access',
                'localStorage mocks not accessible to Web Workers',
                'Global scope pollution from multiple mock frameworks'
            ],
            recommendations: [
                'Implement centralized mock registry',
                'Use message passing for cross-process mock synchronization',
                'Consider using SharedArrayBuffer for mock state (where supported)'
            ]
        };
    }
    async validateMockSetup(page) {
        const validation = await page.evaluate(() => {
            const issues = [];
            const recommendations = [];
            let isValid = true;
            // Check for multiple mock frameworks
            const frameworks = [];
            if (typeof jest !== 'undefined')
                frameworks.push('jest');
            if (typeof window.sinon !== 'undefined')
                frameworks.push('sinon');
            if (typeof window.vi !== 'undefined')
                frameworks.push('vitest');
            if (frameworks.length > 1) {
                issues.push({
                    category: 'Multiple Frameworks',
                    description: `Multiple mock frameworks detected: ${frameworks.join(', ')}`,
                    fix: 'Choose one primary mock framework to avoid conflicts'
                });
                isValid = false;
            }
            if (frameworks.length === 0) {
                issues.push({
                    category: 'No Framework',
                    description: 'No mock frameworks detected',
                    fix: 'Install and configure a mock framework (Jest, Sinon, or Vitest)'
                });
                isValid = false;
            }
            // Check global mock pollution
            const globalMockKeys = Object.keys(window).filter(k => k.includes('mock') || k.includes('stub') || k.includes('spy'));
            if (globalMockKeys.length > 20) {
                issues.push({
                    category: 'Global Pollution',
                    description: `${globalMockKeys.length} mock-related globals detected`,
                    fix: 'Use namespaced mock management to reduce global pollution'
                });
            }
            // Generate recommendations
            recommendations.push('Set up mock framework initialization in test setup files');
            recommendations.push('Implement mock cleanup between tests');
            recommendations.push('Use descriptive mock names for better debugging');
            return { isValid, issues, recommendations };
        });
        return validation;
    }
    generateFrameworkSpecificGuidance() {
        return `
**Jest**:
- Use \`setupFilesAfterEnv\` for consistent mock initialization
- Implement \`beforeEach\` mock cleanup in test files
- Use \`jest.requireActual()\` for selective mocking

**Sinon**:
- Create sandbox instances for isolated mock management
- Use \`sinon.restore()\` for proper cleanup
- Implement stub inheritance for cross-process scenarios

**Vitest**:
- Use \`vi.hoisted()\` for setup-time mock initialization
- Implement \`beforeEach\` cleanup with \`vi.clearAllMocks()\`
- Use \`vi.mock()\` with factory functions for consistent mocking`;
    }
    analyzeTimelineTrends(snapshots) {
        if (snapshots.length < 2) {
            return {
                summary: 'Insufficient data for trend analysis',
                globalMocks: { trend: 'stable', change: '0' },
                localStorageMocks: { trend: 'stable', change: '0' },
                sessionStorageMocks: { trend: 'stable', change: '0' },
                stability: 'unknown',
                persistenceScore: 0,
                consistency: 0,
                averageRecoveryTime: 0,
                reliabilityRating: 'unknown'
            };
        }
        const first = snapshots[0];
        const last = snapshots[snapshots.length - 1];
        const globalChange = last.globalMocks - first.globalMocks;
        const localChange = last.localStorageMocks - first.localStorageMocks;
        const sessionChange = last.sessionStorageMocks - first.sessionStorageMocks;
        return {
            summary: `Analyzed ${snapshots.length} snapshots over ${(last.timestamp - first.timestamp) / 1000}s`,
            globalMocks: {
                trend: globalChange > 0 ? 'increasing' : globalChange < 0 ? 'decreasing' : 'stable',
                change: globalChange.toString()
            },
            localStorageMocks: {
                trend: localChange > 0 ? 'increasing' : localChange < 0 ? 'decreasing' : 'stable',
                change: localChange.toString()
            },
            sessionStorageMocks: {
                trend: sessionChange > 0 ? 'increasing' : sessionChange < 0 ? 'decreasing' : 'stable',
                change: sessionChange.toString()
            },
            stability: Math.abs(globalChange) <= 1 ? 'high' : Math.abs(globalChange) <= 3 ? 'medium' : 'low',
            persistenceScore: Math.max(0, 100 - Math.abs(globalChange) * 10),
            consistency: Math.round((1 - (Math.abs(globalChange) + Math.abs(localChange)) / (first.globalMocks + first.localStorageMocks + 1)) * 100),
            averageRecoveryTime: 0, // Would be calculated from actual recovery events
            reliabilityRating: globalChange === 0 ? 'excellent' : Math.abs(globalChange) <= 2 ? 'good' : 'needs-improvement'
        };
    }
    identifyCriticalEvents(alerts, lossPoints) {
        const events = [];
        alerts.forEach(alert => {
            if (alert.severity === 'high') {
                events.push({
                    type: 'High Severity Alert',
                    timestamp: alert.timestamp,
                    impact: 'Significant mock state change detected',
                    details: alert.changes.join(', '),
                    recovery: 'Investigate root cause and implement state recovery'
                });
            }
        });
        lossPoints.forEach(loss => {
            events.push({
                type: 'Mock Loss Point',
                timestamp: loss.timestamp,
                impact: `${loss.lossPercentage}% of mocks became unavailable`,
                details: `${loss.remaining}/${loss.baseline} mocks remaining`,
                recovery: 'Implement mock state backup and restoration'
            });
        });
        return events.sort((a, b) => a.timestamp - b.timestamp);
    }
    determineLossTrigger(loss) {
        const percentage = parseFloat(loss.lossPercentage);
        if (percentage > 80)
            return 'Complete mock framework reload';
        if (percentage > 50)
            return 'Major state reset or navigation';
        if (percentage > 20)
            return 'Partial mock cleanup or scope change';
        return 'Minor mock adjustments';
    }
    analyzeSpecificMockTracking(snapshots, mockName) {
        const mockData = snapshots.map(s => s.specificMocks?.[mockName]);
        const available = mockData.filter(d => d?.exists).length;
        const changes = mockData.filter((d, i) => i > 0 && d?.exists !== mockData[i - 1]?.exists).length;
        return {
            availability: Math.round((available / snapshots.length) * 100),
            changes,
            longestUnavailable: 0, // Would calculate from actual data
            status: available === snapshots.length ? 'stable' : available > snapshots.length * 0.8 ? 'mostly-available' : 'unstable'
        };
    }
    countNavigationEvents(snapshots) {
        return new Set(snapshots.map(s => s.processInfo?.location)).size - 1;
    }
    countConnectionChanges(snapshots) {
        return new Set(snapshots.map(s => s.processInfo?.connectionType)).size - 1;
    }
    countFrameworkReloads(snapshots) {
        // Count changes in jest/sinon availability
        let reloads = 0;
        for (let i = 1; i < snapshots.length; i++) {
            const prev = snapshots[i - 1];
            const curr = snapshots[i];
            if ((prev.jest && !curr.jest) || (!prev.jest && curr.jest) ||
                (prev.sinon && !curr.sinon) || (!prev.sinon && curr.sinon)) {
                reloads++;
            }
        }
        return reloads;
    }
    analyzeProcessCorrelation(snapshots, alerts) {
        return `Mock state changes correlate with navigation events and framework reloads. Consider implementing state persistence across navigation boundaries.`;
    }
    generateTimelineVisualization(snapshots) {
        if (snapshots.length === 0)
            return 'No data available';
        const duration = snapshots.length;
        const visualization = [];
        // Simple ASCII visualization
        visualization.push('Time  Global  Local  Session');
        snapshots.slice(0, 10).forEach((snapshot, i) => {
            const time = `${i * 1000}ms`.padEnd(6);
            const global = `${snapshot.globalMocks}`.padEnd(8);
            const local = `${snapshot.localStorageMocks}`.padEnd(7);
            const session = `${snapshot.sessionStorageMocks}`;
            visualization.push(`${time}${global}${local}${session}`);
        });
        if (snapshots.length > 10) {
            visualization.push(`... (${snapshots.length - 10} more samples)`);
        }
        return visualization.join('\n');
    }
    generateTimelineRecommendations(trendAnalysis, alerts, lossPoints) {
        const recommendations = [];
        if (trendAnalysis.stability === 'low') {
            recommendations.push('**High Priority**: Implement mock state persistence to handle instability');
        }
        if (alerts.length > 0) {
            recommendations.push('**Medium Priority**: Add proactive monitoring for state changes');
        }
        if (lossPoints.length > 0) {
            recommendations.push('**High Priority**: Implement automatic mock state recovery');
        }
        if (trendAnalysis.reliabilityRating === 'needs-improvement') {
            recommendations.push('**Long-term**: Redesign mock architecture for better reliability');
        }
        return recommendations.join('\n');
    }
    generateExecutiveSummary(depth) {
        return `Mock state management analysis reveals ${depth === 'comprehensive' ? 'comprehensive' : 'moderate'} complexity in cross-process mock accessibility. Key findings indicate process isolation challenges and framework consistency issues that impact test reliability.`;
    }
    generateTechnicalFindings(depth) {
        return `
**Process Isolation**: Web Workers and Service Workers cannot access main thread mocks
**Framework Consistency**: Multiple mock frameworks detected with potential conflicts
**State Persistence**: Mock state not preserved across process boundaries
**Accessibility**: ${depth === 'comprehensive' ? 'Comprehensive' : 'Basic'} analysis shows significant cross-process limitations`;
    }
    generateArchitectureRecommendations() {
        return `
1. **Centralized Mock Registry**: Implement global mock state management
2. **Message-Based Synchronization**: Use postMessage for cross-process mock sharing
3. **State Persistence**: Add localStorage/IndexedDB backup for critical mocks
4. **Process-Aware Mocking**: Design mocks specifically for cross-process scenarios`;
    }
    generateImplementationGuide() {
        return `
\`\`\`javascript
// Centralized Mock Registry
class CrossProcessMockRegistry {
  constructor() {
    this.mocks = new Map();
    this.setupMessageHandling();
  }
  
  register(name, mock) {
    this.mocks.set(name, mock);
    this.broadcast('MOCK_REGISTERED', { name, mock });
  }
  
  setupMessageHandling() {
    if (typeof BroadcastChannel !== 'undefined') {
      this.channel = new BroadcastChannel('mock-sync');
      this.channel.onmessage = (event) => {
        if (event.data.type === 'MOCK_REGISTERED') {
          this.mocks.set(event.data.name, event.data.mock);
        }
      };
    }
  }
}
\`\`\``;
    }
    generateBestPractices() {
        return `
1. **Single Framework**: Use one primary mock framework to avoid conflicts
2. **Cleanup Strategy**: Implement consistent mock cleanup between tests
3. **Process-Aware Design**: Design mocks that work across process boundaries
4. **State Monitoring**: Add monitoring for mock state consistency
5. **Recovery Mechanisms**: Implement automatic mock state recovery`;
    }
    generateActionPlan() {
        return `
**Phase 1 (Week 1-2)**: 
- Audit current mock usage and identify critical mocks
- Implement basic cross-process mock registry
- Add mock state monitoring

**Phase 2 (Week 3-4)**:
- Implement message-based mock synchronization
- Add mock state persistence mechanisms
- Create mock recovery procedures

**Phase 3 (Week 5-6)**:
- Optimize mock architecture for performance
- Add comprehensive monitoring and alerting
- Document mock management best practices`;
    }
    generateCompatibilityMatrix() {
        return `
| Framework | Main Thread | Web Worker | Service Worker | Node.js |
|-----------|-------------|------------|----------------|---------|
| Jest      | ✅ Full     | ❌ None    | ❌ None        | ✅ Full |
| Sinon     | ✅ Full     | ⚠️ Limited | ❌ None        | ✅ Full |
| Vitest    | ✅ Full     | ❌ None    | ❌ None        | ✅ Full |`;
    }
    generatePerformanceAnalysis() {
        return `Mock state synchronization adds ~2-5ms overhead per operation. Cross-process mock access can introduce ~10-50ms latency depending on message passing implementation.`;
    }
    generateSecurityConsiderations() {
        return `
- Avoid exposing sensitive data through global mock state
- Implement proper access controls for cross-process mock sharing  
- Consider security implications of SharedArrayBuffer usage
- Validate mock data when receiving from other processes`;
    }
}
//# sourceMappingURL=mock-state-inspector-handler.js.map