@ruvector/ruvllm 2.5.4 → 2.5.6

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 (63) hide show
  1. package/README.md +282 -282
  2. package/bin/cli.js +1020 -1020
  3. package/dist/cjs/benchmarks/embedding-benchmark.js +1 -1
  4. package/dist/cjs/benchmarks/index.js +1 -1
  5. package/dist/cjs/benchmarks/model-comparison.js +1 -1
  6. package/dist/cjs/benchmarks/routing-benchmark.js +1 -1
  7. package/dist/cjs/contrastive.js +70 -70
  8. package/dist/cjs/engine.js +13 -13
  9. package/dist/cjs/export.js +31 -31
  10. package/dist/cjs/federated.js +1 -1
  11. package/dist/cjs/index.js +1 -1
  12. package/dist/cjs/intelligence.js +1 -1
  13. package/dist/cjs/lora.js +1 -1
  14. package/dist/cjs/models.js +1 -1
  15. package/dist/cjs/native.js +1 -1
  16. package/dist/cjs/session.js +1 -1
  17. package/dist/cjs/simd.js +1 -1
  18. package/dist/cjs/sona.d.ts +36 -0
  19. package/dist/cjs/sona.d.ts.map +1 -1
  20. package/dist/cjs/sona.js +66 -4
  21. package/dist/cjs/streaming.js +1 -1
  22. package/dist/cjs/training.js +1 -1
  23. package/dist/cjs/types.js +1 -1
  24. package/dist/esm/benchmarks/embedding-benchmark.js +1 -1
  25. package/dist/esm/benchmarks/index.js +1 -1
  26. package/dist/esm/benchmarks/model-comparison.js +1 -1
  27. package/dist/esm/benchmarks/routing-benchmark.js +1 -1
  28. package/dist/esm/contrastive.js +70 -70
  29. package/dist/esm/engine.js +13 -13
  30. package/dist/esm/export.js +31 -31
  31. package/dist/esm/federated.js +1 -1
  32. package/dist/esm/index.js +1 -1
  33. package/dist/esm/intelligence.js +1 -1
  34. package/dist/esm/lora.js +1 -1
  35. package/dist/esm/models.js +1 -1
  36. package/dist/esm/native.js +1 -1
  37. package/dist/esm/session.js +1 -1
  38. package/dist/esm/simd.js +1 -1
  39. package/dist/esm/sona.d.ts +36 -0
  40. package/dist/esm/sona.d.ts.map +1 -1
  41. package/dist/esm/sona.js +66 -4
  42. package/dist/esm/streaming.js +1 -1
  43. package/dist/esm/training.js +1 -1
  44. package/dist/esm/types.js +1 -1
  45. package/package.json +133 -133
  46. package/scripts/ensemble-model-compare.js +287 -287
  47. package/scripts/huggingface/README.md +537 -537
  48. package/scripts/huggingface/publish.sh +112 -112
  49. package/scripts/hybrid-model-compare.js +373 -373
  50. package/scripts/improved-model-compare.js +288 -288
  51. package/scripts/optimized-model-compare.js +364 -364
  52. package/scripts/real-model-compare.js +280 -280
  53. package/scripts/training/agentic-flow-capabilities.json +329 -329
  54. package/scripts/training/claude-code-synth.js +505 -505
  55. package/scripts/training/claude-flow-capabilities.json +1322 -1322
  56. package/scripts/training/claude-hard-negatives.js +222 -222
  57. package/scripts/training/contrastive-finetune.js +517 -517
  58. package/scripts/training/ecosystem-triplets.jsonl +1466 -1466
  59. package/scripts/training/generate-ecosystem-triplets.js +1324 -1324
  60. package/scripts/training/routing-dataset.js +634 -634
  61. package/scripts/training/ruvector-capabilities.json +798 -798
  62. package/scripts/training/validate-ecosystem.js +381 -381
  63. package/scripts/training/validation-results.json +22 -22
@@ -1,364 +1,364 @@
1
- #!/usr/bin/env node
2
- /**
3
- * Optimized Model Comparison
4
- *
5
- * Key insight: Shorter, more focused descriptions work better for embeddings.
6
- * This version tests:
7
- * 1. Focused discriminating keywords (no overlap)
8
- * 2. Multi-embedding approach (multiple short phrases per agent)
9
- * 3. Weighted voting from multiple description variants
10
- */
11
-
12
- const { execSync } = require('child_process');
13
- const { existsSync } = require('fs');
14
- const { join } = require('path');
15
- const { homedir } = require('os');
16
-
17
- const MODELS_DIR = join(homedir(), '.ruvllm', 'models');
18
- const QWEN_MODEL = join(MODELS_DIR, 'qwen2.5-0.5b-instruct-q4_k_m.gguf');
19
- const RUVLTRA_MODEL = join(MODELS_DIR, 'ruvltra-claude-code-0.5b-q4_k_m.gguf');
20
-
21
- // V1: Original keywords (baseline)
22
- const DESCRIPTIONS_V1 = {
23
- coder: 'implement create write build add code function class component feature',
24
- researcher: 'research find investigate analyze explore search discover examine',
25
- reviewer: 'review check evaluate assess inspect examine code quality',
26
- tester: 'test unit integration e2e coverage mock assertion spec',
27
- architect: 'design architecture schema system structure plan database',
28
- 'security-architect': 'security vulnerability xss injection audit cve authentication',
29
- debugger: 'debug fix bug error issue broken crash exception trace',
30
- documenter: 'document readme jsdoc comment explain describe documentation',
31
- refactorer: 'refactor extract rename consolidate clean restructure simplify',
32
- optimizer: 'optimize performance slow fast cache speed memory latency',
33
- devops: 'deploy ci cd kubernetes docker pipeline container infrastructure',
34
- 'api-docs': 'openapi swagger api documentation graphql schema endpoint',
35
- planner: 'plan estimate prioritize sprint roadmap schedule milestone',
36
- };
37
-
38
- // V4: Focused discriminating keywords - remove overlap, add unique identifiers
39
- const DESCRIPTIONS_V4 = {
40
- coder: 'implement build create function component feature typescript react',
41
- researcher: 'research investigate explore discover best practices patterns',
42
- reviewer: 'review pull request code quality style check pr',
43
- tester: 'test unit integration e2e tests testing coverage spec',
44
- architect: 'design architecture schema database system structure diagram',
45
- 'security-architect': 'security vulnerability xss injection csrf audit cve',
46
- debugger: 'debug fix bug error exception crash trace null pointer',
47
- documenter: 'jsdoc comments readme documentation describe explain',
48
- refactorer: 'refactor async await modernize restructure extract',
49
- optimizer: 'optimize cache performance speed latency slow fast',
50
- devops: 'deploy ci cd kubernetes docker pipeline infrastructure',
51
- 'api-docs': 'openapi swagger rest api spec endpoint documentation',
52
- planner: 'sprint plan roadmap milestone estimate schedule prioritize',
53
- };
54
-
55
- // V5: Multi-phrase approach - multiple short embeddings per agent, use max similarity
56
- const MULTI_DESCRIPTIONS = {
57
- coder: [
58
- 'implement function',
59
- 'build component',
60
- 'create typescript code',
61
- 'write feature',
62
- ],
63
- researcher: [
64
- 'research best practices',
65
- 'investigate issue',
66
- 'explore solutions',
67
- 'analyze patterns',
68
- ],
69
- reviewer: [
70
- 'review pull request',
71
- 'check code quality',
72
- 'evaluate code',
73
- 'assess implementation',
74
- ],
75
- tester: [
76
- 'write unit tests',
77
- 'add integration tests',
78
- 'create test coverage',
79
- 'test authentication',
80
- ],
81
- architect: [
82
- 'design database schema',
83
- 'plan architecture',
84
- 'system structure',
85
- 'microservices design',
86
- ],
87
- 'security-architect': [
88
- 'audit xss vulnerability',
89
- 'security audit',
90
- 'check injection',
91
- 'cve vulnerability',
92
- ],
93
- debugger: [
94
- 'fix bug',
95
- 'debug error',
96
- 'trace exception',
97
- 'fix null pointer',
98
- ],
99
- documenter: [
100
- 'write jsdoc comments',
101
- 'create readme',
102
- 'document functions',
103
- 'explain code',
104
- ],
105
- refactorer: [
106
- 'refactor to async await',
107
- 'restructure code',
108
- 'modernize legacy',
109
- 'extract function',
110
- ],
111
- optimizer: [
112
- 'cache data',
113
- 'optimize query',
114
- 'improve performance',
115
- 'reduce latency',
116
- ],
117
- devops: [
118
- 'deploy kubernetes',
119
- 'setup ci cd',
120
- 'docker container',
121
- 'infrastructure pipeline',
122
- ],
123
- 'api-docs': [
124
- 'generate openapi',
125
- 'swagger documentation',
126
- 'rest api spec',
127
- 'api endpoint docs',
128
- ],
129
- planner: [
130
- 'create sprint plan',
131
- 'estimate timeline',
132
- 'prioritize tasks',
133
- 'roadmap milestone',
134
- ],
135
- };
136
-
137
- const ROUTING_TESTS = [
138
- { task: 'Implement a binary search function in TypeScript', expected: 'coder' },
139
- { task: 'Write unit tests for the authentication module', expected: 'tester' },
140
- { task: 'Review the pull request for security vulnerabilities', expected: 'reviewer' },
141
- { task: 'Research best practices for React state management', expected: 'researcher' },
142
- { task: 'Design the database schema for user profiles', expected: 'architect' },
143
- { task: 'Fix the null pointer exception in the login handler', expected: 'debugger' },
144
- { task: 'Audit the API endpoints for XSS vulnerabilities', expected: 'security-architect' },
145
- { task: 'Write JSDoc comments for the utility functions', expected: 'documenter' },
146
- { task: 'Refactor the payment module to use async/await', expected: 'refactorer' },
147
- { task: 'Optimize the database queries for the dashboard', expected: 'optimizer' },
148
- { task: 'Set up the CI/CD pipeline for the microservices', expected: 'devops' },
149
- { task: 'Generate OpenAPI documentation for the REST API', expected: 'api-docs' },
150
- { task: 'Create a sprint plan for the next two weeks', expected: 'planner' },
151
- { task: 'Build a React component for user registration', expected: 'coder' },
152
- { task: 'Debug memory leak in the WebSocket handler', expected: 'debugger' },
153
- { task: 'Investigate slow API response times', expected: 'researcher' },
154
- { task: 'Check code for potential race conditions', expected: 'reviewer' },
155
- { task: 'Add integration tests for the payment gateway', expected: 'tester' },
156
- { task: 'Plan the architecture for real-time notifications', expected: 'architect' },
157
- { task: 'Cache the frequently accessed user data', expected: 'optimizer' },
158
- ];
159
-
160
- function getEmbedding(modelPath, text) {
161
- try {
162
- const sanitized = text.replace(/"/g, '\\"').replace(/\n/g, ' ');
163
- const result = execSync(
164
- `llama-embedding -m "${modelPath}" -p "${sanitized}" --embd-output-format json 2>/dev/null`,
165
- { encoding: 'utf-8', maxBuffer: 10 * 1024 * 1024 }
166
- );
167
- const json = JSON.parse(result);
168
- return json.data[json.data.length - 1].embedding;
169
- } catch (err) {
170
- return null;
171
- }
172
- }
173
-
174
- function cosineSimilarity(a, b) {
175
- if (!a || !b || a.length !== b.length) return 0;
176
- let dot = 0, normA = 0, normB = 0;
177
- for (let i = 0; i < a.length; i++) {
178
- dot += a[i] * b[i];
179
- normA += a[i] * a[i];
180
- normB += b[i] * b[i];
181
- }
182
- return dot / (Math.sqrt(normA) * Math.sqrt(normB) || 1);
183
- }
184
-
185
- /**
186
- * Standard single-embedding routing
187
- */
188
- function routeTaskSingle(taskEmbedding, agentEmbeddings) {
189
- let bestAgent = 'coder';
190
- let bestSim = -1;
191
- for (const [agent, emb] of Object.entries(agentEmbeddings)) {
192
- const sim = cosineSimilarity(taskEmbedding, emb);
193
- if (sim > bestSim) {
194
- bestSim = sim;
195
- bestAgent = agent;
196
- }
197
- }
198
- return { agent: bestAgent, confidence: bestSim };
199
- }
200
-
201
- /**
202
- * Multi-embedding routing - use max similarity across multiple phrases
203
- */
204
- function routeTaskMulti(taskEmbedding, multiAgentEmbeddings) {
205
- let bestAgent = 'coder';
206
- let bestSim = -1;
207
-
208
- for (const [agent, embeddings] of Object.entries(multiAgentEmbeddings)) {
209
- // Take max similarity across all phrases for this agent
210
- let maxSim = -1;
211
- for (const emb of embeddings) {
212
- const sim = cosineSimilarity(taskEmbedding, emb);
213
- if (sim > maxSim) maxSim = sim;
214
- }
215
- if (maxSim > bestSim) {
216
- bestSim = maxSim;
217
- bestAgent = agent;
218
- }
219
- }
220
- return { agent: bestAgent, confidence: bestSim };
221
- }
222
-
223
- /**
224
- * Run single-embedding benchmark
225
- */
226
- function runSingleBenchmark(modelPath, descriptions, version) {
227
- process.stdout.write(` [${version}] Computing embeddings... `);
228
-
229
- const agentEmbeddings = {};
230
- for (const [agent, desc] of Object.entries(descriptions)) {
231
- agentEmbeddings[agent] = getEmbedding(modelPath, desc);
232
- }
233
- console.log('done');
234
-
235
- let correct = 0;
236
- for (const test of ROUTING_TESTS) {
237
- const taskEmb = getEmbedding(modelPath, test.task);
238
- const { agent } = routeTaskSingle(taskEmb, agentEmbeddings);
239
- if (agent === test.expected) correct++;
240
- }
241
-
242
- return { accuracy: correct / ROUTING_TESTS.length, correct, total: ROUTING_TESTS.length, version };
243
- }
244
-
245
- /**
246
- * Run multi-embedding benchmark
247
- */
248
- function runMultiBenchmark(modelPath, multiDescriptions, version) {
249
- process.stdout.write(` [${version}] Computing multi-embeddings... `);
250
-
251
- const multiAgentEmbeddings = {};
252
- for (const [agent, phrases] of Object.entries(multiDescriptions)) {
253
- multiAgentEmbeddings[agent] = phrases.map(p => getEmbedding(modelPath, p));
254
- }
255
- console.log('done');
256
-
257
- let correct = 0;
258
- const results = [];
259
- for (const test of ROUTING_TESTS) {
260
- const taskEmb = getEmbedding(modelPath, test.task);
261
- const { agent, confidence } = routeTaskMulti(taskEmb, multiAgentEmbeddings);
262
- const isCorrect = agent === test.expected;
263
- if (isCorrect) correct++;
264
- results.push({ task: test.task, expected: test.expected, got: agent, correct: isCorrect });
265
- }
266
-
267
- return { accuracy: correct / ROUTING_TESTS.length, correct, total: ROUTING_TESTS.length, version, results };
268
- }
269
-
270
- async function main() {
271
- console.log('\n╔═══════════════════════════════════════════════════════════════════════════════════╗');
272
- console.log('║ OPTIMIZED MODEL COMPARISON: Focused & Multi-Embedding ║');
273
- console.log('╚═══════════════════════════════════════════════════════════════════════════════════╝\n');
274
-
275
- if (!existsSync(RUVLTRA_MODEL)) {
276
- console.error('RuvLTRA model not found.');
277
- process.exit(1);
278
- }
279
-
280
- console.log('Strategies:');
281
- console.log(' V1: Original keywords (baseline)');
282
- console.log(' V4: Focused discriminating keywords');
283
- console.log(' V5: Multi-phrase (4 phrases per agent, max similarity)\n');
284
-
285
- // RuvLTRA tests
286
- console.log('─────────────────────────────────────────────────────────────────');
287
- console.log(' RUVLTRA CLAUDE CODE');
288
- console.log('─────────────────────────────────────────────────────────────────');
289
-
290
- const ruvV1 = runSingleBenchmark(RUVLTRA_MODEL, DESCRIPTIONS_V1, 'V1-Original');
291
- const ruvV4 = runSingleBenchmark(RUVLTRA_MODEL, DESCRIPTIONS_V4, 'V4-Focused');
292
- const ruvV5 = runMultiBenchmark(RUVLTRA_MODEL, MULTI_DESCRIPTIONS, 'V5-Multi');
293
-
294
- // Qwen tests
295
- console.log('\n─────────────────────────────────────────────────────────────────');
296
- console.log(' QWEN 0.5B BASE');
297
- console.log('─────────────────────────────────────────────────────────────────');
298
-
299
- const qwenV1 = runSingleBenchmark(QWEN_MODEL, DESCRIPTIONS_V1, 'V1-Original');
300
- const qwenV4 = runSingleBenchmark(QWEN_MODEL, DESCRIPTIONS_V4, 'V4-Focused');
301
- const qwenV5 = runMultiBenchmark(QWEN_MODEL, MULTI_DESCRIPTIONS, 'V5-Multi');
302
-
303
- // Results
304
- console.log('\n═══════════════════════════════════════════════════════════════════════════════════');
305
- console.log(' RESULTS');
306
- console.log('═══════════════════════════════════════════════════════════════════════════════════\n');
307
-
308
- console.log('┌─────────────────────────┬───────────────┬───────────────┬───────────────┐');
309
- console.log('│ Strategy │ RuvLTRA │ Qwen Base │ RuvLTRA Delta │');
310
- console.log('├─────────────────────────┼───────────────┼───────────────┼───────────────┤');
311
-
312
- const fmt = (v) => `${(v * 100).toFixed(1)}%`.padStart(12);
313
- const fmtDelta = (v, base) => {
314
- const delta = (v - base) * 100;
315
- const sign = delta >= 0 ? '+' : '';
316
- return `${sign}${delta.toFixed(1)}%`.padStart(12);
317
- };
318
-
319
- console.log(`│ V1: Original │${fmt(ruvV1.accuracy)} │${fmt(qwenV1.accuracy)} │ baseline │`);
320
- console.log(`│ V4: Focused │${fmt(ruvV4.accuracy)} │${fmt(qwenV4.accuracy)} │${fmtDelta(ruvV4.accuracy, ruvV1.accuracy)} │`);
321
- console.log(`│ V5: Multi-phrase │${fmt(ruvV5.accuracy)} │${fmt(qwenV5.accuracy)} │${fmtDelta(ruvV5.accuracy, ruvV1.accuracy)} │`);
322
- console.log('└─────────────────────────┴───────────────┴───────────────┴───────────────┘');
323
-
324
- // Best result
325
- const allResults = [
326
- { model: 'RuvLTRA', ...ruvV1 },
327
- { model: 'RuvLTRA', ...ruvV4 },
328
- { model: 'RuvLTRA', ...ruvV5 },
329
- { model: 'Qwen', ...qwenV1 },
330
- { model: 'Qwen', ...qwenV4 },
331
- { model: 'Qwen', ...qwenV5 },
332
- ];
333
-
334
- const best = allResults.reduce((a, b) => a.accuracy > b.accuracy ? a : b);
335
-
336
- console.log(`\n BEST: ${best.model} + ${best.version} = ${(best.accuracy * 100).toFixed(1)}%`);
337
-
338
- // Show V5 detailed results
339
- console.log('\n─────────────────────────────────────────────────────────────────');
340
- console.log(' V5 MULTI-PHRASE DETAILED (RuvLTRA)');
341
- console.log('─────────────────────────────────────────────────────────────────');
342
-
343
- for (const r of ruvV5.results) {
344
- const mark = r.correct ? '✓' : '✗';
345
- const task = r.task.slice(0, 50).padEnd(50);
346
- const exp = r.expected.padEnd(18);
347
- const got = r.got.padEnd(18);
348
- console.log(` ${mark} ${task} ${exp} ${r.correct ? '' : '→ ' + got}`);
349
- }
350
-
351
- // Final comparison
352
- const ruvBest = [ruvV1, ruvV4, ruvV5].reduce((a, b) => a.accuracy > b.accuracy ? a : b);
353
- const qwenBest = [qwenV1, qwenV4, qwenV5].reduce((a, b) => a.accuracy > b.accuracy ? a : b);
354
-
355
- console.log('\n═══════════════════════════════════════════════════════════════════════════════════');
356
- console.log(' FINAL WINNER');
357
- console.log('═══════════════════════════════════════════════════════════════════════════════════');
358
- console.log(`\n RuvLTRA best: ${ruvBest.version} = ${(ruvBest.accuracy * 100).toFixed(1)}%`);
359
- console.log(` Qwen best: ${qwenBest.version} = ${(qwenBest.accuracy * 100).toFixed(1)}%`);
360
- console.log(`\n Margin: RuvLTRA leads by ${((ruvBest.accuracy - qwenBest.accuracy) * 100).toFixed(1)} points`);
361
- console.log('\n');
362
- }
363
-
364
- main().catch(console.error);
1
+ #!/usr/bin/env node
2
+ /**
3
+ * Optimized Model Comparison
4
+ *
5
+ * Key insight: Shorter, more focused descriptions work better for embeddings.
6
+ * This version tests:
7
+ * 1. Focused discriminating keywords (no overlap)
8
+ * 2. Multi-embedding approach (multiple short phrases per agent)
9
+ * 3. Weighted voting from multiple description variants
10
+ */
11
+
12
+ const { execSync } = require('child_process');
13
+ const { existsSync } = require('fs');
14
+ const { join } = require('path');
15
+ const { homedir } = require('os');
16
+
17
+ const MODELS_DIR = join(homedir(), '.ruvllm', 'models');
18
+ const QWEN_MODEL = join(MODELS_DIR, 'qwen2.5-0.5b-instruct-q4_k_m.gguf');
19
+ const RUVLTRA_MODEL = join(MODELS_DIR, 'ruvltra-claude-code-0.5b-q4_k_m.gguf');
20
+
21
+ // V1: Original keywords (baseline)
22
+ const DESCRIPTIONS_V1 = {
23
+ coder: 'implement create write build add code function class component feature',
24
+ researcher: 'research find investigate analyze explore search discover examine',
25
+ reviewer: 'review check evaluate assess inspect examine code quality',
26
+ tester: 'test unit integration e2e coverage mock assertion spec',
27
+ architect: 'design architecture schema system structure plan database',
28
+ 'security-architect': 'security vulnerability xss injection audit cve authentication',
29
+ debugger: 'debug fix bug error issue broken crash exception trace',
30
+ documenter: 'document readme jsdoc comment explain describe documentation',
31
+ refactorer: 'refactor extract rename consolidate clean restructure simplify',
32
+ optimizer: 'optimize performance slow fast cache speed memory latency',
33
+ devops: 'deploy ci cd kubernetes docker pipeline container infrastructure',
34
+ 'api-docs': 'openapi swagger api documentation graphql schema endpoint',
35
+ planner: 'plan estimate prioritize sprint roadmap schedule milestone',
36
+ };
37
+
38
+ // V4: Focused discriminating keywords - remove overlap, add unique identifiers
39
+ const DESCRIPTIONS_V4 = {
40
+ coder: 'implement build create function component feature typescript react',
41
+ researcher: 'research investigate explore discover best practices patterns',
42
+ reviewer: 'review pull request code quality style check pr',
43
+ tester: 'test unit integration e2e tests testing coverage spec',
44
+ architect: 'design architecture schema database system structure diagram',
45
+ 'security-architect': 'security vulnerability xss injection csrf audit cve',
46
+ debugger: 'debug fix bug error exception crash trace null pointer',
47
+ documenter: 'jsdoc comments readme documentation describe explain',
48
+ refactorer: 'refactor async await modernize restructure extract',
49
+ optimizer: 'optimize cache performance speed latency slow fast',
50
+ devops: 'deploy ci cd kubernetes docker pipeline infrastructure',
51
+ 'api-docs': 'openapi swagger rest api spec endpoint documentation',
52
+ planner: 'sprint plan roadmap milestone estimate schedule prioritize',
53
+ };
54
+
55
+ // V5: Multi-phrase approach - multiple short embeddings per agent, use max similarity
56
+ const MULTI_DESCRIPTIONS = {
57
+ coder: [
58
+ 'implement function',
59
+ 'build component',
60
+ 'create typescript code',
61
+ 'write feature',
62
+ ],
63
+ researcher: [
64
+ 'research best practices',
65
+ 'investigate issue',
66
+ 'explore solutions',
67
+ 'analyze patterns',
68
+ ],
69
+ reviewer: [
70
+ 'review pull request',
71
+ 'check code quality',
72
+ 'evaluate code',
73
+ 'assess implementation',
74
+ ],
75
+ tester: [
76
+ 'write unit tests',
77
+ 'add integration tests',
78
+ 'create test coverage',
79
+ 'test authentication',
80
+ ],
81
+ architect: [
82
+ 'design database schema',
83
+ 'plan architecture',
84
+ 'system structure',
85
+ 'microservices design',
86
+ ],
87
+ 'security-architect': [
88
+ 'audit xss vulnerability',
89
+ 'security audit',
90
+ 'check injection',
91
+ 'cve vulnerability',
92
+ ],
93
+ debugger: [
94
+ 'fix bug',
95
+ 'debug error',
96
+ 'trace exception',
97
+ 'fix null pointer',
98
+ ],
99
+ documenter: [
100
+ 'write jsdoc comments',
101
+ 'create readme',
102
+ 'document functions',
103
+ 'explain code',
104
+ ],
105
+ refactorer: [
106
+ 'refactor to async await',
107
+ 'restructure code',
108
+ 'modernize legacy',
109
+ 'extract function',
110
+ ],
111
+ optimizer: [
112
+ 'cache data',
113
+ 'optimize query',
114
+ 'improve performance',
115
+ 'reduce latency',
116
+ ],
117
+ devops: [
118
+ 'deploy kubernetes',
119
+ 'setup ci cd',
120
+ 'docker container',
121
+ 'infrastructure pipeline',
122
+ ],
123
+ 'api-docs': [
124
+ 'generate openapi',
125
+ 'swagger documentation',
126
+ 'rest api spec',
127
+ 'api endpoint docs',
128
+ ],
129
+ planner: [
130
+ 'create sprint plan',
131
+ 'estimate timeline',
132
+ 'prioritize tasks',
133
+ 'roadmap milestone',
134
+ ],
135
+ };
136
+
137
+ const ROUTING_TESTS = [
138
+ { task: 'Implement a binary search function in TypeScript', expected: 'coder' },
139
+ { task: 'Write unit tests for the authentication module', expected: 'tester' },
140
+ { task: 'Review the pull request for security vulnerabilities', expected: 'reviewer' },
141
+ { task: 'Research best practices for React state management', expected: 'researcher' },
142
+ { task: 'Design the database schema for user profiles', expected: 'architect' },
143
+ { task: 'Fix the null pointer exception in the login handler', expected: 'debugger' },
144
+ { task: 'Audit the API endpoints for XSS vulnerabilities', expected: 'security-architect' },
145
+ { task: 'Write JSDoc comments for the utility functions', expected: 'documenter' },
146
+ { task: 'Refactor the payment module to use async/await', expected: 'refactorer' },
147
+ { task: 'Optimize the database queries for the dashboard', expected: 'optimizer' },
148
+ { task: 'Set up the CI/CD pipeline for the microservices', expected: 'devops' },
149
+ { task: 'Generate OpenAPI documentation for the REST API', expected: 'api-docs' },
150
+ { task: 'Create a sprint plan for the next two weeks', expected: 'planner' },
151
+ { task: 'Build a React component for user registration', expected: 'coder' },
152
+ { task: 'Debug memory leak in the WebSocket handler', expected: 'debugger' },
153
+ { task: 'Investigate slow API response times', expected: 'researcher' },
154
+ { task: 'Check code for potential race conditions', expected: 'reviewer' },
155
+ { task: 'Add integration tests for the payment gateway', expected: 'tester' },
156
+ { task: 'Plan the architecture for real-time notifications', expected: 'architect' },
157
+ { task: 'Cache the frequently accessed user data', expected: 'optimizer' },
158
+ ];
159
+
160
+ function getEmbedding(modelPath, text) {
161
+ try {
162
+ const sanitized = text.replace(/"/g, '\\"').replace(/\n/g, ' ');
163
+ const result = execSync(
164
+ `llama-embedding -m "${modelPath}" -p "${sanitized}" --embd-output-format json 2>/dev/null`,
165
+ { encoding: 'utf-8', maxBuffer: 10 * 1024 * 1024 }
166
+ );
167
+ const json = JSON.parse(result);
168
+ return json.data[json.data.length - 1].embedding;
169
+ } catch (err) {
170
+ return null;
171
+ }
172
+ }
173
+
174
+ function cosineSimilarity(a, b) {
175
+ if (!a || !b || a.length !== b.length) return 0;
176
+ let dot = 0, normA = 0, normB = 0;
177
+ for (let i = 0; i < a.length; i++) {
178
+ dot += a[i] * b[i];
179
+ normA += a[i] * a[i];
180
+ normB += b[i] * b[i];
181
+ }
182
+ return dot / (Math.sqrt(normA) * Math.sqrt(normB) || 1);
183
+ }
184
+
185
+ /**
186
+ * Standard single-embedding routing
187
+ */
188
+ function routeTaskSingle(taskEmbedding, agentEmbeddings) {
189
+ let bestAgent = 'coder';
190
+ let bestSim = -1;
191
+ for (const [agent, emb] of Object.entries(agentEmbeddings)) {
192
+ const sim = cosineSimilarity(taskEmbedding, emb);
193
+ if (sim > bestSim) {
194
+ bestSim = sim;
195
+ bestAgent = agent;
196
+ }
197
+ }
198
+ return { agent: bestAgent, confidence: bestSim };
199
+ }
200
+
201
+ /**
202
+ * Multi-embedding routing - use max similarity across multiple phrases
203
+ */
204
+ function routeTaskMulti(taskEmbedding, multiAgentEmbeddings) {
205
+ let bestAgent = 'coder';
206
+ let bestSim = -1;
207
+
208
+ for (const [agent, embeddings] of Object.entries(multiAgentEmbeddings)) {
209
+ // Take max similarity across all phrases for this agent
210
+ let maxSim = -1;
211
+ for (const emb of embeddings) {
212
+ const sim = cosineSimilarity(taskEmbedding, emb);
213
+ if (sim > maxSim) maxSim = sim;
214
+ }
215
+ if (maxSim > bestSim) {
216
+ bestSim = maxSim;
217
+ bestAgent = agent;
218
+ }
219
+ }
220
+ return { agent: bestAgent, confidence: bestSim };
221
+ }
222
+
223
+ /**
224
+ * Run single-embedding benchmark
225
+ */
226
+ function runSingleBenchmark(modelPath, descriptions, version) {
227
+ process.stdout.write(` [${version}] Computing embeddings... `);
228
+
229
+ const agentEmbeddings = {};
230
+ for (const [agent, desc] of Object.entries(descriptions)) {
231
+ agentEmbeddings[agent] = getEmbedding(modelPath, desc);
232
+ }
233
+ console.log('done');
234
+
235
+ let correct = 0;
236
+ for (const test of ROUTING_TESTS) {
237
+ const taskEmb = getEmbedding(modelPath, test.task);
238
+ const { agent } = routeTaskSingle(taskEmb, agentEmbeddings);
239
+ if (agent === test.expected) correct++;
240
+ }
241
+
242
+ return { accuracy: correct / ROUTING_TESTS.length, correct, total: ROUTING_TESTS.length, version };
243
+ }
244
+
245
+ /**
246
+ * Run multi-embedding benchmark
247
+ */
248
+ function runMultiBenchmark(modelPath, multiDescriptions, version) {
249
+ process.stdout.write(` [${version}] Computing multi-embeddings... `);
250
+
251
+ const multiAgentEmbeddings = {};
252
+ for (const [agent, phrases] of Object.entries(multiDescriptions)) {
253
+ multiAgentEmbeddings[agent] = phrases.map(p => getEmbedding(modelPath, p));
254
+ }
255
+ console.log('done');
256
+
257
+ let correct = 0;
258
+ const results = [];
259
+ for (const test of ROUTING_TESTS) {
260
+ const taskEmb = getEmbedding(modelPath, test.task);
261
+ const { agent, confidence } = routeTaskMulti(taskEmb, multiAgentEmbeddings);
262
+ const isCorrect = agent === test.expected;
263
+ if (isCorrect) correct++;
264
+ results.push({ task: test.task, expected: test.expected, got: agent, correct: isCorrect });
265
+ }
266
+
267
+ return { accuracy: correct / ROUTING_TESTS.length, correct, total: ROUTING_TESTS.length, version, results };
268
+ }
269
+
270
+ async function main() {
271
+ console.log('\n╔═══════════════════════════════════════════════════════════════════════════════════╗');
272
+ console.log('║ OPTIMIZED MODEL COMPARISON: Focused & Multi-Embedding ║');
273
+ console.log('╚═══════════════════════════════════════════════════════════════════════════════════╝\n');
274
+
275
+ if (!existsSync(RUVLTRA_MODEL)) {
276
+ console.error('RuvLTRA model not found.');
277
+ process.exit(1);
278
+ }
279
+
280
+ console.log('Strategies:');
281
+ console.log(' V1: Original keywords (baseline)');
282
+ console.log(' V4: Focused discriminating keywords');
283
+ console.log(' V5: Multi-phrase (4 phrases per agent, max similarity)\n');
284
+
285
+ // RuvLTRA tests
286
+ console.log('─────────────────────────────────────────────────────────────────');
287
+ console.log(' RUVLTRA CLAUDE CODE');
288
+ console.log('─────────────────────────────────────────────────────────────────');
289
+
290
+ const ruvV1 = runSingleBenchmark(RUVLTRA_MODEL, DESCRIPTIONS_V1, 'V1-Original');
291
+ const ruvV4 = runSingleBenchmark(RUVLTRA_MODEL, DESCRIPTIONS_V4, 'V4-Focused');
292
+ const ruvV5 = runMultiBenchmark(RUVLTRA_MODEL, MULTI_DESCRIPTIONS, 'V5-Multi');
293
+
294
+ // Qwen tests
295
+ console.log('\n─────────────────────────────────────────────────────────────────');
296
+ console.log(' QWEN 0.5B BASE');
297
+ console.log('─────────────────────────────────────────────────────────────────');
298
+
299
+ const qwenV1 = runSingleBenchmark(QWEN_MODEL, DESCRIPTIONS_V1, 'V1-Original');
300
+ const qwenV4 = runSingleBenchmark(QWEN_MODEL, DESCRIPTIONS_V4, 'V4-Focused');
301
+ const qwenV5 = runMultiBenchmark(QWEN_MODEL, MULTI_DESCRIPTIONS, 'V5-Multi');
302
+
303
+ // Results
304
+ console.log('\n═══════════════════════════════════════════════════════════════════════════════════');
305
+ console.log(' RESULTS');
306
+ console.log('═══════════════════════════════════════════════════════════════════════════════════\n');
307
+
308
+ console.log('┌─────────────────────────┬───────────────┬───────────────┬───────────────┐');
309
+ console.log('│ Strategy │ RuvLTRA │ Qwen Base │ RuvLTRA Delta │');
310
+ console.log('├─────────────────────────┼───────────────┼───────────────┼───────────────┤');
311
+
312
+ const fmt = (v) => `${(v * 100).toFixed(1)}%`.padStart(12);
313
+ const fmtDelta = (v, base) => {
314
+ const delta = (v - base) * 100;
315
+ const sign = delta >= 0 ? '+' : '';
316
+ return `${sign}${delta.toFixed(1)}%`.padStart(12);
317
+ };
318
+
319
+ console.log(`│ V1: Original │${fmt(ruvV1.accuracy)} │${fmt(qwenV1.accuracy)} │ baseline │`);
320
+ console.log(`│ V4: Focused │${fmt(ruvV4.accuracy)} │${fmt(qwenV4.accuracy)} │${fmtDelta(ruvV4.accuracy, ruvV1.accuracy)} │`);
321
+ console.log(`│ V5: Multi-phrase │${fmt(ruvV5.accuracy)} │${fmt(qwenV5.accuracy)} │${fmtDelta(ruvV5.accuracy, ruvV1.accuracy)} │`);
322
+ console.log('└─────────────────────────┴───────────────┴───────────────┴───────────────┘');
323
+
324
+ // Best result
325
+ const allResults = [
326
+ { model: 'RuvLTRA', ...ruvV1 },
327
+ { model: 'RuvLTRA', ...ruvV4 },
328
+ { model: 'RuvLTRA', ...ruvV5 },
329
+ { model: 'Qwen', ...qwenV1 },
330
+ { model: 'Qwen', ...qwenV4 },
331
+ { model: 'Qwen', ...qwenV5 },
332
+ ];
333
+
334
+ const best = allResults.reduce((a, b) => a.accuracy > b.accuracy ? a : b);
335
+
336
+ console.log(`\n BEST: ${best.model} + ${best.version} = ${(best.accuracy * 100).toFixed(1)}%`);
337
+
338
+ // Show V5 detailed results
339
+ console.log('\n─────────────────────────────────────────────────────────────────');
340
+ console.log(' V5 MULTI-PHRASE DETAILED (RuvLTRA)');
341
+ console.log('─────────────────────────────────────────────────────────────────');
342
+
343
+ for (const r of ruvV5.results) {
344
+ const mark = r.correct ? '✓' : '✗';
345
+ const task = r.task.slice(0, 50).padEnd(50);
346
+ const exp = r.expected.padEnd(18);
347
+ const got = r.got.padEnd(18);
348
+ console.log(` ${mark} ${task} ${exp} ${r.correct ? '' : '→ ' + got}`);
349
+ }
350
+
351
+ // Final comparison
352
+ const ruvBest = [ruvV1, ruvV4, ruvV5].reduce((a, b) => a.accuracy > b.accuracy ? a : b);
353
+ const qwenBest = [qwenV1, qwenV4, qwenV5].reduce((a, b) => a.accuracy > b.accuracy ? a : b);
354
+
355
+ console.log('\n═══════════════════════════════════════════════════════════════════════════════════');
356
+ console.log(' FINAL WINNER');
357
+ console.log('═══════════════════════════════════════════════════════════════════════════════════');
358
+ console.log(`\n RuvLTRA best: ${ruvBest.version} = ${(ruvBest.accuracy * 100).toFixed(1)}%`);
359
+ console.log(` Qwen best: ${qwenBest.version} = ${(qwenBest.accuracy * 100).toFixed(1)}%`);
360
+ console.log(`\n Margin: RuvLTRA leads by ${((ruvBest.accuracy - qwenBest.accuracy) * 100).toFixed(1)} points`);
361
+ console.log('\n');
362
+ }
363
+
364
+ main().catch(console.error);