tachibot-mcp 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 (214) hide show
  1. package/.env.example +260 -0
  2. package/CHANGELOG.md +54 -0
  3. package/CODE_OF_CONDUCT.md +56 -0
  4. package/CONTRIBUTING.md +54 -0
  5. package/Dockerfile +36 -0
  6. package/LICENSE +644 -0
  7. package/README.md +201 -0
  8. package/SECURITY.md +95 -0
  9. package/dist/personality/komaai-expressions.js +12 -0
  10. package/dist/profiles/balanced.json +33 -0
  11. package/dist/profiles/code_focus.json +33 -0
  12. package/dist/profiles/full.json +33 -0
  13. package/dist/profiles/minimal.json +33 -0
  14. package/dist/profiles/research_power.json +33 -0
  15. package/dist/scripts/build-profiles.js +46 -0
  16. package/dist/src/application/services/focus/FocusModeRegistry.js +46 -0
  17. package/dist/src/application/services/focus/FocusTool.service.js +109 -0
  18. package/dist/src/application/services/focus/ModeRegistry.js +46 -0
  19. package/dist/src/application/services/focus/modes/focus-deep.mode.js +27 -0
  20. package/dist/src/application/services/focus/modes/status.mode.js +50 -0
  21. package/dist/src/application/services/focus/modes/tachibot-status.mode.js +50 -0
  22. package/dist/src/collaborative-orchestrator.js +391 -0
  23. package/dist/src/config/model-constants.js +188 -0
  24. package/dist/src/config/model-defaults.js +57 -0
  25. package/dist/src/config/model-preferences.js +382 -0
  26. package/dist/src/config/timeout-config.js +130 -0
  27. package/dist/src/config.js +173 -0
  28. package/dist/src/domain/interfaces/IFocusMode.js +5 -0
  29. package/dist/src/domain/interfaces/IProvider.js +6 -0
  30. package/dist/src/domain/interfaces/ITool.js +5 -0
  31. package/dist/src/focus-deep.js +245 -0
  32. package/dist/src/infrastructure/ascii/art/robots.ascii.js +16 -0
  33. package/dist/src/mcp-client.js +90 -0
  34. package/dist/src/memory/index.js +17 -0
  35. package/dist/src/memory/memory-config.js +135 -0
  36. package/dist/src/memory/memory-interface.js +174 -0
  37. package/dist/src/memory/memory-manager.js +383 -0
  38. package/dist/src/memory/providers/devlog-provider.js +385 -0
  39. package/dist/src/memory/providers/hybrid-provider.js +399 -0
  40. package/dist/src/memory/providers/local-provider.js +388 -0
  41. package/dist/src/memory/providers/mem0-provider.js +337 -0
  42. package/dist/src/modes/architect.js +477 -0
  43. package/dist/src/modes/auditor.js +362 -0
  44. package/dist/src/modes/challenger.js +841 -0
  45. package/dist/src/modes/code-reviewer.js +382 -0
  46. package/dist/src/modes/commit-guardian.js +424 -0
  47. package/dist/src/modes/documentation-writer.js +572 -0
  48. package/dist/src/modes/scout.js +587 -0
  49. package/dist/src/modes/shared/helpers/challenger-helpers.js +454 -0
  50. package/dist/src/modes/shared/helpers/index.js +17 -0
  51. package/dist/src/modes/shared/helpers/scout-helpers.js +270 -0
  52. package/dist/src/modes/shared/helpers/verifier-helpers.js +332 -0
  53. package/dist/src/modes/test-architect.js +767 -0
  54. package/dist/src/modes/verifier.js +378 -0
  55. package/dist/src/monitoring/performance-monitor.js +435 -0
  56. package/dist/src/optimization/batch-executor.js +121 -0
  57. package/dist/src/optimization/context-pruner.js +196 -0
  58. package/dist/src/optimization/cost-monitor.js +338 -0
  59. package/dist/src/optimization/index.js +65 -0
  60. package/dist/src/optimization/model-router.js +264 -0
  61. package/dist/src/optimization/result-cache.js +114 -0
  62. package/dist/src/optimization/token-optimizer.js +257 -0
  63. package/dist/src/optimization/token-tracker.js +118 -0
  64. package/dist/src/orchestrator-instructions.js +128 -0
  65. package/dist/src/orchestrator-lite.js +139 -0
  66. package/dist/src/orchestrator.js +191 -0
  67. package/dist/src/orchestrators/collaborative/interfaces/IToolExecutionEngine.js +1 -0
  68. package/dist/src/orchestrators/collaborative/interfaces/IToolExecutionStrategy.js +5 -0
  69. package/dist/src/orchestrators/collaborative/interfaces/IVisualizationRenderer.js +1 -0
  70. package/dist/src/orchestrators/collaborative/registries/ModelProviderRegistry.js +95 -0
  71. package/dist/src/orchestrators/collaborative/registries/ToolAdapterRegistry.js +64 -0
  72. package/dist/src/orchestrators/collaborative/services/tool-execution/ToolExecutionService.js +502 -0
  73. package/dist/src/orchestrators/collaborative/services/visualization/VisualizationService.js +206 -0
  74. package/dist/src/orchestrators/collaborative/types/session-types.js +5 -0
  75. package/dist/src/profiles/balanced.js +37 -0
  76. package/dist/src/profiles/code_focus.js +37 -0
  77. package/dist/src/profiles/debug_intensive.js +59 -0
  78. package/dist/src/profiles/full.js +37 -0
  79. package/dist/src/profiles/minimal.js +37 -0
  80. package/dist/src/profiles/research_code.js +59 -0
  81. package/dist/src/profiles/research_power.js +37 -0
  82. package/dist/src/profiles/types.js +5 -0
  83. package/dist/src/profiles/workflow_builder.js +53 -0
  84. package/dist/src/prompt-engineer-lite.js +78 -0
  85. package/dist/src/prompt-engineer.js +399 -0
  86. package/dist/src/reasoning-chain.js +508 -0
  87. package/dist/src/sequential-thinking.js +291 -0
  88. package/dist/src/server-diagnostic.js +74 -0
  89. package/dist/src/server-raw.js +158 -0
  90. package/dist/src/server-simple.js +58 -0
  91. package/dist/src/server.js +514 -0
  92. package/dist/src/session/session-logger.js +617 -0
  93. package/dist/src/session/session-manager.js +571 -0
  94. package/dist/src/session/session-tools.js +400 -0
  95. package/dist/src/tools/advanced-modes.js +200 -0
  96. package/dist/src/tools/claude-integration.js +356 -0
  97. package/dist/src/tools/consolidated/ai-router.js +174 -0
  98. package/dist/src/tools/consolidated/ai-tool.js +48 -0
  99. package/dist/src/tools/consolidated/brainstorm-tool.js +87 -0
  100. package/dist/src/tools/consolidated/environment-detector.js +80 -0
  101. package/dist/src/tools/consolidated/index.js +50 -0
  102. package/dist/src/tools/consolidated/search-tool.js +110 -0
  103. package/dist/src/tools/consolidated/workflow-tool.js +238 -0
  104. package/dist/src/tools/gemini-tools.js +329 -0
  105. package/dist/src/tools/grok-enhanced.js +376 -0
  106. package/dist/src/tools/grok-tools.js +299 -0
  107. package/dist/src/tools/lmstudio-tools.js +223 -0
  108. package/dist/src/tools/openai-tools.js +498 -0
  109. package/dist/src/tools/openrouter-tools.js +317 -0
  110. package/dist/src/tools/optimized-wrapper.js +204 -0
  111. package/dist/src/tools/perplexity-tools.js +294 -0
  112. package/dist/src/tools/pingpong-tool.js +343 -0
  113. package/dist/src/tools/qwen-wrapper.js +74 -0
  114. package/dist/src/tools/tool-router.js +444 -0
  115. package/dist/src/tools/unified-ai-provider.js +260 -0
  116. package/dist/src/tools/workflow-runner.js +425 -0
  117. package/dist/src/tools/workflow-validator-tool.js +107 -0
  118. package/dist/src/types.js +23 -0
  119. package/dist/src/utils/input-validator.js +130 -0
  120. package/dist/src/utils/model-router.js +91 -0
  121. package/dist/src/utils/progress-stream.js +255 -0
  122. package/dist/src/utils/provider-router.js +88 -0
  123. package/dist/src/utils/smart-api-client.js +146 -0
  124. package/dist/src/utils/table-builder.js +218 -0
  125. package/dist/src/utils/timestamp-formatter.js +134 -0
  126. package/dist/src/utils/tool-compressor.js +257 -0
  127. package/dist/src/utils/tool-config.js +201 -0
  128. package/dist/src/validators/dependency-graph-validator.js +147 -0
  129. package/dist/src/validators/interpolation-validator.js +222 -0
  130. package/dist/src/validators/output-usage-validator.js +151 -0
  131. package/dist/src/validators/syntax-validator.js +102 -0
  132. package/dist/src/validators/tool-registry-validator.js +123 -0
  133. package/dist/src/validators/tool-types.js +97 -0
  134. package/dist/src/validators/types.js +8 -0
  135. package/dist/src/validators/workflow-validator.js +134 -0
  136. package/dist/src/visualizer-lite.js +42 -0
  137. package/dist/src/visualizer.js +179 -0
  138. package/dist/src/workflows/circuit-breaker.js +199 -0
  139. package/dist/src/workflows/custom-workflows.js +451 -0
  140. package/dist/src/workflows/engine/AutoSynthesizer.js +97 -0
  141. package/dist/src/workflows/engine/StepParameterResolver.js +74 -0
  142. package/dist/src/workflows/engine/VariableInterpolator.js +123 -0
  143. package/dist/src/workflows/engine/WorkflowDiscovery.js +125 -0
  144. package/dist/src/workflows/engine/WorkflowExecutionEngine.js +485 -0
  145. package/dist/src/workflows/engine/WorkflowExecutor.js +113 -0
  146. package/dist/src/workflows/engine/WorkflowFileManager.js +244 -0
  147. package/dist/src/workflows/engine/WorkflowHelpers.js +114 -0
  148. package/dist/src/workflows/engine/WorkflowOutputFormatter.js +83 -0
  149. package/dist/src/workflows/engine/events/WorkflowEventBus.js +132 -0
  150. package/dist/src/workflows/engine/events/interfaces/IEventBus.js +5 -0
  151. package/dist/src/workflows/engine/handlers/ErrorRecoveryHandler.js +162 -0
  152. package/dist/src/workflows/engine/handlers/PromptEnhancementHandler.js +115 -0
  153. package/dist/src/workflows/engine/handlers/SessionPersistenceHandler.js +167 -0
  154. package/dist/src/workflows/engine/handlers/StepExecutionHandler.js +231 -0
  155. package/dist/src/workflows/engine/handlers/ToolInvocationHandler.js +46 -0
  156. package/dist/src/workflows/engine/interfaces/IAutoSynthesizer.js +5 -0
  157. package/dist/src/workflows/engine/interfaces/IStepParameterResolver.js +5 -0
  158. package/dist/src/workflows/engine/interfaces/IVariableInterpolator.js +5 -0
  159. package/dist/src/workflows/engine/interfaces/IWorkflowDiscovery.js +4 -0
  160. package/dist/src/workflows/engine/interfaces/IWorkflowFileManager.js +5 -0
  161. package/dist/src/workflows/engine/interfaces/IWorkflowOutputFormatter.js +5 -0
  162. package/dist/src/workflows/engine/state/WorkflowStateMachine.js +194 -0
  163. package/dist/src/workflows/engine/state/interfaces/IStateMachine.js +17 -0
  164. package/dist/src/workflows/fallback-strategies.js +373 -0
  165. package/dist/src/workflows/message-queue.js +455 -0
  166. package/dist/src/workflows/model-router.js +189 -0
  167. package/dist/src/workflows/orchestrator-examples.js +174 -0
  168. package/dist/src/workflows/orchestrator-integration.js +200 -0
  169. package/dist/src/workflows/self-healing.js +524 -0
  170. package/dist/src/workflows/tool-mapper.js +407 -0
  171. package/dist/src/workflows/tool-orchestrator.js +796 -0
  172. package/dist/src/workflows/workflow-engine.js +573 -0
  173. package/dist/src/workflows/workflow-parser.js +283 -0
  174. package/dist/src/workflows/workflow-types.js +95 -0
  175. package/dist/src/workflows.js +568 -0
  176. package/dist/test-workflow-file-output.js +93 -0
  177. package/docs/API_KEYS.md +570 -0
  178. package/docs/CLAUDE_CODE_SETUP.md +181 -0
  179. package/docs/CLAUDE_DESKTOP_MANUAL.md +127 -0
  180. package/docs/CONFIGURATION.md +745 -0
  181. package/docs/FOCUS_MODES.md +240 -0
  182. package/docs/INSTALLATION_BOTH.md +145 -0
  183. package/docs/TERMS.md +352 -0
  184. package/docs/TOOLS_REFERENCE.md +1622 -0
  185. package/docs/TOOL_PARAMETERS.md +496 -0
  186. package/docs/TOOL_PROFILES.md +236 -0
  187. package/docs/WORKFLOWS.md +987 -0
  188. package/docs/WORKFLOW_OUTPUT.md +198 -0
  189. package/docs/WORKFLOW_PROGRESS_TRACKING.md +305 -0
  190. package/docs/workflows/design-brainstorm.md +335 -0
  191. package/package.json +97 -0
  192. package/profiles/balanced.json +37 -0
  193. package/profiles/code_focus.json +37 -0
  194. package/profiles/debug_intensive.json +34 -0
  195. package/profiles/full.json +37 -0
  196. package/profiles/minimal.json +37 -0
  197. package/profiles/research_power.json +37 -0
  198. package/profiles/workflow_builder.json +37 -0
  199. package/smithery.yaml +66 -0
  200. package/start.sh +8 -0
  201. package/tools.config.json +81 -0
  202. package/tsconfig.json +18 -0
  203. package/workflows/accessibility-code-audit.yaml +92 -0
  204. package/workflows/code-architecture-review.yaml +202 -0
  205. package/workflows/code-review.yaml +142 -0
  206. package/workflows/core/iterative-problem-solver.yaml +283 -0
  207. package/workflows/creative-brainstorm-yaml.yaml +215 -0
  208. package/workflows/pingpong.yaml +141 -0
  209. package/workflows/system/README.md +412 -0
  210. package/workflows/system/challenger.yaml +175 -0
  211. package/workflows/system/scout.yaml +164 -0
  212. package/workflows/system/verifier.yaml +133 -0
  213. package/workflows/ultra-creative-brainstorm.yaml +318 -0
  214. package/workflows/ux-research-flow.yaml +92 -0
@@ -0,0 +1,477 @@
1
+ import { ModelRouter } from '../workflows/model-router.js';
2
+ import { TokenTracker } from '../optimization/token-tracker.js';
3
+ import { BatchExecutor } from '../optimization/batch-executor.js';
4
+ export class Architect {
5
+ constructor() {
6
+ this.stages = {
7
+ gemini_analysis: {
8
+ model: 'gemini-2.5-flash',
9
+ maxTokens: 1000000,
10
+ tasks: [
11
+ 'fullCodebaseAnalysis',
12
+ 'dependencyMapping',
13
+ 'hotspotIdentification',
14
+ 'architectureExtraction',
15
+ 'metricsCalculation'
16
+ ]
17
+ },
18
+ specialized_verification: {
19
+ models: {
20
+ 'syntax_error': 'gpt-4-mini',
21
+ 'type_error': 'gpt-4-mini',
22
+ 'algorithmic_complexity': 'qwq-32b',
23
+ 'performance_issue': 'qwq-32b',
24
+ 'architectural_smell': 'claude-opus-4.1',
25
+ 'security_vulnerability': 'claude-opus-4.1',
26
+ 'dependency_conflict': 'perplexity-reasoning',
27
+ 'outdated_dependency': 'perplexity-reasoning',
28
+ 'design_pattern_violation': 'claude-opus-4.1',
29
+ 'memory_leak': 'qwq-32b',
30
+ 'race_condition': 'claude-opus-4.1',
31
+ 'code_duplication': 'gpt-4-mini',
32
+ 'circular_dependency': 'claude-opus-4.1'
33
+ },
34
+ dynamicTokens: {
35
+ min: 5000,
36
+ max: 50000,
37
+ allocation: 'based_on_complexity'
38
+ }
39
+ },
40
+ synthesis: {
41
+ model: 'think',
42
+ maxTokens: 10000
43
+ }
44
+ };
45
+ this.modelRouter = new ModelRouter();
46
+ this.tokenTracker = new TokenTracker();
47
+ this.batchExecutor = new BatchExecutor();
48
+ }
49
+ async analyze(query, options = {}) {
50
+ const startTime = Date.now();
51
+ const stageResults = [];
52
+ // Stage 1: Gemini Full Analysis
53
+ const geminiResult = await this.executeGeminiAnalysis(query, options);
54
+ stageResults.push(geminiResult);
55
+ // Extract hotspots and areas for deep analysis
56
+ const hotspots = this.extractHotspots(geminiResult.result);
57
+ const filesForReview = this.identifyFilesForReview(geminiResult.result, hotspots);
58
+ // Stage 2: Specialized Verification (Parallel)
59
+ const specializedResults = await this.executeSpecializedAnalysis(hotspots, filesForReview, options);
60
+ stageResults.push(...specializedResults);
61
+ // Stage 3: Synthesis
62
+ const synthesis = await this.executeSynthesis(stageResults);
63
+ stageResults.push(synthesis);
64
+ // Compile final result
65
+ return this.compileFinalResult(stageResults, hotspots, startTime);
66
+ }
67
+ async executeGeminiAnalysis(query, options) {
68
+ const startTime = Date.now();
69
+ const model = this.selectGeminiModel(options);
70
+ const maxTokens = this.calculateGeminiTokens(options);
71
+ const prompt = this.buildGeminiPrompt(query, options);
72
+ const result = await this.queryGemini(model, prompt, maxTokens);
73
+ return {
74
+ stage: 'gemini_analysis',
75
+ model,
76
+ result,
77
+ tokens: maxTokens,
78
+ duration: Date.now() - startTime
79
+ };
80
+ }
81
+ selectGeminiModel(options) {
82
+ if (options.depth === 'deep' || options.path?.includes('enterprise')) {
83
+ return 'gemini-2.5-pro';
84
+ }
85
+ return 'gemini-2.5-flash';
86
+ }
87
+ calculateGeminiTokens(options) {
88
+ const depthMultiplier = {
89
+ 'shallow': 0.3,
90
+ 'normal': 0.6,
91
+ 'deep': 1.0
92
+ };
93
+ const baseTokens = 1000000;
94
+ const multiplier = depthMultiplier[options.depth || 'normal'];
95
+ return Math.floor(baseTokens * multiplier);
96
+ }
97
+ buildGeminiPrompt(query, options) {
98
+ let prompt = `Analyze the following codebase comprehensively:\n\n`;
99
+ prompt += `Query: ${query}\n\n`;
100
+ if (options.path) {
101
+ prompt += `Path: ${options.path}\n`;
102
+ }
103
+ prompt += `Please provide:\n`;
104
+ prompt += `1. Architecture overview with patterns and components\n`;
105
+ prompt += `2. Dependency graph and external dependencies\n`;
106
+ prompt += `3. Hotspots requiring attention (security, performance, architecture)\n`;
107
+ prompt += `4. Code metrics and quality assessment\n`;
108
+ prompt += `5. Specific files needing deep review\n`;
109
+ if (options.focusAreas && options.focusAreas.length > 0) {
110
+ prompt += `\nFocus particularly on: ${options.focusAreas.join(', ')}\n`;
111
+ }
112
+ prompt += `\nOutput format: Structured JSON with clear categorization`;
113
+ return prompt;
114
+ }
115
+ async queryGemini(model, prompt, maxTokens) {
116
+ // Simulated Gemini response for now
117
+ return {
118
+ architecture: {
119
+ overview: "Modern microservices architecture with event-driven communication",
120
+ patterns: ["Repository", "CQRS", "Event Sourcing", "API Gateway"],
121
+ components: [
122
+ {
123
+ name: "AuthService",
124
+ type: "microservice",
125
+ responsibilities: ["Authentication", "Authorization", "Token management"],
126
+ dependencies: ["DatabaseService", "CacheService"],
127
+ issues: ["Potential race condition in token refresh"]
128
+ }
129
+ ],
130
+ layers: [
131
+ {
132
+ name: "Presentation",
133
+ components: ["WebUI", "MobileAPI"],
134
+ purpose: "User interaction and API exposure"
135
+ }
136
+ ]
137
+ },
138
+ hotspots: [
139
+ {
140
+ type: "security_vulnerability",
141
+ file: "src/auth/token.ts",
142
+ line: 145,
143
+ severity: "high",
144
+ description: "JWT token validation missing expiry check"
145
+ },
146
+ {
147
+ type: "performance_issue",
148
+ file: "src/database/queries.ts",
149
+ line: 89,
150
+ severity: "medium",
151
+ description: "N+1 query problem in user fetching"
152
+ }
153
+ ],
154
+ dependencies: {
155
+ internal: ["auth", "database", "cache", "messaging"],
156
+ external: [
157
+ { name: "express", version: "4.17.1", isOutdated: true },
158
+ { name: "jsonwebtoken", version: "8.5.1", hasVulnerabilities: true }
159
+ ]
160
+ },
161
+ metrics: {
162
+ totalFiles: 156,
163
+ totalLines: 25000,
164
+ complexity: 7.8,
165
+ techDebt: 45,
166
+ maintainabilityIndex: 72
167
+ },
168
+ filesForReview: [
169
+ "src/auth/token.ts",
170
+ "src/database/queries.ts",
171
+ "src/api/routes.ts"
172
+ ]
173
+ };
174
+ }
175
+ extractHotspots(geminiResult) {
176
+ const hotspots = geminiResult.hotspots || [];
177
+ // Add complexity scores
178
+ return hotspots.map(h => ({
179
+ ...h,
180
+ complexity: this.calculateHotspotComplexity(h),
181
+ suggestedModel: this.routeHotspotToModel(h.type)
182
+ }));
183
+ }
184
+ calculateHotspotComplexity(hotspot) {
185
+ const severityScore = {
186
+ 'low': 2,
187
+ 'medium': 4,
188
+ 'high': 6,
189
+ 'critical': 8
190
+ };
191
+ const typeComplexity = {
192
+ 'syntax_error': 1,
193
+ 'type_error': 2,
194
+ 'code_duplication': 2,
195
+ 'performance_issue': 5,
196
+ 'algorithmic_complexity': 7,
197
+ 'architectural_smell': 6,
198
+ 'security_vulnerability': 8,
199
+ 'race_condition': 9
200
+ };
201
+ const severity = severityScore[hotspot.severity] || 5;
202
+ const type = typeComplexity[hotspot.type] || 5;
203
+ return (severity + type) / 2;
204
+ }
205
+ routeHotspotToModel(type) {
206
+ return this.stages.specialized_verification.models[type] || 'claude-opus-4.1';
207
+ }
208
+ identifyFilesForReview(geminiResult, hotspots) {
209
+ const filesByModel = new Map();
210
+ // Group files by suggested model
211
+ for (const hotspot of hotspots) {
212
+ const model = hotspot.suggestedModel || 'claude-opus-4.1';
213
+ if (!filesByModel.has(model)) {
214
+ filesByModel.set(model, []);
215
+ }
216
+ if (hotspot.file) {
217
+ filesByModel.get(model).push(hotspot.file);
218
+ }
219
+ }
220
+ // Add general files for review
221
+ const generalFiles = geminiResult.filesForReview || [];
222
+ for (const file of generalFiles) {
223
+ if (!Array.from(filesByModel.values()).flat().includes(file)) {
224
+ const defaultModel = 'claude-opus-4.1';
225
+ if (!filesByModel.has(defaultModel)) {
226
+ filesByModel.set(defaultModel, []);
227
+ }
228
+ filesByModel.get(defaultModel).push(file);
229
+ }
230
+ }
231
+ return filesByModel;
232
+ }
233
+ async executeSpecializedAnalysis(hotspots, filesForReview, options) {
234
+ const tasks = [];
235
+ // Create parallel tasks for each model
236
+ for (const [model, files] of filesForReview) {
237
+ const relevantHotspots = hotspots.filter(h => h.suggestedModel === model);
238
+ const tokens = this.allocateTokensForModel(model, relevantHotspots, options);
239
+ tasks.push({
240
+ id: `verify_${model}`,
241
+ type: 'verification',
242
+ fn: () => this.verifyWithModel(model, files, relevantHotspots, tokens),
243
+ priority: this.getModelPriority(model),
244
+ timeout: 30000
245
+ });
246
+ }
247
+ // Execute in parallel
248
+ const results = await this.batchExecutor.execute(tasks);
249
+ // Convert to StageResult format
250
+ return results.map((r) => ({
251
+ stage: 'specialized_verification',
252
+ model: r.id.replace('verify_', ''),
253
+ result: r.result,
254
+ tokens: r.result?.tokens || 0,
255
+ duration: r.duration
256
+ }));
257
+ }
258
+ allocateTokensForModel(model, hotspots, options) {
259
+ const baseTokens = this.stages.specialized_verification.dynamicTokens.min;
260
+ const maxTokens = this.stages.specialized_verification.dynamicTokens.max;
261
+ // Calculate based on hotspot complexity
262
+ const avgComplexity = hotspots.reduce((sum, h) => sum + h.complexity, 0) / (hotspots.length || 1);
263
+ const complexityMultiplier = 1 + (avgComplexity / 10) * 4;
264
+ // Depth multiplier
265
+ const depthMultiplier = options.depth === 'deep' ? 2 : options.depth === 'shallow' ? 0.5 : 1;
266
+ const allocated = Math.floor(baseTokens * complexityMultiplier * depthMultiplier);
267
+ return Math.min(allocated, maxTokens);
268
+ }
269
+ getModelPriority(model) {
270
+ const priorities = {
271
+ 'claude-opus-4.1': 10,
272
+ 'qwq-32b': 8,
273
+ 'perplexity-reasoning': 7,
274
+ 'gpt-4-mini': 5
275
+ };
276
+ return priorities[model] || 5;
277
+ }
278
+ async verifyWithModel(model, files, hotspots, tokens) {
279
+ // Simulated model verification
280
+ const prompt = this.buildVerificationPrompt(model, files, hotspots);
281
+ return {
282
+ model,
283
+ files: files.length,
284
+ hotspots: hotspots.length,
285
+ findings: [
286
+ {
287
+ type: 'verification',
288
+ confidence: 0.85,
289
+ details: `Analyzed ${files.length} files with ${model}`
290
+ }
291
+ ],
292
+ tokens
293
+ };
294
+ }
295
+ buildVerificationPrompt(model, files, hotspots) {
296
+ let prompt = `Please verify and deep-analyze the following:\n\n`;
297
+ prompt += `Files to review:\n`;
298
+ files.forEach(f => prompt += `- ${f}\n`);
299
+ prompt += `\nIdentified issues:\n`;
300
+ hotspots.forEach(h => {
301
+ prompt += `- ${h.type} in ${h.file}: ${h.description}\n`;
302
+ });
303
+ prompt += `\nProvide detailed analysis and recommendations.`;
304
+ return prompt;
305
+ }
306
+ async executeSynthesis(stageResults) {
307
+ const startTime = Date.now();
308
+ // Use free think tool for synthesis
309
+ const synthesisInput = this.prepareSynthesisInput(stageResults);
310
+ const synthesis = await this.synthesizeWithThink(synthesisInput);
311
+ return {
312
+ stage: 'synthesis',
313
+ model: 'think',
314
+ result: synthesis,
315
+ tokens: 0, // Free!
316
+ duration: Date.now() - startTime
317
+ };
318
+ }
319
+ prepareSynthesisInput(stageResults) {
320
+ return {
321
+ geminiAnalysis: stageResults.find(r => r.stage === 'gemini_analysis')?.result,
322
+ verifications: stageResults.filter(r => r.stage === 'specialized_verification')
323
+ .map(r => ({ model: r.model, findings: r.result })),
324
+ totalTokens: stageResults.reduce((sum, r) => sum + r.tokens, 0)
325
+ };
326
+ }
327
+ async synthesizeWithThink(input) {
328
+ // Simulated synthesis
329
+ let synthesis = `## Architecture Analysis Synthesis\n\n`;
330
+ synthesis += `### Overview\n`;
331
+ synthesis += `${input.geminiAnalysis?.architecture?.overview || 'Architecture analysis complete'}\n\n`;
332
+ synthesis += `### Key Findings\n`;
333
+ synthesis += `- Analyzed ${input.geminiAnalysis?.metrics?.totalFiles || 0} files\n`;
334
+ synthesis += `- Identified ${input.geminiAnalysis?.hotspots?.length || 0} hotspots\n`;
335
+ synthesis += `- Used ${input.verifications?.length || 0} specialized models for verification\n\n`;
336
+ synthesis += `### Critical Issues\n`;
337
+ const criticalHotspots = input.geminiAnalysis?.hotspots?.filter((h) => h.severity === 'high' || h.severity === 'critical') || [];
338
+ criticalHotspots.forEach((h) => {
339
+ synthesis += `- **${h.type}**: ${h.description} (${h.file})\n`;
340
+ });
341
+ synthesis += `\n### Recommendations\n`;
342
+ synthesis += `1. Address security vulnerabilities immediately\n`;
343
+ synthesis += `2. Optimize performance bottlenecks\n`;
344
+ synthesis += `3. Update outdated dependencies\n`;
345
+ synthesis += `4. Refactor complex components\n`;
346
+ return synthesis;
347
+ }
348
+ compileFinalResult(stageResults, hotspots, startTime) {
349
+ const geminiResult = stageResults.find(r => r.stage === 'gemini_analysis')?.result || {};
350
+ const synthesisResult = stageResults.find(r => r.stage === 'synthesis')?.result || '';
351
+ const totalTokens = stageResults.reduce((sum, r) => sum + r.tokens, 0);
352
+ const totalCost = this.calculateTotalCost(stageResults);
353
+ return {
354
+ architecture: geminiResult.architecture || this.defaultArchitecture(),
355
+ hotspots,
356
+ recommendations: this.generateRecommendations(hotspots, geminiResult),
357
+ dependencies: this.formatDependencyGraph(geminiResult.dependencies),
358
+ metrics: geminiResult.metrics || this.defaultMetrics(),
359
+ synthesis: synthesisResult,
360
+ tokensUsed: totalTokens,
361
+ cost: totalCost
362
+ };
363
+ }
364
+ calculateTotalCost(stageResults) {
365
+ let cost = 0;
366
+ for (const result of stageResults) {
367
+ if (result.model === 'gemini-2.5-flash') {
368
+ cost += (result.tokens / 1000000) * 0.50;
369
+ }
370
+ else if (result.model === 'gemini-2.5-pro') {
371
+ cost += (result.tokens / 1000000) * 3.44;
372
+ }
373
+ else if (result.model === 'think') {
374
+ cost += 0; // Free!
375
+ }
376
+ else {
377
+ cost += this.tokenTracker.calculateCost(result.model, result.tokens);
378
+ }
379
+ }
380
+ return cost;
381
+ }
382
+ generateRecommendations(hotspots, geminiResult) {
383
+ const recommendations = [];
384
+ // Security recommendations
385
+ const securityHotspots = hotspots.filter(h => h.type === 'security_vulnerability');
386
+ if (securityHotspots.length > 0) {
387
+ recommendations.push({
388
+ type: 'security',
389
+ priority: 'critical',
390
+ title: 'Address Security Vulnerabilities',
391
+ description: `Found ${securityHotspots.length} security issues that need immediate attention`,
392
+ affectedFiles: securityHotspots.map(h => h.file),
393
+ estimatedEffort: '1-2 days'
394
+ });
395
+ }
396
+ // Performance recommendations
397
+ const perfHotspots = hotspots.filter(h => h.type === 'performance_issue');
398
+ if (perfHotspots.length > 0) {
399
+ recommendations.push({
400
+ type: 'performance',
401
+ priority: 'high',
402
+ title: 'Optimize Performance Bottlenecks',
403
+ description: `${perfHotspots.length} performance issues affecting system efficiency`,
404
+ affectedFiles: perfHotspots.map(h => h.file),
405
+ estimatedEffort: '2-3 days'
406
+ });
407
+ }
408
+ // Dependency recommendations
409
+ const outdatedDeps = geminiResult.dependencies?.external?.filter((d) => d.isOutdated) || [];
410
+ if (outdatedDeps.length > 0) {
411
+ recommendations.push({
412
+ type: 'dependency',
413
+ priority: 'medium',
414
+ title: 'Update Outdated Dependencies',
415
+ description: `${outdatedDeps.length} dependencies need updating`,
416
+ affectedFiles: ['package.json', 'package-lock.json'],
417
+ estimatedEffort: '0.5 days'
418
+ });
419
+ }
420
+ return recommendations;
421
+ }
422
+ formatDependencyGraph(dependencies) {
423
+ if (!dependencies) {
424
+ return this.defaultDependencyGraph();
425
+ }
426
+ return {
427
+ nodes: this.extractNodes(dependencies),
428
+ edges: this.extractEdges(dependencies),
429
+ cycles: dependencies.cycles || [],
430
+ externalDeps: dependencies.external || []
431
+ };
432
+ }
433
+ extractNodes(dependencies) {
434
+ const nodes = [];
435
+ if (dependencies.internal) {
436
+ dependencies.internal.forEach((name) => {
437
+ nodes.push({
438
+ id: name,
439
+ name,
440
+ type: 'module',
441
+ complexity: 5
442
+ });
443
+ });
444
+ }
445
+ return nodes;
446
+ }
447
+ extractEdges(dependencies) {
448
+ // Would extract from actual dependency analysis
449
+ return [];
450
+ }
451
+ defaultArchitecture() {
452
+ return {
453
+ overview: 'Architecture analysis pending',
454
+ patterns: [],
455
+ components: [],
456
+ layers: [],
457
+ concerns: []
458
+ };
459
+ }
460
+ defaultMetrics() {
461
+ return {
462
+ totalFiles: 0,
463
+ totalLines: 0,
464
+ complexity: 0,
465
+ techDebt: 0,
466
+ maintainabilityIndex: 0
467
+ };
468
+ }
469
+ defaultDependencyGraph() {
470
+ return {
471
+ nodes: [],
472
+ edges: [],
473
+ cycles: [],
474
+ externalDeps: []
475
+ };
476
+ }
477
+ }