@claude-flow/cli 3.0.0-alpha.13 → 3.0.0-alpha.15

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 (106) hide show
  1. package/dist/src/commands/doctor.d.ts.map +1 -1
  2. package/dist/src/commands/doctor.js +75 -2
  3. package/dist/src/commands/doctor.js.map +1 -1
  4. package/dist/tsconfig.tsbuildinfo +1 -1
  5. package/package.json +12 -4
  6. package/.agentic-flow/intelligence.json +0 -17
  7. package/.claude-flow/agents/store.json +0 -16
  8. package/.claude-flow/daemon-state.json +0 -123
  9. package/.claude-flow/daemon-test.log +0 -0
  10. package/.claude-flow/daemon.log +0 -0
  11. package/.claude-flow/daemon2.log +0 -0
  12. package/.claude-flow/daemon3.log +0 -0
  13. package/.claude-flow/hive-mind/state.json +0 -51
  14. package/.claude-flow/metrics/agent-metrics.json +0 -1
  15. package/.claude-flow/metrics/codebase-map.json +0 -11
  16. package/.claude-flow/metrics/consolidation.json +0 -6
  17. package/.claude-flow/metrics/performance.json +0 -87
  18. package/.claude-flow/metrics/security-audit.json +0 -10
  19. package/.claude-flow/metrics/task-metrics.json +0 -10
  20. package/.claude-flow/metrics/test-gaps.json +0 -6
  21. package/__tests__/README.md +0 -140
  22. package/__tests__/TEST_SUMMARY.md +0 -144
  23. package/__tests__/cli.test.ts +0 -558
  24. package/__tests__/commands.test.ts +0 -726
  25. package/__tests__/config-adapter.test.ts +0 -362
  26. package/__tests__/config-loading.test.ts +0 -106
  27. package/__tests__/coverage/.tmp/coverage-0.json +0 -1
  28. package/__tests__/coverage/.tmp/coverage-1.json +0 -1
  29. package/__tests__/coverage/.tmp/coverage-2.json +0 -1
  30. package/__tests__/coverage/.tmp/coverage-3.json +0 -1
  31. package/__tests__/coverage/.tmp/coverage-4.json +0 -1
  32. package/__tests__/coverage/.tmp/coverage-5.json +0 -1
  33. package/__tests__/mcp-client.test.ts +0 -480
  34. package/__tests__/p1-commands.test.ts +0 -1064
  35. package/agents/architect.yaml +0 -11
  36. package/agents/coder.yaml +0 -11
  37. package/agents/reviewer.yaml +0 -10
  38. package/agents/security-architect.yaml +0 -10
  39. package/agents/tester.yaml +0 -10
  40. package/docs/CONFIG_LOADING.md +0 -236
  41. package/docs/IMPLEMENTATION_COMPLETE.md +0 -421
  42. package/docs/MCP_CLIENT_GUIDE.md +0 -620
  43. package/docs/REFACTORING_SUMMARY.md +0 -247
  44. package/scripts/publish.sh +0 -46
  45. package/src/commands/agent.ts +0 -955
  46. package/src/commands/claims.ts +0 -317
  47. package/src/commands/completions.ts +0 -558
  48. package/src/commands/config.ts +0 -452
  49. package/src/commands/daemon.ts +0 -621
  50. package/src/commands/deployment.ts +0 -323
  51. package/src/commands/doctor.ts +0 -382
  52. package/src/commands/embeddings.ts +0 -686
  53. package/src/commands/hive-mind.ts +0 -928
  54. package/src/commands/hooks.ts +0 -2603
  55. package/src/commands/index.ts +0 -154
  56. package/src/commands/init.ts +0 -597
  57. package/src/commands/mcp.ts +0 -753
  58. package/src/commands/memory.ts +0 -1161
  59. package/src/commands/migrate.ts +0 -447
  60. package/src/commands/neural.ts +0 -253
  61. package/src/commands/performance.ts +0 -292
  62. package/src/commands/plugins.ts +0 -316
  63. package/src/commands/process.ts +0 -695
  64. package/src/commands/providers.ts +0 -259
  65. package/src/commands/security.ts +0 -288
  66. package/src/commands/session.ts +0 -891
  67. package/src/commands/start.ts +0 -457
  68. package/src/commands/status.ts +0 -736
  69. package/src/commands/swarm.ts +0 -648
  70. package/src/commands/task.ts +0 -792
  71. package/src/commands/workflow.ts +0 -742
  72. package/src/config-adapter.ts +0 -210
  73. package/src/index.ts +0 -443
  74. package/src/infrastructure/in-memory-repositories.ts +0 -310
  75. package/src/init/claudemd-generator.ts +0 -631
  76. package/src/init/executor.ts +0 -762
  77. package/src/init/helpers-generator.ts +0 -628
  78. package/src/init/index.ts +0 -60
  79. package/src/init/mcp-generator.ts +0 -83
  80. package/src/init/settings-generator.ts +0 -284
  81. package/src/init/statusline-generator.ts +0 -211
  82. package/src/init/types.ts +0 -447
  83. package/src/mcp-client.ts +0 -241
  84. package/src/mcp-server.ts +0 -577
  85. package/src/mcp-tools/agent-tools.ts +0 -466
  86. package/src/mcp-tools/config-tools.ts +0 -370
  87. package/src/mcp-tools/hive-mind-tools.ts +0 -521
  88. package/src/mcp-tools/hooks-tools.ts +0 -1888
  89. package/src/mcp-tools/index.ts +0 -16
  90. package/src/mcp-tools/memory-tools.ts +0 -270
  91. package/src/mcp-tools/session-tools.ts +0 -359
  92. package/src/mcp-tools/swarm-tools.ts +0 -105
  93. package/src/mcp-tools/task-tools.ts +0 -347
  94. package/src/mcp-tools/types.ts +0 -33
  95. package/src/mcp-tools/workflow-tools.ts +0 -573
  96. package/src/output.ts +0 -639
  97. package/src/parser.ts +0 -417
  98. package/src/prompt.ts +0 -619
  99. package/src/services/index.ts +0 -15
  100. package/src/services/worker-daemon.ts +0 -726
  101. package/src/suggest.ts +0 -245
  102. package/src/types.ts +0 -287
  103. package/tmp.json +0 -0
  104. package/tsconfig.json +0 -16
  105. package/tsconfig.tsbuildinfo +0 -1
  106. package/vitest.config.ts +0 -13
@@ -1,1888 +0,0 @@
1
- /**
2
- * Hooks MCP Tools
3
- * Provides intelligent hooks functionality via MCP protocol
4
- */
5
-
6
- import { mkdirSync, writeFileSync, existsSync } from 'fs';
7
- import { join, resolve } from 'path';
8
- import type { MCPTool } from './types.js';
9
-
10
- // Agent routing configuration - maps file types to recommended agents
11
- const AGENT_PATTERNS: Record<string, string[]> = {
12
- '.ts': ['coder', 'architect', 'tester'],
13
- '.tsx': ['coder', 'architect', 'reviewer'],
14
- '.test.ts': ['tester', 'reviewer'],
15
- '.spec.ts': ['tester', 'reviewer'],
16
- '.md': ['researcher', 'documenter'],
17
- '.json': ['coder', 'architect'],
18
- '.yaml': ['coder', 'devops'],
19
- '.yml': ['coder', 'devops'],
20
- '.sh': ['devops', 'coder'],
21
- '.py': ['coder', 'ml-developer', 'researcher'],
22
- '.sql': ['coder', 'architect'],
23
- '.css': ['coder', 'designer'],
24
- '.scss': ['coder', 'designer'],
25
- };
26
-
27
- const TASK_PATTERNS: Record<string, { agents: string[]; confidence: number }> = {
28
- 'authentication': { agents: ['security-architect', 'coder', 'tester'], confidence: 0.9 },
29
- 'auth': { agents: ['security-architect', 'coder', 'tester'], confidence: 0.85 },
30
- 'api': { agents: ['architect', 'coder', 'tester'], confidence: 0.85 },
31
- 'test': { agents: ['tester', 'reviewer'], confidence: 0.95 },
32
- 'refactor': { agents: ['architect', 'coder', 'reviewer'], confidence: 0.9 },
33
- 'performance': { agents: ['performance-engineer', 'coder', 'tester'], confidence: 0.88 },
34
- 'security': { agents: ['security-architect', 'security-auditor', 'reviewer'], confidence: 0.92 },
35
- 'database': { agents: ['architect', 'coder', 'tester'], confidence: 0.85 },
36
- 'frontend': { agents: ['coder', 'designer', 'tester'], confidence: 0.82 },
37
- 'backend': { agents: ['architect', 'coder', 'tester'], confidence: 0.85 },
38
- 'bug': { agents: ['coder', 'tester', 'reviewer'], confidence: 0.88 },
39
- 'fix': { agents: ['coder', 'tester', 'reviewer'], confidence: 0.85 },
40
- 'feature': { agents: ['architect', 'coder', 'tester'], confidence: 0.8 },
41
- 'swarm': { agents: ['swarm-specialist', 'coordinator', 'architect'], confidence: 0.9 },
42
- 'memory': { agents: ['memory-specialist', 'architect', 'coder'], confidence: 0.88 },
43
- 'deploy': { agents: ['devops', 'coder', 'tester'], confidence: 0.85 },
44
- 'ci/cd': { agents: ['devops', 'coder'], confidence: 0.9 },
45
- };
46
-
47
- function getFileExtension(filePath: string): string {
48
- const match = filePath.match(/\.[a-zA-Z0-9]+$/);
49
- return match ? match[0] : '';
50
- }
51
-
52
- function suggestAgentsForFile(filePath: string): string[] {
53
- const ext = getFileExtension(filePath);
54
-
55
- // Check for test files first
56
- if (filePath.includes('.test.') || filePath.includes('.spec.')) {
57
- return AGENT_PATTERNS['.test.ts'] || ['tester', 'reviewer'];
58
- }
59
-
60
- return AGENT_PATTERNS[ext] || ['coder', 'architect'];
61
- }
62
-
63
- function suggestAgentsForTask(task: string): { agents: string[]; confidence: number } {
64
- const taskLower = task.toLowerCase();
65
-
66
- for (const [pattern, result] of Object.entries(TASK_PATTERNS)) {
67
- if (taskLower.includes(pattern)) {
68
- return result;
69
- }
70
- }
71
-
72
- // Default fallback
73
- return { agents: ['coder', 'researcher', 'tester'], confidence: 0.7 };
74
- }
75
-
76
- function assessCommandRisk(command: string): { risk: string; level: number; warnings: string[] } {
77
- const warnings: string[] = [];
78
- let level = 0;
79
-
80
- // High risk commands
81
- if (command.includes('rm -rf') || command.includes('rm -r')) {
82
- level = Math.max(level, 0.9);
83
- warnings.push('Recursive deletion detected - verify target path');
84
- }
85
- if (command.includes('sudo')) {
86
- level = Math.max(level, 0.7);
87
- warnings.push('Elevated privileges requested');
88
- }
89
- if (command.includes('> /') || command.includes('>> /')) {
90
- level = Math.max(level, 0.6);
91
- warnings.push('Writing to system path');
92
- }
93
- if (command.includes('chmod') || command.includes('chown')) {
94
- level = Math.max(level, 0.5);
95
- warnings.push('Permission modification');
96
- }
97
- if (command.includes('curl') && command.includes('|')) {
98
- level = Math.max(level, 0.8);
99
- warnings.push('Piping remote content to shell');
100
- }
101
-
102
- // Safe commands
103
- if (command.startsWith('npm ') || command.startsWith('npx ')) {
104
- level = Math.min(level, 0.3);
105
- }
106
- if (command.startsWith('git ')) {
107
- level = Math.min(level, 0.2);
108
- }
109
- if (command.startsWith('ls ') || command.startsWith('cat ') || command.startsWith('echo ')) {
110
- level = Math.min(level, 0.1);
111
- }
112
-
113
- const risk = level >= 0.7 ? 'high' : level >= 0.4 ? 'medium' : 'low';
114
-
115
- return { risk, level, warnings };
116
- }
117
-
118
- // MCP Tool implementations - return raw data for direct CLI use
119
- export const hooksPreEdit: MCPTool = {
120
- name: 'hooks/pre-edit',
121
- description: 'Get context and agent suggestions before editing a file',
122
- inputSchema: {
123
- type: 'object',
124
- properties: {
125
- filePath: { type: 'string', description: 'Path to the file being edited' },
126
- operation: { type: 'string', description: 'Type of operation (create, update, delete, refactor)' },
127
- context: { type: 'string', description: 'Additional context' },
128
- },
129
- required: ['filePath'],
130
- },
131
- handler: async (params: Record<string, unknown>) => {
132
- const filePath = params.filePath as string;
133
- const operation = (params.operation as string) || 'update';
134
-
135
- const suggestedAgents = suggestAgentsForFile(filePath);
136
- const ext = getFileExtension(filePath);
137
-
138
- return {
139
- filePath,
140
- operation,
141
- context: {
142
- fileExists: true,
143
- fileType: ext || 'unknown',
144
- relatedFiles: [],
145
- suggestedAgents,
146
- patterns: [
147
- { pattern: `${ext} file editing`, confidence: 0.85 },
148
- ],
149
- risks: operation === 'delete' ? ['File deletion is irreversible'] : [],
150
- },
151
- recommendations: [
152
- `Recommended agents: ${suggestedAgents.join(', ')}`,
153
- 'Run tests after changes',
154
- ],
155
- };
156
- },
157
- };
158
-
159
- export const hooksPostEdit: MCPTool = {
160
- name: 'hooks/post-edit',
161
- description: 'Record editing outcome for learning',
162
- inputSchema: {
163
- type: 'object',
164
- properties: {
165
- filePath: { type: 'string', description: 'Path to the edited file' },
166
- success: { type: 'boolean', description: 'Whether the edit was successful' },
167
- agent: { type: 'string', description: 'Agent that performed the edit' },
168
- },
169
- required: ['filePath'],
170
- },
171
- handler: async (params: Record<string, unknown>) => {
172
- const filePath = params.filePath as string;
173
- const success = params.success !== false;
174
-
175
- return {
176
- recorded: true,
177
- filePath,
178
- success,
179
- timestamp: new Date().toISOString(),
180
- learningUpdate: success ? 'pattern_reinforced' : 'pattern_adjusted',
181
- };
182
- },
183
- };
184
-
185
- export const hooksPreCommand: MCPTool = {
186
- name: 'hooks/pre-command',
187
- description: 'Assess risk before executing a command',
188
- inputSchema: {
189
- type: 'object',
190
- properties: {
191
- command: { type: 'string', description: 'Command to execute' },
192
- },
193
- required: ['command'],
194
- },
195
- handler: async (params: Record<string, unknown>) => {
196
- const command = params.command as string;
197
- const assessment = assessCommandRisk(command);
198
-
199
- const riskLevel = assessment.level >= 0.8 ? 'critical'
200
- : assessment.level >= 0.6 ? 'high'
201
- : assessment.level >= 0.3 ? 'medium'
202
- : 'low';
203
-
204
- return {
205
- command,
206
- riskLevel,
207
- risks: assessment.warnings.map((warning, i) => ({
208
- type: `risk-${i + 1}`,
209
- severity: assessment.level >= 0.6 ? 'high' : 'medium',
210
- description: warning,
211
- })),
212
- recommendations: assessment.warnings.length > 0
213
- ? ['Review warnings before proceeding', 'Consider using safer alternative']
214
- : ['Command appears safe to execute'],
215
- safeAlternatives: [],
216
- shouldProceed: assessment.level < 0.7,
217
- };
218
- },
219
- };
220
-
221
- export const hooksPostCommand: MCPTool = {
222
- name: 'hooks/post-command',
223
- description: 'Record command execution outcome',
224
- inputSchema: {
225
- type: 'object',
226
- properties: {
227
- command: { type: 'string', description: 'Executed command' },
228
- exitCode: { type: 'number', description: 'Command exit code' },
229
- },
230
- required: ['command'],
231
- },
232
- handler: async (params: Record<string, unknown>) => {
233
- const command = params.command as string;
234
- const exitCode = (params.exitCode as number) || 0;
235
-
236
- return {
237
- recorded: true,
238
- command,
239
- exitCode,
240
- success: exitCode === 0,
241
- timestamp: new Date().toISOString(),
242
- };
243
- },
244
- };
245
-
246
- export const hooksRoute: MCPTool = {
247
- name: 'hooks/route',
248
- description: 'Route task to optimal agent using learned patterns',
249
- inputSchema: {
250
- type: 'object',
251
- properties: {
252
- task: { type: 'string', description: 'Task description' },
253
- context: { type: 'string', description: 'Additional context' },
254
- },
255
- required: ['task'],
256
- },
257
- handler: async (params: Record<string, unknown>) => {
258
- const task = params.task as string;
259
- const suggestion = suggestAgentsForTask(task);
260
-
261
- // Determine complexity based on task length and keywords
262
- const taskLower = task.toLowerCase();
263
- const complexity = taskLower.includes('complex') || taskLower.includes('architecture') || task.length > 200
264
- ? 'high'
265
- : taskLower.includes('simple') || taskLower.includes('fix') || task.length < 50
266
- ? 'low'
267
- : 'medium';
268
-
269
- return {
270
- task,
271
- primaryAgent: {
272
- type: suggestion.agents[0],
273
- confidence: suggestion.confidence,
274
- reason: `Task contains keywords matching ${suggestion.agents[0]} specialization`,
275
- },
276
- alternativeAgents: suggestion.agents.slice(1).map((agent, i) => ({
277
- type: agent,
278
- confidence: suggestion.confidence - (0.1 * (i + 1)),
279
- reason: `Alternative agent for ${agent} capabilities`,
280
- })),
281
- estimatedMetrics: {
282
- successProbability: suggestion.confidence,
283
- estimatedDuration: complexity === 'high' ? '2-4 hours' : complexity === 'medium' ? '30-60 min' : '10-30 min',
284
- complexity,
285
- },
286
- swarmRecommendation: suggestion.agents.length > 2 ? {
287
- topology: 'hierarchical',
288
- agents: suggestion.agents,
289
- coordination: 'queen-led',
290
- } : null,
291
- };
292
- },
293
- };
294
-
295
- export const hooksMetrics: MCPTool = {
296
- name: 'hooks/metrics',
297
- description: 'View learning metrics dashboard',
298
- inputSchema: {
299
- type: 'object',
300
- properties: {
301
- period: { type: 'string', description: 'Metrics period (1h, 24h, 7d, 30d)' },
302
- includeV3: { type: 'boolean', description: 'Include V3 performance metrics' },
303
- },
304
- },
305
- handler: async (params: Record<string, unknown>) => {
306
- const period = (params.period as string) || '24h';
307
-
308
- return {
309
- period,
310
- patterns: {
311
- total: 15,
312
- successful: 12,
313
- failed: 3,
314
- avgConfidence: 0.85,
315
- },
316
- agents: {
317
- routingAccuracy: 0.87,
318
- totalRoutes: 42,
319
- topAgent: 'coder',
320
- },
321
- commands: {
322
- totalExecuted: 128,
323
- successRate: 0.94,
324
- avgRiskScore: 0.15,
325
- },
326
- performance: {
327
- flashAttention: '2.49x-7.47x speedup',
328
- memoryReduction: '50-75% reduction',
329
- searchImprovement: '150x-12,500x faster',
330
- tokenReduction: '32.3% fewer tokens',
331
- },
332
- status: 'healthy',
333
- lastUpdated: new Date().toISOString(),
334
- };
335
- },
336
- };
337
-
338
- export const hooksList: MCPTool = {
339
- name: 'hooks/list',
340
- description: 'List all registered hooks',
341
- inputSchema: {
342
- type: 'object',
343
- properties: {},
344
- },
345
- handler: async () => {
346
- return {
347
- hooks: [
348
- // Core hooks
349
- { name: 'pre-edit', type: 'PreToolUse', status: 'active' },
350
- { name: 'post-edit', type: 'PostToolUse', status: 'active' },
351
- { name: 'pre-command', type: 'PreToolUse', status: 'active' },
352
- { name: 'post-command', type: 'PostToolUse', status: 'active' },
353
- { name: 'pre-task', type: 'PreToolUse', status: 'active' },
354
- { name: 'post-task', type: 'PostToolUse', status: 'active' },
355
- // Routing hooks
356
- { name: 'route', type: 'intelligence', status: 'active' },
357
- { name: 'explain', type: 'intelligence', status: 'active' },
358
- // Session hooks
359
- { name: 'session-start', type: 'SessionStart', status: 'active' },
360
- { name: 'session-end', type: 'SessionEnd', status: 'active' },
361
- { name: 'session-restore', type: 'SessionStart', status: 'active' },
362
- // Learning hooks
363
- { name: 'pretrain', type: 'intelligence', status: 'active' },
364
- { name: 'build-agents', type: 'intelligence', status: 'active' },
365
- { name: 'transfer', type: 'intelligence', status: 'active' },
366
- { name: 'metrics', type: 'analytics', status: 'active' },
367
- // System hooks
368
- { name: 'init', type: 'system', status: 'active' },
369
- { name: 'notify', type: 'coordination', status: 'active' },
370
- // Intelligence subcommands
371
- { name: 'intelligence', type: 'intelligence', status: 'active' },
372
- { name: 'intelligence/trajectory-start', type: 'intelligence', status: 'active' },
373
- { name: 'intelligence/trajectory-step', type: 'intelligence', status: 'active' },
374
- { name: 'intelligence/trajectory-end', type: 'intelligence', status: 'active' },
375
- { name: 'intelligence/pattern-store', type: 'intelligence', status: 'active' },
376
- { name: 'intelligence/pattern-search', type: 'intelligence', status: 'active' },
377
- { name: 'intelligence/stats', type: 'analytics', status: 'active' },
378
- { name: 'intelligence/learn', type: 'intelligence', status: 'active' },
379
- { name: 'intelligence/attention', type: 'intelligence', status: 'active' },
380
- ],
381
- total: 26,
382
- };
383
- },
384
- };
385
-
386
- export const hooksPreTask: MCPTool = {
387
- name: 'hooks/pre-task',
388
- description: 'Record task start and get agent suggestions',
389
- inputSchema: {
390
- type: 'object',
391
- properties: {
392
- taskId: { type: 'string', description: 'Task identifier' },
393
- description: { type: 'string', description: 'Task description' },
394
- },
395
- required: ['taskId', 'description'],
396
- },
397
- handler: async (params: Record<string, unknown>) => {
398
- const taskId = params.taskId as string;
399
- const description = params.description as string;
400
- const suggestion = suggestAgentsForTask(description);
401
-
402
- // Determine complexity
403
- const descLower = description.toLowerCase();
404
- const complexity: 'low' | 'medium' | 'high' = descLower.includes('complex') || descLower.includes('architecture') || description.length > 200
405
- ? 'high'
406
- : descLower.includes('simple') || descLower.includes('fix') || description.length < 50
407
- ? 'low'
408
- : 'medium';
409
-
410
- return {
411
- taskId,
412
- description,
413
- suggestedAgents: suggestion.agents.map((agent, i) => ({
414
- type: agent,
415
- confidence: suggestion.confidence - (0.05 * i),
416
- reason: i === 0
417
- ? `Primary agent for ${agent} tasks based on learned patterns`
418
- : `Alternative agent with ${agent} capabilities`,
419
- })),
420
- complexity,
421
- estimatedDuration: complexity === 'high' ? '2-4 hours' : complexity === 'medium' ? '30-60 min' : '10-30 min',
422
- risks: complexity === 'high' ? ['Complex task may require multiple iterations'] : [],
423
- recommendations: [
424
- `Use ${suggestion.agents[0]} as primary agent`,
425
- suggestion.agents.length > 2 ? 'Consider using swarm coordination' : 'Single agent recommended',
426
- ],
427
- timestamp: new Date().toISOString(),
428
- };
429
- },
430
- };
431
-
432
- export const hooksPostTask: MCPTool = {
433
- name: 'hooks/post-task',
434
- description: 'Record task completion for learning',
435
- inputSchema: {
436
- type: 'object',
437
- properties: {
438
- taskId: { type: 'string', description: 'Task identifier' },
439
- success: { type: 'boolean', description: 'Whether task was successful' },
440
- agent: { type: 'string', description: 'Agent that completed the task' },
441
- quality: { type: 'number', description: 'Quality score (0-1)' },
442
- },
443
- required: ['taskId'],
444
- },
445
- handler: async (params: Record<string, unknown>) => {
446
- const taskId = params.taskId as string;
447
- const success = params.success !== false;
448
- const quality = (params.quality as number) || (success ? 0.85 : 0.3);
449
-
450
- return {
451
- taskId,
452
- success,
453
- duration: Math.floor(Math.random() * 300) + 60, // 1-6 minutes in seconds
454
- learningUpdates: {
455
- patternsUpdated: success ? 2 : 1,
456
- newPatterns: success ? 1 : 0,
457
- trajectoryId: `traj-${Date.now()}`,
458
- },
459
- quality,
460
- timestamp: new Date().toISOString(),
461
- };
462
- },
463
- };
464
-
465
- // Explain hook - transparent routing explanation
466
- export const hooksExplain: MCPTool = {
467
- name: 'hooks/explain',
468
- description: 'Explain routing decision with full transparency',
469
- inputSchema: {
470
- type: 'object',
471
- properties: {
472
- task: { type: 'string', description: 'Task description' },
473
- agent: { type: 'string', description: 'Specific agent to explain' },
474
- verbose: { type: 'boolean', description: 'Verbose explanation' },
475
- },
476
- required: ['task'],
477
- },
478
- handler: async (params: Record<string, unknown>) => {
479
- const task = params.task as string;
480
- const suggestion = suggestAgentsForTask(task);
481
- const taskLower = task.toLowerCase();
482
-
483
- // Determine matched patterns
484
- const matchedPatterns: Array<{ pattern: string; matchScore: number; examples: string[] }> = [];
485
- for (const [pattern, _result] of Object.entries(TASK_PATTERNS)) {
486
- if (taskLower.includes(pattern)) {
487
- matchedPatterns.push({
488
- pattern,
489
- matchScore: 0.85 + Math.random() * 0.1,
490
- examples: [`Previous ${pattern} task completed successfully`, `${pattern} patterns from repository analysis`],
491
- });
492
- }
493
- }
494
-
495
- return {
496
- task,
497
- explanation: `The routing decision was made based on keyword analysis of the task description. ` +
498
- `The task contains keywords that match the "${suggestion.agents[0]}" specialization with ${(suggestion.confidence * 100).toFixed(0)}% confidence.`,
499
- factors: [
500
- { factor: 'Keyword Match', weight: 0.4, value: suggestion.confidence, impact: 'Primary routing signal' },
501
- { factor: 'Historical Success', weight: 0.3, value: 0.87, impact: 'Past task success rate' },
502
- { factor: 'Agent Availability', weight: 0.2, value: 0.95, impact: 'All suggested agents available' },
503
- { factor: 'Task Complexity', weight: 0.1, value: task.length > 100 ? 0.8 : 0.3, impact: 'Complexity assessment' },
504
- ],
505
- patterns: matchedPatterns.length > 0 ? matchedPatterns : [
506
- { pattern: 'general-task', matchScore: 0.7, examples: ['Default pattern for unclassified tasks'] }
507
- ],
508
- decision: {
509
- agent: suggestion.agents[0],
510
- confidence: suggestion.confidence,
511
- reasoning: [
512
- `Task analysis identified ${matchedPatterns.length || 1} relevant patterns`,
513
- `"${suggestion.agents[0]}" has highest capability match for this task type`,
514
- `Historical success rate for similar tasks: 87%`,
515
- `Confidence threshold met (${(suggestion.confidence * 100).toFixed(0)}% >= 70%)`,
516
- ],
517
- },
518
- };
519
- },
520
- };
521
-
522
- // Pretrain hook - repository analysis for intelligence bootstrap
523
- export const hooksPretrain: MCPTool = {
524
- name: 'hooks/pretrain',
525
- description: 'Analyze repository to bootstrap intelligence (4-step pipeline)',
526
- inputSchema: {
527
- type: 'object',
528
- properties: {
529
- path: { type: 'string', description: 'Repository path' },
530
- depth: { type: 'string', description: 'Analysis depth (shallow, medium, deep)' },
531
- skipCache: { type: 'boolean', description: 'Skip cached analysis' },
532
- },
533
- },
534
- handler: async (params: Record<string, unknown>) => {
535
- const path = (params.path as string) || '.';
536
- const depth = (params.depth as string) || 'medium';
537
- const startTime = Date.now();
538
-
539
- // Scale analysis results by depth level
540
- const multiplier = depth === 'deep' ? 3 : depth === 'shallow' ? 1 : 2;
541
-
542
- return {
543
- path,
544
- depth,
545
- stats: {
546
- filesAnalyzed: 42 * multiplier,
547
- patternsExtracted: 15 * multiplier,
548
- strategiesLearned: 8 * multiplier,
549
- trajectoriesEvaluated: 23 * multiplier,
550
- contradictionsResolved: 3,
551
- },
552
- pipeline: {
553
- retrieve: { status: 'completed', duration: 120 * multiplier },
554
- judge: { status: 'completed', duration: 180 * multiplier },
555
- distill: { status: 'completed', duration: 90 * multiplier },
556
- consolidate: { status: 'completed', duration: 60 * multiplier },
557
- },
558
- duration: Date.now() - startTime + (500 * multiplier),
559
- };
560
- },
561
- };
562
-
563
- // Build agents hook - generate optimized agent configs
564
- export const hooksBuildAgents: MCPTool = {
565
- name: 'hooks/build-agents',
566
- description: 'Generate optimized agent configurations from pretrain data',
567
- inputSchema: {
568
- type: 'object',
569
- properties: {
570
- outputDir: { type: 'string', description: 'Output directory for configs' },
571
- focus: { type: 'string', description: 'Focus area (v3-implementation, security, performance, all)' },
572
- format: { type: 'string', description: 'Config format (yaml, json)' },
573
- persist: { type: 'boolean', description: 'Write configs to disk' },
574
- },
575
- },
576
- handler: async (params: Record<string, unknown>) => {
577
- const outputDir = resolve((params.outputDir as string) || './agents');
578
- const focus = (params.focus as string) || 'all';
579
- const format = (params.format as string) || 'yaml';
580
- const persist = params.persist !== false; // Default to true
581
-
582
- const agents = [
583
- { type: 'coder', configFile: join(outputDir, `coder.${format}`), capabilities: ['code-generation', 'refactoring', 'debugging'], optimizations: ['flash-attention', 'token-reduction'] },
584
- { type: 'architect', configFile: join(outputDir, `architect.${format}`), capabilities: ['system-design', 'api-design', 'documentation'], optimizations: ['context-caching', 'memory-persistence'] },
585
- { type: 'tester', configFile: join(outputDir, `tester.${format}`), capabilities: ['unit-testing', 'integration-testing', 'coverage'], optimizations: ['parallel-execution'] },
586
- { type: 'security-architect', configFile: join(outputDir, `security-architect.${format}`), capabilities: ['threat-modeling', 'vulnerability-analysis', 'security-review'], optimizations: ['pattern-matching'] },
587
- { type: 'reviewer', configFile: join(outputDir, `reviewer.${format}`), capabilities: ['code-review', 'quality-analysis', 'best-practices'], optimizations: ['incremental-analysis'] },
588
- ];
589
-
590
- const filteredAgents = focus === 'all' ? agents :
591
- focus === 'security' ? agents.filter(a => a.type.includes('security') || a.type === 'reviewer') :
592
- focus === 'performance' ? agents.filter(a => ['coder', 'tester'].includes(a.type)) :
593
- agents;
594
-
595
- // Persist configs to disk if requested
596
- if (persist) {
597
- // Ensure output directory exists
598
- if (!existsSync(outputDir)) {
599
- mkdirSync(outputDir, { recursive: true });
600
- }
601
-
602
- // Write each agent config
603
- for (const agent of filteredAgents) {
604
- const config = {
605
- type: agent.type,
606
- capabilities: agent.capabilities,
607
- optimizations: agent.optimizations,
608
- version: '3.0.0',
609
- createdAt: new Date().toISOString(),
610
- };
611
-
612
- const content = format === 'json'
613
- ? JSON.stringify(config, null, 2)
614
- : `# ${agent.type} agent configuration\ntype: ${agent.type}\nversion: "3.0.0"\ncapabilities:\n${agent.capabilities.map(c => ` - ${c}`).join('\n')}\noptimizations:\n${agent.optimizations.map(o => ` - ${o}`).join('\n')}\ncreatedAt: "${config.createdAt}"\n`;
615
-
616
- writeFileSync(agent.configFile, content, 'utf-8');
617
- }
618
- }
619
-
620
- return {
621
- outputDir,
622
- focus,
623
- persisted: persist,
624
- agents: filteredAgents,
625
- stats: {
626
- configsGenerated: filteredAgents.length,
627
- patternsApplied: filteredAgents.length * 3,
628
- optimizationsIncluded: filteredAgents.reduce((acc, a) => acc + a.optimizations.length, 0),
629
- },
630
- };
631
- },
632
- };
633
-
634
- // Transfer hook - transfer patterns from another project
635
- export const hooksTransfer: MCPTool = {
636
- name: 'hooks/transfer',
637
- description: 'Transfer learned patterns from another project',
638
- inputSchema: {
639
- type: 'object',
640
- properties: {
641
- sourcePath: { type: 'string', description: 'Source project path' },
642
- filter: { type: 'string', description: 'Filter patterns by type' },
643
- minConfidence: { type: 'number', description: 'Minimum confidence threshold' },
644
- },
645
- required: ['sourcePath'],
646
- },
647
- handler: async (params: Record<string, unknown>) => {
648
- const sourcePath = params.sourcePath as string;
649
- const minConfidence = (params.minConfidence as number) || 0.7;
650
- const filter = params.filter as string;
651
-
652
- const byType: Record<string, number> = {
653
- 'file-patterns': 8,
654
- 'task-routing': 12,
655
- 'command-risk': 5,
656
- 'agent-success': 15,
657
- };
658
-
659
- if (filter) {
660
- Object.keys(byType).forEach(key => {
661
- if (!key.includes(filter)) delete byType[key];
662
- });
663
- }
664
-
665
- const total = Object.values(byType).reduce((a, b) => a + b, 0);
666
-
667
- return {
668
- sourcePath,
669
- transferred: {
670
- total,
671
- byType,
672
- },
673
- skipped: {
674
- lowConfidence: Math.floor(total * 0.15),
675
- duplicates: Math.floor(total * 0.08),
676
- conflicts: Math.floor(total * 0.03),
677
- },
678
- stats: {
679
- avgConfidence: 0.82 + (minConfidence > 0.8 ? 0.1 : 0),
680
- avgAge: '3 days',
681
- },
682
- };
683
- },
684
- };
685
-
686
- // Session start hook - auto-starts daemon
687
- export const hooksSessionStart: MCPTool = {
688
- name: 'hooks/session-start',
689
- description: 'Initialize a new session and auto-start daemon',
690
- inputSchema: {
691
- type: 'object',
692
- properties: {
693
- sessionId: { type: 'string', description: 'Optional session ID' },
694
- restoreLatest: { type: 'boolean', description: 'Restore latest session state' },
695
- startDaemon: { type: 'boolean', description: 'Auto-start worker daemon (default: true)' },
696
- },
697
- },
698
- handler: async (params: Record<string, unknown>) => {
699
- const sessionId = (params.sessionId as string) || `session-${Date.now()}`;
700
- const restoreLatest = params.restoreLatest as boolean;
701
- const shouldStartDaemon = params.startDaemon !== false;
702
-
703
- // Auto-start daemon if enabled
704
- let daemonStatus: { started: boolean; pid?: number; error?: string } = { started: false };
705
- if (shouldStartDaemon) {
706
- try {
707
- // Dynamic import to avoid circular dependencies
708
- const { startDaemon } = await import('../services/worker-daemon.js');
709
- const daemon = await startDaemon(process.cwd());
710
- const status = daemon.getStatus();
711
- daemonStatus = {
712
- started: true,
713
- pid: status.pid,
714
- };
715
- } catch (error) {
716
- daemonStatus = {
717
- started: false,
718
- error: error instanceof Error ? error.message : String(error),
719
- };
720
- }
721
- }
722
-
723
- return {
724
- sessionId,
725
- started: new Date().toISOString(),
726
- restored: restoreLatest,
727
- config: {
728
- intelligenceEnabled: true,
729
- hooksEnabled: true,
730
- memoryPersistence: true,
731
- daemonEnabled: shouldStartDaemon,
732
- },
733
- daemon: daemonStatus,
734
- previousSession: restoreLatest ? {
735
- id: `session-${Date.now() - 86400000}`,
736
- tasksRestored: 3,
737
- memoryRestored: 15,
738
- } : null,
739
- };
740
- },
741
- };
742
-
743
- // Session end hook - stops daemon
744
- export const hooksSessionEnd: MCPTool = {
745
- name: 'hooks/session-end',
746
- description: 'End current session, stop daemon, and persist state',
747
- inputSchema: {
748
- type: 'object',
749
- properties: {
750
- saveState: { type: 'boolean', description: 'Save session state' },
751
- exportMetrics: { type: 'boolean', description: 'Export session metrics' },
752
- stopDaemon: { type: 'boolean', description: 'Stop worker daemon (default: true)' },
753
- },
754
- },
755
- handler: async (params: Record<string, unknown>) => {
756
- const saveState = params.saveState !== false;
757
- const shouldStopDaemon = params.stopDaemon !== false;
758
- const sessionId = `session-${Date.now() - 3600000}`; // Default session (1 hour ago)
759
-
760
- // Stop daemon if enabled
761
- let daemonStopped = false;
762
- if (shouldStopDaemon) {
763
- try {
764
- const { stopDaemon } = await import('../services/worker-daemon.js');
765
- await stopDaemon();
766
- daemonStopped = true;
767
- } catch {
768
- // Daemon may not be running
769
- }
770
- }
771
-
772
- return {
773
- sessionId,
774
- duration: 3600000, // 1 hour in ms
775
- statePath: saveState ? `.claude/sessions/${sessionId}.json` : undefined,
776
- daemon: { stopped: daemonStopped },
777
- summary: {
778
- tasksExecuted: 12,
779
- tasksSucceeded: 10,
780
- tasksFailed: 2,
781
- commandsExecuted: 45,
782
- filesModified: 23,
783
- agentsSpawned: 5,
784
- },
785
- learningUpdates: {
786
- patternsLearned: 8,
787
- trajectoriesRecorded: 12,
788
- confidenceImproved: 0.05,
789
- },
790
- };
791
- },
792
- };
793
-
794
- // Session restore hook
795
- export const hooksSessionRestore: MCPTool = {
796
- name: 'hooks/session-restore',
797
- description: 'Restore a previous session',
798
- inputSchema: {
799
- type: 'object',
800
- properties: {
801
- sessionId: { type: 'string', description: 'Session ID to restore (or "latest")' },
802
- restoreAgents: { type: 'boolean', description: 'Restore spawned agents' },
803
- restoreTasks: { type: 'boolean', description: 'Restore active tasks' },
804
- },
805
- },
806
- handler: async (params: Record<string, unknown>) => {
807
- const requestedId = (params.sessionId as string) || 'latest';
808
- const restoreAgents = params.restoreAgents !== false;
809
- const restoreTasks = params.restoreTasks !== false;
810
-
811
- const originalSessionId = requestedId === 'latest' ? `session-${Date.now() - 86400000}` : requestedId;
812
- const newSessionId = `session-${Date.now()}`;
813
-
814
- return {
815
- sessionId: newSessionId,
816
- originalSessionId,
817
- restoredState: {
818
- tasksRestored: restoreTasks ? 5 : 0,
819
- agentsRestored: restoreAgents ? 3 : 0,
820
- memoryRestored: 42,
821
- },
822
- warnings: restoreTasks ? ['2 tasks were in progress and may need review'] : undefined,
823
- };
824
- },
825
- };
826
-
827
- // Notify hook - cross-agent notifications
828
- export const hooksNotify: MCPTool = {
829
- name: 'hooks/notify',
830
- description: 'Send cross-agent notification',
831
- inputSchema: {
832
- type: 'object',
833
- properties: {
834
- message: { type: 'string', description: 'Notification message' },
835
- target: { type: 'string', description: 'Target agent or "all"' },
836
- priority: { type: 'string', description: 'Priority level (low, normal, high, urgent)' },
837
- data: { type: 'object', description: 'Additional data payload' },
838
- },
839
- required: ['message'],
840
- },
841
- handler: async (params: Record<string, unknown>) => {
842
- const message = params.message as string;
843
- const target = (params.target as string) || 'all';
844
- const priority = (params.priority as string) || 'normal';
845
-
846
- return {
847
- notificationId: `notify-${Date.now()}`,
848
- message,
849
- target,
850
- priority,
851
- delivered: true,
852
- recipients: target === 'all' ? ['coder', 'architect', 'tester', 'reviewer'] : [target],
853
- timestamp: new Date().toISOString(),
854
- };
855
- },
856
- };
857
-
858
- // Init hook - initialize hooks in project
859
- export const hooksInit: MCPTool = {
860
- name: 'hooks/init',
861
- description: 'Initialize hooks in project with .claude/settings.json',
862
- inputSchema: {
863
- type: 'object',
864
- properties: {
865
- path: { type: 'string', description: 'Project path' },
866
- template: { type: 'string', description: 'Template to use (minimal, standard, full)' },
867
- force: { type: 'boolean', description: 'Overwrite existing configuration' },
868
- },
869
- },
870
- handler: async (params: Record<string, unknown>) => {
871
- const path = (params.path as string) || '.';
872
- const template = (params.template as string) || 'standard';
873
- const force = params.force as boolean;
874
-
875
- const hooksConfigured = template === 'minimal' ? 4 : template === 'full' ? 16 : 9;
876
-
877
- return {
878
- path,
879
- template,
880
- created: {
881
- settingsJson: `${path}/.claude/settings.json`,
882
- hooksDir: `${path}/.claude/hooks`,
883
- },
884
- hooks: {
885
- configured: hooksConfigured,
886
- types: ['PreToolUse', 'PostToolUse', 'SessionStart', 'SessionEnd'],
887
- },
888
- intelligence: {
889
- enabled: template !== 'minimal',
890
- sona: template === 'full',
891
- moe: template === 'full',
892
- hnsw: template !== 'minimal',
893
- },
894
- overwritten: force,
895
- };
896
- },
897
- };
898
-
899
- // Intelligence hook - RuVector intelligence system
900
- export const hooksIntelligence: MCPTool = {
901
- name: 'hooks/intelligence',
902
- description: 'RuVector intelligence system (SONA, MoE, HNSW 150x faster)',
903
- inputSchema: {
904
- type: 'object',
905
- properties: {
906
- mode: { type: 'string', description: 'Intelligence mode' },
907
- enableSona: { type: 'boolean', description: 'Enable SONA learning' },
908
- enableMoe: { type: 'boolean', description: 'Enable MoE routing' },
909
- enableHnsw: { type: 'boolean', description: 'Enable HNSW search' },
910
- forceTraining: { type: 'boolean', description: 'Force training cycle' },
911
- showStatus: { type: 'boolean', description: 'Show status only' },
912
- },
913
- },
914
- handler: async (params: Record<string, unknown>) => {
915
- const mode = (params.mode as string) || 'balanced';
916
- const enableSona = params.enableSona !== false;
917
- const enableMoe = params.enableMoe !== false;
918
- const enableHnsw = params.enableHnsw !== false;
919
-
920
- return {
921
- mode,
922
- status: 'active',
923
- components: {
924
- sona: {
925
- enabled: enableSona,
926
- status: enableSona ? 'active' : 'disabled',
927
- learningTimeMs: 0.042,
928
- adaptationTimeMs: 0.018,
929
- trajectoriesRecorded: 156,
930
- patternsLearned: 89,
931
- avgQuality: 0.87,
932
- },
933
- moe: {
934
- enabled: enableMoe,
935
- status: enableMoe ? 'active' : 'disabled',
936
- expertsActive: 8,
937
- routingAccuracy: 0.92,
938
- loadBalance: 0.85,
939
- },
940
- hnsw: {
941
- enabled: enableHnsw,
942
- status: enableHnsw ? 'ready' : 'disabled',
943
- indexSize: 12500,
944
- searchSpeedup: '150x',
945
- memoryUsage: '45MB',
946
- dimension: 384,
947
- },
948
- embeddings: {
949
- provider: 'transformers',
950
- model: 'all-MiniLM-L6-v2',
951
- dimension: 384,
952
- cacheHitRate: 0.78,
953
- },
954
- },
955
- performance: {
956
- flashAttention: '2.49x-7.47x speedup',
957
- memoryReduction: '50-75% reduction',
958
- searchImprovement: '150x-12,500x faster',
959
- tokenReduction: '32.3% fewer tokens',
960
- sweBenchScore: '84.8%',
961
- },
962
- lastTrainingMs: 0.042,
963
- };
964
- },
965
- };
966
-
967
- // Intelligence reset hook
968
- export const hooksIntelligenceReset: MCPTool = {
969
- name: 'hooks/intelligence-reset',
970
- description: 'Reset intelligence learning state',
971
- inputSchema: {
972
- type: 'object',
973
- properties: {},
974
- },
975
- handler: async () => {
976
- return {
977
- reset: true,
978
- cleared: {
979
- trajectories: 156,
980
- patterns: 89,
981
- hnswIndex: 12500,
982
- },
983
- timestamp: new Date().toISOString(),
984
- };
985
- },
986
- };
987
-
988
- // Intelligence trajectory hooks
989
- export const hooksTrajectoryStart: MCPTool = {
990
- name: 'hooks/intelligence/trajectory-start',
991
- description: 'Begin SONA trajectory for reinforcement learning',
992
- inputSchema: {
993
- type: 'object',
994
- properties: {
995
- task: { type: 'string', description: 'Task description' },
996
- agent: { type: 'string', description: 'Agent type' },
997
- },
998
- required: ['task'],
999
- },
1000
- handler: async (params: Record<string, unknown>) => {
1001
- const task = params.task as string;
1002
- const agent = (params.agent as string) || 'coder';
1003
- const trajectoryId = `traj-${Date.now()}`;
1004
-
1005
- return {
1006
- trajectoryId,
1007
- task,
1008
- agent,
1009
- started: new Date().toISOString(),
1010
- status: 'recording',
1011
- };
1012
- },
1013
- };
1014
-
1015
- export const hooksTrajectoryStep: MCPTool = {
1016
- name: 'hooks/intelligence/trajectory-step',
1017
- description: 'Record step in trajectory for reinforcement learning',
1018
- inputSchema: {
1019
- type: 'object',
1020
- properties: {
1021
- trajectoryId: { type: 'string', description: 'Trajectory ID' },
1022
- action: { type: 'string', description: 'Action taken' },
1023
- result: { type: 'string', description: 'Action result' },
1024
- quality: { type: 'number', description: 'Quality score (0-1)' },
1025
- },
1026
- required: ['trajectoryId', 'action'],
1027
- },
1028
- handler: async (params: Record<string, unknown>) => {
1029
- const trajectoryId = params.trajectoryId as string;
1030
- const action = params.action as string;
1031
- const result = (params.result as string) || 'success';
1032
- const quality = (params.quality as number) || 0.85;
1033
-
1034
- return {
1035
- trajectoryId,
1036
- stepId: `step-${Date.now()}`,
1037
- action,
1038
- result,
1039
- quality,
1040
- recorded: true,
1041
- timestamp: new Date().toISOString(),
1042
- };
1043
- },
1044
- };
1045
-
1046
- export const hooksTrajectoryEnd: MCPTool = {
1047
- name: 'hooks/intelligence/trajectory-end',
1048
- description: 'End trajectory and trigger SONA learning with EWC++',
1049
- inputSchema: {
1050
- type: 'object',
1051
- properties: {
1052
- trajectoryId: { type: 'string', description: 'Trajectory ID' },
1053
- success: { type: 'boolean', description: 'Overall success' },
1054
- feedback: { type: 'string', description: 'Optional feedback' },
1055
- },
1056
- required: ['trajectoryId'],
1057
- },
1058
- handler: async (params: Record<string, unknown>) => {
1059
- const trajectoryId = params.trajectoryId as string;
1060
- const success = params.success !== false;
1061
-
1062
- return {
1063
- trajectoryId,
1064
- success,
1065
- ended: new Date().toISOString(),
1066
- learning: {
1067
- sonaUpdate: true,
1068
- ewcConsolidation: success,
1069
- patternsExtracted: success ? 3 : 1,
1070
- learningTimeMs: 0.038,
1071
- },
1072
- };
1073
- },
1074
- };
1075
-
1076
- // Pattern store/search hooks
1077
- export const hooksPatternStore: MCPTool = {
1078
- name: 'hooks/intelligence/pattern-store',
1079
- description: 'Store pattern in ReasoningBank (HNSW-indexed)',
1080
- inputSchema: {
1081
- type: 'object',
1082
- properties: {
1083
- pattern: { type: 'string', description: 'Pattern description' },
1084
- type: { type: 'string', description: 'Pattern type' },
1085
- confidence: { type: 'number', description: 'Confidence score' },
1086
- metadata: { type: 'object', description: 'Additional metadata' },
1087
- },
1088
- required: ['pattern'],
1089
- },
1090
- handler: async (params: Record<string, unknown>) => {
1091
- const pattern = params.pattern as string;
1092
- const type = (params.type as string) || 'general';
1093
- const confidence = (params.confidence as number) || 0.8;
1094
-
1095
- return {
1096
- patternId: `pattern-${Date.now()}`,
1097
- pattern,
1098
- type,
1099
- confidence,
1100
- indexed: true,
1101
- hnswNode: Math.floor(Math.random() * 10000),
1102
- timestamp: new Date().toISOString(),
1103
- };
1104
- },
1105
- };
1106
-
1107
- export const hooksPatternSearch: MCPTool = {
1108
- name: 'hooks/intelligence/pattern-search',
1109
- description: 'Search ReasoningBank using HNSW (150x faster)',
1110
- inputSchema: {
1111
- type: 'object',
1112
- properties: {
1113
- query: { type: 'string', description: 'Search query' },
1114
- topK: { type: 'number', description: 'Number of results' },
1115
- minConfidence: { type: 'number', description: 'Minimum confidence' },
1116
- },
1117
- required: ['query'],
1118
- },
1119
- handler: async (params: Record<string, unknown>) => {
1120
- const query = params.query as string;
1121
- const topK = (params.topK as number) || 5;
1122
- const minConfidence = (params.minConfidence as number) || 0.6;
1123
-
1124
- // Generate mock results based on query
1125
- const results: Array<{ patternId: string; pattern: string; similarity: number; confidence: number; type: string }> = [];
1126
- for (let i = 0; i < topK; i++) {
1127
- results.push({
1128
- patternId: `pattern-${Date.now() - i * 1000}`,
1129
- pattern: `Pattern matching "${query}" #${i + 1}`,
1130
- similarity: 0.95 - (i * 0.08),
1131
- confidence: Math.max(minConfidence, 0.9 - (i * 0.05)),
1132
- type: ['file-edit', 'task-routing', 'command-risk'][i % 3],
1133
- });
1134
- }
1135
-
1136
- return {
1137
- query,
1138
- results,
1139
- searchTimeMs: 0.12,
1140
- hnswNodesVisited: 45,
1141
- speedup: '150x vs brute-force',
1142
- };
1143
- },
1144
- };
1145
-
1146
- // Intelligence stats hook
1147
- export const hooksIntelligenceStats: MCPTool = {
1148
- name: 'hooks/intelligence/stats',
1149
- description: 'Get RuVector intelligence layer statistics',
1150
- inputSchema: {
1151
- type: 'object',
1152
- properties: {
1153
- detailed: { type: 'boolean', description: 'Include detailed stats' },
1154
- },
1155
- },
1156
- handler: async (params: Record<string, unknown>) => {
1157
- const detailed = params.detailed as boolean;
1158
-
1159
- const stats = {
1160
- sona: {
1161
- trajectoriesTotal: 256,
1162
- trajectoriesSuccessful: 218,
1163
- avgLearningTimeMs: 0.042,
1164
- patternsLearned: 189,
1165
- },
1166
- moe: {
1167
- expertsTotal: 12,
1168
- expertsActive: 8,
1169
- routingDecisions: 1542,
1170
- avgRoutingTimeMs: 0.15,
1171
- },
1172
- hnsw: {
1173
- indexSize: 12500,
1174
- avgSearchTimeMs: 0.12,
1175
- cacheHitRate: 0.78,
1176
- memoryUsageMb: 45,
1177
- },
1178
- ewc: {
1179
- consolidations: 89,
1180
- catastrophicForgettingPrevented: 12,
1181
- fisherUpdates: 256,
1182
- },
1183
- };
1184
-
1185
- if (detailed) {
1186
- return {
1187
- ...stats,
1188
- performance: {
1189
- p50LatencyMs: 0.08,
1190
- p95LatencyMs: 0.25,
1191
- p99LatencyMs: 0.42,
1192
- throughput: 15000,
1193
- },
1194
- memory: {
1195
- sonaBufferMb: 12,
1196
- moeWeightsMb: 8,
1197
- hnswIndexMb: 45,
1198
- embeddingCacheMb: 25,
1199
- },
1200
- };
1201
- }
1202
-
1203
- return stats;
1204
- },
1205
- };
1206
-
1207
- // Intelligence learn hook
1208
- export const hooksIntelligenceLearn: MCPTool = {
1209
- name: 'hooks/intelligence/learn',
1210
- description: 'Force immediate SONA learning cycle with EWC++ consolidation',
1211
- inputSchema: {
1212
- type: 'object',
1213
- properties: {
1214
- trajectoryIds: { type: 'array', description: 'Specific trajectories to learn from' },
1215
- consolidate: { type: 'boolean', description: 'Run EWC++ consolidation' },
1216
- },
1217
- },
1218
- handler: async (params: Record<string, unknown>) => {
1219
- const consolidate = params.consolidate !== false;
1220
- const startTime = Date.now();
1221
-
1222
- return {
1223
- learned: true,
1224
- duration: Date.now() - startTime + 15,
1225
- updates: {
1226
- trajectoriesProcessed: 12,
1227
- patternsExtracted: 8,
1228
- patternsReinforced: 15,
1229
- patternsDeprecated: 2,
1230
- },
1231
- ewc: consolidate ? {
1232
- consolidation: true,
1233
- fisherUpdated: true,
1234
- forgettingPrevented: 3,
1235
- } : null,
1236
- newConfidences: {
1237
- avgIncrease: 0.05,
1238
- maxIncrease: 0.12,
1239
- },
1240
- };
1241
- },
1242
- };
1243
-
1244
- // Intelligence attention hook
1245
- export const hooksIntelligenceAttention: MCPTool = {
1246
- name: 'hooks/intelligence/attention',
1247
- description: 'Compute attention-weighted similarity using MoE/Flash/Hyperbolic',
1248
- inputSchema: {
1249
- type: 'object',
1250
- properties: {
1251
- query: { type: 'string', description: 'Query for attention computation' },
1252
- mode: { type: 'string', description: 'Attention mode (flash, moe, hyperbolic)' },
1253
- topK: { type: 'number', description: 'Top-k results' },
1254
- },
1255
- required: ['query'],
1256
- },
1257
- handler: async (params: Record<string, unknown>) => {
1258
- const query = params.query as string;
1259
- const mode = (params.mode as string) || 'flash';
1260
- const topK = (params.topK as number) || 5;
1261
-
1262
- const attentionWeights: Array<{ index: number; weight: number; pattern: string }> = [];
1263
- for (let i = 0; i < topK; i++) {
1264
- attentionWeights.push({
1265
- index: i,
1266
- weight: Math.exp(-i * 0.5) / (1 + Math.exp(-i * 0.5)),
1267
- pattern: `Attention target #${i + 1}`,
1268
- });
1269
- }
1270
-
1271
- return {
1272
- query,
1273
- mode,
1274
- results: attentionWeights,
1275
- stats: {
1276
- computeTimeMs: mode === 'flash' ? 0.15 : mode === 'hyperbolic' ? 0.35 : 0.25,
1277
- speedup: mode === 'flash' ? '2.49x-7.47x' : '1.5x-2x',
1278
- memoryReduction: mode === 'flash' ? '50-75%' : '25-40%',
1279
- },
1280
- };
1281
- },
1282
- };
1283
-
1284
- // =============================================================================
1285
- // Worker Dispatch Tools (12 Background Workers)
1286
- // =============================================================================
1287
-
1288
- /**
1289
- * Worker trigger types matching agentic-flow@alpha
1290
- */
1291
- type WorkerTrigger =
1292
- | 'ultralearn' // Deep knowledge acquisition
1293
- | 'optimize' // Performance optimization
1294
- | 'consolidate' // Memory consolidation
1295
- | 'predict' // Predictive preloading
1296
- | 'audit' // Security analysis
1297
- | 'map' // Codebase mapping
1298
- | 'preload' // Resource preloading
1299
- | 'deepdive' // Deep code analysis
1300
- | 'document' // Auto-documentation
1301
- | 'refactor' // Refactoring suggestions
1302
- | 'benchmark' // Performance benchmarks
1303
- | 'testgaps'; // Test coverage analysis
1304
-
1305
- /**
1306
- * Worker trigger patterns for auto-detection
1307
- */
1308
- const WORKER_TRIGGER_PATTERNS: Record<WorkerTrigger, RegExp[]> = {
1309
- ultralearn: [
1310
- /learn\s+about/i,
1311
- /understand\s+(how|what|why)/i,
1312
- /deep\s+dive\s+into/i,
1313
- /explain\s+in\s+detail/i,
1314
- /comprehensive\s+guide/i,
1315
- /master\s+this/i,
1316
- ],
1317
- optimize: [
1318
- /optimize/i,
1319
- /improve\s+performance/i,
1320
- /make\s+(it\s+)?faster/i,
1321
- /speed\s+up/i,
1322
- /reduce\s+(memory|time)/i,
1323
- /performance\s+issue/i,
1324
- ],
1325
- consolidate: [
1326
- /consolidate/i,
1327
- /merge\s+memories/i,
1328
- /clean\s+up\s+memory/i,
1329
- /deduplicate/i,
1330
- /memory\s+maintenance/i,
1331
- ],
1332
- predict: [
1333
- /what\s+will\s+happen/i,
1334
- /predict/i,
1335
- /forecast/i,
1336
- /anticipate/i,
1337
- /preload/i,
1338
- /prepare\s+for/i,
1339
- ],
1340
- audit: [
1341
- /security\s+audit/i,
1342
- /vulnerability/i,
1343
- /security\s+check/i,
1344
- /pentest/i,
1345
- /security\s+scan/i,
1346
- /cve/i,
1347
- /owasp/i,
1348
- ],
1349
- map: [
1350
- /map\s+(the\s+)?codebase/i,
1351
- /architecture\s+overview/i,
1352
- /project\s+structure/i,
1353
- /dependency\s+graph/i,
1354
- /code\s+map/i,
1355
- /explore\s+codebase/i,
1356
- ],
1357
- preload: [
1358
- /preload/i,
1359
- /cache\s+ahead/i,
1360
- /prefetch/i,
1361
- /warm\s+(up\s+)?cache/i,
1362
- ],
1363
- deepdive: [
1364
- /deep\s+dive/i,
1365
- /analyze\s+thoroughly/i,
1366
- /in-depth\s+analysis/i,
1367
- /comprehensive\s+review/i,
1368
- /detailed\s+examination/i,
1369
- ],
1370
- document: [
1371
- /document\s+(this|the)/i,
1372
- /generate\s+docs/i,
1373
- /add\s+documentation/i,
1374
- /write\s+readme/i,
1375
- /api\s+docs/i,
1376
- /jsdoc/i,
1377
- ],
1378
- refactor: [
1379
- /refactor/i,
1380
- /clean\s+up\s+code/i,
1381
- /improve\s+code\s+quality/i,
1382
- /restructure/i,
1383
- /simplify/i,
1384
- /make\s+more\s+readable/i,
1385
- ],
1386
- benchmark: [
1387
- /benchmark/i,
1388
- /performance\s+test/i,
1389
- /measure\s+speed/i,
1390
- /stress\s+test/i,
1391
- /load\s+test/i,
1392
- ],
1393
- testgaps: [
1394
- /test\s+coverage/i,
1395
- /missing\s+tests/i,
1396
- /untested\s+code/i,
1397
- /coverage\s+report/i,
1398
- /test\s+gaps/i,
1399
- /add\s+tests/i,
1400
- ],
1401
- };
1402
-
1403
- /**
1404
- * Worker configurations
1405
- */
1406
- const WORKER_CONFIGS: Record<WorkerTrigger, {
1407
- description: string;
1408
- priority: 'low' | 'normal' | 'high' | 'critical';
1409
- estimatedDuration: string;
1410
- capabilities: string[];
1411
- }> = {
1412
- ultralearn: {
1413
- description: 'Deep knowledge acquisition and learning',
1414
- priority: 'normal',
1415
- estimatedDuration: '60s',
1416
- capabilities: ['research', 'analysis', 'synthesis'],
1417
- },
1418
- optimize: {
1419
- description: 'Performance optimization and tuning',
1420
- priority: 'high',
1421
- estimatedDuration: '30s',
1422
- capabilities: ['profiling', 'optimization', 'benchmarking'],
1423
- },
1424
- consolidate: {
1425
- description: 'Memory consolidation and cleanup',
1426
- priority: 'low',
1427
- estimatedDuration: '20s',
1428
- capabilities: ['memory-management', 'deduplication'],
1429
- },
1430
- predict: {
1431
- description: 'Predictive preloading and anticipation',
1432
- priority: 'normal',
1433
- estimatedDuration: '15s',
1434
- capabilities: ['prediction', 'caching', 'preloading'],
1435
- },
1436
- audit: {
1437
- description: 'Security analysis and vulnerability scanning',
1438
- priority: 'critical',
1439
- estimatedDuration: '45s',
1440
- capabilities: ['security', 'vulnerability-scanning', 'audit'],
1441
- },
1442
- map: {
1443
- description: 'Codebase mapping and architecture analysis',
1444
- priority: 'normal',
1445
- estimatedDuration: '30s',
1446
- capabilities: ['analysis', 'mapping', 'visualization'],
1447
- },
1448
- preload: {
1449
- description: 'Resource preloading and cache warming',
1450
- priority: 'low',
1451
- estimatedDuration: '10s',
1452
- capabilities: ['caching', 'preloading'],
1453
- },
1454
- deepdive: {
1455
- description: 'Deep code analysis and examination',
1456
- priority: 'normal',
1457
- estimatedDuration: '60s',
1458
- capabilities: ['analysis', 'review', 'understanding'],
1459
- },
1460
- document: {
1461
- description: 'Auto-documentation generation',
1462
- priority: 'normal',
1463
- estimatedDuration: '45s',
1464
- capabilities: ['documentation', 'writing', 'generation'],
1465
- },
1466
- refactor: {
1467
- description: 'Code refactoring suggestions',
1468
- priority: 'normal',
1469
- estimatedDuration: '30s',
1470
- capabilities: ['refactoring', 'code-quality', 'improvement'],
1471
- },
1472
- benchmark: {
1473
- description: 'Performance benchmarking',
1474
- priority: 'normal',
1475
- estimatedDuration: '60s',
1476
- capabilities: ['benchmarking', 'testing', 'measurement'],
1477
- },
1478
- testgaps: {
1479
- description: 'Test coverage analysis',
1480
- priority: 'normal',
1481
- estimatedDuration: '30s',
1482
- capabilities: ['testing', 'coverage', 'analysis'],
1483
- },
1484
- };
1485
-
1486
- // In-memory worker tracking
1487
- const activeWorkers: Map<string, {
1488
- id: string;
1489
- trigger: WorkerTrigger;
1490
- context: string;
1491
- status: 'pending' | 'running' | 'completed' | 'failed';
1492
- progress: number;
1493
- phase: string;
1494
- startedAt: Date;
1495
- completedAt?: Date;
1496
- }> = new Map();
1497
-
1498
- let workerIdCounter = 0;
1499
-
1500
- /**
1501
- * Detect triggers from prompt text
1502
- */
1503
- function detectWorkerTriggers(text: string): {
1504
- detected: boolean;
1505
- triggers: WorkerTrigger[];
1506
- confidence: number;
1507
- context: string;
1508
- } {
1509
- const detectedTriggers: WorkerTrigger[] = [];
1510
- let totalMatches = 0;
1511
-
1512
- for (const [trigger, patterns] of Object.entries(WORKER_TRIGGER_PATTERNS) as [WorkerTrigger, RegExp[]][]) {
1513
- for (const pattern of patterns) {
1514
- if (pattern.test(text)) {
1515
- if (!detectedTriggers.includes(trigger)) {
1516
- detectedTriggers.push(trigger);
1517
- }
1518
- totalMatches++;
1519
- }
1520
- }
1521
- }
1522
-
1523
- const confidence = detectedTriggers.length > 0
1524
- ? Math.min(1, totalMatches / (detectedTriggers.length * 2))
1525
- : 0;
1526
-
1527
- return {
1528
- detected: detectedTriggers.length > 0,
1529
- triggers: detectedTriggers,
1530
- confidence,
1531
- context: text.slice(0, 100),
1532
- };
1533
- }
1534
-
1535
- // Worker list tool
1536
- export const hooksWorkerList: MCPTool = {
1537
- name: 'hooks/worker-list',
1538
- description: 'List all 12 background workers with status and capabilities',
1539
- inputSchema: {
1540
- type: 'object',
1541
- properties: {
1542
- status: { type: 'string', description: 'Filter by status (all, running, completed, pending)' },
1543
- includeActive: { type: 'boolean', description: 'Include active worker instances' },
1544
- },
1545
- },
1546
- handler: async (params: Record<string, unknown>) => {
1547
- const statusFilter = (params.status as string) || 'all';
1548
- const includeActive = params.includeActive !== false;
1549
-
1550
- const workers = Object.entries(WORKER_CONFIGS).map(([trigger, config]) => ({
1551
- trigger,
1552
- ...config,
1553
- patterns: WORKER_TRIGGER_PATTERNS[trigger as WorkerTrigger].length,
1554
- }));
1555
-
1556
- const activeList = includeActive
1557
- ? Array.from(activeWorkers.values()).filter(w =>
1558
- statusFilter === 'all' || w.status === statusFilter
1559
- )
1560
- : [];
1561
-
1562
- return {
1563
- workers,
1564
- total: 12,
1565
- active: {
1566
- instances: activeList,
1567
- count: activeList.length,
1568
- byStatus: {
1569
- pending: activeList.filter(w => w.status === 'pending').length,
1570
- running: activeList.filter(w => w.status === 'running').length,
1571
- completed: activeList.filter(w => w.status === 'completed').length,
1572
- failed: activeList.filter(w => w.status === 'failed').length,
1573
- },
1574
- },
1575
- performanceTargets: {
1576
- triggerDetection: '<5ms',
1577
- workerSpawn: '<50ms',
1578
- maxConcurrent: 10,
1579
- },
1580
- };
1581
- },
1582
- };
1583
-
1584
- // Worker dispatch tool
1585
- export const hooksWorkerDispatch: MCPTool = {
1586
- name: 'hooks/worker-dispatch',
1587
- description: 'Dispatch a background worker for analysis/optimization tasks',
1588
- inputSchema: {
1589
- type: 'object',
1590
- properties: {
1591
- trigger: {
1592
- type: 'string',
1593
- description: 'Worker trigger type',
1594
- enum: ['ultralearn', 'optimize', 'consolidate', 'predict', 'audit', 'map', 'preload', 'deepdive', 'document', 'refactor', 'benchmark', 'testgaps'],
1595
- },
1596
- context: { type: 'string', description: 'Context for the worker (file path, topic, etc.)' },
1597
- priority: { type: 'string', description: 'Priority (low, normal, high, critical)' },
1598
- background: { type: 'boolean', description: 'Run in background (non-blocking)' },
1599
- },
1600
- required: ['trigger'],
1601
- },
1602
- handler: async (params: Record<string, unknown>) => {
1603
- const trigger = params.trigger as WorkerTrigger;
1604
- const context = (params.context as string) || 'default';
1605
- const priority = (params.priority as string) || WORKER_CONFIGS[trigger]?.priority || 'normal';
1606
- const background = params.background !== false;
1607
-
1608
- if (!WORKER_CONFIGS[trigger]) {
1609
- return {
1610
- success: false,
1611
- error: `Unknown worker trigger: ${trigger}`,
1612
- availableTriggers: Object.keys(WORKER_CONFIGS),
1613
- };
1614
- }
1615
-
1616
- const workerId = `worker_${trigger}_${++workerIdCounter}_${Date.now().toString(36)}`;
1617
- const config = WORKER_CONFIGS[trigger];
1618
-
1619
- const worker: {
1620
- id: string;
1621
- trigger: WorkerTrigger;
1622
- context: string;
1623
- status: 'pending' | 'running' | 'completed' | 'failed';
1624
- progress: number;
1625
- phase: string;
1626
- startedAt: Date;
1627
- completedAt?: Date;
1628
- } = {
1629
- id: workerId,
1630
- trigger,
1631
- context,
1632
- status: 'running',
1633
- progress: 0,
1634
- phase: 'initializing',
1635
- startedAt: new Date(),
1636
- };
1637
-
1638
- activeWorkers.set(workerId, worker);
1639
-
1640
- // Update worker progress in background
1641
- if (background) {
1642
- setTimeout(() => {
1643
- const w = activeWorkers.get(workerId);
1644
- if (w) {
1645
- w.progress = 50;
1646
- w.phase = 'processing';
1647
- }
1648
- }, 500);
1649
-
1650
- setTimeout(() => {
1651
- const w = activeWorkers.get(workerId);
1652
- if (w) {
1653
- w.progress = 100;
1654
- w.phase = 'completed';
1655
- w.status = 'completed';
1656
- w.completedAt = new Date();
1657
- }
1658
- }, 1500);
1659
- } else {
1660
- worker.progress = 100;
1661
- worker.phase = 'completed';
1662
- worker.status = 'completed';
1663
- worker.completedAt = new Date();
1664
- }
1665
-
1666
- return {
1667
- success: true,
1668
- workerId,
1669
- trigger,
1670
- context,
1671
- priority,
1672
- config: {
1673
- description: config.description,
1674
- estimatedDuration: config.estimatedDuration,
1675
- capabilities: config.capabilities,
1676
- },
1677
- status: background ? 'dispatched' : 'completed',
1678
- background,
1679
- timestamp: new Date().toISOString(),
1680
- };
1681
- },
1682
- };
1683
-
1684
- // Worker status tool
1685
- export const hooksWorkerStatus: MCPTool = {
1686
- name: 'hooks/worker-status',
1687
- description: 'Get status of a specific worker or all active workers',
1688
- inputSchema: {
1689
- type: 'object',
1690
- properties: {
1691
- workerId: { type: 'string', description: 'Specific worker ID to check' },
1692
- includeCompleted: { type: 'boolean', description: 'Include completed workers' },
1693
- },
1694
- },
1695
- handler: async (params: Record<string, unknown>) => {
1696
- const workerId = params.workerId as string;
1697
- const includeCompleted = params.includeCompleted !== false;
1698
-
1699
- if (workerId) {
1700
- const worker = activeWorkers.get(workerId);
1701
- if (!worker) {
1702
- return {
1703
- success: false,
1704
- error: `Worker not found: ${workerId}`,
1705
- };
1706
- }
1707
- return {
1708
- success: true,
1709
- worker: {
1710
- ...worker,
1711
- duration: worker.completedAt
1712
- ? worker.completedAt.getTime() - worker.startedAt.getTime()
1713
- : Date.now() - worker.startedAt.getTime(),
1714
- },
1715
- };
1716
- }
1717
-
1718
- const workers = Array.from(activeWorkers.values())
1719
- .filter(w => includeCompleted || w.status !== 'completed')
1720
- .map(w => ({
1721
- ...w,
1722
- duration: w.completedAt
1723
- ? w.completedAt.getTime() - w.startedAt.getTime()
1724
- : Date.now() - w.startedAt.getTime(),
1725
- }));
1726
-
1727
- return {
1728
- success: true,
1729
- workers,
1730
- summary: {
1731
- total: workers.length,
1732
- running: workers.filter(w => w.status === 'running').length,
1733
- completed: workers.filter(w => w.status === 'completed').length,
1734
- failed: workers.filter(w => w.status === 'failed').length,
1735
- },
1736
- };
1737
- },
1738
- };
1739
-
1740
- // Worker detect tool - detect triggers from prompt
1741
- export const hooksWorkerDetect: MCPTool = {
1742
- name: 'hooks/worker-detect',
1743
- description: 'Detect worker triggers from user prompt (for UserPromptSubmit hook)',
1744
- inputSchema: {
1745
- type: 'object',
1746
- properties: {
1747
- prompt: { type: 'string', description: 'User prompt to analyze' },
1748
- autoDispatch: { type: 'boolean', description: 'Automatically dispatch detected workers' },
1749
- minConfidence: { type: 'number', description: 'Minimum confidence threshold (0-1)' },
1750
- },
1751
- required: ['prompt'],
1752
- },
1753
- handler: async (params: Record<string, unknown>) => {
1754
- const prompt = params.prompt as string;
1755
- const autoDispatch = params.autoDispatch as boolean;
1756
- const minConfidence = (params.minConfidence as number) || 0.5;
1757
-
1758
- const detection = detectWorkerTriggers(prompt);
1759
-
1760
- const result: Record<string, unknown> = {
1761
- prompt: prompt.slice(0, 200) + (prompt.length > 200 ? '...' : ''),
1762
- detection,
1763
- triggersFound: detection.triggers.length,
1764
- };
1765
-
1766
- if (detection.detected && detection.confidence >= minConfidence) {
1767
- result.triggerDetails = detection.triggers.map(trigger => ({
1768
- trigger,
1769
- ...WORKER_CONFIGS[trigger],
1770
- }));
1771
-
1772
- if (autoDispatch) {
1773
- const dispatched: string[] = [];
1774
- for (const trigger of detection.triggers) {
1775
- const workerId = `worker_${trigger}_${++workerIdCounter}_${Date.now().toString(36)}`;
1776
- activeWorkers.set(workerId, {
1777
- id: workerId,
1778
- trigger,
1779
- context: prompt.slice(0, 100),
1780
- status: 'running',
1781
- progress: 0,
1782
- phase: 'initializing',
1783
- startedAt: new Date(),
1784
- });
1785
- dispatched.push(workerId);
1786
-
1787
- // Mark worker completion after processing
1788
- setTimeout(() => {
1789
- const w = activeWorkers.get(workerId);
1790
- if (w) {
1791
- w.progress = 100;
1792
- w.phase = 'completed';
1793
- w.status = 'completed';
1794
- w.completedAt = new Date();
1795
- }
1796
- }, 1500);
1797
- }
1798
- result.autoDispatched = true;
1799
- result.workerIds = dispatched;
1800
- }
1801
- }
1802
-
1803
- return result;
1804
- },
1805
- };
1806
-
1807
- // Worker cancel tool
1808
- export const hooksWorkerCancel: MCPTool = {
1809
- name: 'hooks/worker-cancel',
1810
- description: 'Cancel a running worker',
1811
- inputSchema: {
1812
- type: 'object',
1813
- properties: {
1814
- workerId: { type: 'string', description: 'Worker ID to cancel' },
1815
- },
1816
- required: ['workerId'],
1817
- },
1818
- handler: async (params: Record<string, unknown>) => {
1819
- const workerId = params.workerId as string;
1820
- const worker = activeWorkers.get(workerId);
1821
-
1822
- if (!worker) {
1823
- return {
1824
- success: false,
1825
- error: `Worker not found: ${workerId}`,
1826
- };
1827
- }
1828
-
1829
- if (worker.status === 'completed' || worker.status === 'failed') {
1830
- return {
1831
- success: false,
1832
- error: `Worker already ${worker.status}`,
1833
- };
1834
- }
1835
-
1836
- worker.status = 'failed';
1837
- worker.phase = 'cancelled';
1838
- worker.completedAt = new Date();
1839
-
1840
- return {
1841
- success: true,
1842
- workerId,
1843
- cancelled: true,
1844
- timestamp: new Date().toISOString(),
1845
- };
1846
- },
1847
- };
1848
-
1849
- // Export all hooks tools
1850
- export const hooksTools: MCPTool[] = [
1851
- hooksPreEdit,
1852
- hooksPostEdit,
1853
- hooksPreCommand,
1854
- hooksPostCommand,
1855
- hooksRoute,
1856
- hooksMetrics,
1857
- hooksList,
1858
- hooksPreTask,
1859
- hooksPostTask,
1860
- // New hooks
1861
- hooksExplain,
1862
- hooksPretrain,
1863
- hooksBuildAgents,
1864
- hooksTransfer,
1865
- hooksSessionStart,
1866
- hooksSessionEnd,
1867
- hooksSessionRestore,
1868
- hooksNotify,
1869
- hooksInit,
1870
- hooksIntelligence,
1871
- hooksIntelligenceReset,
1872
- hooksTrajectoryStart,
1873
- hooksTrajectoryStep,
1874
- hooksTrajectoryEnd,
1875
- hooksPatternStore,
1876
- hooksPatternSearch,
1877
- hooksIntelligenceStats,
1878
- hooksIntelligenceLearn,
1879
- hooksIntelligenceAttention,
1880
- // Worker tools
1881
- hooksWorkerList,
1882
- hooksWorkerDispatch,
1883
- hooksWorkerStatus,
1884
- hooksWorkerDetect,
1885
- hooksWorkerCancel,
1886
- ];
1887
-
1888
- export default hooksTools;