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

539 lines (536 loc) • 23.6 kB
/** * TDD Implementation Planner * Generates implementation steps from failing tests and TDD methodology * Based on Cycle 22 user feedback - TDD guidance tools */ export class TDDImplementationPlanner { static instance; static getInstance() { if (!TDDImplementationPlanner.instance) { TDDImplementationPlanner.instance = new TDDImplementationPlanner(); } return TDDImplementationPlanner.instance; } planHistory = new Map(); templateLibrary = new Map(); constructor() { this.initializeTemplateLibrary(); } /** * Initialize common TDD step templates */ initializeTemplateLibrary() { // Dashboard TDD Template (from Cycle 22 success) this.templateLibrary.set('dashboard_implementation', [ { step_number: 1, action: 'Write failing test for family overview section', description: 'Create test that expects family_overview_section widget key', step_type: 'test', code_template: ` testWidgets('should display family overview section', (WidgetTester tester) async { await tester.pumpWidget( ProviderScope( overrides: DashboardTestUtils.getAuthenticatedOverrides(), child: const DashboardPage(), ), ); expect(find.byKey(const Key('family_overview_section')), findsOneWidget); });`, validation_criteria: ['Test fails as expected', 'Clear error message about missing widget'], tools_needed: ['flutter_test'], common_pitfalls: ['Testing too many things at once', 'Not mocking authentication'], success_signals: ['Test compiles and runs', 'Specific widget-not-found error'] }, { step_number: 2, action: 'Implement minimal family overview section', description: 'Add Container with correct key to make test pass', step_type: 'implement', code_template: ` Widget _buildFamilyOverviewSection() { return Container( key: const Key('family_overview_section'), child: const Text('Family Overview'), ); }`, validation_criteria: ['Test passes', 'Widget renders correctly'], tools_needed: ['ai-debug visual validation'], common_pitfalls: ['Over-implementing', 'Adding unnecessary complexity'], success_signals: ['Test turns green', 'Visual confirmation in debug session'] } ]); // Authentication Mocking Template this.templateLibrary.set('authentication_mocking', [ { step_number: 1, action: 'Create comprehensive authentication test utility', description: 'Build reusable authentication mocks based on provider gaps', step_type: 'test', code_template: ` class DashboardTestUtils { static List<Override> getAuthenticatedOverrides() => [ unifiedAuthNotifierProvider.overrideWith((ref) => MockAuthNotifier(authenticated: true)), currentUserProvider.overrideWith((ref) => TestUser.default()), unifiedFamilyMembersProvider.overrideWith((ref) => MockFamilyMembers.default()), primaryHouseholdNameProvider.overrideWith((ref) => "Test Household"), ]; }`, validation_criteria: ['All auth providers mocked', 'No authentication errors in tests'], tools_needed: ['provider_gap_analyzer'], common_pitfalls: ['Missing critical providers', 'Inconsistent mock data'], success_signals: ['Tests show authenticated state', 'No auth-related failures'] } ]); // Widget Testing Template this.templateLibrary.set('widget_testing', [ { step_number: 1, action: 'Test widget rendering with proper keys', description: 'Verify all expected widgets render with correct test keys', step_type: 'test', code_template: ` testWidgets('should render all family member cards', (WidgetTester tester) async { final mockMembers = [ TestMember(id: '1', name: 'Alice'), TestMember(id: '2', name: 'Bob'), ]; await tester.pumpWidget( ProviderScope( overrides: [ ...DashboardTestUtils.getAuthenticatedOverrides(), unifiedFamilyMembersProvider.overrideWith((ref) => mockMembers), ], child: const DashboardPage(), ), ); expect(find.byKey(const Key('family_member_status_card_1')), findsOneWidget); expect(find.byKey(const Key('family_member_status_card_2')), findsOneWidget); });`, validation_criteria: ['All expected widgets found', 'Pattern matching works correctly'], tools_needed: ['test_expectation_tracker'], common_pitfalls: ['Hard-coding test data', 'Not testing edge cases'], success_signals: ['All widget keys found', 'Correct number of elements'] } ]); } /** * Generate TDD implementation plan from context */ async generateImplementationPlan(context) { const planId = `tdd_plan_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`; const plan = { planId, title: `TDD Implementation Plan - ${this.generatePlanTitle(context)}`, description: this.generatePlanDescription(context), methodology: this.selectMethodology(context), phases: await this.generatePhases(context), overallProgress: 0, estimatedTimeMinutes: 0, quality_gates: this.generateQualityGates(context), success_criteria: this.generateSuccessCriteria(context) }; // Calculate total time estimate plan.estimatedTimeMinutes = plan.phases.reduce((total, phase) => total + phase.duration_estimate_minutes, 0); // Store plan this.planHistory.set(planId, plan); return plan; } /** * Generate plan title based on context */ generatePlanTitle(context) { if (context.authentication_required) { return 'Authenticated Dashboard Components'; } if (context.ui_components_needed.length > 3) { return 'Complex UI Component System'; } return 'Widget Implementation'; } /** * Generate plan description */ generatePlanDescription(context) { const components = context.ui_components_needed.join(', '); const tests = context.failing_tests.length; return `Implement ${components} using TDD methodology. Address ${tests} failing test(s) with proper authentication mocking and widget rendering. Focus on making tests pass through minimal, correct implementation.`; } /** * Select appropriate TDD methodology */ selectMethodology(context) { if (context.failing_tests.length > 0) { return 'red_green_refactor'; // We already have failing tests } if (context.authentication_required) { return 'behavior_driven'; // Complex authentication scenarios } if (context.complexity_level === 'complex') { return 'acceptance_driven'; // High-level requirements } return 'test_first'; // Standard TDD approach } /** * Generate TDD phases */ async generatePhases(context) { const phases = []; if (context.methodology === 'red_green_refactor') { // Red Phase: Ensure tests fail correctly phases.push({ name: 'Red Phase - Validate Failing Tests', description: 'Ensure tests fail for the right reasons and provide clear feedback', phase_type: 'red', steps: await this.generateRedPhaseSteps(context), duration_estimate_minutes: 15, prerequisites: ['Test environment setup', 'Authentication mocks prepared'], success_indicators: ['Tests fail with clear widget-not-found errors', 'No infrastructure issues'] }); // Green Phase: Minimal implementation phases.push({ name: 'Green Phase - Minimal Implementation', description: 'Implement just enough to make tests pass', phase_type: 'green', steps: await this.generateGreenPhaseSteps(context), duration_estimate_minutes: 30, prerequisites: ['Red phase completed', 'Implementation targets identified'], success_indicators: ['All tests pass', 'Visual confirmation in debug session'] }); // Refactor Phase: Improve implementation phases.push({ name: 'Refactor Phase - Enhance Implementation', description: 'Improve implementation while maintaining test coverage', phase_type: 'refactor', steps: await this.generateRefactorPhaseSteps(context), duration_estimate_minutes: 20, prerequisites: ['Green phase completed', 'All tests passing'], success_indicators: ['Code quality improved', 'Tests still pass', 'Performance acceptable'] }); } // Validation Phase (always included) phases.push({ name: 'Validation Phase - Comprehensive Testing', description: 'Validate complete implementation with edge cases', phase_type: 'validation', steps: await this.generateValidationPhaseSteps(context), duration_estimate_minutes: 25, prerequisites: ['Implementation completed', 'Core tests passing'], success_indicators: ['All edge cases covered', 'Performance meets targets', 'No regressions'] }); return phases; } /** * Generate Red Phase steps */ async generateRedPhaseSteps(context) { const steps = [ { step_number: 1, action: 'Run existing failing tests', description: 'Execute tests to confirm they fail for the right reasons', step_type: 'test', validation_criteria: ['Tests fail with widget-not-found errors', 'No authentication errors'], tools_needed: ['flutter_test', 'ai-debug session'], common_pitfalls: ['Tests fail due to infrastructure issues', 'Authentication not mocked properly'], success_signals: ['Clear error messages about missing widgets', 'Authentication state correct'] }, { step_number: 2, action: 'Visual validation of current state', description: 'Use ai-debug to see actual UI state vs test expectations', step_type: 'debug', validation_criteria: ['Screenshot shows login screen or empty state', 'Missing widgets clearly identified'], tools_needed: ['ai-debug take_screenshot', 'test_expectation_tracker'], common_pitfalls: ['Not checking actual UI state', 'Assuming tests are wrong'], success_signals: ['Clear visual confirmation of missing components', 'Understanding of implementation gap'] } ]; // Add authentication validation if needed if (context.authentication_required) { steps.push({ step_number: 3, action: 'Validate authentication mocks', description: 'Ensure all required auth providers are properly mocked', step_type: 'validate', validation_criteria: ['No auth-related test failures', 'Authenticated state visible in debug'], tools_needed: ['provider_gap_analyzer', 'ai-debug monitor_realtime'], common_pitfalls: ['Missing critical auth providers', 'Inconsistent mock data'], success_signals: ['Dashboard shows authenticated content', 'No authentication errors'] }); } return steps; } /** * Generate Green Phase steps */ async generateGreenPhaseSteps(context) { const steps = []; // Generate implementation steps for each UI component context.ui_components_needed.forEach((component, index) => { steps.push({ step_number: index + 1, action: `Implement ${component}`, description: `Add minimal ${component} implementation with correct test key`, step_type: 'implement', code_template: this.generateComponentCodeTemplate(component), validation_criteria: [`Test for ${component} passes`, 'Widget renders correctly'], tools_needed: ['ai-debug visual validation', 'test runner'], common_pitfalls: ['Over-implementing features', 'Missing test keys', 'Complex logic in minimal implementation'], success_signals: [`${component} test turns green`, 'Visual confirmation in debug session'] }); }); // Add integration step steps.push({ step_number: steps.length + 1, action: 'Integrate all components', description: 'Ensure all components work together correctly', step_type: 'validate', validation_criteria: ['All individual tests pass', 'Integration test passes', 'No visual regressions'], tools_needed: ['ai-debug comprehensive validation', 'test_expectation_tracker'], common_pitfalls: ['Components conflict with each other', 'Layout issues', 'State management problems'], success_signals: ['All tests green', 'Visual confirmation of complete dashboard', 'No console errors'] }); return steps; } /** * Generate Refactor Phase steps */ async generateRefactorPhaseSteps(context) { return [ { step_number: 1, action: 'Extract reusable components', description: 'Identify and extract common UI patterns', step_type: 'refactor', validation_criteria: ['Code duplication reduced', 'Tests still pass', 'Components reusable'], tools_needed: ['static analysis', 'test runner'], common_pitfalls: ['Over-abstracting too early', 'Breaking existing tests', 'Performance degradation'], success_signals: ['Cleaner code structure', 'Maintained test coverage', 'Improved maintainability'] }, { step_number: 2, action: 'Optimize performance', description: 'Improve rendering performance while maintaining functionality', step_type: 'refactor', validation_criteria: ['Performance metrics improved', 'Tests still pass', 'No visual regressions'], tools_needed: ['ai-debug performance monitoring', 'Flutter DevTools'], common_pitfalls: ['Premature optimization', 'Breaking functionality', 'Complex performance code'], success_signals: ['Faster rendering times', 'Maintained user experience', 'Clean performance code'] } ]; } /** * Generate Validation Phase steps */ async generateValidationPhaseSteps(context) { return [ { step_number: 1, action: 'Comprehensive test validation', description: 'Run all tests and validate complete functionality', step_type: 'validate', validation_criteria: ['All tests pass', 'No test flakiness', 'Edge cases covered'], tools_needed: ['test runner', 'test_expectation_tracker'], common_pitfalls: ['Ignoring edge cases', 'Flaky tests', 'Incomplete test coverage'], success_signals: ['100% test pass rate', 'Reliable test execution', 'Comprehensive coverage'] }, { step_number: 2, action: 'Visual regression testing', description: 'Ensure UI appears correctly across different scenarios', step_type: 'validate', validation_criteria: ['Visual consistency maintained', 'No UI regressions', 'Responsive design works'], tools_needed: ['ai-debug visual comparison', 'screenshot testing'], common_pitfalls: ['Not testing different screen sizes', 'Ignoring accessibility', 'Missing error states'], success_signals: ['Consistent visual appearance', 'Good accessibility scores', 'Proper error handling'] }, { step_number: 3, action: 'Integration validation', description: 'Validate complete user workflows work end-to-end', step_type: 'validate', validation_criteria: ['User workflows complete successfully', 'No integration issues', 'Performance acceptable'], tools_needed: ['ai-debug user flow testing', 'integration tests'], common_pitfalls: ['Not testing real user scenarios', 'Missing integration points', 'Performance issues'], success_signals: ['Complete user workflows work', 'Good integration health', 'Acceptable performance'] } ]; } /** * Generate component code template */ generateComponentCodeTemplate(component) { const templates = { 'family_overview_section': ` Widget _buildFamilyOverviewSection() { return Container( key: const Key('family_overview_section'), padding: const EdgeInsets.all(16), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Text('Family Overview', style: Theme.of(context).textTheme.headlineSmall), const SizedBox(height: 16), // Add family member cards here ], ), ); }`, 'family_member_status_cards': ` Widget _buildFamilyMemberCards() { return Consumer( builder: (context, ref, child) { final familyMembers = ref.watch(unifiedFamilyMembersProvider); return ListView.builder( shrinkWrap: true, physics: const NeverScrollableScrollPhysics(), itemCount: familyMembers.length, itemBuilder: (context, index) { final member = familyMembers[index]; return Card( key: Key('family_member_status_card_\${member.id}'), child: ListTile( title: Text(member.name), subtitle: Text('Status: \${member.status}'), ), ); }, ); }, ); }`, 'quick_actions': ` Widget _buildQuickActions() { return Row( mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: [ ElevatedButton( key: const Key('add_family_event_quick_action'), onPressed: () => _addFamilyEvent(), child: const Text('Add Event'), ), ElevatedButton( key: const Key('add_family_chore_quick_action'), onPressed: () => _addFamilyChore(), child: const Text('Add Chore'), ), ], ); }` }; return templates[component] || ` Widget _build${component.split('_').map(word => word[0].toUpperCase() + word.slice(1)).join('')}() { return Container( key: const Key('${component}'), child: const Text('${component}'), ); }`; } /** * Generate quality gates */ generateQualityGates(context) { return [ { name: 'Test Coverage', criteria: ['All UI components have tests', 'Edge cases covered', 'No test flakiness'], automated_checks: ['Test pass rate > 95%', 'Code coverage > 80%'], manual_validations: ['Visual confirmation of all components', 'User workflow testing'], blocking: true }, { name: 'Authentication Integration', criteria: ['All auth providers mocked correctly', 'No auth-related errors', 'Authenticated state works'], automated_checks: ['Provider gap analysis passes', 'No authentication test failures'], manual_validations: ['Visual confirmation of authenticated dashboard', 'Manual login flow testing'], blocking: context.authentication_required }, { name: 'Performance', criteria: ['Rendering time < 2s', 'No memory leaks', 'Smooth interactions'], automated_checks: ['Performance benchmarks pass', 'Memory usage within limits'], manual_validations: ['Manual performance testing', 'Real device testing'], blocking: false } ]; } /** * Generate success criteria */ generateSuccessCriteria(context) { const criteria = [ 'All tests pass consistently', 'Visual confirmation of all UI components', 'No authentication-related errors', 'User workflows complete successfully' ]; if (context.complexity_level === 'complex') { criteria.push('Performance meets targets'); criteria.push('Integration points work correctly'); } if (context.authentication_required) { criteria.push('Dashboard shows authenticated content'); criteria.push('All auth providers properly mocked'); } return criteria; } /** * Get plan by ID */ getPlan(planId) { return this.planHistory.get(planId); } /** * Update plan progress */ updatePlanProgress(planId, phaseIndex, stepIndex) { const plan = this.planHistory.get(planId); if (!plan) return; const totalSteps = plan.phases.reduce((total, phase) => total + phase.steps.length, 0); const completedSteps = plan.phases.slice(0, phaseIndex).reduce((total, phase) => total + phase.steps.length, 0) + stepIndex + 1; plan.overallProgress = Math.round((completedSteps / totalSteps) * 100); } /** * Generate architecture guidance */ generateArchitectureGuidance(context) { return { component_separation: [ 'Separate UI components from business logic', 'Use composition over inheritance', 'Keep widgets focused on single responsibility' ], provider_structure: [ 'Group related providers together', 'Use provider dependencies correctly', 'Mock all external dependencies in tests' ], test_organization: [ 'One test file per widget/component', 'Group tests by functionality', 'Use descriptive test names' ], mocking_strategy: [ 'Mock all external dependencies', 'Use consistent mock data across tests', 'Create reusable test utilities' ], integration_points: [ 'Test authentication flow end-to-end', 'Validate provider interactions', 'Test error handling scenarios' ] }; } /** * Clear plan history (for testing) */ clearHistory() { this.planHistory.clear(); } } //# sourceMappingURL=tdd-implementation-planner.js.map