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,22 +1,20 @@
1
1
  /**
2
2
  * File system utilities for MCP ADR Analysis Server
3
- * Handles file discovery, reading, and analysis operations
3
+ * Generates prompts for AI-driven file discovery, reading, and analysis operations
4
4
  */
5
- import { promises as fs } from 'fs';
6
- import { extname, basename, dirname } from 'path';
7
- import { glob } from 'fast-glob';
5
+ import { dirname } from 'path';
8
6
  import { FileSystemError } from '../types/index.js';
9
7
  /**
10
- * Discover and analyze project structure
8
+ * Generate prompt for AI-driven project structure analysis
11
9
  */
12
10
  export async function analyzeProjectStructure(projectPath) {
13
11
  try {
14
- // Verify project path exists
15
- const stats = await fs.stat(projectPath);
16
- if (!stats.isDirectory()) {
17
- throw new FileSystemError(`Path is not a directory: ${projectPath}`);
18
- }
19
- // Discover all files (excluding common ignore patterns)
12
+ console.error(`[DEBUG] Starting prompt generation for project path: ${projectPath}`);
13
+ // Pure prompt-driven approach - delegate all path resolution and validation to AI
14
+ const safeProjectPath = projectPath || '.';
15
+ console.error(`[DEBUG] Using prompt-driven analysis for path: ${safeProjectPath}`);
16
+ // Note: Path validation is delegated to the AI agent that will perform the actual scanning
17
+ // Define file patterns for analysis
20
18
  const filePatterns = [
21
19
  '**/*',
22
20
  '!node_modules/**',
@@ -27,128 +25,836 @@ export async function analyzeProjectStructure(projectPath) {
27
25
  '!.mcp-adr-cache/**',
28
26
  '!*.log',
29
27
  ];
30
- const filePaths = await glob(filePatterns, {
31
- cwd: projectPath,
32
- absolute: true,
33
- onlyFiles: true,
34
- });
35
- const directoryPaths = await glob(['**/*'], {
36
- cwd: projectPath,
37
- absolute: true,
38
- onlyDirectories: true,
39
- });
40
- // Process file information
41
- const files = [];
42
- for (const filePath of filePaths) {
43
- try {
44
- const fileStats = await fs.stat(filePath);
45
- const relativePath = filePath.replace(projectPath + '/', '');
46
- files.push({
47
- path: relativePath,
48
- name: basename(filePath),
49
- extension: extname(filePath),
50
- size: fileStats.size,
51
- directory: dirname(relativePath),
52
- });
53
- }
54
- catch (error) {
55
- // Skip files that can't be accessed
56
- continue;
57
- }
58
- }
28
+ console.error(`[DEBUG] Generated prompt for file patterns:`, filePatterns);
29
+ console.error(`[DEBUG] Target directory: ${safeProjectPath}`);
30
+ // Generate comprehensive analysis prompt
31
+ const prompt = `
32
+ # Project Structure Analysis Request
33
+
34
+ Please analyze the project structure at: **${safeProjectPath}**
35
+
36
+ ## Path Resolution Instructions
37
+
38
+ The AI agent should:
39
+ 1. **Resolve the project path safely**: If path is "." or "./", use the current working directory
40
+ 2. **Validate path security**: Ensure the path is not a system directory (/, /usr, /bin, etc.)
41
+ 3. **Handle relative paths**: Resolve relative paths from the current working directory
42
+ 4. **Prevent unauthorized access**: Reject any attempts to scan system or sensitive directories
43
+
44
+ ## Prerequisites
45
+
46
+ 1. **Path Validation**: First verify the path exists and is accessible
47
+ - Check if the path exists and is a directory
48
+ - Report any access issues or invalid paths
49
+ - Proceed with analysis only if the path is valid
50
+
51
+ ## Analysis Requirements
52
+
53
+ 2. **File Discovery**: Scan the directory using the following patterns:
54
+ ${filePatterns.map(pattern => ` - ${pattern}`).join('\n')}
55
+
56
+ 3. **Technology Stack Detection**: Identify:
57
+ - Programming languages (based on file extensions)
58
+ - Frameworks and libraries (from package.json, requirements.txt, etc.)
59
+ - Build tools and configuration files
60
+ - Testing frameworks and tools
61
+
62
+ 4. **Architectural Patterns**: Analyze:
63
+ - Directory structure and organization
64
+ - Code organization patterns (MVC, microservices, etc.)
65
+ - Configuration management approaches
66
+ - Documentation patterns
67
+
68
+ 5. **Project Ecosystem**: Examine:
69
+ - Dependencies and package management
70
+ - Development tools and workflows
71
+ - CI/CD configurations
72
+ - Documentation and README files
73
+
74
+ ## Expected Output Format
75
+
76
+ Please provide a structured analysis including:
77
+
78
+ \`\`\`json
79
+ {
80
+ "rootPath": "<resolved-absolute-path>",
81
+ "totalFiles": <number>,
82
+ "totalDirectories": <number>,
83
+ "technologies": [
84
+ {
85
+ "name": "technology_name",
86
+ "type": "language|framework|tool",
87
+ "confidence": 0.95,
88
+ "evidence": ["file1.ext", "config.json"]
89
+ }
90
+ ],
91
+ "patterns": [
92
+ {
93
+ "name": "pattern_name",
94
+ "type": "architectural|organizational",
95
+ "description": "pattern description",
96
+ "evidence": ["directory_structure", "file_patterns"]
97
+ }
98
+ ],
99
+ "files": [
100
+ {
101
+ "path": "relative/path/to/file",
102
+ "name": "filename.ext",
103
+ "extension": ".ext",
104
+ "directory": "relative/path/to",
105
+ "category": "source|config|documentation|test"
106
+ }
107
+ ],
108
+ "directories": ["dir1", "dir2/subdir"],
109
+ "summary": "Brief project description and key findings"
110
+ }
111
+ \`\`\`
112
+
113
+ ## Analysis Instructions
114
+
115
+ 1. Start by scanning the resolved project directory (safely resolve the provided path)
116
+ 2. Apply the file patterns to exclude unnecessary files
117
+ 3. Categorize files by type and purpose
118
+ 4. Identify technology stack from file extensions and configuration files
119
+ 5. Analyze directory structure for architectural patterns
120
+ 6. Provide confidence scores for technology detection
121
+ 7. Include evidence for all findings
122
+ `;
123
+ const instructions = `
124
+ ## Implementation Steps
125
+
126
+ 1. **Directory Scanning**: Use appropriate file system tools to scan the resolved project path
127
+ 2. **Pattern Filtering**: Apply exclusion patterns: ${filePatterns.filter(p => p.startsWith('!')).join(', ')}
128
+ 3. **File Analysis**: Examine file extensions, names, and content (for config files)
129
+ 4. **Technology Detection**: Look for package.json, requirements.txt, Cargo.toml, etc.
130
+ 5. **Pattern Recognition**: Analyze directory structure and file organization
131
+ 6. **Result Compilation**: Format findings according to the specified JSON structure
132
+
133
+ ## Safety Checks
134
+
135
+ - ✅ Path resolution delegated to AI agent with security validation
136
+ - ✅ System directory protection enabled
137
+ - ✅ File patterns defined for efficient scanning
138
+ - ✅ Exclusion patterns prevent scanning large/unnecessary directories
139
+
140
+ ## Context Information
141
+
142
+ - **Project Path**: ${safeProjectPath}
143
+ - **Analysis Type**: Comprehensive project ecosystem analysis
144
+ - **Output Format**: Structured JSON with technology stack and architectural patterns
145
+ `;
59
146
  return {
60
- rootPath: projectPath,
61
- files,
62
- directories: directoryPaths.map(dir => dir.replace(projectPath + '/', '')),
63
- totalFiles: files.length,
64
- totalDirectories: directoryPaths.length,
147
+ prompt,
148
+ instructions,
149
+ context: {
150
+ projectPath: safeProjectPath,
151
+ absoluteProjectPath: 'resolved-by-ai-agent',
152
+ filePatterns
153
+ }
65
154
  };
66
155
  }
67
156
  catch (error) {
68
- throw new FileSystemError(`Failed to analyze project structure: ${error instanceof Error ? error.message : String(error)}`, { projectPath });
157
+ // If it's already a FileSystemError, re-throw it to preserve the specific error message
158
+ if (error instanceof FileSystemError) {
159
+ throw error;
160
+ }
161
+ throw new FileSystemError(`Failed to generate project analysis prompt: ${error instanceof Error ? error.message : String(error)}`, { projectPath, absoluteProjectPath: 'resolved-by-ai-agent' });
69
162
  }
70
163
  }
71
164
  /**
72
- * Read file content safely
165
+ * Generate prompt for AI-driven file content reading
73
166
  */
74
167
  export async function readFileContent(filePath) {
75
168
  try {
76
- return await fs.readFile(filePath, 'utf-8');
169
+ console.error(`[DEBUG] Generating file read prompt for: ${filePath}`);
170
+ // Pure prompt-driven approach - delegate file reading to AI agent
171
+ const safeFilePath = filePath || '';
172
+ const prompt = `
173
+ # File Content Reading Request
174
+
175
+ Please read the content of the file: **${safeFilePath}**
176
+
177
+ ## Path Security Validation
178
+
179
+ The AI agent must:
180
+ 1. **Validate file path security**: Ensure the path is not a system directory (/, /usr, /bin, /etc, /var, /tmp, etc.)
181
+ 2. **Resolve relative paths safely**: Handle relative paths from the current working directory
182
+ 3. **Prevent unauthorized access**: Reject attempts to read sensitive system files or directories outside the project scope
183
+ 4. **Validate file existence**: Check if the file exists before attempting to read
184
+
185
+ ## File Reading Requirements
186
+
187
+ 1. **Safe File Access**: Read the file content using appropriate file system tools
188
+ 2. **Encoding Handling**: Read the file as UTF-8 text content
189
+ 3. **Error Handling**: Provide clear error messages for:
190
+ - File not found
191
+ - Permission denied
192
+ - Invalid file path
193
+ - Binary files or unsupported formats
194
+
195
+ ## Expected Output Format
196
+
197
+ \`\`\`json
198
+ {
199
+ "success": true,
200
+ "filePath": "${safeFilePath}",
201
+ "content": "file content as string",
202
+ "metadata": {
203
+ "size": <file_size_in_bytes>,
204
+ "encoding": "utf-8",
205
+ "lastModified": "ISO_timestamp"
206
+ },
207
+ "security": {
208
+ "pathValidated": true,
209
+ "accessAuthorized": true,
210
+ "systemDirectoryCheck": "passed"
211
+ }
212
+ }
213
+ \`\`\`
214
+
215
+ ## Error Response Format (if file cannot be read)
216
+
217
+ \`\`\`json
218
+ {
219
+ "success": false,
220
+ "filePath": "${safeFilePath}",
221
+ "error": "detailed error message",
222
+ "errorType": "FILE_NOT_FOUND|PERMISSION_DENIED|INVALID_PATH|SECURITY_VIOLATION",
223
+ "security": {
224
+ "pathValidated": boolean,
225
+ "accessAuthorized": boolean,
226
+ "systemDirectoryCheck": "passed|failed",
227
+ "rejectionReason": "specific reason if access denied"
228
+ }
229
+ }
230
+ \`\`\`
231
+ `;
232
+ const instructions = `
233
+ ## Implementation Steps
234
+
235
+ 1. **Security Validation**:
236
+ - Validate the file path: ${safeFilePath}
237
+ - Ensure it's not a system directory or sensitive location
238
+ - Check for path traversal attempts (../, .\\, etc.)
239
+
240
+ 2. **File Access**:
241
+ - Check if the file exists and is readable
242
+ - Verify file permissions allow reading
243
+ - Handle symbolic links safely
244
+
245
+ 3. **Content Reading**:
246
+ - Read file content as UTF-8 text
247
+ - Handle large files appropriately
248
+ - Detect and handle binary files
249
+
250
+ 4. **Response Generation**:
251
+ - Format response according to the specified JSON structure
252
+ - Include comprehensive metadata and security validation results
253
+ - Provide detailed error information if reading fails
254
+
255
+ ## Safety Checks
256
+
257
+ - ✅ Path security validation delegated to AI agent
258
+ - ✅ System directory protection enabled
259
+ - ✅ File access permission validation required
260
+ - ✅ Comprehensive error handling specified
261
+
262
+ ## Context Information
263
+
264
+ - **File Path**: ${safeFilePath}
265
+ - **Operation**: Safe file content reading
266
+ - **Security Level**: High (with path validation and access control)
267
+ `;
268
+ return {
269
+ prompt,
270
+ instructions,
271
+ context: {
272
+ filePath: safeFilePath,
273
+ operation: 'file_read',
274
+ securityLevel: 'high',
275
+ expectedFormat: 'json'
276
+ }
277
+ };
77
278
  }
78
279
  catch (error) {
79
- throw new FileSystemError(`Failed to read file: ${error instanceof Error ? error.message : String(error)}`, { filePath });
280
+ throw new FileSystemError(`Failed to generate file read prompt: ${error instanceof Error ? error.message : String(error)}`, { filePath });
80
281
  }
81
282
  }
82
283
  /**
83
- * Find files matching specific patterns
284
+ * Generate prompt for AI-driven file discovery
84
285
  */
85
286
  export async function findFiles(projectPath, patterns, options = {}) {
86
287
  try {
87
- const filePaths = await glob(patterns, {
88
- cwd: projectPath,
89
- absolute: true,
90
- });
91
- const files = [];
92
- for (const filePath of filePaths) {
93
- try {
94
- const fileStats = await fs.stat(filePath);
95
- const relativePath = filePath.replace(projectPath + '/', '');
96
- const fileInfo = {
97
- path: relativePath,
98
- name: basename(filePath),
99
- extension: extname(filePath),
100
- size: fileStats.size,
101
- directory: dirname(relativePath),
102
- };
103
- if (options.includeContent) {
104
- fileInfo.content = await readFileContent(filePath);
105
- }
106
- files.push(fileInfo);
107
- }
108
- catch (error) {
109
- // Skip files that can't be accessed
110
- continue;
288
+ // Pure prompt-driven approach - delegate all path resolution and validation to AI
289
+ const safeProjectPath = projectPath || '.';
290
+ const prompt = `
291
+ # File Discovery Request
292
+
293
+ Please find files matching the specified patterns in: **${safeProjectPath}**
294
+
295
+ ## Path Resolution Instructions
296
+ 1. **Safely resolve the project path**: If path is "." or "./", use the current working directory
297
+ 2. **Validate path security**: Ensure the path is not a system directory (/, /usr, /bin, etc.)
298
+ 3. **Handle relative paths**: Resolve relative paths from the current working directory
299
+
300
+ ## Search Patterns
301
+ ${patterns.map(pattern => `- ${pattern}`).join('\n')}
302
+
303
+ ## Requirements
304
+ - Search in the resolved directory (safely resolve ${safeProjectPath})
305
+ - Apply patterns to filter files
306
+ - ${options.includeContent ? 'Include file content in results' : 'Return file metadata only'}
307
+
308
+ ## Expected Output Format
309
+
310
+ \`\`\`json
311
+ {
312
+ "files": [
313
+ {
314
+ "path": "relative/path/to/file",
315
+ "name": "filename.ext",
316
+ "extension": ".ext",
317
+ "size": 1234,
318
+ "directory": "relative/path/to"${options.includeContent ? ',\n "content": "file content here"' : ''}
319
+ }
320
+ ],
321
+ "totalFiles": <number>,
322
+ "searchPatterns": ${JSON.stringify(patterns)},
323
+ "searchPath": "<resolved-absolute-path>"
324
+ }
325
+ \`\`\`
326
+ `;
327
+ const instructions = `
328
+ ## Implementation Steps
329
+ 1. Scan the resolved directory (safely resolve ${safeProjectPath})
330
+ 2. Apply patterns: ${patterns.join(', ')}
331
+ 3. Collect file metadata (name, size, extension, path)
332
+ ${options.includeContent ? '4. Read and include file content' : '4. Skip file content reading'}
333
+ 5. Format results as JSON
334
+
335
+ ## Context
336
+ - Base directory: ${safeProjectPath}
337
+ - Include content: ${options.includeContent || false}
338
+ - Pattern count: ${patterns.length}
339
+ `;
340
+ return {
341
+ prompt,
342
+ instructions,
343
+ context: {
344
+ projectPath: safeProjectPath,
345
+ absoluteProjectPath: 'resolved-by-ai-agent',
346
+ patterns,
347
+ includeContent: options.includeContent || false
111
348
  }
112
- }
113
- return files;
349
+ };
114
350
  }
115
351
  catch (error) {
116
- throw new FileSystemError(`Failed to find files: ${error instanceof Error ? error.message : String(error)}`, { projectPath, patterns });
352
+ throw new FileSystemError(`Failed to generate file discovery prompt: ${error instanceof Error ? error.message : String(error)}`, { projectPath, patterns });
117
353
  }
118
354
  }
119
355
  /**
120
- * Check if file exists
356
+ * Generate prompt for AI-driven file existence check
121
357
  */
122
358
  export async function fileExists(filePath) {
123
359
  try {
124
- await fs.access(filePath);
125
- return true;
360
+ console.error(`[DEBUG] Generating file existence check prompt for: ${filePath}`);
361
+ // Pure prompt-driven approach - delegate file existence check to AI agent
362
+ const safeFilePath = filePath || '';
363
+ const prompt = `
364
+ # File Existence Check Request
365
+
366
+ Please check if the file exists: **${safeFilePath}**
367
+
368
+ ## Path Security Validation
369
+
370
+ The AI agent must:
371
+ 1. **Validate file path security**: Ensure the path is not a system directory (/, /usr, /bin, /etc, /var, /tmp, etc.)
372
+ 2. **Resolve relative paths safely**: Handle relative paths from the current working directory
373
+ 3. **Prevent unauthorized access**: Reject attempts to check sensitive system files or directories outside the project scope
374
+ 4. **Validate path format**: Check for valid file path format and reject malicious patterns
375
+
376
+ ## File Existence Check Requirements
377
+
378
+ 1. **Safe Path Resolution**: Resolve the file path using appropriate file system tools
379
+ 2. **Access Validation**: Check if the file exists and is accessible
380
+ 3. **Security Compliance**: Ensure the check doesn't expose sensitive information
381
+ 4. **Error Handling**: Handle various scenarios:
382
+ - File exists and is accessible
383
+ - File does not exist
384
+ - Path is invalid or malformed
385
+ - Permission denied
386
+ - Path points to a directory instead of a file
387
+
388
+ ## Expected Output Format
389
+
390
+ \`\`\`json
391
+ {
392
+ "success": true,
393
+ "filePath": "${safeFilePath}",
394
+ "exists": true,
395
+ "metadata": {
396
+ "type": "file|directory|symlink",
397
+ "accessible": true,
398
+ "lastChecked": "ISO_timestamp"
399
+ },
400
+ "security": {
401
+ "pathValidated": true,
402
+ "accessAuthorized": true,
403
+ "systemDirectoryCheck": "passed"
404
+ }
405
+ }
406
+ \`\`\`
407
+
408
+ ## Response Format for Non-Existent File
409
+
410
+ \`\`\`json
411
+ {
412
+ "success": true,
413
+ "filePath": "${safeFilePath}",
414
+ "exists": false,
415
+ "metadata": {
416
+ "type": null,
417
+ "accessible": false,
418
+ "lastChecked": "ISO_timestamp"
419
+ },
420
+ "security": {
421
+ "pathValidated": true,
422
+ "accessAuthorized": true,
423
+ "systemDirectoryCheck": "passed"
424
+ }
425
+ }
426
+ \`\`\`
427
+
428
+ ## Error Response Format (for security violations or invalid paths)
429
+
430
+ \`\`\`json
431
+ {
432
+ "success": false,
433
+ "filePath": "${safeFilePath}",
434
+ "exists": false,
435
+ "error": "detailed error message",
436
+ "errorType": "INVALID_PATH|SECURITY_VIOLATION|PERMISSION_DENIED|MALFORMED_PATH",
437
+ "security": {
438
+ "pathValidated": boolean,
439
+ "accessAuthorized": boolean,
440
+ "systemDirectoryCheck": "passed|failed",
441
+ "rejectionReason": "specific reason if access denied"
442
+ }
443
+ }
444
+ \`\`\`
445
+ `;
446
+ const instructions = `
447
+ ## Implementation Steps
448
+
449
+ 1. **Security Validation**:
450
+ - Validate the file path: ${safeFilePath}
451
+ - Ensure it's not a system directory or sensitive location
452
+ - Check for path traversal attempts (../, .\\, etc.)
453
+ - Validate path format and reject malicious patterns
454
+
455
+ 2. **Path Resolution**:
456
+ - Resolve relative paths from the current working directory
457
+ - Handle symbolic links appropriately
458
+ - Normalize path separators for the operating system
459
+
460
+ 3. **Existence Check**:
461
+ - Check if the file exists at the resolved path
462
+ - Determine if it's a file, directory, or symbolic link
463
+ - Verify accessibility without reading content
464
+
465
+ 4. **Response Generation**:
466
+ - Format response according to the specified JSON structure
467
+ - Include comprehensive metadata and security validation results
468
+ - Provide clear boolean result in the "exists" field
469
+ - Include detailed error information if check fails
470
+
471
+ ## Safety Checks
472
+
473
+ - ✅ Path security validation delegated to AI agent
474
+ - ✅ System directory protection enabled
475
+ - ✅ File access permission validation required
476
+ - ✅ Comprehensive error handling specified
477
+ - ✅ Boolean result format clearly defined
478
+
479
+ ## Context Information
480
+
481
+ - **File Path**: ${safeFilePath}
482
+ - **Operation**: Safe file existence check
483
+ - **Security Level**: High (with path validation and access control)
484
+ - **Expected Result**: Boolean existence status with metadata
485
+ `;
486
+ return {
487
+ prompt,
488
+ instructions,
489
+ context: {
490
+ filePath: safeFilePath,
491
+ operation: 'file_exists_check',
492
+ securityLevel: 'high',
493
+ expectedFormat: 'json',
494
+ resultType: 'boolean'
495
+ }
496
+ };
126
497
  }
127
- catch {
128
- return false;
498
+ catch (error) {
499
+ throw new FileSystemError(`Failed to generate file existence check prompt: ${error instanceof Error ? error.message : String(error)}`, { filePath });
129
500
  }
130
501
  }
131
502
  /**
132
- * Ensure directory exists
503
+ * Generate prompt for AI-driven directory creation
133
504
  */
134
505
  export async function ensureDirectory(dirPath) {
135
506
  try {
136
- await fs.mkdir(dirPath, { recursive: true });
507
+ console.error(`[DEBUG] Generating directory creation prompt for: ${dirPath}`);
508
+ // Pure prompt-driven approach - delegate directory creation to AI agent
509
+ const safeDirPath = dirPath || '';
510
+ const prompt = `
511
+ # Directory Creation Request
512
+
513
+ Please ensure the directory exists: **${safeDirPath}**
514
+
515
+ ## Path Security Validation
516
+
517
+ The AI agent must:
518
+ 1. **Validate directory path security**: Ensure the path is not a system directory (/, /usr, /bin, /etc, /var, /tmp, etc.)
519
+ 2. **Resolve relative paths safely**: Handle relative paths from the current working directory
520
+ 3. **Prevent unauthorized access**: Reject attempts to create directories in sensitive system locations
521
+ 4. **Validate path format**: Check for valid directory path format and reject malicious patterns
522
+
523
+ ## Directory Creation Requirements
524
+
525
+ 1. **Safe Path Resolution**: Resolve the directory path using appropriate file system tools
526
+ 2. **Recursive Creation**: Create parent directories if they don't exist (recursive: true)
527
+ 3. **Permission Handling**: Ensure appropriate permissions for directory creation
528
+ 4. **Error Handling**: Handle various scenarios:
529
+ - Directory already exists (success)
530
+ - Parent directories don't exist (create them)
531
+ - Permission denied
532
+ - Invalid path or malformed directory name
533
+ - Disk space issues
534
+
535
+ ## Action Confirmation Required
536
+
537
+ Before creating any directories, confirm the action with the user:
538
+
539
+ **Action**: Create directory structure
540
+ **Target**: ${safeDirPath}
541
+ **Type**: Directory creation (recursive)
542
+ **Impact**: Creates directory and any missing parent directories
543
+
544
+ ## Expected Output Format
545
+
546
+ \`\`\`json
547
+ {
548
+ "success": true,
549
+ "dirPath": "${safeDirPath}",
550
+ "created": true,
551
+ "metadata": {
552
+ "type": "directory",
553
+ "recursive": true,
554
+ "permissions": "755",
555
+ "createdAt": "ISO_timestamp"
556
+ },
557
+ "security": {
558
+ "pathValidated": true,
559
+ "accessAuthorized": true,
560
+ "systemDirectoryCheck": "passed"
561
+ },
562
+ "confirmation": {
563
+ "actionConfirmed": true,
564
+ "userApproved": true
565
+ }
566
+ }
567
+ \`\`\`
568
+
569
+ ## Response Format for Existing Directory
570
+
571
+ \`\`\`json
572
+ {
573
+ "success": true,
574
+ "dirPath": "${safeDirPath}",
575
+ "created": false,
576
+ "metadata": {
577
+ "type": "directory",
578
+ "alreadyExists": true,
579
+ "permissions": "existing_permissions",
580
+ "lastModified": "ISO_timestamp"
581
+ },
582
+ "security": {
583
+ "pathValidated": true,
584
+ "accessAuthorized": true,
585
+ "systemDirectoryCheck": "passed"
586
+ }
587
+ }
588
+ \`\`\`
589
+
590
+ ## Error Response Format
591
+
592
+ \`\`\`json
593
+ {
594
+ "success": false,
595
+ "dirPath": "${safeDirPath}",
596
+ "created": false,
597
+ "error": "detailed error message",
598
+ "errorType": "PERMISSION_DENIED|INVALID_PATH|SECURITY_VIOLATION|DISK_FULL",
599
+ "security": {
600
+ "pathValidated": boolean,
601
+ "accessAuthorized": boolean,
602
+ "systemDirectoryCheck": "passed|failed",
603
+ "rejectionReason": "specific reason if access denied"
604
+ }
605
+ }
606
+ \`\`\`
607
+ `;
608
+ const instructions = `
609
+ ## Implementation Steps
610
+
611
+ 1. **Security Validation**:
612
+ - Validate the directory path: ${safeDirPath}
613
+ - Ensure it's not a system directory or sensitive location
614
+ - Check for path traversal attempts (../, .\\, etc.)
615
+ - Validate path format and reject malicious patterns
616
+
617
+ 2. **Action Confirmation**:
618
+ - Present the directory creation action to the user for confirmation
619
+ - Include details about what directories will be created
620
+ - Wait for user approval before proceeding
621
+
622
+ 3. **Directory Creation**:
623
+ - Check if the directory already exists
624
+ - Create parent directories recursively if needed
625
+ - Set appropriate permissions (755 or system default)
626
+ - Handle symbolic links appropriately
627
+
628
+ 4. **Response Generation**:
629
+ - Format response according to the specified JSON structure
630
+ - Include comprehensive metadata and security validation results
631
+ - Provide detailed error information if creation fails
632
+ - Include confirmation status
633
+
634
+ ## Safety Checks
635
+
636
+ - ✅ Path security validation delegated to AI agent
637
+ - ✅ System directory protection enabled
638
+ - ✅ Action confirmation required before directory creation
639
+ - ✅ Recursive directory creation with permission handling
640
+ - ✅ Comprehensive error handling specified
641
+
642
+ ## Context Information
643
+
644
+ - **Directory Path**: ${safeDirPath}
645
+ - **Operation**: Safe directory creation (recursive)
646
+ - **Security Level**: High (with path validation and access control)
647
+ - **Confirmation Required**: Yes (action confirmation pattern)
648
+ `;
649
+ return {
650
+ prompt,
651
+ instructions,
652
+ context: {
653
+ dirPath: safeDirPath,
654
+ operation: 'directory_creation',
655
+ securityLevel: 'high',
656
+ expectedFormat: 'json',
657
+ confirmationRequired: true,
658
+ recursive: true
659
+ }
660
+ };
137
661
  }
138
662
  catch (error) {
139
- throw new FileSystemError(`Failed to create directory: ${error instanceof Error ? error.message : String(error)}`, { dirPath });
663
+ throw new FileSystemError(`Failed to generate directory creation prompt: ${error instanceof Error ? error.message : String(error)}`, { dirPath });
140
664
  }
141
665
  }
142
666
  /**
143
- * Write file with directory creation
667
+ * Generate prompt for AI-driven file writing with directory creation
144
668
  */
145
669
  export async function writeFile(filePath, content) {
146
670
  try {
147
- await ensureDirectory(dirname(filePath));
148
- await fs.writeFile(filePath, content, 'utf-8');
671
+ console.error(`[DEBUG] Generating file write prompt for: ${filePath}`);
672
+ // Pure prompt-driven approach - delegate file writing to AI agent
673
+ const safeFilePath = filePath || '';
674
+ const safeContent = content || '';
675
+ const contentPreview = safeContent.length > 200 ? safeContent.substring(0, 200) + '...' : safeContent;
676
+ const prompt = `
677
+ # File Writing Request
678
+
679
+ Please write content to the file: **${safeFilePath}**
680
+
681
+ ## Path Security Validation
682
+
683
+ The AI agent must:
684
+ 1. **Validate file path security**: Ensure the path is not a system directory (/, /usr, /bin, /etc, /var, /tmp, etc.)
685
+ 2. **Resolve relative paths safely**: Handle relative paths from the current working directory
686
+ 3. **Prevent unauthorized access**: Reject attempts to write to sensitive system files or directories
687
+ 4. **Validate path format**: Check for valid file path format and reject malicious patterns
688
+
689
+ ## Content Security Validation
690
+
691
+ The AI agent must:
692
+ 1. **Content sanitization**: Validate content for security issues (no malicious scripts, etc.)
693
+ 2. **Encoding validation**: Ensure content is properly encoded as UTF-8
694
+ 3. **Size validation**: Check content size is reasonable
695
+ 4. **Format validation**: Verify content format matches file extension expectations
696
+
697
+ ## File Writing Requirements
698
+
699
+ 1. **Directory Creation**: Ensure parent directory exists (create if needed)
700
+ 2. **Safe File Writing**: Write content using appropriate file system tools
701
+ 3. **Encoding Handling**: Write the file as UTF-8 text content
702
+ 4. **Atomic Operations**: Use atomic write operations when possible
703
+ 5. **Permission Handling**: Set appropriate file permissions
704
+ 6. **Backup Consideration**: Consider backing up existing files if they exist
705
+
706
+ ## Action Confirmation Required
707
+
708
+ Before writing any files, confirm the action with the user:
709
+
710
+ **Action**: Write file content
711
+ **Target**: ${safeFilePath}
712
+ **Content Size**: ${safeContent.length} characters
713
+ **Content Preview**: ${contentPreview}
714
+ **Type**: File creation/modification
715
+ **Impact**: Creates file and any missing parent directories
716
+
717
+ ## Expected Output Format
718
+
719
+ \`\`\`json
720
+ {
721
+ "success": true,
722
+ "filePath": "${safeFilePath}",
723
+ "written": true,
724
+ "metadata": {
725
+ "type": "file",
726
+ "size": ${safeContent.length},
727
+ "encoding": "utf-8",
728
+ "permissions": "644",
729
+ "createdAt": "ISO_timestamp",
730
+ "directoryCreated": boolean
731
+ },
732
+ "security": {
733
+ "pathValidated": true,
734
+ "contentValidated": true,
735
+ "accessAuthorized": true,
736
+ "systemDirectoryCheck": "passed"
737
+ },
738
+ "confirmation": {
739
+ "actionConfirmed": true,
740
+ "userApproved": true
741
+ }
742
+ }
743
+ \`\`\`
744
+
745
+ ## Response Format for File Update
746
+
747
+ \`\`\`json
748
+ {
749
+ "success": true,
750
+ "filePath": "${safeFilePath}",
751
+ "written": true,
752
+ "metadata": {
753
+ "type": "file",
754
+ "size": ${safeContent.length},
755
+ "encoding": "utf-8",
756
+ "permissions": "644",
757
+ "updatedAt": "ISO_timestamp",
758
+ "previousSize": <previous_file_size>,
759
+ "directoryCreated": false
760
+ },
761
+ "security": {
762
+ "pathValidated": true,
763
+ "contentValidated": true,
764
+ "accessAuthorized": true,
765
+ "systemDirectoryCheck": "passed"
766
+ },
767
+ "confirmation": {
768
+ "actionConfirmed": true,
769
+ "userApproved": true
770
+ }
771
+ }
772
+ \`\`\`
773
+
774
+ ## Error Response Format
775
+
776
+ \`\`\`json
777
+ {
778
+ "success": false,
779
+ "filePath": "${safeFilePath}",
780
+ "written": false,
781
+ "error": "detailed error message",
782
+ "errorType": "PERMISSION_DENIED|INVALID_PATH|SECURITY_VIOLATION|CONTENT_INVALID|DISK_FULL",
783
+ "security": {
784
+ "pathValidated": boolean,
785
+ "contentValidated": boolean,
786
+ "accessAuthorized": boolean,
787
+ "systemDirectoryCheck": "passed|failed",
788
+ "rejectionReason": "specific reason if access denied"
789
+ }
790
+ }
791
+ \`\`\`
792
+ `;
793
+ const instructions = `
794
+ ## Implementation Steps
795
+
796
+ 1. **Security Validation**:
797
+ - Validate the file path: ${safeFilePath}
798
+ - Ensure it's not a system directory or sensitive location
799
+ - Check for path traversal attempts (../, .\\, etc.)
800
+ - Validate content for security issues
801
+
802
+ 2. **Action Confirmation**:
803
+ - Present the file writing action to the user for confirmation
804
+ - Include details about the file path and content preview
805
+ - Show content size and any directories that will be created
806
+ - Wait for user approval before proceeding
807
+
808
+ 3. **Directory Preparation**:
809
+ - Extract directory path from file path: ${dirname(safeFilePath)}
810
+ - Ensure parent directory exists (create recursively if needed)
811
+ - Validate directory permissions
812
+
813
+ 4. **File Writing**:
814
+ - Check if file already exists (for backup consideration)
815
+ - Write content to file using UTF-8 encoding
816
+ - Set appropriate file permissions (644 or system default)
817
+ - Use atomic write operations when possible
818
+
819
+ 5. **Response Generation**:
820
+ - Format response according to the specified JSON structure
821
+ - Include comprehensive metadata and security validation results
822
+ - Provide detailed error information if writing fails
823
+ - Include confirmation status and directory creation details
824
+
825
+ ## Safety Checks
826
+
827
+ - ✅ Path security validation delegated to AI agent
828
+ - ✅ Content security validation required
829
+ - ✅ System directory protection enabled
830
+ - ✅ Action confirmation required before file writing
831
+ - ✅ Directory creation with permission handling
832
+ - ✅ Comprehensive error handling specified
833
+
834
+ ## Context Information
835
+
836
+ - **File Path**: ${safeFilePath}
837
+ - **Content Size**: ${safeContent.length} characters
838
+ - **Operation**: Safe file writing with directory creation
839
+ - **Security Level**: High (with path and content validation)
840
+ - **Confirmation Required**: Yes (action confirmation pattern)
841
+ `;
842
+ return {
843
+ prompt,
844
+ instructions,
845
+ context: {
846
+ filePath: safeFilePath,
847
+ contentSize: safeContent.length,
848
+ operation: 'file_write',
849
+ securityLevel: 'high',
850
+ expectedFormat: 'json',
851
+ confirmationRequired: true,
852
+ directoryCreation: true
853
+ }
854
+ };
149
855
  }
150
856
  catch (error) {
151
- throw new FileSystemError(`Failed to write file: ${error instanceof Error ? error.message : String(error)}`, { filePath });
857
+ throw new FileSystemError(`Failed to generate file write prompt: ${error instanceof Error ? error.message : String(error)}`, { filePath });
152
858
  }
153
859
  }
154
860
  /**