mcp-adr-analysis-server 2.10.3 → 2.11.0

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.
@@ -43,101 +43,25 @@ export async function generateRules(args) {
43
43
  }
44
44
  const result = await extractRulesFromAdrs(adrDirectory, existingRules, projectPath);
45
45
  enhancedPrompt = knowledgeContext + result.extractionPrompt;
46
- // Execute the rule extraction with AI if enabled, otherwise return prompt
47
- const { executePromptWithFallback, formatMCPResponse } = await import('../utils/prompt-execution.js');
48
- const executionResult = await executePromptWithFallback(enhancedPrompt, result.instructions, {
49
- temperature: 0.1,
50
- maxTokens: 6000,
51
- systemPrompt: `You are an expert software architect specializing in architectural rule extraction and governance.
52
- Analyze the provided ADRs to extract actionable architectural rules and governance policies.
53
- Leverage the provided architectural governance knowledge to create comprehensive, industry-standard rules.
54
- Focus on creating specific, measurable rules that can be validated automatically.
55
- Provide clear reasoning for each rule and practical implementation guidance.
56
- Consider compliance standards, governance frameworks, and architectural best practices.`,
57
- responseFormat: 'text',
58
- });
59
- if (executionResult.isAIGenerated) {
60
- // AI execution successful - return actual rule extraction results
61
- return formatMCPResponse({
62
- ...executionResult,
63
- content: `# ADR-Based Rule Generation Results (GKP Enhanced)
64
-
65
- ## Enhancement Features
66
- - **Generated Knowledge Prompting**: ${knowledgeEnhancement ? '✅ Enabled' : '❌ Disabled'}
67
- - **Enhanced Mode**: ${enhancedMode ? '✅ Enabled' : '❌ Disabled'}
68
- - **Knowledge Domains**: Governance frameworks, software architecture, compliance standards
69
-
70
- ## Analysis Information
71
- - **ADR Directory**: ${adrDirectory}
72
- - **Existing Rules**: ${existingRules?.length || 0} rules
73
- - **Output Format**: ${outputFormat.toUpperCase()}
74
-
75
- ${knowledgeContext
76
- ? `## Applied Governance Knowledge
77
-
78
- ${knowledgeContext}
79
- `
80
- : ''}
81
-
82
- ## AI Rule Extraction Results
83
-
84
- ${executionResult.content}
85
-
86
- ## Next Steps
87
-
88
- Based on the extracted rules:
89
-
90
- 1. **Review Generated Rules**: Examine each rule for accuracy and completeness
91
- 2. **Save Rule Set**: Create ${outputFormat.toUpperCase()} files for the extracted rules
92
- 3. **Implement Validation**: Set up automated rule checking in your CI/CD pipeline
93
- 4. **Team Training**: Share rules with development team for adoption
94
- 5. **Monitor Compliance**: Track rule adherence and adjust as needed
95
-
96
- ## Integration Commands
97
-
98
- To validate code against these rules, use:
99
- \`\`\`json
100
- {
101
- "tool": "validate_rules",
102
- "args": {
103
- "filePath": "path/to/code/file.js",
104
- "rules": [extracted rules from above]
105
- }
106
- }
107
- \`\`\`
108
-
109
- To create a machine-readable rule set:
110
- \`\`\`json
111
- {
112
- "tool": "create_rule_set",
113
- "args": {
114
- "name": "ADR-Based Architectural Rules",
115
- "adrRules": [extracted rules from above],
116
- "outputFormat": "${outputFormat}"
117
- }
118
- }
119
- \`\`\`
120
- `,
121
- });
122
- }
123
- else {
124
- // Fallback to prompt-only mode
125
- return {
126
- content: [
127
- {
128
- type: 'text',
129
- text: `# Rule Generation: ADR-Based Rules (GKP Enhanced)
46
+ // CE-MCP: return prompt text for the host LLM. The directive path in
47
+ // mcp-adr-analysis-server.ts intercepts this tool before it reaches here
48
+ // when CE-MCP mode is active; this return serves legacy/prompt-only mode.
49
+ return {
50
+ content: [
51
+ {
52
+ type: 'text',
53
+ text: `# Rule Generation: ADR-Based Rules (GKP Enhanced)
130
54
 
131
55
  ## Enhancement Status
132
56
  - **Generated Knowledge Prompting**: ${knowledgeEnhancement ? '✅ Applied' : '❌ Disabled'}
133
57
  - **Enhanced Mode**: ${enhancedMode ? '✅ Applied' : '❌ Disabled'}
134
58
 
135
59
  ${knowledgeContext
136
- ? `## Governance Knowledge Context
60
+ ? `## Governance Knowledge Context
137
61
 
138
62
  ${knowledgeContext}
139
63
  `
140
- : ''}
64
+ : ''}
141
65
 
142
66
  ${result.instructions}
143
67
 
@@ -153,10 +77,9 @@ ${enhancedPrompt}
153
77
  4. **Save rules** in ${outputFormat.toUpperCase()} format using the rule format utilities
154
78
  5. **Integrate with validation tools** for automated compliance checking
155
79
  `,
156
- },
157
- ],
158
- };
159
- }
80
+ },
81
+ ],
82
+ };
160
83
  }
161
84
  case 'patterns': {
162
85
  let enhancedPrompt = '';
@@ -251,91 +174,12 @@ ${enhancedPrompt}
251
174
  const existingRuleNames = existingRules?.map(r => r.name);
252
175
  const result = await generateRulesFromPatterns(projectPath, existingRuleNames);
253
176
  enhancedPrompt = knowledgeContext + patternImplementationContext + result.generationPrompt;
254
- // Execute the pattern-based rule generation with AI if enabled, otherwise return prompt
255
- const { executePromptWithFallback, formatMCPResponse } = await import('../utils/prompt-execution.js');
256
- const executionResult = await executePromptWithFallback(enhancedPrompt, result.instructions, {
257
- temperature: 0.1,
258
- maxTokens: 6000,
259
- systemPrompt: `You are an expert software architect specializing in code pattern analysis and rule generation.
260
- Analyze the provided codebase to identify consistent patterns and generate actionable architectural rules.
261
- Leverage the provided design pattern and code quality knowledge to create comprehensive, industry-standard rules.
262
- Focus on creating rules that enforce consistency, quality, and maintainability based on observed patterns.
263
- Consider established design patterns, code quality metrics, and architectural best practices.
264
- Provide confidence scores and practical implementation guidance for each rule.`,
265
- responseFormat: 'text',
266
- });
267
- if (executionResult.isAIGenerated) {
268
- // AI execution successful - return actual pattern-based rule generation results
269
- return formatMCPResponse({
270
- ...executionResult,
271
- content: `# Pattern-Based Rule Generation Results (Enhanced with Smart Code Linking)
272
-
273
- ## Enhancement Features
274
- - **Smart Code Linking**: ${patternImplementationContext ? '✅ Active' : '❌ No patterns found'}
275
- - **Generated Knowledge Prompting**: ${knowledgeEnhancement ? '✅ Enabled' : '❌ Disabled'}
276
- - **Enhanced Mode**: ${enhancedMode ? '✅ Enabled' : '❌ Disabled'}
277
- - **Knowledge Domains**: Design patterns, code quality, software architecture
278
-
279
- ## Analysis Information
280
- - **Project Path**: ${projectPath}
281
- - **Existing Rules**: ${existingRules?.length || 0} rules
282
- - **Output Format**: ${outputFormat.toUpperCase()}
283
-
284
- ${patternImplementationContext ? `${patternImplementationContext}` : ''}
285
-
286
- ${knowledgeContext
287
- ? `## Applied Pattern Knowledge
288
-
289
- ${knowledgeContext}
290
- `
291
- : ''}
292
-
293
- ## AI Pattern Analysis Results
294
-
295
- ${executionResult.content}
296
-
297
- ## Next Steps
298
-
299
- Based on the pattern analysis:
300
-
301
- 1. **Review Generated Rules**: Examine each rule for relevance and accuracy
302
- 2. **Validate Patterns**: Confirm patterns are representative of desired practices
303
- 3. **Implement High-Confidence Rules**: Start with rules that have high confidence scores
304
- 4. **Combine with ADR Rules**: Merge with ADR-extracted rules for comprehensive coverage
305
- 5. **Set Up Validation**: Implement automated checking for pattern-based rules
306
-
307
- ## Pattern-Based Benefits
308
-
309
- These rules offer:
310
- - **Consistency Enforcement**: Based on actual project patterns
311
- - **Team Alignment**: Reflects current team practices
312
- - **Gradual Improvement**: Incremental quality improvements
313
- - **Automated Detection**: High automatability for validation tools
314
-
315
- ## Integration Commands
316
-
317
- To create a comprehensive rule set combining patterns and ADRs:
318
- \`\`\`json
319
- {
320
- "tool": "generate_rules",
321
- "args": {
322
- "source": "both",
323
- "projectPath": "${projectPath}",
324
- "adrDirectory": "${adrDirectory}",
325
- "outputFormat": "${outputFormat}"
326
- }
327
- }
328
- \`\`\`
329
- `,
330
- });
331
- }
332
- else {
333
- // Fallback to prompt-only mode
334
- return {
335
- content: [
336
- {
337
- type: 'text',
338
- text: `# Rule Generation: Pattern-Based Rules (Enhanced with Smart Code Linking)
177
+ // CE-MCP: return prompt text directly; directive intercepts in CE-MCP mode.
178
+ return {
179
+ content: [
180
+ {
181
+ type: 'text',
182
+ text: `# Rule Generation: Pattern-Based Rules (Enhanced with Smart Code Linking)
339
183
 
340
184
  ## Enhancement Status
341
185
  - **Smart Code Linking**: ${patternImplementationContext ? '✅ Pattern implementations discovered' : '❌ No patterns found'}
@@ -343,286 +187,36 @@ To create a comprehensive rule set combining patterns and ADRs:
343
187
  - **Enhanced Mode**: ${enhancedMode ? '✅ Applied' : '❌ Disabled'}
344
188
 
345
189
  ${patternImplementationContext
346
- ? `${patternImplementationContext}
190
+ ? `${patternImplementationContext}
347
191
 
348
192
  `
349
- : ''}${knowledgeContext
350
- ? `## Governance Knowledge Context
193
+ : ''}${knowledgeContext
194
+ ? `## Governance Knowledge Context
351
195
 
352
196
  ${knowledgeContext}
353
197
  `
354
- : ''}
198
+ : ''}
355
199
 
356
200
  ${result.instructions}
357
201
 
358
202
  ## Enhanced AI Analysis Prompt
359
203
 
360
204
  ${enhancedPrompt}
361
-
362
- ## Next Steps
363
-
364
- 1. **Submit the enhanced prompt** to an AI agent for comprehensive pattern analysis
365
- 2. **Parse the JSON response** to get generated rules and pattern metrics
366
- 3. **Review pattern-based rules** using the discovered implementation context
367
- 4. **Combine with ADR-extracted rules** for comprehensive rule set
368
- 5. **Implement validation** for high-confidence pattern rules
369
-
370
- ## Pattern Implementation Benefits
371
-
372
- The Smart Code Linking enhancement provides:
373
- - **Real Examples**: Rules based on actual pattern implementations found in your codebase
374
- - **Context-Aware**: Better understanding of how patterns are actually used
375
- - **Higher Confidence**: Rules validated against existing code patterns
376
- - **Team Alignment**: Rules that reflect current team practices and implementations
377
205
  `,
378
- },
379
- ],
380
- };
381
- }
206
+ },
207
+ ],
208
+ };
382
209
  }
383
210
  case 'both': {
384
- let comprehensiveKnowledgeContext = '';
385
- let comprehensivePatternContext = '';
386
- // Smart Code Linking - comprehensive pattern and ADR implementation discovery
387
- try {
388
- // Find all code and documentation files
389
- const findResult = await findFiles(projectPath, [
390
- '**/*.{ts,js,jsx,tsx,py,java,cs,go,rs,rb,php,swift,kt,scala,c,cpp}',
391
- '**/*.{md,adoc,rst}',
392
- '!**/node_modules/**',
393
- '!**/dist/**',
394
- '!**/build/**',
395
- '!**/target/**',
396
- ]);
397
- if (findResult.files.length > 0) {
398
- // Use Smart Code Linking to find comprehensive architectural patterns and ADR implementations
399
- const comprehensiveContext = [
400
- 'architectural decisions',
401
- 'design patterns',
402
- 'architectural patterns',
403
- 'software architecture',
404
- 'architectural governance',
405
- 'code standards',
406
- 'best practices',
407
- 'quality attributes',
408
- 'security patterns',
409
- 'performance patterns',
410
- 'scalability patterns',
411
- 'maintainability',
412
- 'testability',
413
- 'deployment patterns',
414
- 'integration patterns',
415
- ].join(' ');
416
- const relatedCodeResult = await findRelatedCode('comprehensive-architecture-analysis', comprehensiveContext, projectPath, {
417
- useAI: true,
418
- maxFiles: 30,
419
- includeContent: false,
420
- });
421
- if (relatedCodeResult.relatedFiles.length > 0) {
422
- // Categorize files by type for better analysis
423
- const codeFiles = relatedCodeResult.relatedFiles.filter(f => f.extension?.match(/\.(ts|js|jsx|tsx|py|java|cs|go|rs|rb|php|swift|kt|scala|c|cpp)$/));
424
- const docFiles = relatedCodeResult.relatedFiles.filter(f => f.extension?.match(/\.(md|adoc|rst)$/));
425
- comprehensivePatternContext = [
426
- '',
427
- '## 🔗 Comprehensive Architecture Discovery',
428
- '',
429
- `Found **${relatedCodeResult.relatedFiles.length}** files relevant to architectural rule generation:`,
430
- '',
431
- `### Code Implementation Files (${codeFiles.length})`,
432
- ...codeFiles.slice(0, 12).map((file, index) => `${index + 1}. **${file.path}**`),
433
- codeFiles.length > 12 ? `*Showing top 12 of ${codeFiles.length} code files*` : '',
434
- '',
435
- docFiles.length > 0
436
- ? [
437
- `### Documentation Files (${docFiles.length})`,
438
- ...docFiles
439
- .slice(0, 8)
440
- .map((file, index) => `${index + 1}. **${file.path}**`),
441
- docFiles.length > 8
442
- ? `*Showing top 8 of ${docFiles.length} documentation files*`
443
- : '',
444
- '',
445
- ].join('\n')
446
- : '',
447
- `**Overall Analysis Confidence**: ${(relatedCodeResult.confidence * 100).toFixed(0)}%`,
448
- `**Architectural Keywords**: ${relatedCodeResult.keywords?.slice(0, 12).join(', ') || 'N/A'}`,
449
- '',
450
- '## Technology Stack Analysis',
451
- ...Object.entries(relatedCodeResult.relatedFiles.reduce((acc, file) => {
452
- const ext = file.extension || 'unknown';
453
- acc[ext] = (acc[ext] || 0) + 1;
454
- return acc;
455
- }, {}))
456
- .slice(0, 8)
457
- .map(([ext, count]) => `- **${ext.toUpperCase()}**: ${count} files`),
458
- '',
459
- ]
460
- .filter(Boolean)
461
- .join('\n');
462
- }
463
- }
464
- }
465
- catch (error) {
466
- console.warn('Smart Code Linking failed for comprehensive analysis:', error);
467
- }
468
- // Generate comprehensive domain knowledge if enabled
469
- if (enhancedMode && knowledgeEnhancement) {
470
- try {
471
- const { generateArchitecturalKnowledge } = await import('../utils/knowledge-generation.js');
472
- const knowledgeResult = await generateArchitecturalKnowledge({
473
- projectPath,
474
- technologies: [],
475
- patterns: [],
476
- projectType: 'comprehensive-rule-generation',
477
- }, {
478
- domains: ['api-design', 'security-patterns', 'performance-optimization'],
479
- depth: 'advanced',
480
- cacheEnabled: true,
481
- });
482
- comprehensiveKnowledgeContext = `\n## Comprehensive Architectural Knowledge Enhancement\n\n${knowledgeResult.prompt}\n\n---\n`;
483
- }
484
- catch (error) {
485
- console.error('[WARNING] GKP knowledge generation failed for comprehensive analysis:', error);
486
- comprehensiveKnowledgeContext =
487
- '<!-- Comprehensive knowledge generation unavailable -->\n';
488
- }
489
- }
490
211
  const adrResult = await extractRulesFromAdrs(adrDirectory, existingRules, projectPath);
491
212
  const existingRuleNames = existingRules?.map(r => r.name);
492
213
  const patternResult = await generateRulesFromPatterns(projectPath, existingRuleNames);
493
- // Create comprehensive prompt combining both ADR and pattern analysis with knowledge enhancement
494
- const comprehensivePrompt = `${comprehensiveKnowledgeContext}${comprehensivePatternContext}
495
- # Comprehensive Architectural Rule Generation
496
-
497
- Generate a complete set of architectural rules by analyzing both ADRs and code patterns with Smart Code Linking context.
498
-
499
- ## ADR-Based Rule Extraction
500
-
501
- ${adrResult.extractionPrompt}
502
-
503
- ## Pattern-Based Rule Generation
504
-
505
- ${patternResult.generationPrompt}
506
-
507
- ## Consolidation Requirements
508
-
509
- After extracting rules from both sources:
510
-
511
- 1. **Merge and Deduplicate**: Combine rules from ADRs and patterns, removing duplicates
512
- 2. **Resolve Conflicts**: When ADR rules conflict with pattern rules, prioritize ADR rules (explicit decisions)
513
- 3. **Assign Priorities**: High priority for ADR rules, medium for consistent patterns, low for inconsistent patterns
514
- 4. **Create Dependencies**: Identify relationships between rules and create dependency chains
515
- 5. **Validate Completeness**: Ensure rules cover all major architectural concerns
516
-
517
- ## Output Requirements
518
-
519
- Provide a unified rule set with:
520
- - **Rule Source**: Whether from ADR, pattern, or both
521
- - **Confidence Score**: 1-10 rating of rule validity
522
- - **Priority Level**: High/Medium/Low implementation priority
523
- - **Validation Pattern**: How to automatically check compliance
524
- - **Examples**: Valid and invalid code examples
525
- - **Dependencies**: Other rules this rule depends on
526
- `;
527
- // Execute the comprehensive rule generation with AI if enabled, otherwise return prompt
528
- const { executePromptWithFallback, formatMCPResponse } = await import('../utils/prompt-execution.js');
529
- const executionResult = await executePromptWithFallback(comprehensivePrompt, `${adrResult.instructions}\n\n${patternResult.instructions}`, {
530
- temperature: 0.1,
531
- maxTokens: 8000,
532
- systemPrompt: `You are an expert software architect specializing in comprehensive architectural rule generation.
533
- Analyze both ADRs and code patterns to create a unified, actionable rule set for the project.
534
- Leverage the provided comprehensive architectural knowledge including governance frameworks, design patterns, and compliance standards.
535
- Focus on creating rules that are specific, measurable, and can be validated automatically.
536
- Prioritize explicit architectural decisions (ADRs) over implicit patterns when conflicts arise.
537
- Consider industry best practices, compliance requirements, and established architectural principles.`,
538
- responseFormat: 'text',
539
- });
540
- if (executionResult.isAIGenerated) {
541
- // AI execution successful - return actual comprehensive rule generation results
542
- return formatMCPResponse({
543
- ...executionResult,
544
- content: `# Comprehensive Rule Generation Results (Enhanced with Smart Code Linking & GKP)
545
-
546
- ## Enhancement Features
547
- - **Smart Code Linking**: ${comprehensivePatternContext ? '✅ Active' : '❌ No patterns found'}
548
- - **Generated Knowledge Prompting**: ${knowledgeEnhancement ? '✅ Enabled' : '❌ Disabled'}
549
- - **Enhanced Mode**: ${enhancedMode ? '✅ Enabled' : '❌ Disabled'}
550
- - **Knowledge Domains**: Governance frameworks, software architecture, design patterns, compliance standards, code quality
551
- - **Knowledge Depth**: Advanced (comprehensive coverage)
552
-
553
- ## Analysis Information
554
- - **ADR Directory**: ${adrDirectory}
555
- - **Project Path**: ${projectPath}
556
- - **Existing Rules**: ${existingRules?.length || 0} rules
557
- - **Output Format**: ${outputFormat.toUpperCase()}
558
-
559
- ${comprehensivePatternContext ? `${comprehensivePatternContext}` : ''}
560
-
561
- ${comprehensiveKnowledgeContext
562
- ? `## Applied Comprehensive Knowledge
563
-
564
- ${comprehensiveKnowledgeContext}
565
- `
566
- : ''}
567
-
568
- ## AI Comprehensive Analysis Results
569
-
570
- ${executionResult.content}
571
-
572
- ## Next Steps
573
-
574
- Based on the comprehensive analysis:
575
-
576
- 1. **Review Unified Rule Set**: Examine the consolidated rules for completeness
577
- 2. **Validate Rule Priorities**: Confirm priority assignments align with project needs
578
- 3. **Implement High-Priority Rules**: Start with rules marked as high priority
579
- 4. **Set Up Automated Validation**: Configure CI/CD to check rule compliance
580
- 5. **Create Rule Documentation**: Document rules for team reference and training
581
-
582
- ## Comprehensive Benefits
583
-
584
- This approach provides:
585
- - **Complete Coverage**: Both explicit (ADR) and implicit (pattern) rules
586
- - **Balanced Approach**: Combines intentional decisions with observed practices
587
- - **High Confidence**: Rules backed by both documentation and code evidence
588
- - **Practical Implementation**: Rules that can be validated and enforced
589
- - **Team Alignment**: Rules that reflect both intentions and reality
590
-
591
- ## Integration Commands
592
-
593
- To create the final rule set:
594
- \`\`\`json
595
- {
596
- "tool": "create_rule_set",
597
- "args": {
598
- "name": "Comprehensive Architectural Rules",
599
- "adrRules": [ADR rules from above],
600
- "patternRules": [pattern rules from above],
601
- "outputFormat": "${outputFormat}"
602
- }
603
- }
604
- \`\`\`
605
-
606
- To validate code against the complete rule set:
607
- \`\`\`json
608
- {
609
- "tool": "validate_rules",
610
- "args": {
611
- "filePath": "path/to/code/file.js",
612
- "rules": [unified rules from above]
613
- }
614
- }
615
- \`\`\`
616
- `,
617
- });
618
- }
619
- else {
620
- // Fallback to prompt-only mode
621
- return {
622
- content: [
623
- {
624
- type: 'text',
625
- text: `# Comprehensive Rule Generation
214
+ // CE-MCP: return prompt text directly; directive intercepts in CE-MCP mode.
215
+ return {
216
+ content: [
217
+ {
218
+ type: 'text',
219
+ text: `# Comprehensive Rule Generation
626
220
 
627
221
  This comprehensive analysis will generate architectural rules from both ADRs and code patterns for complete coverage.
628
222
 
@@ -656,10 +250,9 @@ Submit the pattern analysis prompt to generate rules from code patterns
656
250
  - Prioritize based on confidence and impact
657
251
  - Create unified rule set with dependencies
658
252
  `,
659
- },
660
- ],
661
- };
662
- }
253
+ },
254
+ ],
255
+ };
663
256
  }
664
257
  default:
665
258
  throw new McpAdrError(`Unknown rule generation source: ${source}`, 'INVALID_INPUT');
@@ -673,7 +266,7 @@ Submit the pattern analysis prompt to generate rules from code patterns
673
266
  * Validate code against architectural rules
674
267
  */
675
268
  export async function validateRules(args) {
676
- const { filePath, fileContent, fileName, rules, validationType = 'file', reportFormat = 'detailed', projectPath = process.cwd(), findRelatedFiles = false, } = args;
269
+ const { filePath, fileContent, fileName, rules, validationType = 'file', reportFormat: _reportFormat = 'detailed', } = args;
677
270
  try {
678
271
  const { validateCodeAgainstRules } = await import('../utils/rule-generation.js');
679
272
  if (!filePath && !fileContent) {
@@ -682,52 +275,6 @@ export async function validateRules(args) {
682
275
  if (!rules || rules.length === 0) {
683
276
  throw new McpAdrError('Rules array is required and cannot be empty', 'INVALID_INPUT');
684
277
  }
685
- // Smart Code Linking - find related files for comprehensive validation context
686
- let relatedFilesContext = '';
687
- if (findRelatedFiles && filePath) {
688
- try {
689
- // Create context from the file being validated and the rules
690
- const validationContext = [
691
- `File being validated: ${filePath}`,
692
- 'Architectural rules validation',
693
- ...rules.slice(0, 5).map(rule => `Rule: ${rule.name} - ${rule.description}`),
694
- ].join('\n');
695
- const relatedCodeResult = await findRelatedCode('rule-validation-context', validationContext, projectPath, {
696
- useAI: true,
697
- maxFiles: 12,
698
- includeContent: false,
699
- });
700
- if (relatedCodeResult.relatedFiles.length > 0) {
701
- // Filter out the file being validated itself
702
- const otherRelatedFiles = relatedCodeResult.relatedFiles.filter(f => f.path !== filePath && !filePath.endsWith(f.path));
703
- if (otherRelatedFiles.length > 0) {
704
- relatedFilesContext = [
705
- '',
706
- '## 🔗 Related Files for Validation Context',
707
- '',
708
- `Found **${otherRelatedFiles.length}** related files that may need similar validation:`,
709
- '',
710
- ...otherRelatedFiles
711
- .slice(0, 8)
712
- .map((file, index) => `${index + 1}. **${file.path}**`),
713
- otherRelatedFiles.length > 8
714
- ? `*Showing top 8 of ${otherRelatedFiles.length} related files*`
715
- : '',
716
- '',
717
- `**Context Confidence**: ${(relatedCodeResult.confidence * 100).toFixed(0)}%`,
718
- '',
719
- '💡 **Recommendation**: Consider validating these related files against the same rules for comprehensive compliance.',
720
- '',
721
- ]
722
- .filter(Boolean)
723
- .join('\n');
724
- }
725
- }
726
- }
727
- catch (error) {
728
- console.warn('Smart Code Linking failed for validation context:', error);
729
- }
730
- }
731
278
  // Convert rules to ArchitecturalRule format
732
279
  const architecturalRules = rules.map(rule => ({
733
280
  id: rule.id,
@@ -758,84 +305,12 @@ export async function validateRules(args) {
758
305
  instructions: `Validation for ${tempFileName} with ${rules.length} rules`,
759
306
  };
760
307
  }
761
- // Execute the rule validation with AI if enabled, otherwise return prompt
762
- const { executePromptWithFallback, formatMCPResponse } = await import('../utils/prompt-execution.js');
763
- const executionResult = await executePromptWithFallback(result.validationPrompt, result.instructions, {
764
- temperature: 0.1,
765
- maxTokens: 5000,
766
- systemPrompt: `You are a senior software architect specializing in code quality and architectural compliance.
767
- Analyze the provided code against architectural rules to identify violations and provide improvement recommendations.
768
- Focus on providing specific, actionable feedback with clear explanations and fix suggestions.
769
- Prioritize violations by severity and impact on system architecture.`,
770
- responseFormat: 'text',
771
- });
772
- if (executionResult.isAIGenerated) {
773
- // AI execution successful - return actual rule validation results
774
- return formatMCPResponse({
775
- ...executionResult,
776
- content: `# Code Validation Results (Enhanced with Smart Code Linking)
777
-
778
- ## Validation Information
779
- - **File**: ${fileName || filePath || 'Content provided'}
780
- - **Validation Type**: ${validationType}
781
- - **Rules Applied**: ${rules.length} rules
782
- - **Report Format**: ${reportFormat}
783
- - **Smart Code Linking**: ${relatedFilesContext ? '✅ Related files discovered' : findRelatedFiles ? '❌ No related files found' : '⚪ Not requested'}
784
-
785
- ${relatedFilesContext ? `${relatedFilesContext}` : ''}
786
-
787
- ## AI Validation Results
788
-
789
- ${executionResult.content}
790
-
791
- ## Next Steps
792
-
793
- Based on the validation results:
794
-
795
- 1. **Address Critical Issues**: Fix any critical violations immediately
796
- 2. **Plan Error Fixes**: Schedule error-level violations for next release
797
- 3. **Batch Warning Fixes**: Group warning-level issues for efficient resolution
798
- 4. **Track Compliance**: Monitor improvement trends over time
799
- 5. **Update Rules**: Refine rules based on validation experience
800
-
801
- ## Violation Severity Levels
802
-
803
- - **Critical**: Must be fixed immediately (security, breaking changes)
804
- - **Error**: Should be fixed before deployment (functionality issues)
805
- - **Warning**: Should be addressed in next iteration (quality issues)
806
- - **Info**: Consider for future improvements (style, optimization)
807
-
808
- ## Compliance Tracking
809
-
810
- Use validation results to:
811
- - Track compliance trends over time
812
- - Identify problematic areas or patterns
813
- - Measure improvement after fixes
814
- - Generate compliance reports for stakeholders
815
-
816
- ## Re-validation Command
817
-
818
- After applying fixes, re-validate with:
819
- \`\`\`json
820
- {
821
- "tool": "validate_rules",
822
- "args": {
823
- "filePath": "${filePath || 'updated-file-path'}",
824
- "rules": [same rules array],
825
- "reportFormat": "${reportFormat}"
826
- }
827
- }
828
- \`\`\`
829
- `,
830
- });
831
- }
832
- else {
833
- // Fallback to prompt-only mode
834
- return {
835
- content: [
836
- {
837
- type: 'text',
838
- text: `# Code Validation Against Architectural Rules
308
+ // CE-MCP: return prompt text directly; directive intercepts in CE-MCP mode.
309
+ return {
310
+ content: [
311
+ {
312
+ type: 'text',
313
+ text: `# Code Validation Against Architectural Rules
839
314
 
840
315
  ${result.instructions}
841
316
 
@@ -851,10 +326,9 @@ ${result.validationPrompt}
851
326
  4. **Apply suggested fixes** to improve compliance
852
327
  5. **Re-validate** to confirm improvements
853
328
  `,
854
- },
855
- ],
856
- };
857
- }
329
+ },
330
+ ],
331
+ };
858
332
  }
859
333
  catch (error) {
860
334
  throw new McpAdrError(`Failed to validate rules: ${error instanceof Error ? error.message : String(error)}`, 'RULE_VALIDATION_ERROR');