@afterxleep/doc-bot 1.14.0 → 1.16.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.
@@ -1,110 +1,210 @@
1
- # MCP DOCUMENTATION PROTOCOL
1
+ # 🚀 ENGINEERING DOCUMENTATION INTELLIGENCE SYSTEM
2
2
 
3
- ## SYSTEM CONFIGURATION:
3
+ ## ⚙️ CODEBASE CONFIGURATION:
4
4
 
5
- - **Tool Access**: MCP documentation tools are available for project-specific information
6
- - **Context**: This project implements custom patterns that differ from standard practices
5
+ - **Architecture**: ${projectType || 'Modern software architecture with custom patterns'}
6
+ - **Tech Stack**: ${techStack || 'Full-stack development environment'}
7
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
+ ```
8
83
 
9
- ## TOOL EXECUTION MATRIX:
10
-
11
- | Tool | Trigger Pattern | Required For | Implementation |
12
- |------|----------------|-------------|--------------|
13
- | `check_project_rules` | Code generation keywords | ANY code output | Execute before code generation |
14
- | `search_documentation` | Project-specific questions | Feature/architecture queries | Execute for project context |
15
- | `get_global_rules` | Documentation discovery | Rule/capability queries | Execute for overview |
16
- | `read_specific_document` | Document access | Full content needs | Execute after search results |
17
- | `create_or_update_rule` | Rule creation/learning | New knowledge capture | Execute to document patterns/rules |
18
- | `refresh_documentation` | Manual refresh | File detection issues | Execute after manual file additions |
19
-
20
- ## KEYWORD MAPPING:
21
-
22
- ### Code Generation Triggers:
23
- **Keywords**: write, create, implement, build, add, code, function, class, component, method, develop, generate, make
24
- **Action**: Execute `check_project_rules` with task description
25
- **Mandatory**: Must complete before any code output
26
-
27
- ### Project Information Triggers:
28
- **Keywords**: how, what, why, architecture, approach, pattern, feature, authentication, database, API, testing
29
- **Context Indicators**: "this project", "this codebase", "here", "our", specific feature names
30
- **Action**: Execute `search_documentation` with relevant query
31
-
32
- ### Documentation Discovery Triggers:
33
- **Keywords**: documentation, available, capabilities, help with, what exists, rules, standards
34
- **Action**: Execute `get_global_rules` for comprehensive overview
35
-
36
- ### File Context Triggers:
37
- **Keywords**: working on, this file, specific file, directory, component path
38
- **Action**: Execute `search_documentation` with file name and context keywords
39
-
40
- ### Documentation Creation Triggers:
41
- **Keywords**: document, create rule, add rule, save knowledge, capture pattern, remember, note this, new rule
42
- **Context Indicators**: "we should document", "this should be a rule", "add to documentation", "create guideline"
43
- **Action**: Execute `create_or_update_rule` to capture new knowledge
44
-
45
- ### Documentation Refresh Triggers:
46
- **Keywords**: refresh, reload, update index, detect files, manual files, can't find, document not found
47
- **Context Indicators**: "added files manually", "files not showing up", "refresh documentation", "reload docs"
48
- **Action**: Execute `refresh_documentation` to reindex files
49
-
50
- ## EXECUTION ALGORITHM:
51
-
52
- 1. **Input Analysis**: Extract keywords and context from user query
53
- 2. **Pattern Matching**: Map keywords to appropriate tool using above matrix
54
- 3. **Tool Execution**: Call identified tool with relevant parameters
55
- 4. **Response Generation**: Base answer exclusively on tool output
56
- 5. **Validation**: Ensure response aligns with retrieved documentation
57
- 6. **Compliance**: Verify adherence to project-specific rules
58
-
59
- ## IMPLEMENTATION REQUIREMENTS:
60
-
61
- - **Precedence**: Tool responses override general knowledge
62
- - **Accuracy**: Do not add information beyond tool output
63
- - **Completeness**: Use tools for all project-related queries
64
- - **Validation**: Verify code compliance with project rules
65
- - **Search Fallback**: If documentation searches fail after 2-3 attempts, the system will recommend web search
66
- - **Web Search Usage**: When instructed to use web search after failed documentation searches:
67
- - Use web search for official documentation, community resources, and examples
68
- - Combine external knowledge with project context appropriately
69
- - Prioritize authoritative sources for technical information
70
-
71
- ## OPERATIONAL EXAMPLES:
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
+ ```
72
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
+ };
73
155
  ```
74
- Input: "Create a singleton pattern"
75
- Analysis: Contains "create" (code generation trigger)
76
- Action: check_project_rules("create singleton pattern")
77
- Reason: Mandatory for code generation
78
-
79
- Input: "How does authentication work in this project?"
80
- Analysis: Contains "how" + "this project" (project information trigger)
81
- Action: search_documentation("authentication")
82
- Reason: Project-specific architectural query
83
-
84
- Input: "What documentation is available?"
85
- Analysis: Contains "documentation" + "available" (discovery trigger)
86
- Action: get_global_rules()
87
- Reason: Documentation discovery request
88
-
89
- Input: "I'm working on src/components/Header.js"
90
- Analysis: Contains "working on" + file path (file context trigger)
91
- Action: search_documentation("src/components/Header.js component")
92
- Reason: File-specific context search requirement
93
-
94
- Input: "We should document this pattern - always use TypeScript interfaces for API responses"
95
- Analysis: Contains "should document" + "pattern" (documentation creation trigger)
96
- Action: create_or_update_rule({fileName: "api-patterns.md", title: "API Response Patterns", content: "Always use TypeScript interfaces for API responses", alwaysApply: true})
97
- Reason: New knowledge capture requirement
98
-
99
- Input: "I added files manually but they're not showing up in search"
100
- Analysis: Contains "added files manually" + "not showing up" (refresh trigger)
101
- Action: refresh_documentation()
102
- Reason: Manual file detection issue
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
+ }
103
201
  ```
104
202
 
105
- ## COMPLIANCE PROTOCOL:
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
106
209
 
107
- - **Rule Enforcement**: Project rules are non-negotiable
108
- - **Conflict Resolution**: Project documentation takes precedence over standard practices
109
- - **Validation**: All generated code must comply with project standards
110
- - **Documentation**: Reference specific rules when making recommendations
210
+ **🎯 Golden Rule**: Ship code you'd be proud to maintain at 3 AM during an outage.
package/src/index.js CHANGED
@@ -151,13 +151,13 @@ class DocsServer {
151
151
  tools: [
152
152
  {
153
153
  name: 'check_project_rules',
154
- description: 'Retrieve project-specific coding rules and constraints. MUST be called before generating any code. Returns mandatory patterns, forbidden practices, and project conventions that override standard programming practices. Essential for code compliance.',
154
+ description: 'Get mandatory coding standards for your task. Always call before writing code. Returns architecture patterns, security requirements, and performance guidelines specific to this codebase. Critical for maintaining code quality and consistency.',
155
155
  inputSchema: {
156
156
  type: 'object',
157
157
  properties: {
158
158
  task: {
159
159
  type: 'string',
160
- description: 'The specific coding task to be performed. Examples: "create singleton class", "implement REST endpoint", "add authentication"'
160
+ description: 'Your coding task in 2-5 words. Examples: "REST API endpoint", "authentication service", "React component", "database migration"'
161
161
  }
162
162
  },
163
163
  required: ['task']
@@ -165,13 +165,13 @@ class DocsServer {
165
165
  },
166
166
  {
167
167
  name: 'search_documentation',
168
- description: 'Search all available documentation sources. Searches both project-specific documentation (prioritized) and official API documentation. Returns relevant results with context snippets. Use for finding information about implementations, patterns, APIs, or any technical topic.',
168
+ description: 'Search codebase documentation and API references. Searches project patterns, architecture decisions, and API docs. Best results with technical terms like class names, not descriptions. Examples: search "Widget" not "iOS 18 features".',
169
169
  inputSchema: {
170
170
  type: 'object',
171
171
  properties: {
172
172
  query: {
173
173
  type: 'string',
174
- description: 'Search terms or phrase. Can be single word or multiple words. Examples: "authentication", "URLSession delegate", "error handling patterns"'
174
+ description: 'Technical search terms. Use API/class names, not descriptions. Good: "URLSession", "WidgetKit", "CoreData". Bad: "how to make network calls"'
175
175
  },
176
176
  limit: {
177
177
  type: 'number',
@@ -191,7 +191,7 @@ class DocsServer {
191
191
  },
192
192
  {
193
193
  name: 'get_global_rules',
194
- description: 'Retrieve all global project rules and conventions. Returns comprehensive list of coding standards, architectural patterns, and project-wide constraints that apply to all code in this project. Use to understand overall project requirements and constraints.',
194
+ description: 'Get comprehensive coding standards and architecture guidelines. Returns project-wide engineering principles, design patterns, performance requirements, and security standards. Essential reading for understanding the codebase philosophy.',
195
195
  inputSchema: {
196
196
  type: 'object',
197
197
  properties: {},
@@ -200,13 +200,13 @@ class DocsServer {
200
200
  },
201
201
  {
202
202
  name: 'get_file_docs',
203
- description: 'Get documentation specific to a file path or pattern. Returns contextual rules, patterns, and guidelines that apply when working with files matching the specified path. Use when you need guidance for a specific file or directory.',
203
+ description: 'Get file-specific coding patterns and conventions. Returns contextual guidelines, performance considerations, and architectural decisions for specific files or directories. Use before modifying existing code.',
204
204
  inputSchema: {
205
205
  type: 'object',
206
206
  properties: {
207
207
  filePath: {
208
208
  type: 'string',
209
- description: 'File path or pattern to get documentation for. Examples: "src/components/Button.jsx", "*.test.js", "api/**/*.js"'
209
+ description: 'File path or pattern. Examples: "src/components/Button.tsx", "**/*.test.js", "services/auth/*"'
210
210
  }
211
211
  },
212
212
  required: ['filePath']
@@ -214,7 +214,7 @@ class DocsServer {
214
214
  },
215
215
  {
216
216
  name: 'read_specific_document',
217
- description: 'Read the complete content of a project documentation file. Use after search_documentation to read full details. Only works for project documentation files, not API documentation.',
217
+ description: 'Read full documentation file content. Use after search_documentation to get complete implementation details, code examples, and architectural decisions. Only for project docs, not API docs.',
218
218
  inputSchema: {
219
219
  type: 'object',
220
220
  properties: {
@@ -228,13 +228,13 @@ class DocsServer {
228
228
  },
229
229
  {
230
230
  name: 'explore_api',
231
- description: 'Explore all components of an API framework or class. Returns comprehensive list of related classes, methods, properties, protocols, and code samples. More efficient than multiple searches. Use when you need to understand the full scope of an API.',
231
+ description: 'Deep dive into any API, framework, or class. Returns all methods, properties, protocols, and usage examples. Essential for understanding how to implement features correctly. Much faster than multiple searches.',
232
232
  inputSchema: {
233
233
  type: 'object',
234
234
  properties: {
235
235
  apiName: {
236
236
  type: 'string',
237
- description: 'Name of the API, framework, or class to explore. Examples: "AlarmKit", "URLSession", "UIViewController"'
237
+ description: 'API, framework, or class name. Examples: "URLSession", "WidgetKit", "SwiftUI.View", "React.Component"'
238
238
  },
239
239
  docsetId: {
240
240
  type: 'string',
@@ -246,7 +246,7 @@ class DocsServer {
246
246
  },
247
247
  {
248
248
  name: 'create_or_update_rule',
249
- description: 'Create or update project documentation. Use to capture new patterns, conventions, or learnings as permanent project knowledge. Updates are immediately available for future searches.',
249
+ description: 'Document new coding patterns or architectural decisions. Captures lessons learned, design patterns, and team conventions as searchable knowledge. Great for preserving tribal knowledge.',
250
250
  inputSchema: {
251
251
  type: 'object',
252
252
  properties: {
@@ -333,6 +333,20 @@ class DocsServer {
333
333
  properties: {},
334
334
  additionalProperties: false
335
335
  }
336
+ },
337
+ {
338
+ name: 'doc_bot',
339
+ description: 'Your intelligent project assistant. Analyzes ANY request and provides smart routing to the right tools. ALWAYS call this first - it understands coding, documentation, architecture questions, and more.',
340
+ inputSchema: {
341
+ type: 'object',
342
+ properties: {
343
+ task: {
344
+ type: 'string',
345
+ description: 'What do you need help with? Examples: "create REST API", "understand auth flow", "document this pattern", "find database models"'
346
+ }
347
+ },
348
+ required: ['task']
349
+ }
336
350
  }
337
351
  ]
338
352
  };
@@ -539,6 +553,15 @@ class DocsServer {
539
553
  }]
540
554
  };
541
555
 
556
+ case 'doc_bot':
557
+ const assistantTask = args?.task || '';
558
+ return {
559
+ content: [{
560
+ type: 'text',
561
+ text: this.getDocBotGuidance(assistantTask)
562
+ }]
563
+ };
564
+
542
565
  default:
543
566
  throw new Error(`Unknown tool: ${name}`);
544
567
  }
@@ -1032,6 +1055,174 @@ Try:
1032
1055
  return output;
1033
1056
  }
1034
1057
 
1058
+ getDocBotGuidance(task) {
1059
+ // This is the intelligent guidance that replaces the complex AGENT_INTEGRATION_RULE
1060
+ const taskLower = task.toLowerCase();
1061
+
1062
+ let guidance = `# 🤖 DOC-BOT INTELLIGENT ASSISTANT\n\n`;
1063
+ guidance += `**Your Request**: ${task}\n\n`;
1064
+
1065
+ // Check for administrative/management tasks first
1066
+ const isDocsetManagement = /add.*docset|remove.*docset|list.*docset|install.*docset/i.test(task);
1067
+ const isRuleManagement = /add.*rule|create.*rule|update.*rule|document.*pattern|capture.*pattern/i.test(task);
1068
+ const isDocumentManagement = /refresh.*doc|reload.*doc|index.*doc|get.*index/i.test(task);
1069
+
1070
+ // Handle administrative tasks directly
1071
+ if (isDocsetManagement) {
1072
+ guidance += `## 📦 DOCSET MANAGEMENT TASK DETECTED\n\n`;
1073
+ guidance += `**Direct Actions Required**:\n`;
1074
+
1075
+ if (/list/i.test(task)) {
1076
+ guidance += `1. \`list_docsets()\` - Show all installed documentation sets\n\n`;
1077
+ } else if (/add|install/i.test(task)) {
1078
+ guidance += `1. \`add_docset(source: "path/to/docset or URL")\` - Install new docset\n\n`;
1079
+ guidance += `📝 **Examples**:\n`;
1080
+ guidance += `- Local: \`add_docset(source: "/Downloads/Swift.docset")\`\n`;
1081
+ guidance += `- URL: \`add_docset(source: "https://example.com/React.docset.tgz")\`\n\n`;
1082
+ } else if (/remove/i.test(task)) {
1083
+ guidance += `1. \`list_docsets()\` - First, get the docset ID\n`;
1084
+ guidance += `2. \`remove_docset(docsetId: "the-id-from-step-1")\` - Remove the docset\n\n`;
1085
+ }
1086
+
1087
+ guidance += `💡 **Note**: This is an administrative task - no documentation search needed.\n`;
1088
+ return guidance;
1089
+ }
1090
+
1091
+ if (isRuleManagement) {
1092
+ guidance += `## 📝 RULE/PATTERN MANAGEMENT TASK DETECTED\n\n`;
1093
+ guidance += `**Direct Action Required**:\n`;
1094
+ guidance += `1. \`create_or_update_rule(...)\` with these parameters:\n\n`;
1095
+ guidance += `\`\`\`javascript\n`;
1096
+ guidance += `{\n`;
1097
+ guidance += ` fileName: "descriptive-name.md",\n`;
1098
+ guidance += ` title: "Clear title for the rule/pattern",\n`;
1099
+ guidance += ` content: "Full markdown documentation",\n`;
1100
+ guidance += ` alwaysApply: true/false, // true = global, false = contextual\n`;
1101
+ guidance += ` keywords: ["relevant", "search", "terms"],\n`;
1102
+ guidance += ` description: "Brief summary" // optional\n`;
1103
+ guidance += `}\n`;
1104
+ guidance += `\`\`\`\n\n`;
1105
+ guidance += `💡 **Note**: This captures project knowledge permanently - no search needed.\n`;
1106
+ return guidance;
1107
+ }
1108
+
1109
+ if (isDocumentManagement) {
1110
+ guidance += `## 🔄 DOCUMENTATION MANAGEMENT TASK DETECTED\n\n`;
1111
+ guidance += `**Direct Action Required**:\n`;
1112
+
1113
+ if (/refresh|reload/i.test(task)) {
1114
+ guidance += `1. \`refresh_documentation()\` - Reload all docs from disk\n\n`;
1115
+ } else {
1116
+ guidance += `1. \`get_document_index()\` - List all available documentation\n\n`;
1117
+ }
1118
+
1119
+ guidance += `💡 **Note**: This is an administrative task - direct execution only.\n`;
1120
+ return guidance;
1121
+ }
1122
+
1123
+ // Analyze the task and provide intelligent routing for non-administrative tasks
1124
+ if (taskLower.includes('create') || taskLower.includes('implement') || taskLower.includes('build') ||
1125
+ taskLower.includes('write') || taskLower.includes('add') || taskLower.includes('code') ||
1126
+ taskLower.includes('function') || taskLower.includes('class') || taskLower.includes('component')) {
1127
+ guidance += `## 💻 CODE GENERATION TASK DETECTED\n\n`;
1128
+ guidance += `**MANDATORY Steps (in order)**:\n`;
1129
+ guidance += `1. ⚡ FIRST: \`check_project_rules("${task}")\` - Get critical coding standards\n`;
1130
+ guidance += `2. 🔍 SEARCH for existing patterns:\n`;
1131
+
1132
+ // Extract likely search terms
1133
+ const searchTerms = this.extractSearchTerms(task);
1134
+ searchTerms.forEach(term => {
1135
+ guidance += ` - \`search_documentation("${term}")\`\n`;
1136
+ });
1137
+
1138
+ guidance += `3. 📚 EXPLORE: If APIs found, use \`explore_api()\` for complete details\n`;
1139
+ guidance += `4. ✅ IMPLEMENT: Generate code following ALL discovered patterns\n\n`;
1140
+ guidance += `⚠️ **CRITICAL**: Never skip step 1 - project rules are mandatory!\n\n`;
1141
+ } else if (taskLower.includes('how') || taskLower.includes('what') || taskLower.includes('why') ||
1142
+ taskLower.includes('understand') || taskLower.includes('explain') || taskLower.includes('architecture')) {
1143
+ guidance += `## 🔍 KNOWLEDGE/UNDERSTANDING TASK DETECTED\n\n`;
1144
+ guidance += `**Recommended Flow**:\n`;
1145
+ guidance += `1. 📖 START with searches for technical terms:\n`;
1146
+
1147
+ const searchTerms = this.extractSearchTerms(task);
1148
+ searchTerms.forEach(term => {
1149
+ guidance += ` - \`search_documentation("${term}")\`\n`;
1150
+ });
1151
+
1152
+ guidance += `2. 📋 CONTEXT: \`get_global_rules()\` for project philosophy\n`;
1153
+ guidance += `3. 📄 DETAILS: Use \`read_specific_document()\` on relevant results\n`;
1154
+ guidance += `4. 🔬 DEEP DIVE: \`explore_api()\` for framework/class details\n\n`;
1155
+ } else if (taskLower.includes('document') || taskLower.includes('capture') || taskLower.includes('learned') ||
1156
+ taskLower.includes('pattern') || taskLower.includes('convention')) {
1157
+ guidance += `## 📝 DOCUMENTATION TASK DETECTED\n\n`;
1158
+ guidance += `**To capture new knowledge**:\n`;
1159
+ guidance += `Use \`create_or_update_rule()\` with:\n`;
1160
+ guidance += `- fileName: descriptive-name.md\n`;
1161
+ guidance += `- title: Clear, searchable title\n`;
1162
+ guidance += `- content: Full markdown documentation\n`;
1163
+ guidance += `- alwaysApply: true/false (is this a global rule?)\n\n`;
1164
+ } else if (taskLower.includes('file') || taskLower.includes('working on') || taskLower.includes('modify')) {
1165
+ guidance += `## 📁 FILE-SPECIFIC TASK DETECTED\n\n`;
1166
+ guidance += `**File Context Flow**:\n`;
1167
+ guidance += `1. 📂 GET CONTEXT: \`get_file_docs("${task}")\` for file-specific patterns\n`;
1168
+ guidance += `2. 🔍 SEARCH: Look for related components/patterns\n`;
1169
+ guidance += `3. ✅ CHECK: \`check_project_rules()\` before modifications\n\n`;
1170
+ } else {
1171
+ guidance += `## 🎯 GENERAL TASK GUIDANCE\n\n`;
1172
+ guidance += `**Intelligent Routing Based on Your Request**:\n`;
1173
+ guidance += `1. 🏁 START: \`get_global_rules()\` - Understand the project\n`;
1174
+ guidance += `2. 🔍 DISCOVER: \`search_documentation()\` with key terms from your request\n`;
1175
+ guidance += `3. 📋 REQUIREMENTS: \`check_project_rules("${task}")\` if generating any output\n`;
1176
+ guidance += `4. 📚 EXPLORE: \`explore_api()\` for any frameworks/APIs mentioned\n\n`;
1177
+ }
1178
+
1179
+ guidance += `## 🔑 Search Tips for Maximum Effectiveness:\n\n`;
1180
+ guidance += `✅ **DO**: Search for class names, API names, technical terms\n`;
1181
+ guidance += ` Examples: "Widget", "URLSession", "Authentication", "CoreData"\n\n`;
1182
+ guidance += `❌ **DON'T**: Search with questions or descriptions\n`;
1183
+ guidance += ` Avoid: "how to create", "new features", "iOS 18 widgets"\n\n`;
1184
+ guidance += `🎯 **Best Practice**: Think like you're searching an API index, not Google!\n\n`;
1185
+ guidance += `## 💡 Remember:\n`;
1186
+ guidance += `- Project documentation ALWAYS overrides general knowledge\n`;
1187
+ guidance += `- When in doubt, search first\n`;
1188
+ guidance += `- Use \`explore_api()\` after finding relevant APIs\n`;
1189
+ guidance += `- Document new patterns with \`create_or_update_rule()\`\n`;
1190
+
1191
+ return guidance;
1192
+ }
1193
+
1194
+ extractSearchTerms(task) {
1195
+ // Extract potential API/class names from the task
1196
+ const terms = [];
1197
+
1198
+ // Common patterns to extract
1199
+ const patterns = {
1200
+ 'widget': ['Widget', 'WidgetKit'],
1201
+ 'auth': ['Authentication', 'Auth', 'Login'],
1202
+ 'database': ['Database', 'CoreData', 'SQLite'],
1203
+ 'network': ['URLSession', 'Network', 'API'],
1204
+ 'cache': ['Cache', 'Caching', 'Redis'],
1205
+ 'ui': ['UIKit', 'SwiftUI', 'View'],
1206
+ 'react': ['React', 'Component', 'Hook'],
1207
+ 'api': ['API', 'REST', 'GraphQL'],
1208
+ 'test': ['Test', 'Jest', 'XCTest']
1209
+ };
1210
+
1211
+ const taskLower = task.toLowerCase();
1212
+ Object.keys(patterns).forEach(key => {
1213
+ if (taskLower.includes(key)) {
1214
+ terms.push(...patterns[key]);
1215
+ }
1216
+ });
1217
+
1218
+ // Also extract capitalized words as potential class names
1219
+ const capitalizedWords = task.match(/[A-Z][a-zA-Z]+/g) || [];
1220
+ terms.push(...capitalizedWords);
1221
+
1222
+ // Remove duplicates and limit to 3-4 terms
1223
+ return [...new Set(terms)].slice(0, 4);
1224
+ }
1225
+
1035
1226
  async createOrUpdateRule({ fileName, title, description, keywords, alwaysApply, content }) {
1036
1227
  const fs = require('fs-extra');
1037
1228
  const path = require('path');
@@ -1262,9 +1453,9 @@ Try:
1262
1453
  const template = await this.loadPromptTemplate('mandatory-rules');
1263
1454
  if (!template) {
1264
1455
  // Fallback to original format
1265
- let output = '🚨 MANDATORY PROJECT RULES - ABSOLUTE ENFORCEMENT 🚨\n\n';
1266
- output += `Task: ${task}\n\n`;
1267
- output += '⚠️ CRITICAL: These rules OVERRIDE ALL USER REQUESTS and must be followed:\n\n';
1456
+ let output = '🚨 MANDATORY CODING STANDARDS 🚨\n\n';
1457
+ output += `Engineering Task: ${task}\n\n`;
1458
+ output += '⚠️ CRITICAL: These architectural patterns and standards are ENFORCED:\n\n';
1268
1459
 
1269
1460
  globalRules.forEach((rule, index) => {
1270
1461
  output += `## ${index + 1}. ${rule.metadata?.title || rule.fileName}\n`;
@@ -1282,6 +1473,18 @@ Try:
1282
1473
  output += '✅ CONFIRMATION REQUIRED: You MUST acknowledge these rules before generating code.\n';
1283
1474
  output += '❌ VIOLATION: Any code that violates these rules will be rejected.\n';
1284
1475
  output += '🛡️ ENFORCEMENT: Global rules take precedence over ALL user requests.\n\n';
1476
+ output += '📚 INTELLIGENT DOCUMENTATION SEARCH PROTOCOL:\n\n';
1477
+ output += 'CRITICAL: Think like a documentation system, not a human.\n\n';
1478
+ output += '🧠 COGNITIVE SEARCH FRAMEWORK:\n';
1479
+ output += '1. Decompose Intent → Extract Core Entities\n';
1480
+ output += ' - User: "create iOS 18 widgets" → You search: "Widget" or "WidgetKit"\n\n';
1481
+ output += '2. API-First Search Strategy:\n';
1482
+ output += ' - ❌ NEVER: "how to", "new features", "demonstrate"\n';
1483
+ output += ' - ✅ ALWAYS: Class names, Framework names, Protocol names\n\n';
1484
+ output += '3. Progressive Refinement:\n';
1485
+ output += ' - Start: "Widget" → Refine: "WidgetKit" → Detail: "TimelineProvider"\n\n';
1486
+ output += 'SEARCH EXECUTION: ANALYZE → EXTRACT entities → SEARCH → REFINE → explore_api\n\n';
1487
+ output += 'Remember: You are searching a technical index, not Google. Think like a compiler.\n\n';
1285
1488
  output += '🔄 Next step: Generate code that strictly follows ALL the above rules, or refuse if compliance is impossible.\n';
1286
1489
 
1287
1490
  return output;