mcp-adr-analysis-server 1.1.0 → 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.
Files changed (118) hide show
  1. package/README.md +367 -150
  2. package/dist/src/config/ai-config.d.ts +81 -0
  3. package/dist/src/config/ai-config.d.ts.map +1 -0
  4. package/dist/src/config/ai-config.js +134 -0
  5. package/dist/src/config/ai-config.js.map +1 -0
  6. package/dist/src/index.d.ts +97 -1
  7. package/dist/src/index.d.ts.map +1 -1
  8. package/dist/src/index.js +2430 -186
  9. package/dist/src/index.js.map +1 -1
  10. package/dist/src/prompts/adr-suggestion-prompts.d.ts +2 -2
  11. package/dist/src/prompts/adr-suggestion-prompts.d.ts.map +1 -1
  12. package/dist/src/prompts/adr-suggestion-prompts.js +25 -17
  13. package/dist/src/prompts/adr-suggestion-prompts.js.map +1 -1
  14. package/dist/src/prompts/analysis-prompts.js +1 -1
  15. package/dist/src/prompts/analysis-prompts.js.map +1 -1
  16. package/dist/src/resources/index.d.ts +1 -1
  17. package/dist/src/resources/index.d.ts.map +1 -1
  18. package/dist/src/resources/index.js +52 -44
  19. package/dist/src/resources/index.js.map +1 -1
  20. package/dist/src/templates/domain-knowledge-templates.d.ts +36 -0
  21. package/dist/src/templates/domain-knowledge-templates.d.ts.map +1 -0
  22. package/dist/src/templates/domain-knowledge-templates.js +376 -0
  23. package/dist/src/templates/domain-knowledge-templates.js.map +1 -0
  24. package/dist/src/tools/adr-suggestion-tool.d.ts +8 -3
  25. package/dist/src/tools/adr-suggestion-tool.d.ts.map +1 -1
  26. package/dist/src/tools/adr-suggestion-tool.js +561 -172
  27. package/dist/src/tools/adr-suggestion-tool.js.map +1 -1
  28. package/dist/src/tools/content-masking-tool.d.ts.map +1 -1
  29. package/dist/src/tools/content-masking-tool.js +168 -22
  30. package/dist/src/tools/content-masking-tool.js.map +1 -1
  31. package/dist/src/tools/deployment-analysis-tool.d.ts.map +1 -1
  32. package/dist/src/tools/deployment-analysis-tool.js +64 -27
  33. package/dist/src/tools/deployment-analysis-tool.js.map +1 -1
  34. package/dist/src/tools/environment-analysis-tool.d.ts.map +1 -1
  35. package/dist/src/tools/environment-analysis-tool.js +65 -29
  36. package/dist/src/tools/environment-analysis-tool.js.map +1 -1
  37. package/dist/src/tools/research-question-tool.d.ts.map +1 -1
  38. package/dist/src/tools/research-question-tool.js +150 -49
  39. package/dist/src/tools/research-question-tool.js.map +1 -1
  40. package/dist/src/tools/rule-generation-tool.d.ts.map +1 -1
  41. package/dist/src/tools/rule-generation-tool.js +328 -143
  42. package/dist/src/tools/rule-generation-tool.js.map +1 -1
  43. package/dist/src/types/ape-framework.d.ts +566 -0
  44. package/dist/src/types/ape-framework.d.ts.map +1 -0
  45. package/dist/src/types/ape-framework.js +98 -0
  46. package/dist/src/types/ape-framework.js.map +1 -0
  47. package/dist/src/types/index.d.ts +96 -93
  48. package/dist/src/types/index.d.ts.map +1 -1
  49. package/dist/src/types/knowledge-generation.d.ts +671 -0
  50. package/dist/src/types/knowledge-generation.d.ts.map +1 -0
  51. package/dist/src/types/knowledge-generation.js +107 -0
  52. package/dist/src/types/knowledge-generation.js.map +1 -0
  53. package/dist/src/types/reflexion-framework.d.ts +652 -0
  54. package/dist/src/types/reflexion-framework.d.ts.map +1 -0
  55. package/dist/src/types/reflexion-framework.js +85 -0
  56. package/dist/src/types/reflexion-framework.js.map +1 -0
  57. package/dist/src/utils/adr-suggestions.d.ts +1 -1
  58. package/dist/src/utils/adr-suggestions.d.ts.map +1 -1
  59. package/dist/src/utils/adr-suggestions.js +8 -50
  60. package/dist/src/utils/adr-suggestions.js.map +1 -1
  61. package/dist/src/utils/ai-executor.d.ts +125 -0
  62. package/dist/src/utils/ai-executor.d.ts.map +1 -0
  63. package/dist/src/utils/ai-executor.js +292 -0
  64. package/dist/src/utils/ai-executor.js.map +1 -0
  65. package/dist/src/utils/automatic-prompt-engineering.d.ts +72 -0
  66. package/dist/src/utils/automatic-prompt-engineering.d.ts.map +1 -0
  67. package/dist/src/utils/automatic-prompt-engineering.js +820 -0
  68. package/dist/src/utils/automatic-prompt-engineering.js.map +1 -0
  69. package/dist/src/utils/cache.d.ts +54 -22
  70. package/dist/src/utils/cache.d.ts.map +1 -1
  71. package/dist/src/utils/cache.js +1234 -143
  72. package/dist/src/utils/cache.js.map +1 -1
  73. package/dist/src/utils/config.d.ts +2 -2
  74. package/dist/src/utils/config.js +3 -3
  75. package/dist/src/utils/config.js.map +1 -1
  76. package/dist/src/utils/deployment-analysis.d.ts.map +1 -1
  77. package/dist/src/utils/deployment-analysis.js +57 -38
  78. package/dist/src/utils/deployment-analysis.js.map +1 -1
  79. package/dist/src/utils/environment-analysis.d.ts.map +1 -1
  80. package/dist/src/utils/environment-analysis.js +113 -100
  81. package/dist/src/utils/environment-analysis.js.map +1 -1
  82. package/dist/src/utils/file-system.d.ts +42 -13
  83. package/dist/src/utils/file-system.d.ts.map +1 -1
  84. package/dist/src/utils/file-system.js +795 -89
  85. package/dist/src/utils/file-system.js.map +1 -1
  86. package/dist/src/utils/index.d.ts +9 -0
  87. package/dist/src/utils/index.d.ts.map +1 -0
  88. package/dist/src/utils/index.js +13 -0
  89. package/dist/src/utils/index.js.map +1 -0
  90. package/dist/src/utils/knowledge-generation.d.ts +79 -0
  91. package/dist/src/utils/knowledge-generation.d.ts.map +1 -0
  92. package/dist/src/utils/knowledge-generation.js +646 -0
  93. package/dist/src/utils/knowledge-generation.js.map +1 -0
  94. package/dist/src/utils/output-masking.d.ts.map +1 -1
  95. package/dist/src/utils/output-masking.js +2 -1
  96. package/dist/src/utils/output-masking.js.map +1 -1
  97. package/dist/src/utils/prompt-composition.d.ts +234 -0
  98. package/dist/src/utils/prompt-composition.d.ts.map +1 -0
  99. package/dist/src/utils/prompt-composition.js +379 -0
  100. package/dist/src/utils/prompt-composition.js.map +1 -0
  101. package/dist/src/utils/prompt-execution.d.ts +88 -0
  102. package/dist/src/utils/prompt-execution.d.ts.map +1 -0
  103. package/dist/src/utils/prompt-execution.js +227 -0
  104. package/dist/src/utils/prompt-execution.js.map +1 -0
  105. package/dist/src/utils/reflexion.d.ts +92 -0
  106. package/dist/src/utils/reflexion.d.ts.map +1 -0
  107. package/dist/src/utils/reflexion.js +1100 -0
  108. package/dist/src/utils/reflexion.js.map +1 -0
  109. package/dist/src/utils/research-integration.d.ts.map +1 -1
  110. package/dist/src/utils/research-integration.js +156 -100
  111. package/dist/src/utils/research-integration.js.map +1 -1
  112. package/dist/src/utils/research-questions.d.ts.map +1 -1
  113. package/dist/src/utils/research-questions.js +85 -24
  114. package/dist/src/utils/research-questions.js.map +1 -1
  115. package/dist/src/utils/rule-generation.d.ts.map +1 -1
  116. package/dist/src/utils/rule-generation.js +92 -108
  117. package/dist/src/utils/rule-generation.js.map +1 -1
  118. package/package.json +9 -3
@@ -1,44 +1,124 @@
1
1
  /**
2
2
  * MCP Tool for ADR suggestions and implicit decision detection
3
- * Implements prompt-driven ADR recommendation system
3
+ * Enhanced with Knowledge Generation and Reflexion capabilities
4
+ * Implements prompt-driven ADR recommendation system with learning
4
5
  */
5
6
  import { McpAdrError } from '../types/index.js';
7
+ import { generateArchitecturalKnowledge } from '../utils/knowledge-generation.js';
8
+ import { executeWithReflexion, retrieveRelevantMemories, createToolReflexionConfig } from '../utils/reflexion.js';
9
+ import { executeADRSuggestionPrompt, formatMCPResponse } from '../utils/prompt-execution.js';
6
10
  /**
7
- * Suggest ADRs based on project analysis
11
+ * Suggest ADRs based on project analysis with advanced prompting techniques
12
+ * Enhanced with Knowledge Generation and Reflexion learning capabilities
8
13
  */
9
14
  export async function suggestAdrs(args) {
10
- const { projectPath = process.cwd(), analysisType = 'comprehensive', beforeCode, afterCode, changeDescription, commitMessages, existingAdrs, } = args;
15
+ const { projectPath = process.cwd(), analysisType = 'comprehensive', beforeCode, afterCode, changeDescription, commitMessages, existingAdrs, enhancedMode = true, // Default to enhanced mode
16
+ learningEnabled = true, // Default to learning enabled
17
+ knowledgeEnhancement = true, // Default to knowledge enhancement
18
+ } = args;
11
19
  try {
12
20
  const { analyzeImplicitDecisions, analyzeCodeChanges } = await import('../utils/adr-suggestions.js');
13
21
  switch (analysisType) {
14
22
  case 'implicit_decisions': {
15
- const result = await analyzeImplicitDecisions(projectPath, existingAdrs);
23
+ let enhancedPrompt = '';
24
+ let enhancementInfo = '';
25
+ // Apply enhancements if enabled
26
+ if (enhancedMode && (knowledgeEnhancement || learningEnabled)) {
27
+ let knowledgeContext = '';
28
+ // Generate domain knowledge for implicit decision detection
29
+ if (knowledgeEnhancement) {
30
+ try {
31
+ const knowledgeResult = await generateArchitecturalKnowledge({
32
+ projectPath,
33
+ technologies: [],
34
+ patterns: [],
35
+ projectType: 'implicit-decision-detection'
36
+ }, {
37
+ domains: ['api-design', 'database-design'],
38
+ depth: 'basic',
39
+ cacheEnabled: true
40
+ });
41
+ knowledgeContext = `\n## Knowledge Enhancement\n${knowledgeResult.prompt}\n`;
42
+ }
43
+ catch (error) {
44
+ console.error('[WARNING] Knowledge generation failed:', error);
45
+ }
46
+ }
47
+ // Apply learning if enabled
48
+ if (learningEnabled) {
49
+ try {
50
+ const reflexionConfig = createToolReflexionConfig('suggest_adrs');
51
+ const baseResult = await analyzeImplicitDecisions(projectPath, existingAdrs);
52
+ const reflexionResult = await executeWithReflexion({
53
+ prompt: baseResult.analysisPrompt + knowledgeContext,
54
+ instructions: baseResult.instructions,
55
+ context: { projectPath, analysisType: 'implicit_decisions', existingAdrs }
56
+ }, reflexionConfig);
57
+ enhancedPrompt = reflexionResult.prompt;
58
+ enhancementInfo = `
59
+ ## Enhancement Status
60
+ - **Knowledge Generation**: ${knowledgeEnhancement ? '✅ Applied' : '❌ Disabled'}
61
+ - **Reflexion Learning**: ✅ Applied
62
+ - **Learning from**: Past implicit decision detection tasks
63
+
64
+ `;
65
+ }
66
+ catch (error) {
67
+ console.error('[WARNING] Reflexion enhancement failed:', error);
68
+ const result = await analyzeImplicitDecisions(projectPath, existingAdrs);
69
+ enhancedPrompt = result.analysisPrompt + knowledgeContext;
70
+ }
71
+ }
72
+ else {
73
+ const result = await analyzeImplicitDecisions(projectPath, existingAdrs);
74
+ enhancedPrompt = result.analysisPrompt + knowledgeContext;
75
+ enhancementInfo = `
76
+ ## Enhancement Status
77
+ - **Knowledge Generation**: ${knowledgeEnhancement ? '✅ Applied' : '❌ Disabled'}
78
+ - **Reflexion Learning**: ❌ Disabled
79
+
80
+ `;
81
+ }
82
+ }
83
+ else {
84
+ const result = await analyzeImplicitDecisions(projectPath, existingAdrs);
85
+ enhancedPrompt = result.analysisPrompt;
86
+ enhancementInfo = `
87
+ ## Enhancement Status
88
+ - **Enhanced Mode**: ❌ Disabled
89
+ - All advanced features are disabled for this analysis
90
+
91
+ `;
92
+ }
93
+ const baseResult = await analyzeImplicitDecisions(projectPath, existingAdrs);
16
94
  return {
17
95
  content: [
18
96
  {
19
97
  type: 'text',
20
- text: `# ADR Suggestions: Implicit Decisions Analysis
98
+ text: `# ADR Suggestions: Enhanced Implicit Decisions Analysis
21
99
 
22
- ${result.instructions}
100
+ ${enhancementInfo}
23
101
 
24
- ## AI Analysis Prompt
102
+ ${baseResult.instructions}
25
103
 
26
- ${result.analysisPrompt}
104
+ ## Enhanced AI Analysis Prompt
105
+
106
+ ${enhancedPrompt}
27
107
 
28
108
  ## Next Steps
29
109
 
30
- 1. **Submit the prompt** to an AI agent for comprehensive analysis
110
+ 1. **Submit the enhanced prompt** to an AI agent for comprehensive analysis
31
111
  2. **Review the detected decisions** and prioritize based on impact and risk
32
112
  3. **Use the \`generate_adr_from_decision\` tool** to create ADRs for high-priority decisions
33
113
  4. **Integrate with existing ADR workflow** for review and approval
34
114
 
35
115
  ## Expected Output
36
116
 
37
- The AI will identify implicit architectural decisions in your codebase and provide:
38
- - Detailed decision analysis with evidence
39
- - Priority and risk assessments
40
- - Suggested ADR titles and content
41
- - Recommendations for documentation strategy
117
+ The enhanced AI analysis will identify implicit architectural decisions and provide:
118
+ - Detailed decision analysis with evidence and domain knowledge
119
+ - Priority and risk assessments informed by past experiences
120
+ - Suggested ADR titles and content with improved quality
121
+ - Recommendations for documentation strategy based on learning
42
122
  `,
43
123
  },
44
124
  ],
@@ -48,74 +128,249 @@ The AI will identify implicit architectural decisions in your codebase and provi
48
128
  if (!beforeCode || !afterCode || !changeDescription) {
49
129
  throw new McpAdrError('Code change analysis requires beforeCode, afterCode, and changeDescription', 'INVALID_INPUT');
50
130
  }
51
- const result = await analyzeCodeChanges(beforeCode, afterCode, changeDescription, commitMessages);
131
+ let enhancedPrompt = '';
132
+ let enhancementInfo = '';
133
+ // Apply enhancements if enabled
134
+ if (enhancedMode && (knowledgeEnhancement || learningEnabled)) {
135
+ let knowledgeContext = '';
136
+ // Generate domain knowledge for code change analysis
137
+ if (knowledgeEnhancement) {
138
+ try {
139
+ const knowledgeResult = await generateArchitecturalKnowledge({
140
+ projectPath: projectPath || process.cwd(),
141
+ technologies: [],
142
+ patterns: [],
143
+ projectType: 'code-change-analysis'
144
+ }, {
145
+ domains: ['api-design', 'performance-optimization'],
146
+ depth: 'basic',
147
+ cacheEnabled: true
148
+ });
149
+ knowledgeContext = `\n## Knowledge Enhancement\n${knowledgeResult.prompt}\n`;
150
+ }
151
+ catch (error) {
152
+ console.error('[WARNING] Knowledge generation failed:', error);
153
+ }
154
+ }
155
+ // Apply learning if enabled
156
+ if (learningEnabled) {
157
+ try {
158
+ const reflexionConfig = createToolReflexionConfig('suggest_adrs', {
159
+ evaluationCriteria: ['task-success', 'accuracy', 'relevance']
160
+ });
161
+ const baseResult = await analyzeCodeChanges(beforeCode, afterCode, changeDescription, commitMessages);
162
+ const reflexionResult = await executeWithReflexion({
163
+ prompt: baseResult.analysisPrompt + knowledgeContext,
164
+ instructions: baseResult.instructions,
165
+ context: {
166
+ analysisType: 'code_changes',
167
+ changeDescription,
168
+ hasCommitMessages: !!commitMessages?.length
169
+ }
170
+ }, reflexionConfig);
171
+ enhancedPrompt = reflexionResult.prompt;
172
+ enhancementInfo = `
173
+ ## Enhancement Status
174
+ - **Knowledge Generation**: ${knowledgeEnhancement ? '✅ Applied' : '❌ Disabled'}
175
+ - **Reflexion Learning**: ✅ Applied
176
+ - **Learning from**: Past code change analysis tasks
177
+
178
+ `;
179
+ }
180
+ catch (error) {
181
+ console.error('[WARNING] Reflexion enhancement failed:', error);
182
+ const result = await analyzeCodeChanges(beforeCode, afterCode, changeDescription, commitMessages);
183
+ enhancedPrompt = result.analysisPrompt + knowledgeContext;
184
+ }
185
+ }
186
+ else {
187
+ const result = await analyzeCodeChanges(beforeCode, afterCode, changeDescription, commitMessages);
188
+ enhancedPrompt = result.analysisPrompt + knowledgeContext;
189
+ enhancementInfo = `
190
+ ## Enhancement Status
191
+ - **Knowledge Generation**: ${knowledgeEnhancement ? '✅ Applied' : '❌ Disabled'}
192
+ - **Reflexion Learning**: ❌ Disabled
193
+
194
+ `;
195
+ }
196
+ }
197
+ else {
198
+ const result = await analyzeCodeChanges(beforeCode, afterCode, changeDescription, commitMessages);
199
+ enhancedPrompt = result.analysisPrompt;
200
+ enhancementInfo = `
201
+ ## Enhancement Status
202
+ - **Enhanced Mode**: ❌ Disabled
203
+ - All advanced features are disabled for this analysis
204
+
205
+ `;
206
+ }
207
+ const baseResult = await analyzeCodeChanges(beforeCode, afterCode, changeDescription, commitMessages);
52
208
  return {
53
209
  content: [
54
210
  {
55
211
  type: 'text',
56
- text: `# ADR Suggestions: Code Change Analysis
212
+ text: `# ADR Suggestions: Enhanced Code Change Analysis
57
213
 
58
- ${result.instructions}
214
+ ${enhancementInfo}
215
+
216
+ ${baseResult.instructions}
59
217
 
60
- ## AI Analysis Prompt
218
+ ## Enhanced AI Analysis Prompt
61
219
 
62
- ${result.analysisPrompt}
220
+ ${enhancedPrompt}
63
221
 
64
222
  ## Next Steps
65
223
 
66
- 1. **Submit the prompt** to an AI agent for change analysis
224
+ 1. **Submit the enhanced prompt** to an AI agent for change analysis
67
225
  2. **Review the identified decisions** reflected in the code changes
68
226
  3. **Document significant decisions** as ADRs using the generation tool
69
227
  4. **Follow up with development team** for any clarification questions
70
228
 
71
229
  ## Expected Output
72
230
 
73
- The AI will analyze the code changes and provide:
74
- - Architectural decisions reflected in the changes
75
- - Change motivation and context analysis
76
- - Impact and risk assessment
77
- - Recommendations for documentation
231
+ The enhanced AI analysis will provide:
232
+ - Architectural decisions reflected in the changes with domain context
233
+ - Change motivation and context analysis informed by past experiences
234
+ - Impact and risk assessment with improved accuracy
235
+ - Recommendations for documentation based on learning patterns
78
236
  `,
79
237
  },
80
238
  ],
81
239
  };
82
240
  }
83
241
  case 'comprehensive': {
242
+ let enhancedPrompt = '';
243
+ let knowledgeContext = '';
244
+ let reflexionContext = '';
245
+ // Step 1: Generate domain-specific knowledge if enabled
246
+ if (knowledgeEnhancement) {
247
+ try {
248
+ const knowledgeResult = await generateArchitecturalKnowledge({
249
+ projectPath,
250
+ technologies: [], // Will be auto-detected from project
251
+ patterns: [],
252
+ projectType: 'software-architecture',
253
+ existingAdrs: existingAdrs || []
254
+ }, {
255
+ domains: ['api-design', 'database-design', 'microservices'],
256
+ depth: 'intermediate',
257
+ cacheEnabled: true
258
+ });
259
+ knowledgeContext = `
260
+ ## Domain-Specific Knowledge Enhancement
261
+
262
+ The following architectural knowledge has been generated to enhance ADR suggestions:
263
+
264
+ ${knowledgeResult.prompt}
265
+
266
+ ---
267
+ `;
268
+ }
269
+ catch (error) {
270
+ console.error('[WARNING] Knowledge generation failed:', error);
271
+ knowledgeContext = '<!-- Knowledge generation unavailable -->\n';
272
+ }
273
+ }
274
+ // Step 2: Apply Reflexion learning if enabled
275
+ if (learningEnabled) {
276
+ try {
277
+ // Retrieve relevant memories from past ADR suggestion tasks
278
+ const memoryResult = await retrieveRelevantMemories('adr-suggestion', { projectPath, analysisType: 'comprehensive', existingAdrs }, { maxResults: 5, relevanceThreshold: 0.6 });
279
+ reflexionContext = `
280
+ ## Learning from Past Experiences
281
+
282
+ The following insights from past ADR suggestion tasks will inform this analysis:
283
+
284
+ ${memoryResult.prompt}
285
+
286
+ ---
287
+ `;
288
+ }
289
+ catch (error) {
290
+ console.error('[WARNING] Reflexion memory retrieval failed:', error);
291
+ reflexionContext = '<!-- Learning context unavailable -->\n';
292
+ }
293
+ }
294
+ // Step 3: Get the base analysis
84
295
  const implicitResult = await analyzeImplicitDecisions(projectPath, existingAdrs);
85
- return {
86
- content: [
87
- {
88
- type: 'text',
89
- text: `# ADR Suggestions: Comprehensive Analysis
90
-
91
- This comprehensive analysis will identify all potential ADRs for your project.
296
+ // Step 4: Apply Reflexion execution if learning is enabled
297
+ if (learningEnabled) {
298
+ try {
299
+ const reflexionConfig = createToolReflexionConfig('suggest_adrs', {
300
+ reflectionDepth: 'detailed',
301
+ evaluationCriteria: ['task-success', 'relevance', 'clarity'],
302
+ learningRate: 0.7
303
+ });
304
+ const reflexionResult = await executeWithReflexion({
305
+ prompt: implicitResult.analysisPrompt,
306
+ instructions: implicitResult.instructions,
307
+ context: {
308
+ projectPath,
309
+ analysisType: 'comprehensive',
310
+ existingAdrs,
311
+ knowledgeEnhanced: knowledgeEnhancement,
312
+ learningEnabled: true
313
+ }
314
+ }, reflexionConfig);
315
+ enhancedPrompt = `
316
+ ## Enhanced Analysis with Learning
317
+
318
+ ${reflexionResult.prompt}
319
+
320
+ ---
321
+ `;
322
+ }
323
+ catch (error) {
324
+ console.error('[WARNING] Reflexion execution failed:', error);
325
+ enhancedPrompt = implicitResult.analysisPrompt;
326
+ }
327
+ }
328
+ else {
329
+ enhancedPrompt = implicitResult.analysisPrompt;
330
+ }
331
+ // Execute the analysis with AI if enabled, otherwise return prompt
332
+ const executionResult = await executeADRSuggestionPrompt(enhancedPrompt, implicitResult.instructions, {
333
+ temperature: 0.1,
334
+ maxTokens: 4000,
335
+ });
336
+ if (executionResult.isAIGenerated) {
337
+ // AI execution successful - return actual analysis results
338
+ return formatMCPResponse({
339
+ ...executionResult,
340
+ content: `# ADR Suggestions: AI Analysis Results
341
+
342
+ ## Enhancement Features
343
+ - **Knowledge Generation**: ${knowledgeEnhancement ? '✅ Enabled' : '❌ Disabled'}
344
+ - **Reflexion Learning**: ${learningEnabled ? '✅ Enabled' : '❌ Disabled'}
345
+ - **Enhanced Mode**: ${enhancedMode ? '✅ Enabled' : '❌ Disabled'}
92
346
 
93
347
  ## Project Analysis
94
348
  - **Project Path**: ${projectPath}
95
- - **Existing ADRs**: ${existingAdrs?.length || 0} ADRs found
96
- - **Analysis Type**: Comprehensive (implicit decisions + patterns)
349
+ - **Existing ADRs**: ${existingAdrs?.length || 0} ADRs provided
350
+ - **Analysis Type**: Comprehensive (AI-driven with enhancements)
97
351
 
98
- ## Implicit Decisions Analysis
352
+ ${knowledgeContext}
99
353
 
100
- ${implicitResult.instructions}
354
+ ${reflexionContext}
101
355
 
102
- ## AI Analysis Prompt
356
+ ## AI Analysis Results
103
357
 
104
- ${implicitResult.analysisPrompt}
358
+ ${executionResult.content}
105
359
 
106
- ## Recommended Workflow
360
+ ## Next Steps
107
361
 
108
- ### 1. **Initial Analysis**
109
- Submit the prompt above to get comprehensive decision detection
362
+ Based on the analysis above:
110
363
 
111
- ### 2. **Priority Review**
112
- - Focus on **high** and **critical** priority decisions first
113
- - Consider **risk level** and **complexity** for planning
114
- - Group related decisions using suggested clusters
364
+ 1. **Review Suggested ADRs**: Examine each suggested architectural decision
365
+ 2. **Prioritize by Impact**: Focus on high-impact decisions first
366
+ 3. **Generate ADRs**: Use the \`generate_adr_from_decision\` tool for priority decisions
367
+ 4. **Implement Changes**: Plan and execute the architectural changes
368
+ 5. **Update Documentation**: Keep ADRs current as decisions evolve
115
369
 
116
- ### 3. **ADR Generation**
117
- Use \`generate_adr_from_decision\` tool for each prioritized decision:
118
- \`\`\`
370
+ ## Integration Workflow
371
+
372
+ For each suggested decision, use:
373
+ \`\`\`json
119
374
  {
120
375
  "tool": "generate_adr_from_decision",
121
376
  "args": {
@@ -124,30 +379,68 @@ Use \`generate_adr_from_decision\` tool for each prioritized decision:
124
379
  "context": "Context from analysis",
125
380
  "decision": "Decision description",
126
381
  "consequences": "Consequences from analysis"
127
- },
128
- "templateFormat": "nygard",
129
- "existingAdrs": ["list of existing ADRs"]
382
+ }
130
383
  }
131
384
  }
132
385
  \`\`\`
386
+ `,
387
+ });
388
+ }
389
+ else {
390
+ // Fallback to prompt-only mode
391
+ return {
392
+ content: [
393
+ {
394
+ type: 'text',
395
+ text: `# ADR Suggestions: Enhanced Comprehensive Analysis
396
+
397
+ This enhanced analysis uses advanced prompting techniques to provide superior ADR suggestions.
398
+
399
+ ## Enhancement Features
400
+ - **Knowledge Generation**: ${knowledgeEnhancement ? '✅ Enabled' : '❌ Disabled'}
401
+ - **Reflexion Learning**: ${learningEnabled ? '✅ Enabled' : '❌ Disabled'}
402
+ - **Enhanced Mode**: ${enhancedMode ? '✅ Enabled' : '❌ Disabled'}
403
+
404
+ ## Project Analysis
405
+ - **Project Path**: ${projectPath}
406
+ - **Existing ADRs**: ${existingAdrs?.length || 0} ADRs provided
407
+ - **Analysis Type**: Comprehensive (AI-driven with enhancements)
408
+
409
+ ${knowledgeContext}
410
+
411
+ ${reflexionContext}
412
+
413
+ ## AI Analysis Instructions
414
+
415
+ ${implicitResult.instructions}
416
+
417
+ ## Enhanced AI Analysis Prompt
418
+
419
+ ${enhancedPrompt}
420
+
421
+ ## Recommended Workflow
422
+
423
+ ### 1. **Initial Analysis**
424
+ Submit the prompt above to get comprehensive decision detection
425
+
426
+ ### 2. **Priority Review**
427
+ - Focus on **high** and **critical** priority decisions first
428
+ - Consider **risk level** and **complexity** for planning
429
+ - Group related decisions using suggested clusters
430
+
431
+ ### 3. **ADR Generation**
432
+ Use \`generate_adr_from_decision\` tool for each prioritized decision
133
433
 
134
434
  ### 4. **Integration**
135
435
  - Save generated ADRs to your ADR directory
136
436
  - Update ADR index/catalog
137
437
  - Schedule team review sessions
138
438
  - Plan implementation tasks
139
-
140
- ## Expected Outcomes
141
-
142
- This analysis will help you:
143
- - **Identify undocumented decisions** in your architecture
144
- - **Prioritize documentation efforts** based on impact and risk
145
- - **Generate high-quality ADRs** using AI assistance
146
- - **Improve architectural governance** and decision tracking
147
439
  `,
148
- },
149
- ],
150
- };
440
+ },
441
+ ],
442
+ };
443
+ }
151
444
  }
152
445
  default:
153
446
  throw new McpAdrError(`Unknown analysis type: ${analysisType}`, 'INVALID_INPUT');
@@ -175,11 +468,79 @@ export async function generateAdrFromDecision(args) {
175
468
  const adrNumber = generateNextAdrNumber(existingAdrs);
176
469
  const filename = suggestAdrFilename(decisionData.title, adrNumber);
177
470
  const fullPath = `${adrDirectory}/${filename}`;
178
- return {
179
- content: [
180
- {
181
- type: 'text',
182
- text: `# ADR Generation: ${decisionData.title}
471
+ // Execute ADR generation with AI if enabled
472
+ const { executeADRGenerationPrompt } = await import('../utils/prompt-execution.js');
473
+ const executionResult = await executeADRGenerationPrompt(result.generationPrompt, result.instructions, {
474
+ temperature: 0.1,
475
+ maxTokens: 6000,
476
+ responseFormat: 'text',
477
+ });
478
+ if (executionResult.isAIGenerated) {
479
+ // AI execution successful - return actual ADR content
480
+ return formatMCPResponse({
481
+ ...executionResult,
482
+ content: `# Generated ADR: ${decisionData.title}
483
+
484
+ ## ADR Metadata
485
+ - **ADR Number**: ${adrNumber}
486
+ - **Filename**: ${filename}
487
+ - **Full Path**: ${fullPath}
488
+ - **Template Format**: ${templateFormat.toUpperCase()}
489
+
490
+ ## Generated ADR Content
491
+
492
+ ${executionResult.content}
493
+
494
+ ## File Creation Instructions
495
+
496
+ To save this ADR to your project:
497
+
498
+ 1. **Create the ADR directory** (if it doesn't exist):
499
+ \`\`\`bash
500
+ mkdir -p ${adrDirectory}
501
+ \`\`\`
502
+
503
+ 2. **Save the ADR content** to the file:
504
+ \`\`\`bash
505
+ cat > "${fullPath}" << 'EOF'
506
+ ${executionResult.content}
507
+ EOF
508
+ \`\`\`
509
+
510
+ 3. **Verify the file** was created successfully:
511
+ \`\`\`bash
512
+ ls -la "${fullPath}"
513
+ \`\`\`
514
+
515
+ ## Next Steps
516
+
517
+ 1. **Review the generated ADR** for accuracy and completeness
518
+ 2. **Save the file** using the instructions above
519
+ 3. **Update your ADR index** or catalog
520
+ 4. **Share with stakeholders** for review and approval
521
+ 5. **Plan implementation** of the architectural decision
522
+
523
+ ## Quality Checklist
524
+
525
+ - ✅ **Title** is clear and descriptive
526
+ - ✅ **Context** explains the problem and constraints
527
+ - ✅ **Decision** is specific and actionable
528
+ - ✅ **Consequences** cover both positive and negative impacts
529
+ - ✅ **Format** follows ${templateFormat.toUpperCase()} template standards
530
+ - ✅ **Numbering** is sequential (${adrNumber})
531
+ `,
532
+ });
533
+ }
534
+ else {
535
+ // Fallback to prompt-only mode
536
+ const { ensureDirectory, writeFile } = await import('../utils/file-system.js');
537
+ const ensureDirPrompt = await ensureDirectory(adrDirectory);
538
+ const writeFilePrompt = await writeFile(fullPath, '[ADR_CONTENT_PLACEHOLDER]');
539
+ return {
540
+ content: [
541
+ {
542
+ type: 'text',
543
+ text: `# ADR Generation: ${decisionData.title}
183
544
 
184
545
  ${result.instructions}
185
546
 
@@ -189,150 +550,178 @@ ${result.instructions}
189
550
  - **Full Path**: ${fullPath}
190
551
  - **Template Format**: ${templateFormat.toUpperCase()}
191
552
 
192
- ## AI Generation Prompt
553
+ ## Step 1: Create ADR Directory
554
+ ${ensureDirPrompt.prompt}
555
+
556
+ ## Step 2: Generate ADR Content
193
557
 
194
558
  ${result.generationPrompt}
195
559
 
196
- ## Next Steps
560
+ ## Step 3: Save ADR to File
197
561
 
198
- 1. **Submit the generation prompt** to an AI agent for ADR creation
199
- 2. **Review the generated ADR** for completeness and accuracy
200
- 3. **Save the ADR** to the suggested location: \`${fullPath}\`
201
- 4. **Update ADR index** and notify relevant stakeholders
202
- 5. **Schedule review** with architecture team
562
+ After generating the ADR content from Step 2, create the ADR file:
203
563
 
204
- ## Quality Checklist
564
+ ${writeFilePrompt.prompt}
205
565
 
206
- Before finalizing the ADR, ensure:
207
- - [ ] **Title** is clear and descriptive
208
- - [ ] **Context** explains the problem and constraints
209
- - [ ] **Decision** is specific and actionable
210
- - [ ] **Consequences** cover both positive and negative impacts
211
- - [ ] **Alternatives** are documented (if applicable)
212
- - [ ] **Evidence** supports the decision (if applicable)
213
- - [ ] **Format** follows team standards
214
- - [ ] **Numbering** is correct and sequential
215
-
216
- ## Integration Tips
217
-
218
- - Add the ADR to your project's ADR index
219
- - Link to related ADRs and documentation
220
- - Include implementation tasks in project planning
221
- - Schedule follow-up reviews for complex decisions
566
+ **Important**: Replace \`[ADR_CONTENT_PLACEHOLDER]\` with the actual generated ADR content from Step 2.
222
567
  `,
223
- },
224
- ],
225
- };
568
+ },
569
+ ],
570
+ };
571
+ }
226
572
  }
227
573
  catch (error) {
228
574
  throw new McpAdrError(`Failed to generate ADR: ${error instanceof Error ? error.message : String(error)}`, 'GENERATION_ERROR');
229
575
  }
230
576
  }
231
577
  /**
232
- * Discover existing ADRs in the project
578
+ * Generate prompt for AI to discover existing ADRs in the project
233
579
  */
234
580
  export async function discoverExistingAdrs(args) {
235
581
  const { adrDirectory = 'docs/adrs', includeContent = false } = args;
236
- try {
237
- const { findFiles } = await import('../utils/file-system.js');
238
- // Find all ADR files
239
- const adrFiles = await findFiles(process.cwd(), [`${adrDirectory}/**/*.md`], {
240
- includeContent,
241
- });
242
- if (adrFiles.length === 0) {
243
- return {
244
- content: [
245
- {
246
- type: 'text',
247
- text: `# ADR Discovery Results
582
+ // Create the discovery prompt
583
+ const discoveryPrompt = `
584
+ # ADR Discovery Request
248
585
 
249
- ## No ADRs Found
250
- No ADR files were found in the directory: \`${adrDirectory}\`
586
+ Please scan the project directory **${adrDirectory}** to discover existing ADRs.
251
587
 
252
- ## Suggestions
253
- 1. **Check directory path**: Ensure the ADR directory path is correct
254
- 2. **Initialize ADR directory**: Create the directory if it doesn't exist
255
- 3. **Use different pattern**: ADRs might be stored with different naming conventions
256
- 4. **Start fresh**: Begin documenting architectural decisions with new ADRs
588
+ ## Discovery Tasks
257
589
 
258
- ## Getting Started
259
- Use the \`suggest_adrs\` tool to identify decisions that should be documented:
260
- \`\`\`
590
+ 1. **Directory Scanning**
591
+ - Use file system tools to list all files in \`${adrDirectory}\`
592
+ - Look for files with \`.md\` extension
593
+ - Check for common ADR naming patterns (e.g., \`ADR-001-\`, \`001-\`, etc.)
594
+
595
+ 2. **Content Analysis** ${includeContent ? '(with content)' : '(metadata only)'}
596
+ - Read each ADR file to extract metadata
597
+ - Identify title, status, date, and key information
598
+ - ${includeContent ? 'Extract full content for analysis' : 'Focus on headers and metadata'}
599
+
600
+ 3. **ADR Inventory Generation**
601
+ - Create a list of all discovered ADRs
602
+ - Extract titles, statuses, and dates
603
+ - Generate a summary of the ADR collection
604
+
605
+ ## Search Patterns
606
+
607
+ Look for files matching these patterns:
608
+ - \`${adrDirectory}/**/*.md\`
609
+ - Files starting with numbers (e.g., \`001-\`, \`0001-\`)
610
+ - Files containing "ADR" in the name
611
+ - Files with architectural decision keywords
612
+
613
+ ## Alternative Locations
614
+
615
+ If no ADRs are found in \`${adrDirectory}\`, also check:
616
+ - \`docs/\` directory
617
+ - \`documentation/\` directory
618
+ - \`decisions/\` directory
619
+ - Root directory for isolated ADR files
620
+
621
+ ## Output Format
622
+
623
+ Provide findings in JSON format with:
624
+ - discoveryResults: directory, totalAdrs, adrs array
625
+ - summary: byStatus and byCategory breakdowns
626
+ - recommendations: next steps based on discovered ADRs
627
+ `;
628
+ const instructions = `
629
+ # ADR Discovery Instructions
630
+
631
+ 1. **Scan Directory**: Use file system tools to scan ${adrDirectory}
632
+ 2. **Identify ADRs**: Look for markdown files with ADR patterns
633
+ 3. **Extract Metadata**: Get title, status, date from each ADR
634
+ 4. **Generate Summary**: Create categorized summary of findings
635
+ 5. **Provide Recommendations**: Suggest next steps based on discovery
636
+
637
+ ## Expected Output
638
+
639
+ Return a comprehensive JSON object with discovery results, summary statistics, and actionable recommendations.
640
+ `;
641
+ // Execute the ADR discovery with AI if enabled, otherwise return prompt
642
+ const { executePromptWithFallback, formatMCPResponse } = await import('../utils/prompt-execution.js');
643
+ const executionResult = await executePromptWithFallback(discoveryPrompt, instructions, {
644
+ temperature: 0.1,
645
+ maxTokens: 4000,
646
+ systemPrompt: `You are an expert in architectural documentation analysis and file system operations.
647
+ Scan the specified directory to discover existing ADRs and provide comprehensive analysis.
648
+ Focus on extracting accurate metadata and providing actionable insights about the ADR collection.
649
+ Use appropriate file system tools to scan directories and read file contents.`,
650
+ responseFormat: 'text'
651
+ });
652
+ if (executionResult.isAIGenerated) {
653
+ // AI execution successful - return actual ADR discovery results
654
+ return formatMCPResponse({
655
+ ...executionResult,
656
+ content: `# ADR Discovery Results
657
+
658
+ ## Discovery Information
659
+ - **ADR Directory**: ${adrDirectory}
660
+ - **Include Content**: ${includeContent ? 'Yes' : 'No (metadata only)'}
661
+
662
+ ## AI Discovery Results
663
+
664
+ ${executionResult.content}
665
+
666
+ ## Next Steps
667
+
668
+ Based on the discovered ADRs:
669
+
670
+ 1. **Review ADR Collection**: Examine the discovered ADRs for completeness
671
+ 2. **Identify Gaps**: Look for missing architectural decisions
672
+ 3. **Update Outdated ADRs**: Review and update deprecated or outdated decisions
673
+ 4. **Generate New ADRs**: Use discovered patterns to suggest new ADRs
674
+ 5. **Create ADR Index**: Maintain an up-to-date catalog of all ADRs
675
+
676
+ ## Integration Commands
677
+
678
+ To suggest new ADRs based on discovered ones:
679
+ \`\`\`json
261
680
  {
262
681
  "tool": "suggest_adrs",
263
682
  "args": {
683
+ "existingAdrs": ["list of discovered ADR titles"],
264
684
  "analysisType": "comprehensive"
265
685
  }
266
686
  }
267
687
  \`\`\`
688
+
689
+ To generate a todo list from discovered ADRs:
690
+ \`\`\`json
691
+ {
692
+ "tool": "generate_adr_todo",
693
+ "args": {
694
+ "adrDirectory": "${adrDirectory}",
695
+ "scope": "all"
696
+ }
697
+ }
698
+ \`\`\`
268
699
  `,
269
- },
270
- ],
271
- };
272
- }
273
- // Extract ADR metadata
274
- const adrList = adrFiles.map(file => {
275
- const titleMatch = file.content?.match(/^#\s+(.+)$/m);
276
- const statusMatch = file.content?.match(/##\s+Status\s*\n\s*(.+)/i);
277
- const dateMatch = file.content?.match(/\b(\d{4}-\d{2}-\d{2})\b/);
278
- return {
279
- filename: file.name,
280
- path: file.path,
281
- title: titleMatch?.[1] || file.name.replace(/\.md$/, ''),
282
- status: statusMatch?.[1] || 'Unknown',
283
- date: dateMatch?.[1] || 'Unknown',
284
- size: file.size,
285
- };
286
700
  });
701
+ }
702
+ else {
703
+ // Fallback to prompt-only mode
287
704
  return {
288
705
  content: [
289
706
  {
290
707
  type: 'text',
291
- text: `# ADR Discovery Results
292
-
293
- ## Summary
294
- - **Directory**: ${adrDirectory}
295
- - **Total ADRs**: ${adrFiles.length}
296
- - **Total Size**: ${adrFiles.reduce((sum, f) => sum + (f.size || 0), 0)} bytes
297
-
298
- ## Discovered ADRs
299
- ${adrList
300
- .map((adr, index) => `
301
- ### ${index + 1}. ${adr.title}
302
- - **File**: ${adr.filename}
303
- - **Path**: ${adr.path}
304
- - **Status**: ${adr.status}
305
- - **Date**: ${adr.date}
306
- - **Size**: ${adr.size} bytes
307
- `)
308
- .join('')}
309
-
310
- ## ADR Titles (for reference)
311
- ${adrList.map(adr => `- ${adr.title}`).join('\n')}
708
+ text: `# ADR Discovery: AI-Driven Scan
709
+
710
+ ## Instructions for AI Agent
711
+
712
+ Please scan the project directory **${adrDirectory}** to discover existing ADRs.
713
+
714
+ ${discoveryPrompt}
715
+
716
+ ${instructions}
312
717
 
313
718
  ## Next Steps
314
- 1. **Review existing ADRs** for completeness and currency
315
- 2. **Identify gaps** using the \`suggest_adrs\` tool
316
- 3. **Update outdated ADRs** as needed
317
- 4. **Establish ADR workflow** for future decisions
318
719
 
319
- ## Usage with ADR Tools
320
- Use the discovered ADR titles with other tools:
321
- \`\`\`
322
- {
323
- "tool": "suggest_adrs",
324
- "args": {
325
- "existingAdrs": [${adrList.map(adr => `"${adr.title}"`).join(', ')}]
326
- }
327
- }
328
- \`\`\`
720
+ After discovery, use the results with other ADR tools for comprehensive analysis.
329
721
  `,
330
722
  },
331
723
  ],
332
724
  };
333
725
  }
334
- catch (error) {
335
- throw new McpAdrError(`Failed to discover ADRs: ${error instanceof Error ? error.message : String(error)}`, 'DISCOVERY_ERROR');
336
- }
337
726
  }
338
727
  //# sourceMappingURL=adr-suggestion-tool.js.map