mcp-adr-analysis-server 2.0.1 → 2.0.3

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