@afterxleep/doc-bot 1.16.0 → 1.17.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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@afterxleep/doc-bot",
3
- "version": "1.16.0",
3
+ "version": "1.17.0",
4
4
  "description": "Generic MCP server for intelligent documentation access in any project",
5
5
  "type": "module",
6
6
  "main": "src/index.js",
@@ -0,0 +1,69 @@
1
+ # FILE CONTEXT DOCUMENTATION
2
+
3
+ **File**: `${filePath}`
4
+
5
+ ## CONTEXTUAL STANDARDS
6
+
7
+ ${docsContent}
8
+
9
+ ## SMART IMPLEMENTATION CHECKLIST
10
+
11
+ ### Quick Analysis (< 10 seconds)
12
+ 1. **Scan Patterns** - What patterns does this file use?
13
+ 2. **Check Dependencies** - What does it import?
14
+ 3. **Note Conventions** - Naming, structure, style
15
+
16
+ ### Implementation Rules
17
+ 1. **Match Style** - Follow the file's existing patterns
18
+ 2. **Preserve Logic** - Don't break existing functionality
19
+ 3. **Minimal Changes** - Small, focused modifications
20
+
21
+ ## DECISION FRAMEWORK
22
+
23
+ ### Need More Context?
24
+
25
+ ```javascript
26
+ if (changeIsSimple) {
27
+ // Just make the change
28
+ applyDirectFix();
29
+ } else if (needsPatternContext) {
30
+ // One quick search
31
+ search_documentation(specificPattern);
32
+ } else {
33
+ // Use file's existing patterns
34
+ followLocalConventions();
35
+ }
36
+ ```
37
+
38
+ ## PERFORMANCE CONSIDERATIONS
39
+
40
+ **For Hot Paths:**
41
+ - Keep complexity at current level or better
42
+ - Don't introduce blocking operations
43
+ - Maintain existing optimizations
44
+
45
+ **For Regular Code:**
46
+ - Prioritize readability
47
+ - Follow SOLID principles
48
+ - Keep it simple
49
+
50
+ ## VALIDATION
51
+
52
+ Before committing:
53
+ - ✓ Follows file conventions
54
+ - ✓ Maintains contracts
55
+ - ✓ Preserves performance
56
+ - ✓ Doesn't break tests
57
+
58
+ ## QUICK WINS
59
+
60
+ **Common tasks that need NO documentation search:**
61
+ - Adding logging/debugging
62
+ - Fixing typos or syntax
63
+ - Adding comments
64
+ - Simple refactoring
65
+ - Error handling with try/catch
66
+
67
+ ## THE LOCAL PATTERN RULE
68
+
69
+ When in doubt, copy what the file already does. Local consistency > global perfection.
@@ -0,0 +1,142 @@
1
+ # ENGINEERING STANDARDS & ARCHITECTURE GUIDELINES
2
+
3
+ ## INTELLIGENT CODE GENERATION FRAMEWORK
4
+
5
+ ### When to Search Project Documentation
6
+
7
+ **Search when task involves:**
8
+ - Custom components unique to this codebase
9
+ - Business logic implementation
10
+ - Integration patterns
11
+ - Authentication/authorization schemes
12
+ - Data models and schemas
13
+ - API design patterns
14
+
15
+ **Specific triggers:**
16
+ - "How do we structure microservices?"
17
+ - "Our repository pattern implementation"
18
+ - "User permission calculation algorithm"
19
+ - "How services communicate in our system"
20
+ - "Our caching strategy for API responses"
21
+
22
+ ### When to Use Agent Knowledge
23
+
24
+ **Use existing knowledge for:**
25
+ - Language syntax and features
26
+ - Standard design patterns
27
+ - Common algorithms
28
+ - Well-known framework basics
29
+ - Popular library usage
30
+
31
+ **Knowledge domains:**
32
+ - **Language Features**: async/await, generics, decorators, closures
33
+ - **Design Patterns**: MVC, Observer, Factory, Dependency Injection
34
+ - **Standard Algorithms**: sorting, searching, graph traversal
35
+ - **Framework Basics**: React hooks, Express middleware, Django models
36
+ - **Common Libraries**: lodash methods, axios, standard utilities
37
+
38
+ ## CONFIDENCE CALIBRATION
39
+
40
+ ### Decision Matrix
41
+
42
+ ```javascript
43
+ function shouldSearchDocs(task) {
44
+ const signals = {
45
+ projectSpecific: assessProjectSpecificity(task), // 0-100
46
+ complexity: assessComplexity(task), // 0-100
47
+ riskLevel: assessRisk(task) // 0-100
48
+ };
49
+
50
+ // Search if any signal is high
51
+ return signals.projectSpecific > 60 ||
52
+ signals.complexity > 70 ||
53
+ signals.riskLevel > 50;
54
+ }
55
+ ```
56
+
57
+ ### Quick Decision Rules
58
+
59
+ 1. **Universal Task** → Skip search
60
+ 2. **Project Pattern** → Single targeted search
61
+ 3. **Complex Feature** → Progressive search (max 2-3)
62
+ 4. **Unclear Requirement** → Start simple, enhance if needed
63
+
64
+ ## COMPLIANCE & QUALITY GATES
65
+
66
+ ### Non-Negotiable Standards
67
+
68
+ - **Architecture**: Follow established patterns
69
+ - **Security**: Never expose sensitive data
70
+ - **Performance**: Avoid N+1 queries, optimize hot paths
71
+ - **Error Handling**: Consistent error patterns
72
+ - **Testing**: Maintain coverage standards
73
+
74
+ ### Quality Metrics
75
+
76
+ - **Code Coverage**: Minimum 80% for new code
77
+ - **Complexity**: Cyclomatic complexity < 10
78
+ - **Performance**: No blocking I/O in hot paths
79
+ - **Security**: All inputs validated
80
+ - **Maintainability**: Clear naming, single responsibility
81
+
82
+ ## SEARCH OPTIMIZATION PROTOCOL
83
+
84
+ ### Efficient Search Strategy
85
+
86
+ 1. **Parse Intent** → Extract technical entities
87
+ 2. **Search Hierarchy** → Specific to general
88
+ 3. **Early Exit** → Stop when confidence > 80%
89
+ 4. **Fallback** → Use general knowledge after 2 failed attempts
90
+
91
+ ### Search Patterns
92
+
93
+ ```javascript
94
+ // Good: Specific technical terms
95
+ search("WidgetKit", "Widget", "iOS")
96
+
97
+ // Bad: Descriptive phrases
98
+ search("how to make iOS widgets")
99
+
100
+ // Good: API/Class names
101
+ search("URLSession", "Authentication")
102
+
103
+ // Bad: General concepts
104
+ search("networking", "security")
105
+ ```
106
+
107
+ ## IMPLEMENTATION GUIDANCE
108
+
109
+ ### Found Documentation
110
+
111
+ ```javascript
112
+ if (documentation.found) {
113
+ // 1. Read most relevant
114
+ await read_specific_document(results[0]);
115
+
116
+ // 2. Explore APIs if needed
117
+ if (needsAPIDetails) {
118
+ await explore_api(className);
119
+ }
120
+
121
+ // 3. Apply patterns
122
+ implementWithPatterns(documentation);
123
+ }
124
+ ```
125
+
126
+ ### No Documentation Found
127
+
128
+ ```javascript
129
+ if (!documentation.found && attempts >= 2) {
130
+ // Use standard patterns
131
+ applyBestPractices();
132
+
133
+ // Note for user
134
+ addComment("Implemented with industry standards - verify against project patterns");
135
+ }
136
+ ```
137
+
138
+ ## GOLDEN RULE
139
+
140
+ **Ship code you'd be proud to maintain at 3 AM during an outage.**
141
+
142
+ Balance speed with quality. Use documentation when it adds value. Default to simplicity.
@@ -0,0 +1,90 @@
1
+ # CODE GENERATION COMPLIANCE MATRIX
2
+
3
+ **Task**: ${task}
4
+
5
+ ## MANDATORY STANDARDS
6
+
7
+ ${rulesContent}
8
+
9
+ ## IMPLEMENTATION PROTOCOL
10
+
11
+ ### 1. Architecture Alignment
12
+ Generated code MUST follow project architecture patterns
13
+
14
+ ### 2. Type Safety
15
+ Enforce type constraints and validation requirements
16
+
17
+ ### 3. Error Handling
18
+ Apply project-specific error handling patterns
19
+
20
+ ### 4. Performance
21
+ Adhere to performance optimization guidelines
22
+
23
+ ### 5. Security
24
+ Implement security patterns as defined in rules
25
+
26
+ ## ENFORCEMENT MATRIX
27
+
28
+ | Violation Type | Action | Example |
29
+ |----------------|--------|---------|
30
+ | Architecture | BLOCK + Suggest | "Use Repository pattern, not direct DB" |
31
+ | Security | BLOCK + Explain | "Never expose API keys in client" |
32
+ | Performance | WARN + Alternative | "Use batch ops instead of N+1" |
33
+ | Style | AUTO-CORRECT | "Apply project formatting" |
34
+
35
+ ## SMART SEARCH METHODOLOGY
36
+
37
+ ### Efficient Pattern Recognition
38
+
39
+ 1. **Extract Key Terms** - Not descriptions
40
+ ```javascript
41
+ // User: "implement OAuth2 with refresh tokens"
42
+ searchTerms = ["OAuth2", "OAuth", "RefreshToken", "Authentication"]
43
+ // NOT: ["implement", "with", "tokens"]
44
+ ```
45
+
46
+ 2. **Search Hierarchy**
47
+ - Exact match → Class/API names
48
+ - Partial match → Related components
49
+ - Broad match → Framework/pattern names
50
+
51
+ 3. **Early Termination**
52
+ - Found with high confidence (>80%) → Stop
53
+ - 2 attempts with no results → Use general knowledge
54
+ - User provides implementation → Skip search
55
+
56
+ ### Search Optimization Rules
57
+
58
+ **DO:**
59
+ - Search for technical nouns (Widget, URLSession)
60
+ - Use API/framework names (SwiftUI, WidgetKit)
61
+ - Try variations of technical terms
62
+
63
+ **DON'T:**
64
+ - Search for descriptions ("how to make widgets")
65
+ - Use generic verbs ("create", "build", "implement")
66
+ - Keep searching after 2 failed attempts
67
+
68
+ ## COMPLIANCE CHECKLIST
69
+
70
+ - [ ] Code follows architectural patterns
71
+ - [ ] Security requirements implemented
72
+ - [ ] Performance guidelines respected
73
+ - [ ] Error handling matches standards
74
+ - [ ] Code style adheres to conventions
75
+
76
+ ## QUICK DECISION TREE
77
+
78
+ ```
79
+ Is this a project-specific pattern?
80
+ ├─ NO → Use industry best practices
81
+ └─ YES → Search for pattern (max 2 attempts)
82
+ ├─ Found → Apply pattern
83
+ └─ Not Found → Use best practices + note
84
+ ```
85
+
86
+ ## EFFICIENCY REMINDER
87
+
88
+ **Time is valuable. Don't over-search.**
89
+
90
+ If you can't find project patterns in 2 tries, implement with industry standards and move on.
@@ -0,0 +1,59 @@
1
+ # DOCUMENTATION SEARCH RESULTS
2
+
3
+ **Query**: `${query}`
4
+ **Results**: ${resultCount} matches
5
+
6
+ ${results}
7
+
8
+ ## SEARCH EFFECTIVENESS
9
+
10
+ ${resultCount > 0 ? `### ✅ Results Found
11
+ **Next Steps:**
12
+ 1. Read the most relevant result with \`read_specific_document\`
13
+ 2. Explore APIs if needed with \`explore_api\`
14
+ 3. Check compliance with \`check_project_rules\`
15
+
16
+ **Priority**: Start with exact matches, then partial matches.` : `### ⚠️ No Results Found
17
+
18
+ **Smart Fallback Strategy:**
19
+ 1. **One Retry**: Try a single, more specific technical term
20
+ 2. **If Still Nothing**: Use general programming knowledge
21
+ 3. **Note to User**: "Implemented with industry standards"
22
+
23
+ **Search Tips:**
24
+ - Use API/class names, not descriptions
25
+ - Try parent class or framework name
26
+ - Search like reading an API index`}
27
+
28
+ ## IMPLEMENTATION GUIDANCE
29
+
30
+ ### With Documentation
31
+ ```javascript
32
+ if (results.length > 0) {
33
+ // Read most relevant
34
+ await read_specific_document(results[0].fileName);
35
+
36
+ // Only explore if needed
37
+ if (needsAPIDetails) {
38
+ await explore_api(results[0].name);
39
+ }
40
+ }
41
+ ```
42
+
43
+ ### Without Documentation (After 2 Attempts)
44
+ ```javascript
45
+ // Don't keep searching - use your knowledge
46
+ implementWithBestPractices();
47
+ // Be transparent
48
+ addComment("Following industry standards - verify against project patterns if needed");
49
+ ```
50
+
51
+ ## EFFICIENCY PRINCIPLE
52
+
53
+ **Found something useful?** → Read it and implement
54
+ **Found nothing twice?** → Stop searching, start coding
55
+ **User corrects you?** → Then search for their specific pattern
56
+
57
+ ## THE 2-ATTEMPT RULE
58
+
59
+ Never search more than twice for the same concept. If project documentation doesn't have it, it probably follows standard patterns.
@@ -0,0 +1,270 @@
1
+ # INTENT-DRIVEN DOCUMENTATION SYSTEM
2
+
3
+ ## PRIMARY DIRECTIVE
4
+
5
+ Think like a senior developer: Understand WHAT the user needs and WHY, then decide:
6
+
7
+ 1. **Fast Path**: Use agent knowledge for universal programming tasks
8
+ 2. **Discovery Path**: Use doc-bot tools only when project-specific knowledge adds value
9
+ 3. **Hybrid Path**: Combine both for features that need project patterns
10
+
11
+ ## SMART INTENT ANALYSIS
12
+
13
+ ### Core Question: "Can I solve this without project documentation?"
14
+
15
+ - **YES** → Fast Path (agent knowledge only)
16
+ - **NO** → Analyze what specific project info is needed
17
+ - **MAYBE** → Start fast, search only if stuck
18
+
19
+ ### Speed vs Accuracy Trade-off
20
+
21
+ - User seems rushed/frustrated → Prioritize speed
22
+ - User asks "proper way" → Prioritize project patterns
23
+ - User fixing urgent bug → Fast fix first, patterns later
24
+ - User building new feature → Get patterns right first time
25
+
26
+ ## DECISION FRAMEWORK
27
+
28
+ ### ⚠️ MANDATORY RULE CHECK
29
+
30
+ **ALWAYS use `check_project_rules` tool when:**
31
+ - Writing ANY new code
32
+ - Modifying existing code beyond trivial fixes
33
+ - Even for "simple" tasks - rules with `alwaysApply: true` must be enforced
34
+
35
+ **Exception:** Only skip for pure fixes like typos, renames, or adding comments.
36
+
37
+ ## DOC-BOT TOOLS REFERENCE
38
+
39
+ ### Important: Direct Tool Access
40
+ **You can call these tools DIRECTLY** - no orchestration layer required. The tools are exposed by the MCP server and can be called independently based on your judgment.
41
+
42
+ ### Optional: The `doc_bot` Helper Tool
43
+ - **Purpose**: Provides guidance on which tools to use for a task
44
+ - **When to use**: If you're unsure which tools to call
45
+ - **Input**: `task` (description of what you're doing)
46
+ - **Returns**: Text guidance suggesting tool sequence
47
+ - **Note**: This is OPTIONAL - you can skip it and call tools directly
48
+
49
+ ### Core Tools for Code Generation
50
+
51
+ 1. **`check_project_rules`** - MANDATORY before writing code
52
+ - Input: `task` (2-5 words describing what you're doing)
53
+ - Returns: Architecture patterns, security requirements, performance guidelines
54
+ - Example: `check_project_rules("user authentication")`
55
+
56
+ 2. **`search_documentation`** - Find project patterns
57
+ - Input: `query` (technical terms, not descriptions)
58
+ - Use: API/class names like "Widget", not "how to make widgets"
59
+ - Optional: `limit`, `docsetId`, `type`
60
+
61
+ 3. **`get_global_rules`** - Understand codebase philosophy
62
+ - No inputs required
63
+ - Returns: Project-wide principles and standards
64
+ - Use: When starting major features or understanding architecture
65
+
66
+ 4. **`get_file_docs`** - File-specific patterns
67
+ - Input: `filePath` (exact path or pattern)
68
+ - Use: Before modifying existing files
69
+ - Example: `get_file_docs("src/services/auth.js")`
70
+
71
+ 5. **`read_specific_document`** - Read full doc content
72
+ - Input: `fileName` (exact match required)
73
+ - Use: After `search_documentation` finds relevant docs
74
+
75
+ 6. **`explore_api`** - Deep dive into APIs
76
+ - Input: `apiName` (class/framework name)
77
+ - Use: When implementing with specific APIs
78
+ - Example: `explore_api("WidgetKit")`
79
+
80
+ ### 🚀 FAST PATH (Minimal doc-bot tools, < 30 seconds)
81
+
82
+ **Triggers:**
83
+ - Typos, syntax errors, compilation errors
84
+ - Variable/function renames
85
+ - Adding comments or logging
86
+ - Standard bug fixes (null checks, undefined vars)
87
+ - General "what is X?" questions
88
+ - Error messages with obvious fixes
89
+
90
+ **Required for code generation:** Still call `check_project_rules()` for non-trivial code changes
91
+
92
+ **Key Insight**: Fast doesn't mean skipping mandatory rules - it means no unnecessary searches.
93
+
94
+ ### 🔍 DISCOVERY PATH (Use doc-bot strategically)
95
+
96
+ **Triggers:**
97
+ - "How do WE...", "In THIS project...", "Our pattern for..."
98
+ - "Where is X implemented?"
99
+ - Architecture or design questions
100
+ - Integration with existing systems
101
+ - Following team conventions
102
+
103
+ **Smart Search Strategy:**
104
+ 1. Start with most specific term
105
+ 2. If no results, try broader term ONCE
106
+ 3. Still nothing? Use agent knowledge + disclaimer
107
+
108
+ ### 🎯 HYBRID PATH (Minimal doc-bot + agent knowledge)
109
+
110
+ **Triggers:**
111
+ - "Add/Implement X" (new feature)
112
+ - "Optimize X" (existing code)
113
+ - "Refactor to match standards"
114
+
115
+ **Execution:**
116
+ 1. Quick `check_project_rules(feature)` - 1 call max
117
+ 2. If patterns found → follow them
118
+ 3. If not → implement with best practices
119
+ 4. Don't over-search - 2 attempts maximum
120
+
121
+ ## SMART EFFICIENCY PRINCIPLES
122
+
123
+ ### 1. Think Before Searching
124
+
125
+ **Ask yourself:**
126
+ - Can I solve this with standard programming knowledge? → Don't search
127
+ - Is this about HOW this specific project works? → Search once
128
+ - Am I searching just to be thorough? → Stop
129
+
130
+ ### 2. Progressive Enhancement
131
+
132
+ 1. Try solving with agent knowledge first
133
+ 2. If user says "that's not how we do it" → search_documentation
134
+ 3. If user seems satisfied → stop, don't over-engineer
135
+
136
+ ### 3. Time-Box Searches
137
+
138
+ - Simple fix: 0 searches
139
+ - Standard task: Max 1 search, 1 retry
140
+ - Complex feature: Max 3 searches total
141
+ - If not found in 2 attempts → proceed with best practices
142
+
143
+ ### 4. User Feedback Signals
144
+
145
+ **Speed up when user says:**
146
+ - "quick fix", "just", "simple", "for now"
147
+ - Shows frustration with delays
148
+ - Provides specific implementation details
149
+
150
+ **Be thorough when user says:**
151
+ - "proper", "correct", "production", "best practice"
152
+ - "follow our patterns", "like we usually do"
153
+ - Building something new or public-facing
154
+
155
+ ## ULTRA-SMART BEHAVIOR PATTERNS
156
+
157
+ ### Pattern Recognition Examples
158
+
159
+ **"Fix the typo in getUserName"**
160
+ - Intent: Typo fix
161
+ - Thinking: Pure text fix, no logic change
162
+ - Action: Direct fix, no tools needed
163
+ - Time: < 10 seconds
164
+
165
+ **"How do we handle errors?"**
166
+ - Intent: Project pattern discovery
167
+ - Thinking: "we" = project-specific
168
+ - Action: `search_documentation("error handling")`
169
+ - Time: 30-60 seconds
170
+
171
+ **"Add error handling to this function"**
172
+ - Intent: Code modification
173
+ - Thinking: Adding code = check rules
174
+ - Action: `check_project_rules("error handling")` first, then implement
175
+ - Time: < 30 seconds
176
+
177
+ **"Implement user authentication"**
178
+ - Intent: New feature
179
+ - Thinking: Major feature = full compliance needed
180
+ - Action:
181
+ 1. `check_project_rules("authentication service")`
182
+ 2. `search_documentation("auth")` if patterns unclear
183
+ 3. `explore_api("AuthenticationServices")` if using specific API
184
+ - Time: 1-2 minutes
185
+
186
+ ### MANDATORY RULES ENFORCEMENT
187
+
188
+ **Even for "simple" code changes:**
189
+ ```javascript
190
+ // User: "Add a null check here"
191
+ 1. check_project_rules("input validation") // MANDATORY - might have specific patterns
192
+ 2. Apply the null check pattern from rules
193
+ 3. If no pattern found, use standard approach
194
+ ```
195
+
196
+ **Tool Usage Examples:**
197
+ ```javascript
198
+ // Starting a new feature
199
+ await check_project_rules("payment processing");
200
+ await get_global_rules(); // If need architecture overview
201
+
202
+ // Modifying existing code
203
+ await get_file_docs("src/services/payment.js");
204
+ await check_project_rules("refactoring");
205
+
206
+ // Finding patterns
207
+ const results = await search_documentation("caching");
208
+ if (results.length > 0) {
209
+ await read_specific_document(results[0].fileName);
210
+ }
211
+
212
+ // Using specific APIs
213
+ await explore_api("StripeAPI");
214
+ ```
215
+
216
+ **Only skip rules for:**
217
+ - Fixing typos in strings/comments
218
+ - Renaming variables (no logic change)
219
+ - Adding debug logs (temporary)
220
+ - Removing commented code
221
+
222
+ ### Adaptive Intelligence
223
+
224
+ **Start Fast, Get Smarter:**
225
+ 1. Default to speed for unclear requests
226
+ 2. If user corrects you → learn and search
227
+ 3. Remember patterns within conversation
228
+ 4. Don't repeat searches that found nothing
229
+
230
+ **Context Clues for Speed:**
231
+ - Stack trace present → Fast fix
232
+ - "Broken/failing" → Fix first, optimize later
233
+ - Multiple files mentioned → May need patterns
234
+ - Single line number → Almost never needs search
235
+
236
+ ## SUCCESS METRICS
237
+
238
+ **You're succeeding when:**
239
+ - User gets help in < 30 seconds for simple tasks
240
+ - Project patterns used only when they add value
241
+ - No "searching documentation..." for obvious fixes
242
+ - User doesn't have to say "just do X" repeatedly
243
+ - Complex features still follow project patterns
244
+
245
+ ## THE GOLDEN RULES
246
+
247
+ ### Rule 1: ALWAYS Check Project Rules for Code Generation
248
+ **Before writing code, call `check_project_rules()`** - Rules with `alwaysApply: true` are MANDATORY, even for "simple" tasks.
249
+
250
+ ### Rule 2: Be Smart About Documentation
251
+ **Think like a senior dev who knows when to look things up vs when to just fix it.**
252
+
253
+ ### Rule 3: Speed + Compliance
254
+ **Fast when possible. Compliant always. Smart about everything.**
255
+
256
+ ## COMPLIANCE SUMMARY
257
+
258
+ ✅ **MUST check rules for:**
259
+ - Any new code generation
260
+ - Code modifications (beyond trivial)
261
+ - Bug fixes that change logic
262
+ - Adding any functionality
263
+
264
+ ❌ **Can skip rules for:**
265
+ - Typo fixes in strings/comments
266
+ - Variable renames (no logic change)
267
+ - Adding temporary debug statements
268
+ - Removing dead code
269
+
270
+ **Remember:** `alwaysApply: true` rules are NON-NEGOTIABLE. Check them even if you think you know the answer.
package/src/index.js CHANGED
@@ -61,12 +61,21 @@ class DocsServer {
61
61
 
62
62
  async loadPromptTemplate(templateName) {
63
63
  if (!this.promptTemplates[templateName]) {
64
- const templatePath = path.join(__dirname, '../prompts', `${templateName}.txt`);
64
+ // Try markdown first, fall back to txt for backward compatibility
65
+ const mdPath = path.join(__dirname, '../prompts', `${templateName}.md`);
66
+ const txtPath = path.join(__dirname, '../prompts', `${templateName}.txt`);
67
+
65
68
  try {
66
- this.promptTemplates[templateName] = await fs.readFile(templatePath, 'utf8');
67
- } catch (error) {
68
- console.error(`Failed to load prompt template ${templateName}:`, error);
69
- return null;
69
+ // Try loading markdown version first
70
+ this.promptTemplates[templateName] = await fs.readFile(mdPath, 'utf8');
71
+ } catch (mdError) {
72
+ try {
73
+ // Fall back to txt version
74
+ this.promptTemplates[templateName] = await fs.readFile(txtPath, 'utf8');
75
+ } catch (txtError) {
76
+ console.error(`Failed to load prompt template ${templateName}:`, mdError.message);
77
+ return null;
78
+ }
70
79
  }
71
80
  }
72
81
  return this.promptTemplates[templateName];
@@ -1,52 +0,0 @@
1
- # 📁 CODE CONTEXT DOCUMENTATION
2
-
3
- **File/Pattern**: `${filePath}`
4
-
5
- ## 🎯 CONTEXTUAL CODING STANDARDS:
6
-
7
- ${docsContent}
8
-
9
- ## 🔧 IMPLEMENTATION CHECKLIST:
10
-
11
- ### Pre-Implementation Analysis:
12
- ```typescript
13
- interface FileContext {
14
- dependencies: string[]; // What does this file import?
15
- exports: string[]; // What does this file export?
16
- patterns: string[]; // Design patterns used
17
- performance: string[]; // Hot paths or bottlenecks
18
- security: string[]; // Security considerations
19
- }
20
- ```
21
-
22
- ### Code Modification Protocol:
23
- 1. **🔍 Analyze Current Implementation**
24
- - Review existing patterns and conventions
25
- - Identify architectural decisions
26
- - Note performance optimizations
27
-
28
- 2. **🏗️ Apply Contextual Rules**
29
- - File-specific patterns override globals
30
- - Maintain consistency with surrounding code
31
- - Preserve existing optimizations
32
-
33
- 3. **✅ Validation Requirements**
34
- ```javascript
35
- // Before committing changes:
36
- assert(follows_file_conventions);
37
- assert(maintains_dependencies);
38
- assert(preserves_contracts);
39
- assert(passes_type_checking);
40
- ```
41
-
42
- ### 🚀 Performance Considerations:
43
- - **Hot Paths**: Code in this context may be performance-critical
44
- - **Memory**: Watch for memory leaks in long-running processes
45
- - **Complexity**: Keep O(n) complexity unless documented otherwise
46
-
47
- ### 🛡️ Security Context:
48
- - **Input Validation**: Required for user-facing code
49
- - **Authentication**: Check if auth context needed
50
- - **Data Sanitization**: Required for DB operations
51
-
52
- **💡 Developer Note**: This file's patterns were chosen for specific reasons. Understand the "why" before changing the "how".
@@ -1,83 +0,0 @@
1
- # 🏗️ ENGINEERING STANDARDS & ARCHITECTURAL GUIDELINES
2
-
3
- ## 🧠 INTELLIGENT CODE GENERATION DECISION TREE:
4
-
5
- ### 🔍 Search Project Documentation When:
6
- ```javascript
7
- if (task.involves(['custom_components', 'business_logic', 'integrations',
8
- 'authentication', 'data_models', 'api_patterns'])) {
9
- return SEARCH_DOCUMENTATION;
10
- }
11
- ```
12
-
13
- #### Specific Triggers:
14
- - **Architecture Decisions**: "How do we structure microservices?"
15
- - **Custom Abstractions**: "Our repository pattern implementation"
16
- - **Business Logic**: "User permission calculation algorithm"
17
- - **Integration Points**: "How services communicate in our system"
18
- - **Performance Patterns**: "Our caching strategy for API responses"
19
-
20
- ### ⚡ Apply Developer Knowledge When:
21
- ```javascript
22
- if (task.involves(['language_syntax', 'standard_patterns', 'algorithms',
23
- 'common_libraries', 'well_known_frameworks'])) {
24
- return USE_KNOWLEDGE;
25
- }
26
- ```
27
-
28
- #### Knowledge Domains:
29
- - **Language Features**: async/await, generics, decorators, closures
30
- - **Design Patterns**: MVC, Observer, Factory, Dependency Injection
31
- - **Standard Algorithms**: sorting, searching, graph traversal
32
- - **Framework Basics**: React hooks, Express middleware, Django models
33
- - **Common Libraries**: lodash methods, moment.js, axios
34
-
35
- ## 🎯 CONFIDENCE CALIBRATION FOR ENGINEERS:
36
-
37
- ```typescript
38
- interface ConfidenceScore {
39
- projectSpecific: number; // 0-100: How unique to this codebase?
40
- complexity: number; // 0-100: Implementation complexity?
41
- riskLevel: number; // 0-100: Risk if wrong?
42
- }
43
-
44
- function shouldSearchDocs(score: ConfidenceScore): boolean {
45
- return score.projectSpecific > 60 ||
46
- score.complexity > 70 ||
47
- score.riskLevel > 50;
48
- }
49
- ```
50
-
51
- **🚀 Optimization Rule**: Search for architecture, skip for syntax.
52
-
53
- **Global Coding Standards**: The following engineering principles govern all code:
54
-
55
- ${rulesContent}
56
-
57
- ## 🏆 ENGINEERING EXCELLENCE BENEFITS:
58
-
59
- - **🔧 Maintainability**: Consistent patterns reduce cognitive load by 40%
60
- - **🚀 Performance**: Optimized patterns prevent common bottlenecks
61
- - **🛡️ Security**: Enforced patterns eliminate vulnerability classes
62
- - **📈 Scalability**: Architecture patterns support 10x growth
63
- - **⚡ Developer Velocity**: Standards reduce decision fatigue
64
-
65
- ## 💻 CODE GENERATION IMPERATIVES:
66
-
67
- ```yaml
68
- priorities:
69
- 1: Correctness # Bug-free implementation
70
- 2: Performance # O(n) vs O(n²) matters
71
- 3: Maintainability # Future devs will thank you
72
- 4: Security # Defense in depth
73
- 5: Testability # 80%+ coverage target
74
-
75
- enforcement:
76
- - NEVER compromise security for convenience
77
- - ALWAYS consider edge cases and error states
78
- - PREFER composition over inheritance
79
- - ENFORCE type safety where available
80
- - DOCUMENT complex algorithms inline
81
- ```
82
-
83
- **🎓 Remember**: You're writing code that will outlive its authors. Code for clarity.
@@ -1,117 +0,0 @@
1
- # CODE GENERATION COMPLIANCE MATRIX
2
-
3
- **Engineering Task**: ${task}
4
-
5
- **Mandatory Coding Standards**: The following rules are ENFORCED for all code generation:
6
-
7
- ${rulesContent}
8
-
9
- ## CODE IMPLEMENTATION PROTOCOL:
10
-
11
- 1. **Architecture Alignment**: Generated code MUST follow project architecture patterns
12
- 2. **Type Safety**: Enforce type constraints and validation requirements
13
- 3. **Error Handling**: Apply project-specific error handling patterns
14
- 4. **Performance**: Adhere to performance optimization guidelines
15
- 5. **Security**: Implement security patterns as defined in rules
16
-
17
- ## ENGINEERING ENFORCEMENT MATRIX:
18
-
19
- | Violation Type | Required Action | Example |
20
- |----------------|-----------------|---------|
21
- | Architecture Violation | BLOCK + Suggest Pattern | "Use Repository pattern, not direct DB access" |
22
- | Security Violation | BLOCK + Explain Risk | "Never expose API keys in client code" |
23
- | Performance Anti-pattern | WARN + Provide Alternative | "Use batch operations instead of N+1 queries" |
24
- | Style Violation | AUTO-CORRECT | "Apply project formatting standards" |
25
-
26
- ## COMPLIANCE VERIFICATION CHECKLIST:
27
-
28
- - [ ] Code follows architectural patterns defined above
29
- - [ ] All security requirements are implemented
30
- - [ ] Performance guidelines are respected
31
- - [ ] Error handling matches project standards
32
- - [ ] Code style adheres to project conventions
33
-
34
- ## 🔍 DEVELOPER DOCUMENTATION SEARCH PROTOCOL:
35
-
36
- **⚡ PERFORMANCE IMPACT**: Inefficient searches delay implementation. Master these patterns:
37
-
38
- ### CODE-FIRST SEARCH METHODOLOGY:
39
-
40
- #### 1. **Parse Developer Intent → Extract Technical Entities**
41
- ```typescript
42
- // Developer request: "implement OAuth2 with refresh tokens"
43
- const searchEntities = {
44
- primary: ["OAuth2", "OAuth"], // Protocol/Standard names
45
- secondary: ["RefreshToken", "Token"], // Component names
46
- framework: ["Authentication", "Auth"] // Framework context
47
- };
48
- ```
49
-
50
- #### 2. **Technical Taxonomy Search Hierarchy**
51
- ```
52
- Layer 1: Framework/Library → "React", "Express", "Django"
53
- Layer 2: Design Pattern → "Observer", "Factory", "Singleton"
54
- Layer 3: Implementation → "useState", "middleware", "decorator"
55
- Layer 4: Configuration → "webpack", "tsconfig", "eslint"
56
- ```
57
-
58
- #### 3. **API Resolution Strategy**
59
- Transform natural language to API nomenclature:
60
- ```javascript
61
- const searchTransform = {
62
- "make API calls": ["fetch", "axios", "HttpClient"],
63
- "handle errors": ["try-catch", "ErrorBoundary", "exception"],
64
- "manage state": ["Redux", "Context", "useState", "Vuex"],
65
- "test my code": ["Jest", "Mocha", "Testing", "TestCase"],
66
- "deploy app": ["Docker", "CI/CD", "Kubernetes", "Deploy"]
67
- };
68
- ```
69
-
70
- ### 🎯 SEARCH OPTIMIZATION MATRIX:
71
-
72
- | Developer Says | Primary Search | Fallback Search | Framework Hint |
73
- |----------------|----------------|-----------------|----------------|
74
- | "REST API endpoints" | "REST", "API" | "Controller", "Route" | Express/FastAPI |
75
- | "state management" | "State", "Store" | "Redux", "Context" | React/Vue |
76
- | "async operations" | "async", "Promise" | "await", "then" | JavaScript |
77
- | "database queries" | "Query", "ORM" | "Model", "Schema" | TypeORM/Prisma |
78
- | "authentication flow" | "Auth", "JWT" | "Login", "Session" | Passport/Auth0 |
79
-
80
- ### 💡 INTELLIGENT SEARCH PATTERNS:
81
-
82
- ```python
83
- def optimize_search_query(user_input):
84
- # 1. Remove implementation verbs
85
- query = remove_verbs(["implement", "create", "build", "add"])
86
-
87
- # 2. Extract technical nouns
88
- entities = extract_entities(query)
89
-
90
- # 3. Expand abbreviations
91
- expanded = expand_abbreviations({
92
- "API": "Application Programming Interface",
93
- "DB": "Database",
94
- "Auth": "Authentication",
95
- "UI": "UserInterface"
96
- })
97
-
98
- # 4. Try incremental searches
99
- return progressive_search(entities, max_attempts=3)
100
- ```
101
-
102
- ### 🚀 EXECUTION PIPELINE:
103
-
104
- ```mermaid
105
- graph LR
106
- A[Parse Task] --> B[Extract Entities]
107
- B --> C{Found Docs?}
108
- C -->|Yes| D[explore_api]
109
- C -->|No| E[Broaden Search]
110
- E --> F[Try Synonyms]
111
- F --> C
112
- D --> G[Implement Code]
113
- ```
114
-
115
- **🧠 REMEMBER**: You're querying a codebase knowledge graph, not a search engine. Think in types, classes, and interfaces.
116
-
117
- **Status**: Rules loaded and active for current session
@@ -1,48 +0,0 @@
1
- # 🔍 CODE DOCUMENTATION SEARCH RESULTS
2
-
3
- **Query**: `${query}`
4
- **Results**: ${resultCount} matches found
5
-
6
- ${results}
7
-
8
- ## 🎯 SEARCH EFFECTIVENESS ANALYSIS:
9
-
10
- ${resultCount > 0 ? `### ✅ Results Found - Action Required:
11
- 1. **Review** all results above for implementation patterns
12
- 2. **Use** \`read_specific_document\` for detailed code examples
13
- 3. **Apply** \`explore_api\` for comprehensive API documentation
14
- 4. **Validate** with \`check_project_rules\` before coding
15
-
16
- **Priority Order**: Start with exact matches, then partial matches.` : `### ⚠️ No Results - Fallback Strategy:
17
- 1. **Refine Search**: Try single technical terms (e.g., "Widget" not "iOS widgets")
18
- 2. **Broaden Scope**: Search parent class/framework names
19
- 3. **Check Synonyms**: Auth → Authentication, DB → Database
20
- 4. **Framework Search**: If component failed, try framework name
21
-
22
- **Developer Tip**: Search like you're reading an API index, not Google.`}
23
-
24
- ## 💻 IMPLEMENTATION GUIDANCE:
25
-
26
- ```javascript
27
- // Found results? Follow this pattern:
28
- if (results.length > 0) {
29
- // 1. Read most relevant document
30
- await read_specific_document(results[0].fileName);
31
-
32
- // 2. Explore APIs if needed
33
- if (results[0].type === 'API') {
34
- await explore_api(results[0].name);
35
- }
36
-
37
- // 3. Check compliance rules
38
- await check_project_rules(implementationTask);
39
- } else {
40
- // No results? Use general engineering knowledge for:
41
- // - Standard algorithms (sorting, searching)
42
- // - Language syntax (loops, conditionals)
43
- // - Common patterns (MVC, REST)
44
- // - Well-known libraries (React, Express)
45
- }
46
- ```
47
-
48
- **🚀 Next Action**: ${resultCount > 0 ? 'Read the top result to understand implementation details.' : 'Refine your search using technical terms or proceed with standard patterns.'}
@@ -1,210 +0,0 @@
1
- # 🚀 ENGINEERING DOCUMENTATION INTELLIGENCE SYSTEM
2
-
3
- ## ⚙️ CODEBASE CONFIGURATION:
4
-
5
- - **Architecture**: ${projectType || 'Modern software architecture with custom patterns'}
6
- - **Tech Stack**: ${techStack || 'Full-stack development environment'}
7
- - **Documentation Coverage**: ${availableTopics}
8
- - **Code Standards**: Enforced via automated tooling
9
-
10
- ## 🛠️ DEVELOPER TOOL EXECUTION MATRIX:
11
-
12
- | Tool | Use Case | Criticality | Response Time |
13
- |------|----------|-------------|---------------|
14
- | `check_project_rules` | Before ANY code generation | 🔴 CRITICAL | <100ms |
15
- | `search_documentation` | Architecture/API/Pattern queries | 🟡 HIGH | <200ms |
16
- | `explore_api` | Deep dive into classes/frameworks | 🟡 HIGH | <150ms |
17
- | `get_global_rules` | Coding standards overview | 🟢 MEDIUM | <100ms |
18
- | `read_specific_document` | Detailed implementation guide | 🟢 MEDIUM | <100ms |
19
- | `create_or_update_rule` | Capture new patterns/learnings | 🔵 LOW | <200ms |
20
-
21
- ## 🧠 INTELLIGENT KEYWORD RECOGNITION ENGINE:
22
-
23
- ### 💻 Code Generation Intent Detection:
24
- ```regex
25
- /\b(write|create|implement|build|code|function|class|component|
26
- method|interface|type|schema|model|controller|service|
27
- repository|factory|singleton|observer|decorator)\b/i
28
- ```
29
- **🎯 Action**: `check_project_rules(task)` → Mandatory pre-flight check
30
-
31
- ### 🏗️ Architecture & Pattern Queries:
32
- ```regex
33
- /\b(how|what|why|architecture|pattern|design|structure|
34
- approach|strategy|implementation|integration|workflow)\b.*
35
- (this|our|project|codebase|system|application)/i
36
- ```
37
- **🎯 Action**: `search_documentation(technical_terms)` → Extract nouns, search APIs
38
-
39
- ### 📚 Standards & Documentation Discovery:
40
- ```regex
41
- /\b(documentation|docs|standards|guidelines|rules|conventions|
42
- best practices|examples|reference|available|exists)\b/i
43
- ```
44
- **🎯 Action**: `get_global_rules()` → Show coding standards overview
45
-
46
- ### 🔧 API & Framework Exploration:
47
- ```regex
48
- /\b(explore|examine|understand|deep dive|all methods|
49
- properties|complete API|framework|library|SDK)\b/i
50
- ```
51
- **🎯 Action**: `explore_api(class_or_framework_name)` → Comprehensive API docs
52
-
53
- ### 📝 Knowledge Capture & Learning:
54
- ```regex
55
- /\b(document this|capture|remember|note|learned|discovered|
56
- pattern found|should be a rule|add to docs)\b/i
57
- ```
58
- **🎯 Action**: `create_or_update_rule()` → Persist new knowledge
59
-
60
- ## 🚀 SMART EXECUTION PIPELINE:
61
-
62
- ```python
63
- class DocumentationPipeline:
64
- def process_request(self, user_input: str):
65
- # 1. Intent Recognition
66
- intent = self.classify_intent(user_input)
67
- entities = self.extract_entities(user_input)
68
-
69
- # 2. Smart Tool Selection
70
- if intent == CodeGeneration:
71
- rules = await check_project_rules(entities.task)
72
- docs = await search_documentation(entities.tech_terms)
73
-
74
- elif intent == APIExploration:
75
- api_docs = await explore_api(entities.class_name)
76
-
77
- elif intent == Architecture:
78
- patterns = await search_documentation(entities.pattern)
79
-
80
- # 3. Response Synthesis
81
- return self.generate_code_with_context(rules, docs)
82
- ```
83
-
84
- ### 🎯 Execution Priorities:
85
- 1. **Safety First**: Always check rules before generating code
86
- 2. **Context Aware**: Search project docs for custom patterns
87
- 3. **Performance**: Use cached results when available
88
- 4. **Accuracy**: Validate against project standards
89
-
90
- ## 💡 INTELLIGENT IMPLEMENTATION PROTOCOL:
91
-
92
- ### 🏆 Code Quality Principles:
93
- ```yaml
94
- precedence:
95
- 1: Project Documentation # Your codebase rules
96
- 2: Official API Docs # Framework/library docs
97
- 3: Industry Standards # SOLID, DRY, KISS
98
- 4: General Knowledge # Last resort
99
-
100
- validation:
101
- - Type Safety: Enforce strong typing where available
102
- - Error Handling: Never swallow exceptions silently
103
- - Security: Input validation on all boundaries
104
- - Performance: Profile before optimizing
105
- - Testing: Minimum 80% coverage target
106
- ```
107
-
108
- ### 🔄 Smart Fallback Strategy:
109
- ```javascript
110
- async function getImplementationGuidance(query) {
111
- try {
112
- // 1. Try project documentation first
113
- const projectDocs = await search_documentation(query);
114
- if (projectDocs.length > 0) return projectDocs;
115
-
116
- // 2. Try different search terms (max 3 attempts)
117
- for (const term of generateSearchVariations(query)) {
118
- const results = await search_documentation(term);
119
- if (results.length > 0) return results;
120
- }
121
-
122
- // 3. Web search fallback for external resources
123
- return {
124
- fallback: true,
125
- message: "Search official docs, Stack Overflow, or GitHub examples",
126
- searchTerms: extractTechnicalTerms(query)
127
- };
128
- } catch (error) {
129
- return handleError(error);
130
- }
131
- }
132
- ```
133
-
134
- ## 🎮 REAL-WORLD DEVELOPER SCENARIOS:
135
-
136
- ### Scenario 1: Building a Feature
137
- ```typescript
138
- // Developer: "Create a user authentication service"
139
- const pipeline = {
140
- step1: await check_project_rules("authentication service"),
141
- step2: await search_documentation("Auth", "Authentication", "User"),
142
- step3: await explore_api("AuthenticationServices"),
143
- step4: generateCodeWithContext(rules, patterns, apis)
144
- };
145
- ```
146
-
147
- ### Scenario 2: Understanding Architecture
148
- ```typescript
149
- // Developer: "How does our caching layer work?"
150
- const analysis = {
151
- search1: await search_documentation("cache", "caching"),
152
- search2: await search_documentation("Redis", "Memcached"),
153
- result: found ? read_specific_document(doc) : explore_api("Cache")
154
- };
155
- ```
156
-
157
- ### Scenario 3: Implementing iOS Widget
158
- ```typescript
159
- // Developer: "Create iOS 18 widget demo"
160
- const implementation = {
161
- rules: await check_project_rules("iOS widget"),
162
- // Smart search - API names not descriptions!
163
- apis: await search_documentation("Widget", "WidgetKit"),
164
- explore: await explore_api("WidgetKit"),
165
- code: generateSwiftUIWidget(context)
166
- };
167
- ```
168
-
169
- ### Scenario 4: Performance Optimization
170
- ```typescript
171
- // Developer: "Optimize database queries in UserService"
172
- const optimization = {
173
- context: await get_file_docs("services/UserService.js"),
174
- patterns: await search_documentation("query optimization", "N+1"),
175
- rules: await check_project_rules("database optimization"),
176
- implement: applyBatchingPattern(queries)
177
- };
178
- ```
179
-
180
- ## ⚖️ ENGINEERING COMPLIANCE & QUALITY GATES:
181
-
182
- ### 🛡️ Non-Negotiable Standards:
183
- ```javascript
184
- class CodeComplianceChecker {
185
- async validate(generatedCode) {
186
- const checks = {
187
- architecture: this.followsProjectPatterns(generatedCode),
188
- security: this.hasNoVulnerabilities(generatedCode),
189
- performance: this.meetsPerformanceTargets(generatedCode),
190
- testing: this.hasAdequateTests(generatedCode),
191
- documentation: this.isProperlyDocumented(generatedCode)
192
- };
193
-
194
- if (!checks.architecture) {
195
- throw new ComplianceError("Code violates architecture patterns");
196
- }
197
-
198
- return checks;
199
- }
200
- }
201
- ```
202
-
203
- ### 📊 Quality Metrics:
204
- - **Code Coverage**: Minimum 80% for new code
205
- - **Complexity**: Cyclomatic complexity < 10
206
- - **Performance**: No N+1 queries, no blocking I/O
207
- - **Security**: All inputs validated, no hardcoded secrets
208
- - **Maintainability**: Clear naming, single responsibility
209
-
210
- **🎯 Golden Rule**: Ship code you'd be proud to maintain at 3 AM during an outage.