mcp-adr-analysis-server 2.0.1 → 2.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/src/index.js CHANGED
@@ -193,7 +193,7 @@ export class McpAdrAnalysisServer {
193
193
  },
194
194
  {
195
195
  name: 'generate_adr_todo',
196
- description: 'Generate or update todo.md from existing ADRs',
196
+ description: 'Generate TDD-focused todo.md from existing ADRs with two-phase approach: test generation and production code',
197
197
  inputSchema: {
198
198
  type: 'object',
199
199
  properties: {
@@ -206,6 +206,83 @@ export class McpAdrAnalysisServer {
206
206
  enum: ['all', 'pending', 'in_progress'],
207
207
  description: 'Scope of tasks to include',
208
208
  default: 'all'
209
+ },
210
+ phase: {
211
+ type: 'string',
212
+ enum: ['both', 'test', 'production'],
213
+ description: 'TDD phase: both (default), test (mock test generation), production (implementation after tests)',
214
+ default: 'both'
215
+ },
216
+ linkAdrs: {
217
+ type: 'boolean',
218
+ description: 'Link all ADRs to create comprehensive system test coverage',
219
+ default: true
220
+ },
221
+ includeRules: {
222
+ type: 'boolean',
223
+ description: 'Include architectural rules validation in TDD tasks',
224
+ default: true
225
+ },
226
+ ruleSource: {
227
+ type: 'string',
228
+ enum: ['adrs', 'patterns', 'both'],
229
+ description: 'Source for architectural rules (only used if includeRules is true)',
230
+ default: 'both'
231
+ }
232
+ }
233
+ }
234
+ },
235
+ {
236
+ name: 'compare_adr_progress',
237
+ description: 'Compare TODO.md progress against ADRs and current environment to validate implementation status',
238
+ inputSchema: {
239
+ type: 'object',
240
+ properties: {
241
+ todoPath: {
242
+ type: 'string',
243
+ description: 'Path to TODO.md file to analyze',
244
+ default: 'TODO.md'
245
+ },
246
+ adrDirectory: {
247
+ type: 'string',
248
+ description: 'Directory containing ADR files',
249
+ default: 'docs/adrs'
250
+ },
251
+ projectPath: {
252
+ type: 'string',
253
+ description: 'Path to project root for environment analysis',
254
+ default: '.'
255
+ },
256
+ validationType: {
257
+ type: 'string',
258
+ enum: ['full', 'todo-only', 'adr-only', 'environment-only'],
259
+ description: 'Type of validation to perform',
260
+ default: 'full'
261
+ },
262
+ includeFileChecks: {
263
+ type: 'boolean',
264
+ description: 'Include file existence and implementation checks',
265
+ default: true
266
+ },
267
+ includeRuleValidation: {
268
+ type: 'boolean',
269
+ description: 'Include architectural rule compliance validation',
270
+ default: true
271
+ },
272
+ deepCodeAnalysis: {
273
+ type: 'boolean',
274
+ description: 'Perform deep code analysis to distinguish mock from production implementations',
275
+ default: true
276
+ },
277
+ functionalValidation: {
278
+ type: 'boolean',
279
+ description: 'Validate that code actually functions according to ADR goals, not just exists',
280
+ default: true
281
+ },
282
+ strictMode: {
283
+ type: 'boolean',
284
+ description: 'Enable strict validation mode with reality-check mechanisms against overconfident assessments',
285
+ default: true
209
286
  }
210
287
  }
211
288
  }
@@ -1083,6 +1160,9 @@ export class McpAdrAnalysisServer {
1083
1160
  case 'generate_adr_todo':
1084
1161
  response = await this.generateAdrTodo(args);
1085
1162
  break;
1163
+ case 'compare_adr_progress':
1164
+ response = await this.compareAdrProgress(args);
1165
+ break;
1086
1166
  case 'analyze_content_security':
1087
1167
  response = await this.analyzeContentSecurity(args);
1088
1168
  break;
@@ -2544,7 +2624,7 @@ The enhanced process maintains full traceability from PRD requirements to genera
2544
2624
  }
2545
2625
  }
2546
2626
  async generateAdrTodo(args) {
2547
- const { scope = 'all' } = args;
2627
+ const { scope = 'all', phase = 'both', linkAdrs = true, includeRules = true, ruleSource = 'both' } = args;
2548
2628
  const { getAdrDirectoryPath } = await import('./utils/config.js');
2549
2629
  const path = await import('path');
2550
2630
  // Use absolute ADR path relative to project
@@ -2553,120 +2633,280 @@ The enhanced process maintains full traceability from PRD requirements to genera
2553
2633
  getAdrDirectoryPath(this.config);
2554
2634
  // Keep relative path for display purposes
2555
2635
  const adrDirectory = args.adrDirectory || this.config.adrDirectory;
2556
- this.logger.info(`Generating todo prompt for ADRs in: ${absoluteAdrPath}`);
2636
+ this.logger.info(`Generating TDD-focused todo for ADRs in: ${absoluteAdrPath} (phase: ${phase})`);
2557
2637
  try {
2558
2638
  const { findFiles } = await import('./utils/file-system.js');
2559
2639
  // Generate file discovery prompt for ADR files using project path as base
2560
2640
  const adrFilesPrompt = await findFiles(this.config.projectPath, [`${absoluteAdrPath}/**/*.md`], { includeContent: true });
2561
- // Generate comprehensive todo creation prompt
2641
+ // For ADR linking, also discover all project structure
2642
+ let projectStructurePrompt = '';
2643
+ if (linkAdrs) {
2644
+ const projectFiles = await findFiles(this.config.projectPath, [
2645
+ '**/*.{ts,js,py,java,cs,go,rb,php,swift,kt,rs,cpp,c,h}',
2646
+ '!node_modules/**',
2647
+ '!dist/**',
2648
+ '!build/**',
2649
+ '!.git/**'
2650
+ ], {
2651
+ includeContent: false
2652
+ });
2653
+ projectStructurePrompt = `
2654
+ ## Project Structure (for ADR linking)
2655
+ ${projectFiles.prompt}
2656
+ `;
2657
+ }
2658
+ // For rules integration, extract architectural rules from ADRs
2659
+ let rulesPrompt = '';
2660
+ if (includeRules) {
2661
+ try {
2662
+ const rulesResult = await this.generateRules({
2663
+ source: ruleSource,
2664
+ adrDirectory: adrDirectory,
2665
+ projectPath: this.config.projectPath,
2666
+ outputFormat: 'json'
2667
+ });
2668
+ if (rulesResult.content) {
2669
+ rulesPrompt = `
2670
+ ## Architectural Rules (for compliance validation)
2671
+ The following architectural rules have been extracted from ADRs and should be validated in tests:
2672
+
2673
+ ${Array.isArray(rulesResult.content) ? rulesResult.content.map((c) => c.text || c).join('\n') : rulesResult.content}
2674
+ `;
2675
+ }
2676
+ }
2677
+ catch (error) {
2678
+ this.logger.warn(`Failed to extract rules: ${error instanceof Error ? error.message : String(error)}`);
2679
+ rulesPrompt = `
2680
+ ## Architectural Rules (failed to extract)
2681
+ Note: Could not extract architectural rules automatically. Manual rule validation may be needed.
2682
+ `;
2683
+ }
2684
+ }
2685
+ // Generate TDD-focused todo creation prompt
2562
2686
  const todoPrompt = `
2563
- # ADR Todo Generation Request
2687
+ # TDD-Focused ADR Todo Generation Request
2564
2688
 
2565
2689
  ## Step 1: File Discovery
2566
2690
  ${adrFilesPrompt.prompt}
2691
+ ${projectStructurePrompt}
2692
+ ${rulesPrompt}
2693
+
2694
+ ## Step 2: TDD Todo Generation Analysis
2567
2695
 
2568
- ## Step 2: Todo Generation Analysis
2696
+ Once you have discovered and read the ADR files, please analyze them and generate a comprehensive TDD-focused todo.md file.
2569
2697
 
2570
- Once you have discovered and read the ADR files, please analyze them and generate a comprehensive todo.md file.
2698
+ ## TDD Phase: ${phase}
2699
+ ${phase === 'test' ? '**Focus on Phase 1: Mock Test Generation Only**' : ''}
2700
+ ${phase === 'production' ? '**Focus on Phase 2: Production Code Implementation (assumes tests exist)**' : ''}
2701
+ ${phase === 'both' ? '**Generate both Phase 1 (Tests) and Phase 2 (Production) tasks**' : ''}
2571
2702
 
2572
2703
  ## Requirements
2573
2704
 
2574
2705
  1. **Extract Tasks**: Identify all implementation tasks from ADRs
2575
- 2. **Categorize**: Group tasks by ADR and priority
2576
- 3. **Status Detection**: Determine task completion status based on:
2577
- - File existence checks
2578
- - Code analysis hints
2579
- - Implementation evidence
2580
- 4. **Progress Tracking**: Calculate overall progress
2581
- 5. **Scope Filter**: ${scope === 'all' ? 'Include all tasks' : `Focus on ${scope} tasks only`}
2582
-
2583
- ## Todo.md Format
2706
+ 2. **TDD Approach**: For each task, create:
2707
+ - Phase 1: Mock test specifications
2708
+ - Phase 2: Production implementation tasks
2709
+ 3. **ADR Linking**: ${linkAdrs ? 'Link related ADRs to create comprehensive system tests' : 'Focus on individual ADR tasks'}
2710
+ 4. **Rules Integration**: ${includeRules ? `Include architectural rules validation in tests (source: ${ruleSource})` : 'Skip architectural rules validation'}
2711
+ 5. **Categorize**: Group tasks by ADR and testing phase
2712
+ 6. **Status Detection**: Determine task completion status
2713
+ 7. **Progress Tracking**: Calculate overall progress for both test and implementation phases
2714
+ 8. **Scope Filter**: ${scope === 'all' ? 'Include all tasks' : `Focus on ${scope} tasks only`}
2715
+
2716
+ ## TDD Todo.md Format
2584
2717
 
2585
2718
  \`\`\`markdown
2586
- # ADR Implementation Progress
2719
+ # TDD-Focused ADR Implementation Progress
2587
2720
 
2588
2721
  **Last Updated**: [Date]
2589
2722
  **Overall Progress**: [X]% Complete
2723
+ **Test Coverage**: [X]% Complete
2724
+ **Implementation Coverage**: [X]% Complete
2590
2725
 
2591
2726
  ## Summary
2592
2727
  - Total ADRs: [count]
2593
- - Total Tasks: [count]
2728
+ - Total Tasks: [count] (Tests: [count], Implementation: [count])
2594
2729
  - Completed: [count]
2595
2730
  - In Progress: [count]
2596
2731
  - Pending: [count]
2597
2732
 
2598
- ## Tasks by ADR
2733
+ ## System Architecture Overview (from linked ADRs)
2734
+ [Brief summary of how all ADRs connect to form the complete system]
2735
+
2736
+ ## Phase 1: Test Generation Tasks
2737
+
2738
+ ### ADR-001: [Title]
2739
+ #### Test Specifications
2740
+ - [ ] TEST: Unit test for [component/function]
2741
+ - Mock: [what to mock]
2742
+ - Expected: [expected behavior]
2743
+ - Coverage: [what this tests]
2744
+ - [ ] TEST: Integration test for [feature]
2745
+ - Setup: [test environment]
2746
+ - Scenario: [test scenario]
2747
+ - Assertions: [what to verify]
2748
+ ${includeRules ? `- [ ] RULE: Architectural rule validation test for [rule name]
2749
+ - Validation: [what rule to check]
2750
+ - Pattern: [validation pattern/regex]
2751
+ - Expected: [compliant behavior]` : ''}
2752
+
2753
+ ### ADR-002: [Title]
2754
+ #### Test Specifications
2755
+ - [ ] TEST: [test description]
2756
+ ${includeRules ? '- [ ] RULE: [rule validation test]' : ''}
2757
+ ...
2758
+
2759
+ ## Phase 2: Production Implementation Tasks
2599
2760
 
2600
2761
  ### ADR-001: [Title]
2601
- - [ ] Task 1 description
2602
- - [x] Task 2 description (completed)
2603
- - [/] Task 3 description (in progress)
2762
+ #### Implementation Tasks (after tests pass)
2763
+ - [ ] IMPL: Implement [component/function]
2764
+ - Precondition: Unit test for [component] exists
2765
+ - Definition: [what to implement]
2766
+ - Acceptance: All related tests pass
2767
+ ${includeRules ? ` - Compliance: Must pass architectural rule validation` : ''}
2768
+ - [ ] IMPL: [implementation task]
2604
2769
 
2605
2770
  ### ADR-002: [Title]
2606
- - [ ] Task 1 description
2771
+ #### Implementation Tasks
2772
+ - [ ] IMPL: [implementation description]
2773
+ ${includeRules ? ' - Compliance: [specific rule requirements]' : ''}
2607
2774
  ...
2775
+
2776
+ ## ADR Dependencies and Links
2777
+ - ADR-001 → ADR-002: [relationship description]
2778
+ - ADR-002 → ADR-003: [relationship description]
2779
+
2780
+ ## Test-First Development Workflow
2781
+ 1. Complete all Phase 1 tests for a component
2782
+ ${includeRules ? '2. Complete architectural rule validation tests' : ''}
2783
+ ${includeRules ? '3' : '2'}. Run tests (they should fail)
2784
+ ${includeRules ? '4' : '3'}. Implement Phase 2 production code
2785
+ ${includeRules ? '5' : '4'}. Run tests (they should pass)
2786
+ ${includeRules ? '6. Validate architectural rule compliance' : ''}
2787
+ ${includeRules ? '7' : '5'}. Refactor if needed while maintaining rule compliance
2608
2788
  \`\`\`
2609
2789
 
2610
2790
  Please provide:
2611
2791
  1. Comprehensive task extraction from all ADRs
2612
- 2. Status assessment for each task
2613
- 3. Progress calculation
2614
- 4. Prioritized task list
2615
- 5. Implementation recommendations
2792
+ 2. Test specifications for each implementation task
2793
+ ${includeRules ? '3. Architectural rule validation tests and compliance checks' : ''}
2794
+ ${includeRules ? '4' : '3'}. Clear separation of test and implementation phases
2795
+ ${includeRules ? '5' : '4'}. ADR relationship mapping for system-wide test coverage
2796
+ ${includeRules ? '6' : '5'}. TDD workflow recommendations with rule compliance integration
2616
2797
  `;
2617
2798
  // Execute the todo generation with AI if enabled, otherwise return prompt
2618
2799
  const { executePromptWithFallback, formatMCPResponse } = await import('./utils/prompt-execution.js');
2619
- const executionResult = await executePromptWithFallback(todoPrompt, 'Generate comprehensive todo.md file from ADR analysis with task extraction and progress tracking', {
2800
+ const executionResult = await executePromptWithFallback(todoPrompt, 'Generate TDD-focused todo.md file from ADR analysis with test-first approach and system-wide coverage', {
2620
2801
  temperature: 0.1,
2621
- maxTokens: 6000,
2622
- systemPrompt: `You are an expert project manager specializing in ADR implementation tracking.
2623
- Analyze the provided ADRs to extract actionable tasks and create a comprehensive todo.md file.
2624
- Focus on identifying concrete implementation steps, tracking progress, and providing clear priorities.
2625
- Ensure the todo.md file follows the specified format and includes all necessary details.`,
2802
+ maxTokens: 8000,
2803
+ systemPrompt: `You are an expert in Test-Driven Development (TDD) and architectural implementation.
2804
+ Analyze the provided ADRs to extract actionable tasks following a strict TDD approach.
2805
+
2806
+ Key responsibilities:
2807
+ 1. For each implementation task, FIRST define the test specifications
2808
+ 2. Create mock test descriptions that verify the expected behavior
2809
+ 3. Link related ADRs to ensure comprehensive system test coverage
2810
+ 4. Separate test generation (Phase 1) from production code (Phase 2)
2811
+ 5. Ensure every production task has corresponding test coverage
2812
+ 6. Map ADR dependencies to identify integration test requirements
2813
+ ${includeRules ? '7. Include architectural rule validation in test specifications' : ''}
2814
+ ${includeRules ? '8. Create compliance checks for extracted architectural rules' : ''}
2815
+ ${includeRules ? '9. Ensure implementation tasks include rule compliance verification' : ''}
2816
+
2817
+ Follow the TDD red-green-refactor cycle:
2818
+ - Red: Write failing tests first (Phase 1)${includeRules ? ' including rule validation tests' : ''}
2819
+ - Green: Implement minimal code to pass tests (Phase 2)
2820
+ - Refactor: Improve code while keeping tests green${includeRules ? ' and maintaining rule compliance' : ''}
2821
+
2822
+ ${includeRules ? 'The architectural rules provide constraints and patterns that must be validated in tests and followed in implementation.' : ''}
2823
+
2824
+ The todo.md should serve as the glue connecting all ADRs into a cohesive, testable${includeRules ? ', rule-compliant' : ''} system.`,
2626
2825
  responseFormat: 'text'
2627
2826
  });
2628
2827
  if (executionResult.isAIGenerated) {
2629
2828
  // AI execution successful - return actual todo generation results
2630
2829
  return formatMCPResponse({
2631
2830
  ...executionResult,
2632
- content: `# ADR Todo Generation Results
2831
+ content: `# TDD-Focused ADR Todo Generation Results
2633
2832
 
2634
2833
  ## Analysis Information
2635
2834
  - **ADR Directory**: ${adrDirectory}
2636
2835
  - **Scope**: ${scope}
2836
+ - **TDD Phase**: ${phase}
2837
+ - **ADR Linking**: ${linkAdrs ? 'Enabled' : 'Disabled'}
2838
+ - **Rules Integration**: ${includeRules ? `Enabled (${ruleSource})` : 'Disabled'}
2637
2839
 
2638
- ## AI Todo Generation Results
2840
+ ## AI-Generated TDD Todo Results
2639
2841
 
2640
2842
  ${executionResult.content}
2641
2843
 
2642
- ## Next Steps
2844
+ ## TDD Implementation Workflow
2643
2845
 
2644
- Based on the generated todo list:
2846
+ ### Phase 1: Test Generation (Red Phase)
2847
+ 1. **Review Test Specifications**: Examine each test task for completeness
2848
+ 2. **Create Mock Tests**: Implement test files with proper mocking
2849
+ 3. **Define Assertions**: Ensure tests verify expected behavior
2850
+ 4. **Run Tests**: Confirm all tests fail (red phase)
2645
2851
 
2646
- 1. **Review Generated Tasks**: Examine each task for accuracy and completeness
2647
- 2. **Prioritize Implementation**: Order tasks by importance and dependencies
2648
- 3. **Assign Responsibilities**: Determine who will work on each task
2649
- 4. **Track Progress**: Use the todo.md file to monitor implementation progress
2650
- 5. **Update Regularly**: Keep the todo list current as work progresses
2852
+ ### Phase 2: Production Implementation (Green Phase)
2853
+ 1. **Implement Minimal Code**: Write just enough code to pass tests
2854
+ 2. **Run Tests Again**: Verify tests now pass (green phase)
2855
+ 3. **Check Coverage**: Ensure all ADR requirements are tested
2856
+ 4. **Integration Testing**: Verify ADR interactions work correctly
2651
2857
 
2652
- ## Todo Management
2858
+ ### Phase 3: Refactoring (Refactor Phase)
2859
+ 1. **Improve Code Quality**: Refactor while keeping tests green
2860
+ 2. **Update Documentation**: Keep ADRs and tests in sync
2861
+ 3. **Performance Optimization**: Optimize without breaking tests
2653
2862
 
2654
- The generated todo.md file includes:
2655
- - **Overall Progress**: Percentage completion tracking
2656
- - **Task Categories**: Tasks organized by ADR
2657
- - **Status Indicators**: Clear progress markers ([ ], [x], [/])
2658
- - **Priority Levels**: High, medium, low priority assignments
2659
- - **Implementation Guidance**: Specific steps for each task
2863
+ ## ADR System Integration
2864
+
2865
+ The todo.md serves as the glue connecting all ADRs by:
2866
+ - **Mapping Dependencies**: Shows how ADRs relate to each other
2867
+ - **System-wide Coverage**: Ensures no gaps in test coverage
2868
+ - **Progress Tracking**: Monitors both test and implementation completion
2869
+ - **Working Environment**: Defines the expected system outcome
2660
2870
 
2661
2871
  ## Integration Commands
2662
2872
 
2663
- To update the todo list as work progresses:
2873
+ ### Generate Test Phase Only:
2874
+ \`\`\`json
2875
+ {
2876
+ "tool": "generate_adr_todo",
2877
+ "args": {
2878
+ "adrDirectory": "${adrDirectory}",
2879
+ "phase": "test",
2880
+ "linkAdrs": true,
2881
+ "includeRules": true,
2882
+ "ruleSource": "both"
2883
+ }
2884
+ }
2885
+ \`\`\`
2886
+
2887
+ ### Generate Production Phase Only:
2888
+ \`\`\`json
2889
+ {
2890
+ "tool": "generate_adr_todo",
2891
+ "args": {
2892
+ "adrDirectory": "${adrDirectory}",
2893
+ "phase": "production",
2894
+ "scope": "pending",
2895
+ "includeRules": true
2896
+ }
2897
+ }
2898
+ \`\`\`
2899
+
2900
+ ### Update Full TDD Todo with Rules:
2664
2901
  \`\`\`json
2665
2902
  {
2666
2903
  "tool": "generate_adr_todo",
2667
2904
  "args": {
2668
2905
  "adrDirectory": "${adrDirectory}",
2669
- "scope": "pending"
2906
+ "phase": "both",
2907
+ "linkAdrs": true,
2908
+ "includeRules": true,
2909
+ "ruleSource": "both"
2670
2910
  }
2671
2911
  }
2672
2912
  \`\`\`
@@ -2679,7 +2919,7 @@ To update the todo list as work progresses:
2679
2919
  content: [
2680
2920
  {
2681
2921
  type: 'text',
2682
- text: `ADR todo generation for: ${adrDirectory}\n\nPlease generate todo.md using the following prompt:\n\n${todoPrompt}`
2922
+ text: `TDD-focused ADR todo generation for: ${adrDirectory}\n\nPhase: ${phase}\nADR Linking: ${linkAdrs ? 'Enabled' : 'Disabled'}\nRules Integration: ${includeRules ? `Enabled (${ruleSource})` : 'Disabled'}\nScope: ${scope}\n\nPlease generate a TDD-focused todo.md using the following prompt:\n\n${todoPrompt}`
2683
2923
  }
2684
2924
  ]
2685
2925
  };
@@ -2689,6 +2929,388 @@ To update the todo list as work progresses:
2689
2929
  throw new McpAdrError(`Failed to generate ADR todo: ${error instanceof Error ? error.message : String(error)}`, 'GENERATION_ERROR');
2690
2930
  }
2691
2931
  }
2932
+ async compareAdrProgress(args) {
2933
+ const { todoPath = 'TODO.md', adrDirectory = this.config.adrDirectory, projectPath = this.config.projectPath, validationType = 'full', includeFileChecks = true, includeRuleValidation = true, deepCodeAnalysis = true, functionalValidation = true, strictMode = true } = args;
2934
+ const { getAdrDirectoryPath } = await import('./utils/config.js');
2935
+ const path = await import('path');
2936
+ // Resolve paths
2937
+ const absoluteTodoPath = path.resolve(projectPath, todoPath);
2938
+ const absoluteAdrPath = adrDirectory ?
2939
+ path.resolve(projectPath, adrDirectory) :
2940
+ getAdrDirectoryPath(this.config);
2941
+ this.logger.info(`Comparing ADR progress: TODO(${absoluteTodoPath}) vs ADRs(${absoluteAdrPath}) vs Environment(${projectPath})`);
2942
+ try {
2943
+ const { findFiles } = await import('./utils/file-system.js');
2944
+ // Step 1: Discover TODO.md file
2945
+ let todoPrompt = '';
2946
+ if (validationType === 'full' || validationType === 'todo-only') {
2947
+ try {
2948
+ const todoContent = await findFiles(projectPath, [todoPath], { includeContent: true });
2949
+ todoPrompt = `
2950
+ ## TODO.md Analysis
2951
+ ${todoContent.prompt}
2952
+ `;
2953
+ }
2954
+ catch (error) {
2955
+ todoPrompt = `
2956
+ ## TODO.md Analysis
2957
+ Error: Could not read TODO.md file at ${absoluteTodoPath}
2958
+ `;
2959
+ }
2960
+ }
2961
+ // Step 2: Discover ADR files
2962
+ let adrPrompt = '';
2963
+ if (validationType === 'full' || validationType === 'adr-only') {
2964
+ const adrFiles = await findFiles(projectPath, [`${absoluteAdrPath}/**/*.md`], { includeContent: true });
2965
+ adrPrompt = `
2966
+ ## ADR Files Analysis
2967
+ ${adrFiles.prompt}
2968
+ `;
2969
+ }
2970
+ // Step 3: Discover project environment
2971
+ let environmentPrompt = '';
2972
+ if (validationType === 'full' || validationType === 'environment-only') {
2973
+ const includeContent = deepCodeAnalysis || functionalValidation;
2974
+ const projectFiles = await findFiles(projectPath, [
2975
+ '**/*.{ts,js,py,java,cs,go,rb,php,swift,kt,rs,cpp,c,h,json,yaml,yml,md}',
2976
+ '!node_modules/**',
2977
+ '!dist/**',
2978
+ '!build/**',
2979
+ '!.git/**',
2980
+ '!coverage/**',
2981
+ '!.mcp-adr-cache/**'
2982
+ ], { includeContent });
2983
+ environmentPrompt = `
2984
+ ## Project Environment Analysis
2985
+ ${projectFiles.prompt}
2986
+ `;
2987
+ }
2988
+ // Step 4: Include architectural rules if requested
2989
+ let rulesPrompt = '';
2990
+ if (includeRuleValidation) {
2991
+ try {
2992
+ const rulesResult = await this.generateRules({
2993
+ source: 'both',
2994
+ adrDirectory: adrDirectory,
2995
+ projectPath: projectPath,
2996
+ outputFormat: 'json'
2997
+ });
2998
+ if (rulesResult.content) {
2999
+ rulesPrompt = `
3000
+ ## Architectural Rules Validation
3001
+ ${Array.isArray(rulesResult.content) ? rulesResult.content.map((c) => c.text || c).join('\n') : rulesResult.content}
3002
+ `;
3003
+ }
3004
+ }
3005
+ catch (error) {
3006
+ this.logger.warn(`Failed to extract rules for validation: ${error instanceof Error ? error.message : String(error)}`);
3007
+ rulesPrompt = `
3008
+ ## Architectural Rules Validation
3009
+ Note: Could not extract architectural rules for validation.
3010
+ `;
3011
+ }
3012
+ }
3013
+ // Generate comparison prompt
3014
+ const comparisonPrompt = `
3015
+ # ADR Progress Validation Request
3016
+
3017
+ ## Validation Type: ${validationType}
3018
+ ${todoPrompt}
3019
+ ${adrPrompt}
3020
+ ${environmentPrompt}
3021
+ ${rulesPrompt}
3022
+
3023
+ ## Validation Requirements
3024
+
3025
+ Please perform a comprehensive comparison and validation between the TODO.md, ADRs, and current project environment:
3026
+
3027
+ ### 1. TODO vs ADR Alignment
3028
+ - Verify that all tasks in TODO.md correspond to actual ADR requirements
3029
+ - Identify missing tasks that should be in TODO.md based on ADRs
3030
+ - Check for obsolete tasks that no longer align with current ADRs
3031
+ - Validate that task descriptions match ADR specifications
3032
+
3033
+ ### 2. Implementation Status Verification
3034
+ ${includeFileChecks ? `- Check file existence for tasks marked as completed
3035
+ - Verify that implemented code matches task specifications
3036
+ - Identify discrepancies between TODO status and actual implementation
3037
+ - Validate that file structures align with ADR requirements` : '- File existence checks disabled'}
3038
+
3039
+ ${deepCodeAnalysis ? `### 2.1. Deep Code Analysis (Mock vs Production Detection)
3040
+ - **Mock Detection**: Identify placeholder functions, TODO comments, and stub implementations
3041
+ - **Production Readiness**: Verify code has actual business logic, not just interfaces
3042
+ - **Implementation Depth**: Check for proper error handling, edge cases, and real functionality
3043
+ - **Completeness Validation**: Ensure functions do more than return mock data or throw NotImplementedException` : ''}
3044
+
3045
+ ${functionalValidation ? `### 2.2. Functional Validation Against ADR Goals
3046
+ - **Goal Alignment**: Verify implementations actually achieve the architectural goals stated in ADRs
3047
+ - **Environment Testing**: Check if code can run in the intended environment described by ADRs
3048
+ - **Integration Verification**: Validate that components work together as architected
3049
+ - **Performance Requirements**: Verify non-functional requirements from ADRs are met` : ''}
3050
+
3051
+ ### 3. Environment vs ADR Compliance
3052
+ - Compare current project structure with ADR decisions
3053
+ - Identify technology choices that deviate from ADRs
3054
+ - Verify that architectural patterns are implemented as specified
3055
+ - Check for missing components or files required by ADRs
3056
+
3057
+ ${includeRuleValidation ? `### 4. Architectural Rule Compliance
3058
+ - Validate current code against extracted architectural rules
3059
+ - Identify rule violations in the existing codebase
3060
+ - Check if TODO tasks include necessary rule compliance steps
3061
+ - Verify that completed tasks maintain rule compliance` : ''}
3062
+
3063
+ ## Expected Output Format
3064
+
3065
+ \`\`\`markdown
3066
+ # ADR Progress Validation Report
3067
+
3068
+ **Validation Date**: [Date]
3069
+ **Validation Type**: ${validationType}
3070
+ **Project Path**: ${projectPath}
3071
+
3072
+ ## Summary
3073
+ - **Total ADRs**: [count]
3074
+ - **Total TODO Tasks**: [count]
3075
+ - **Completed Tasks**: [count]
3076
+ - **Alignment Score**: [percentage]%
3077
+ - **Compliance Score**: [percentage]%
3078
+
3079
+ ## Alignment Analysis
3080
+
3081
+ ### ✅ Properly Aligned Tasks
3082
+ - [Task name]: Correctly implements [ADR reference]
3083
+ - [Task name]: Status verified, implementation complete
3084
+
3085
+ ### ⚠️ Misaligned Tasks
3086
+ - [Task name]: Description doesn't match [ADR reference]
3087
+ - [Task name]: Status marked complete but implementation missing
3088
+
3089
+ ### ❌ Missing Tasks
3090
+ - [Missing task]: Required by [ADR reference] but not in TODO
3091
+ - [Missing task]: Implementation needed for [specific requirement]
3092
+
3093
+ ### 🗑️ Obsolete Tasks
3094
+ - [Task name]: No longer needed due to [ADR change/superseded]
3095
+
3096
+ ## Implementation Status
3097
+
3098
+ ### File Existence Validation
3099
+ ${includeFileChecks ? `- ✅ [filename]: Exists and matches expectations
3100
+ - ❌ [filename]: Missing but marked as implemented
3101
+ - ⚠️ [filename]: Exists but doesn't match specifications` : '- File checks disabled'}
3102
+
3103
+ ${deepCodeAnalysis ? `### Mock vs Production Code Analysis
3104
+ - ✅ **Production Ready**: [component] - Full implementation with business logic
3105
+ - ⚠️ **Partial Implementation**: [component] - Some functionality missing or incomplete
3106
+ - ❌ **Mock/Stub Only**: [component] - Contains only placeholders, interfaces, or TODO comments
3107
+ - 🔍 **Requires Verification**: [component] - Implementation exists but needs deeper inspection
3108
+
3109
+ #### Mock Detection Indicators Found:
3110
+ - TODO comments: [count] instances
3111
+ - Placeholder functions: [count] instances
3112
+ - NotImplementedException: [count] instances
3113
+ - Mock return values: [count] instances
3114
+ - Empty function bodies: [count] instances` : ''}
3115
+
3116
+ ${functionalValidation ? `### Functional Validation Results
3117
+ - ✅ **ADR Goal Achieved**: [goal] - Implementation fully meets architectural objective
3118
+ - ⚠️ **Partial Goal Achievement**: [goal] - Implementation partially meets requirements
3119
+ - ❌ **Goal Not Met**: [goal] - Implementation doesn't achieve stated ADR objective
3120
+ - 🚫 **Environment Incompatible**: [component] - Code won't run in target environment
3121
+
3122
+ #### Environment Readiness Assessment:
3123
+ - **Dependency Management**: [status] - All required dependencies available
3124
+ - **Configuration**: [status] - Environment-specific config properly handled
3125
+ - **Integration Points**: [status] - External system connections functional
3126
+ - **Performance Criteria**: [status] - Meets ADR performance requirements` : ''}
3127
+
3128
+ ### Code Implementation Review
3129
+ - [Component]: Implementation status and quality assessment
3130
+ - [Feature]: Comparison with ADR requirements
3131
+
3132
+ ## Environment Compliance
3133
+
3134
+ ### Architecture Alignment
3135
+ - ✅ [Decision]: Correctly implemented
3136
+ - ❌ [Decision]: Not implemented or incorrectly implemented
3137
+ - ⚠️ [Decision]: Partially implemented
3138
+
3139
+ ### Technology Stack Validation
3140
+ - [Technology]: Usage aligns with [ADR reference]
3141
+ - [Technology]: Deviation from [ADR decision]
3142
+
3143
+ ${includeRuleValidation ? `## Rule Compliance Analysis
3144
+
3145
+ ### Rule Violations
3146
+ - [Rule name]: [violation description and location]
3147
+ - [Rule name]: [compliance status]
3148
+
3149
+ ### Compliance Recommendations
3150
+ - [Recommendation]: Steps to achieve compliance
3151
+ - [Fix]: Specific changes needed` : ''}
3152
+
3153
+ ## Recommendations
3154
+
3155
+ ### High Priority Actions
3156
+ 1. [Action]: [Reason and expected outcome]
3157
+ 2. [Action]: [Priority justification]
3158
+
3159
+ ### Medium Priority Actions
3160
+ 1. [Action]: [Impact and timeline]
3161
+
3162
+ ### Low Priority Actions
3163
+ 1. [Action]: [Optional improvements]
3164
+
3165
+ ## Next Steps
3166
+ 1. Address high-priority alignment issues
3167
+ 2. Update TODO.md with missing tasks
3168
+ 3. Verify implementation of completed tasks
3169
+ 4. Resolve rule compliance violations
3170
+ \`\`\`
3171
+
3172
+ Please provide a comprehensive validation report that helps ensure the TODO.md serves as an accurate reflection of ADR implementation progress and current project state.
3173
+ `;
3174
+ // Execute the comparison with AI if enabled, otherwise return prompt
3175
+ const { executePromptWithFallback, formatMCPResponse } = await import('./utils/prompt-execution.js');
3176
+ const executionResult = await executePromptWithFallback(comparisonPrompt, 'Compare TODO.md progress against ADRs and project environment for validation and alignment', {
3177
+ temperature: 0.1,
3178
+ maxTokens: 10000,
3179
+ systemPrompt: `You are an expert project auditor specializing in ADR implementation validation.
3180
+ Your role is to ensure that TODO lists accurately reflect ADR requirements and implementation reality.
3181
+
3182
+ Key responsibilities:
3183
+ 1. Cross-reference TODO tasks with ADR specifications
3184
+ 2. Verify implementation status against actual project state
3185
+ 3. Identify gaps, misalignments, and obsolete items
3186
+ 4. Validate architectural rule compliance
3187
+ 5. Provide actionable recommendations for improvement
3188
+
3189
+ ${strictMode ? `## STRICT VALIDATION MODE ENABLED
3190
+
3191
+ **CRITICAL**: Apply maximum scrutiny to distinguish between mock and production code:
3192
+
3193
+ ### Mock Detection (Mark as ❌ or ⚠️):
3194
+ - Functions that only return hardcoded values or throw NotImplementedException
3195
+ - Classes with empty method bodies or only getter/setter stubs
3196
+ - TODO comments indicating incomplete work
3197
+ - Interface definitions without concrete implementations
3198
+ - Test data or placeholder responses instead of real business logic
3199
+ - Comments like "// TODO: implement this" or "// placeholder"
3200
+
3201
+ ### Production Verification (Only mark ✅ if ALL criteria met):
3202
+ - Complete business logic implementation with proper error handling
3203
+ - Real data processing, not just mock responses
3204
+ - Proper integration with external systems/databases as specified in ADRs
3205
+ - Environment-specific configuration and dependency management
3206
+ - Performance and security requirements from ADRs actually implemented
3207
+
3208
+ ### ADR Goal Achievement (Be highly critical):
3209
+ - Implementation MUST actually solve the architectural problem stated in the ADR
3210
+ - Code MUST run successfully in the intended environment described by ADRs
3211
+ - Non-functional requirements (performance, security, scalability) MUST be demonstrably met
3212
+ - Integration points MUST be functional, not just stubbed
3213
+
3214
+ **DO NOT** be lenient about completion status. If there's ANY doubt about production readiness, mark as incomplete.` : ''}
3215
+
3216
+ Focus on accuracy, completeness, and practical next steps.
3217
+ Be thorough but concise in your analysis.
3218
+ Prioritize findings by impact and urgency.
3219
+ ${strictMode ? 'Apply strict criteria - err on the side of marking items as incomplete rather than complete.' : ''}`,
3220
+ responseFormat: 'text'
3221
+ });
3222
+ if (executionResult.isAIGenerated) {
3223
+ // AI execution successful
3224
+ return formatMCPResponse({
3225
+ ...executionResult,
3226
+ content: `# ADR Progress Validation Results
3227
+
3228
+ ## Validation Information
3229
+ - **TODO Path**: ${todoPath}
3230
+ - **ADR Directory**: ${adrDirectory}
3231
+ - **Project Path**: ${projectPath}
3232
+ - **Validation Type**: ${validationType}
3233
+ - **File Checks**: ${includeFileChecks ? 'Enabled' : 'Disabled'}
3234
+ - **Rule Validation**: ${includeRuleValidation ? 'Enabled' : 'Disabled'}
3235
+ - **Deep Code Analysis**: ${deepCodeAnalysis ? 'Enabled' : 'Disabled'}
3236
+ - **Functional Validation**: ${functionalValidation ? 'Enabled' : 'Disabled'}
3237
+ - **Strict Mode**: ${strictMode ? 'Enabled - High scrutiny for mock vs production' : 'Disabled'}
3238
+
3239
+ ## AI-Generated Validation Report
3240
+
3241
+ ${executionResult.content}
3242
+
3243
+ ## Integration Commands
3244
+
3245
+ ### Regenerate TODO after fixes:
3246
+ \`\`\`json
3247
+ {
3248
+ "tool": "generate_adr_todo",
3249
+ "args": {
3250
+ "adrDirectory": "${adrDirectory}",
3251
+ "phase": "both",
3252
+ "linkAdrs": true,
3253
+ "includeRules": ${includeRuleValidation}
3254
+ }
3255
+ }
3256
+ \`\`\`
3257
+
3258
+ ### Validate architectural rules:
3259
+ \`\`\`json
3260
+ {
3261
+ "tool": "validate_rules",
3262
+ "args": {
3263
+ "projectPath": "${projectPath}",
3264
+ "adrDirectory": "${adrDirectory}"
3265
+ }
3266
+ }
3267
+ \`\`\`
3268
+
3269
+ ### Re-run strict validation after updates:
3270
+ \`\`\`json
3271
+ {
3272
+ "tool": "compare_adr_progress",
3273
+ "args": {
3274
+ "todoPath": "${todoPath}",
3275
+ "adrDirectory": "${adrDirectory}",
3276
+ "validationType": "full",
3277
+ "deepCodeAnalysis": true,
3278
+ "functionalValidation": true,
3279
+ "strictMode": true
3280
+ }
3281
+ }
3282
+ \`\`\`
3283
+
3284
+ ### Quick validation (environment only):
3285
+ \`\`\`json
3286
+ {
3287
+ "tool": "compare_adr_progress",
3288
+ "args": {
3289
+ "validationType": "environment-only",
3290
+ "functionalValidation": true,
3291
+ "strictMode": false
3292
+ }
3293
+ }
3294
+ \`\`\`
3295
+ `,
3296
+ });
3297
+ }
3298
+ else {
3299
+ // Fallback to prompt-only mode
3300
+ return {
3301
+ content: [
3302
+ {
3303
+ type: 'text',
3304
+ text: `ADR progress comparison for: ${todoPath}\n\nValidation Type: ${validationType}\nFile Checks: ${includeFileChecks ? 'Enabled' : 'Disabled'}\nRule Validation: ${includeRuleValidation ? 'Enabled' : 'Disabled'}\nDeep Code Analysis: ${deepCodeAnalysis ? 'Enabled' : 'Disabled'}\nFunctional Validation: ${functionalValidation ? 'Enabled' : 'Disabled'}\nStrict Mode: ${strictMode ? 'Enabled' : 'Disabled'}\n\nPlease perform ADR progress validation using the following prompt:\n\n${comparisonPrompt}`
3305
+ }
3306
+ ]
3307
+ };
3308
+ }
3309
+ }
3310
+ catch (error) {
3311
+ throw new McpAdrError(`Failed to compare ADR progress: ${error instanceof Error ? error.message : String(error)}`, 'VALIDATION_ERROR');
3312
+ }
3313
+ }
2692
3314
  /**
2693
3315
  * Content masking tool implementations
2694
3316
  */