@soulcraft/brainy 1.5.0 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (141) hide show
  1. package/CHANGELOG.md +188 -0
  2. package/LICENSE +2 -2
  3. package/README.md +201 -596
  4. package/bin/brainy-interactive.js +564 -0
  5. package/bin/brainy-ts.js +18 -0
  6. package/bin/brainy.js +672 -81
  7. package/dist/augmentationPipeline.d.ts +48 -220
  8. package/dist/augmentationPipeline.js +60 -508
  9. package/dist/augmentationRegistry.d.ts +22 -31
  10. package/dist/augmentationRegistry.js +28 -79
  11. package/dist/augmentations/apiServerAugmentation.d.ts +108 -0
  12. package/dist/augmentations/apiServerAugmentation.js +502 -0
  13. package/dist/augmentations/batchProcessingAugmentation.d.ts +95 -0
  14. package/dist/augmentations/batchProcessingAugmentation.js +567 -0
  15. package/dist/augmentations/brainyAugmentation.d.ts +153 -0
  16. package/dist/augmentations/brainyAugmentation.js +145 -0
  17. package/dist/augmentations/cacheAugmentation.d.ts +105 -0
  18. package/dist/augmentations/cacheAugmentation.js +238 -0
  19. package/dist/augmentations/conduitAugmentations.d.ts +54 -156
  20. package/dist/augmentations/conduitAugmentations.js +156 -1082
  21. package/dist/augmentations/connectionPoolAugmentation.d.ts +62 -0
  22. package/dist/augmentations/connectionPoolAugmentation.js +316 -0
  23. package/dist/augmentations/defaultAugmentations.d.ts +53 -0
  24. package/dist/augmentations/defaultAugmentations.js +88 -0
  25. package/dist/augmentations/entityRegistryAugmentation.d.ts +126 -0
  26. package/dist/augmentations/entityRegistryAugmentation.js +386 -0
  27. package/dist/augmentations/indexAugmentation.d.ts +117 -0
  28. package/dist/augmentations/indexAugmentation.js +284 -0
  29. package/dist/augmentations/intelligentVerbScoringAugmentation.d.ts +152 -0
  30. package/dist/augmentations/intelligentVerbScoringAugmentation.js +554 -0
  31. package/dist/augmentations/metricsAugmentation.d.ts +202 -0
  32. package/dist/augmentations/metricsAugmentation.js +291 -0
  33. package/dist/augmentations/monitoringAugmentation.d.ts +94 -0
  34. package/dist/augmentations/monitoringAugmentation.js +227 -0
  35. package/dist/augmentations/neuralImport.d.ts +50 -117
  36. package/dist/augmentations/neuralImport.js +255 -629
  37. package/dist/augmentations/requestDeduplicatorAugmentation.d.ts +52 -0
  38. package/dist/augmentations/requestDeduplicatorAugmentation.js +162 -0
  39. package/dist/augmentations/serverSearchAugmentations.d.ts +43 -22
  40. package/dist/augmentations/serverSearchAugmentations.js +125 -72
  41. package/dist/augmentations/storageAugmentation.d.ts +54 -0
  42. package/dist/augmentations/storageAugmentation.js +93 -0
  43. package/dist/augmentations/storageAugmentations.d.ts +96 -0
  44. package/dist/augmentations/storageAugmentations.js +182 -0
  45. package/dist/augmentations/synapseAugmentation.d.ts +156 -0
  46. package/dist/augmentations/synapseAugmentation.js +312 -0
  47. package/dist/augmentations/walAugmentation.d.ts +108 -0
  48. package/dist/augmentations/walAugmentation.js +515 -0
  49. package/dist/brainyData.d.ts +404 -130
  50. package/dist/brainyData.js +1331 -853
  51. package/dist/chat/BrainyChat.d.ts +16 -8
  52. package/dist/chat/BrainyChat.js +60 -32
  53. package/dist/chat/ChatCLI.d.ts +1 -1
  54. package/dist/chat/ChatCLI.js +6 -6
  55. package/dist/cli/catalog.d.ts +3 -3
  56. package/dist/cli/catalog.js +116 -70
  57. package/dist/cli/commands/core.d.ts +61 -0
  58. package/dist/cli/commands/core.js +348 -0
  59. package/dist/cli/commands/neural.d.ts +25 -0
  60. package/dist/cli/commands/neural.js +508 -0
  61. package/dist/cli/commands/utility.d.ts +37 -0
  62. package/dist/cli/commands/utility.js +276 -0
  63. package/dist/cli/index.d.ts +7 -0
  64. package/dist/cli/index.js +167 -0
  65. package/dist/cli/interactive.d.ts +164 -0
  66. package/dist/cli/interactive.js +542 -0
  67. package/dist/cortex/neuralImport.js +5 -5
  68. package/dist/critical/model-guardian.js +11 -4
  69. package/dist/embeddings/lightweight-embedder.d.ts +23 -0
  70. package/dist/embeddings/lightweight-embedder.js +136 -0
  71. package/dist/embeddings/universal-memory-manager.d.ts +38 -0
  72. package/dist/embeddings/universal-memory-manager.js +206 -0
  73. package/dist/embeddings/worker-embedding.d.ts +7 -0
  74. package/dist/embeddings/worker-embedding.js +77 -0
  75. package/dist/embeddings/worker-manager.d.ts +28 -0
  76. package/dist/embeddings/worker-manager.js +162 -0
  77. package/dist/examples/basicUsage.js +7 -7
  78. package/dist/graph/pathfinding.d.ts +78 -0
  79. package/dist/graph/pathfinding.js +393 -0
  80. package/dist/hnsw/hnswIndex.d.ts +13 -0
  81. package/dist/hnsw/hnswIndex.js +35 -0
  82. package/dist/hnsw/hnswIndexOptimized.d.ts +1 -0
  83. package/dist/hnsw/hnswIndexOptimized.js +3 -0
  84. package/dist/index.d.ts +9 -11
  85. package/dist/index.js +21 -11
  86. package/dist/indices/fieldIndex.d.ts +76 -0
  87. package/dist/indices/fieldIndex.js +357 -0
  88. package/dist/mcp/brainyMCPAdapter.js +3 -2
  89. package/dist/mcp/mcpAugmentationToolset.js +11 -17
  90. package/dist/neural/embeddedPatterns.d.ts +41 -0
  91. package/dist/neural/embeddedPatterns.js +4044 -0
  92. package/dist/neural/naturalLanguageProcessor.d.ts +94 -0
  93. package/dist/neural/naturalLanguageProcessor.js +317 -0
  94. package/dist/neural/naturalLanguageProcessorStatic.d.ts +64 -0
  95. package/dist/neural/naturalLanguageProcessorStatic.js +151 -0
  96. package/dist/neural/neuralAPI.d.ts +255 -0
  97. package/dist/neural/neuralAPI.js +612 -0
  98. package/dist/neural/patternLibrary.d.ts +101 -0
  99. package/dist/neural/patternLibrary.js +313 -0
  100. package/dist/neural/patterns.d.ts +27 -0
  101. package/dist/neural/patterns.js +68 -0
  102. package/dist/neural/staticPatternMatcher.d.ts +35 -0
  103. package/dist/neural/staticPatternMatcher.js +153 -0
  104. package/dist/scripts/precomputePatternEmbeddings.d.ts +19 -0
  105. package/dist/scripts/precomputePatternEmbeddings.js +100 -0
  106. package/dist/storage/adapters/fileSystemStorage.d.ts +5 -0
  107. package/dist/storage/adapters/fileSystemStorage.js +20 -0
  108. package/dist/storage/adapters/s3CompatibleStorage.d.ts +5 -0
  109. package/dist/storage/adapters/s3CompatibleStorage.js +16 -0
  110. package/dist/storage/enhancedClearOperations.d.ts +83 -0
  111. package/dist/storage/enhancedClearOperations.js +345 -0
  112. package/dist/storage/storageFactory.js +31 -27
  113. package/dist/triple/TripleIntelligence.d.ts +134 -0
  114. package/dist/triple/TripleIntelligence.js +548 -0
  115. package/dist/types/augmentations.d.ts +45 -344
  116. package/dist/types/augmentations.js +5 -2
  117. package/dist/types/brainyDataInterface.d.ts +20 -10
  118. package/dist/types/graphTypes.d.ts +46 -0
  119. package/dist/types/graphTypes.js +16 -2
  120. package/dist/utils/BoundedRegistry.d.ts +29 -0
  121. package/dist/utils/BoundedRegistry.js +54 -0
  122. package/dist/utils/embedding.js +20 -3
  123. package/dist/utils/hybridModelManager.js +10 -5
  124. package/dist/utils/metadataFilter.d.ts +33 -19
  125. package/dist/utils/metadataFilter.js +58 -23
  126. package/dist/utils/metadataIndex.d.ts +37 -6
  127. package/dist/utils/metadataIndex.js +427 -64
  128. package/dist/utils/requestDeduplicator.d.ts +10 -0
  129. package/dist/utils/requestDeduplicator.js +24 -0
  130. package/dist/utils/unifiedCache.d.ts +103 -0
  131. package/dist/utils/unifiedCache.js +311 -0
  132. package/package.json +43 -128
  133. package/scripts/ensure-models.js +108 -0
  134. package/scripts/prepare-models.js +387 -0
  135. package/OFFLINE_MODELS.md +0 -56
  136. package/dist/intelligence/neuralEngine.d.ts +0 -207
  137. package/dist/intelligence/neuralEngine.js +0 -706
  138. package/dist/utils/modelLoader.d.ts +0 -32
  139. package/dist/utils/modelLoader.js +0 -219
  140. package/dist/utils/modelManager.d.ts +0 -77
  141. package/dist/utils/modelManager.js +0 -219
@@ -0,0 +1,508 @@
1
+ /**
2
+ * 🧠 Neural Similarity API Commands
3
+ *
4
+ * CLI interface for semantic similarity, clustering, and neural operations
5
+ */
6
+ import inquirer from 'inquirer';
7
+ import chalk from 'chalk';
8
+ import ora from 'ora';
9
+ import fs from 'fs';
10
+ import path from 'path';
11
+ import { BrainyData } from '../../brainyData.js';
12
+ import { NeuralAPI } from '../../neural/neuralAPI.js';
13
+ export const neuralCommand = {
14
+ command: 'neural [action]',
15
+ describe: '🧠 Neural similarity and clustering operations',
16
+ builder: (yargs) => {
17
+ return yargs
18
+ .positional('action', {
19
+ describe: 'Neural operation to perform',
20
+ type: 'string',
21
+ choices: ['similar', 'clusters', 'hierarchy', 'neighbors', 'path', 'outliers', 'visualize']
22
+ })
23
+ .option('id', {
24
+ describe: 'Item ID for similarity operations',
25
+ type: 'string',
26
+ alias: 'i'
27
+ })
28
+ .option('query', {
29
+ describe: 'Query text for similarity search',
30
+ type: 'string',
31
+ alias: 'q'
32
+ })
33
+ .option('threshold', {
34
+ describe: 'Similarity threshold (0-1)',
35
+ type: 'number',
36
+ default: 0.7,
37
+ alias: 't'
38
+ })
39
+ .option('format', {
40
+ describe: 'Output format',
41
+ type: 'string',
42
+ choices: ['json', 'table', 'tree', 'graph'],
43
+ default: 'table',
44
+ alias: 'f'
45
+ })
46
+ .option('output', {
47
+ describe: 'Output file path',
48
+ type: 'string',
49
+ alias: 'o'
50
+ })
51
+ .option('limit', {
52
+ describe: 'Maximum number of results',
53
+ type: 'number',
54
+ default: 10,
55
+ alias: 'l'
56
+ })
57
+ .option('algorithm', {
58
+ describe: 'Clustering algorithm',
59
+ type: 'string',
60
+ choices: ['hierarchical', 'kmeans', 'dbscan', 'auto'],
61
+ default: 'auto',
62
+ alias: 'a'
63
+ })
64
+ .option('dimensions', {
65
+ describe: 'Visualization dimensions (2 or 3)',
66
+ type: 'number',
67
+ choices: [2, 3],
68
+ default: 2,
69
+ alias: 'd'
70
+ })
71
+ .option('explain', {
72
+ describe: 'Include detailed explanations',
73
+ type: 'boolean',
74
+ default: false,
75
+ alias: 'e'
76
+ });
77
+ },
78
+ handler: async (argv) => {
79
+ console.log(chalk.cyan('\n🧠 NEURAL SIMILARITY API'));
80
+ console.log(chalk.gray('━'.repeat(50)));
81
+ // Initialize Brainy and Neural API
82
+ const brain = new BrainyData();
83
+ const neural = new NeuralAPI(brain);
84
+ try {
85
+ const action = argv.action || await promptForAction();
86
+ switch (action) {
87
+ case 'similar':
88
+ await handleSimilarCommand(neural, argv);
89
+ break;
90
+ case 'clusters':
91
+ await handleClustersCommand(neural, argv);
92
+ break;
93
+ case 'hierarchy':
94
+ await handleHierarchyCommand(neural, argv);
95
+ break;
96
+ case 'neighbors':
97
+ await handleNeighborsCommand(neural, argv);
98
+ break;
99
+ case 'path':
100
+ await handlePathCommand(neural, argv);
101
+ break;
102
+ case 'outliers':
103
+ await handleOutliersCommand(neural, argv);
104
+ break;
105
+ case 'visualize':
106
+ await handleVisualizeCommand(neural, argv);
107
+ break;
108
+ default:
109
+ console.log(chalk.red(`āŒ Unknown action: ${action}`));
110
+ showHelp();
111
+ }
112
+ }
113
+ catch (error) {
114
+ console.error(chalk.red('šŸ’„ Error:'), error instanceof Error ? error.message : error);
115
+ process.exit(1);
116
+ }
117
+ }
118
+ };
119
+ async function promptForAction() {
120
+ const answer = await inquirer.prompt([{
121
+ type: 'list',
122
+ name: 'action',
123
+ message: 'Choose a neural operation:',
124
+ choices: [
125
+ { name: 'šŸ”— Calculate similarity between items', value: 'similar' },
126
+ { name: 'šŸŽÆ Find semantic clusters', value: 'clusters' },
127
+ { name: '🌳 Show item hierarchy', value: 'hierarchy' },
128
+ { name: 'šŸ•øļø Find semantic neighbors', value: 'neighbors' },
129
+ { name: 'šŸ›£ļø Find semantic path between items', value: 'path' },
130
+ { name: '🚨 Detect outliers', value: 'outliers' },
131
+ { name: 'šŸ“Š Generate visualization data', value: 'visualize' }
132
+ ]
133
+ }]);
134
+ return answer.action;
135
+ }
136
+ async function handleSimilarCommand(neural, argv) {
137
+ const spinner = ora('🧠 Calculating semantic similarity...').start();
138
+ try {
139
+ let itemA, itemB;
140
+ if (argv.id && argv.query) {
141
+ itemA = argv.id;
142
+ itemB = argv.query;
143
+ }
144
+ else if (argv._ && argv._.length >= 3) {
145
+ itemA = argv._[1];
146
+ itemB = argv._[2];
147
+ }
148
+ else {
149
+ spinner.stop();
150
+ const answers = await inquirer.prompt([
151
+ {
152
+ type: 'input',
153
+ name: 'itemA',
154
+ message: 'First item (ID or text):',
155
+ validate: (input) => input.length > 0
156
+ },
157
+ {
158
+ type: 'input',
159
+ name: 'itemB',
160
+ message: 'Second item (ID or text):',
161
+ validate: (input) => input.length > 0
162
+ }
163
+ ]);
164
+ itemA = answers.itemA;
165
+ itemB = answers.itemB;
166
+ spinner.start();
167
+ }
168
+ const result = await neural.similar(itemA, itemB, {
169
+ explain: argv.explain,
170
+ includeBreakdown: argv.explain
171
+ });
172
+ spinner.succeed('āœ… Similarity calculated');
173
+ if (typeof result === 'number') {
174
+ console.log(`\nšŸ”— Similarity: ${chalk.cyan((result * 100).toFixed(1))}%`);
175
+ }
176
+ else {
177
+ console.log(`\nšŸ”— Similarity: ${chalk.cyan((result.score * 100).toFixed(1))}%`);
178
+ if (result.explanation) {
179
+ console.log(`šŸ’­ Explanation: ${result.explanation}`);
180
+ }
181
+ if (result.breakdown) {
182
+ console.log('\nšŸ“Š Breakdown:');
183
+ console.log(` Semantic: ${chalk.yellow((result.breakdown.semantic * 100).toFixed(1))}%`);
184
+ if (result.breakdown.taxonomic !== undefined) {
185
+ console.log(` Taxonomic: ${chalk.yellow((result.breakdown.taxonomic * 100).toFixed(1))}%`);
186
+ }
187
+ if (result.breakdown.contextual !== undefined) {
188
+ console.log(` Contextual: ${chalk.yellow((result.breakdown.contextual * 100).toFixed(1))}%`);
189
+ }
190
+ }
191
+ if (result.hierarchy) {
192
+ console.log(`\n🌳 Hierarchy: ${result.hierarchy.sharedParent ?
193
+ `Shared parent at distance ${result.hierarchy.distance}` :
194
+ 'No shared parent found'}`);
195
+ }
196
+ }
197
+ if (argv.output) {
198
+ await saveToFile(argv.output, result, argv.format);
199
+ }
200
+ }
201
+ catch (error) {
202
+ spinner.fail('šŸ’„ Failed to calculate similarity');
203
+ throw error;
204
+ }
205
+ }
206
+ async function handleClustersCommand(neural, argv) {
207
+ const spinner = ora('šŸŽÆ Finding semantic clusters...').start();
208
+ try {
209
+ const options = {
210
+ algorithm: argv.algorithm,
211
+ threshold: argv.threshold,
212
+ maxClusters: argv.limit
213
+ };
214
+ const clusters = await neural.clusters(argv.query || options);
215
+ spinner.succeed(`āœ… Found ${clusters.length} clusters`);
216
+ if (argv.format === 'json') {
217
+ console.log(JSON.stringify(clusters, null, 2));
218
+ }
219
+ else {
220
+ console.log(`\nšŸŽÆ ${chalk.cyan(clusters.length)} Semantic Clusters:\n`);
221
+ clusters.forEach((cluster, index) => {
222
+ console.log(`${chalk.yellow(`Cluster ${index + 1}:`)} ${cluster.label || cluster.id}`);
223
+ console.log(` šŸ“Š Confidence: ${chalk.green((cluster.confidence * 100).toFixed(1))}%`);
224
+ console.log(` šŸ‘„ Members: ${cluster.members.length}`);
225
+ if (cluster.members.length <= 5) {
226
+ cluster.members.forEach(member => {
227
+ console.log(` • ${member}`);
228
+ });
229
+ }
230
+ else {
231
+ cluster.members.slice(0, 3).forEach(member => {
232
+ console.log(` • ${member}`);
233
+ });
234
+ console.log(` ... and ${cluster.members.length - 3} more`);
235
+ }
236
+ console.log();
237
+ });
238
+ }
239
+ if (argv.output) {
240
+ await saveToFile(argv.output, clusters, argv.format);
241
+ }
242
+ }
243
+ catch (error) {
244
+ spinner.fail('šŸ’„ Failed to find clusters');
245
+ throw error;
246
+ }
247
+ }
248
+ async function handleHierarchyCommand(neural, argv) {
249
+ const spinner = ora('🌳 Building semantic hierarchy...').start();
250
+ try {
251
+ const id = argv.id || argv._[1];
252
+ if (!id) {
253
+ spinner.stop();
254
+ const answer = await inquirer.prompt([{
255
+ type: 'input',
256
+ name: 'id',
257
+ message: 'Enter item ID:',
258
+ validate: (input) => input.length > 0
259
+ }]);
260
+ spinner.start();
261
+ const hierarchy = await neural.hierarchy(answer.id);
262
+ displayHierarchy(hierarchy);
263
+ }
264
+ else {
265
+ const hierarchy = await neural.hierarchy(id);
266
+ spinner.succeed('āœ… Hierarchy built');
267
+ displayHierarchy(hierarchy);
268
+ }
269
+ if (argv.output) {
270
+ const hierarchy = await neural.hierarchy(id || argv._[1]);
271
+ await saveToFile(argv.output, hierarchy, argv.format);
272
+ }
273
+ }
274
+ catch (error) {
275
+ spinner.fail('šŸ’„ Failed to build hierarchy');
276
+ throw error;
277
+ }
278
+ }
279
+ function displayHierarchy(hierarchy) {
280
+ console.log(`\n🌳 Semantic Hierarchy for ${chalk.cyan(hierarchy.self.id)}:`);
281
+ if (hierarchy.root) {
282
+ console.log(`šŸ” Root: ${hierarchy.root.id} (${(hierarchy.root.similarity * 100).toFixed(1)}%)`);
283
+ }
284
+ if (hierarchy.grandparent) {
285
+ console.log(`šŸ‘“ Grandparent: ${hierarchy.grandparent.id} (${(hierarchy.grandparent.similarity * 100).toFixed(1)}%)`);
286
+ }
287
+ if (hierarchy.parent) {
288
+ console.log(`šŸ‘Ø Parent: ${hierarchy.parent.id} (${(hierarchy.parent.similarity * 100).toFixed(1)}%)`);
289
+ }
290
+ console.log(`šŸŽÆ ${chalk.bold('Self:')} ${hierarchy.self.id}`);
291
+ if (hierarchy.siblings && hierarchy.siblings.length > 0) {
292
+ console.log(`šŸ‘„ Siblings: ${hierarchy.siblings.length}`);
293
+ hierarchy.siblings.forEach((sibling) => {
294
+ console.log(` • ${sibling.id} (${(sibling.similarity * 100).toFixed(1)}%)`);
295
+ });
296
+ }
297
+ if (hierarchy.children && hierarchy.children.length > 0) {
298
+ console.log(`šŸ‘¶ Children: ${hierarchy.children.length}`);
299
+ hierarchy.children.forEach((child) => {
300
+ console.log(` • ${child.id} (${(child.similarity * 100).toFixed(1)}%)`);
301
+ });
302
+ }
303
+ }
304
+ async function handleNeighborsCommand(neural, argv) {
305
+ const spinner = ora('šŸ•øļø Finding semantic neighbors...').start();
306
+ try {
307
+ const id = argv.id || argv._[1];
308
+ if (!id) {
309
+ spinner.stop();
310
+ const answer = await inquirer.prompt([{
311
+ type: 'input',
312
+ name: 'id',
313
+ message: 'Enter item ID:',
314
+ validate: (input) => input.length > 0
315
+ }]);
316
+ spinner.start();
317
+ }
318
+ const targetId = id || (await inquirer.prompt([{
319
+ type: 'input',
320
+ name: 'id',
321
+ message: 'Enter item ID:',
322
+ validate: (input) => input.length > 0
323
+ }])).id;
324
+ const graph = await neural.neighbors(targetId, {
325
+ limit: argv.limit,
326
+ includeEdges: true
327
+ });
328
+ spinner.succeed(`āœ… Found ${graph.neighbors.length} neighbors`);
329
+ console.log(`\nšŸ•øļø Neighbors of ${chalk.cyan(graph.center)}:`);
330
+ graph.neighbors.forEach((neighbor, index) => {
331
+ console.log(`${index + 1}. ${neighbor.id} (${(neighbor.similarity * 100).toFixed(1)}%)`);
332
+ if (neighbor.type) {
333
+ console.log(` Type: ${neighbor.type}`);
334
+ }
335
+ if (neighbor.connections) {
336
+ console.log(` Connections: ${neighbor.connections}`);
337
+ }
338
+ });
339
+ if (graph.edges && graph.edges.length > 0) {
340
+ console.log(`\nšŸ”— ${graph.edges.length} semantic connections found`);
341
+ }
342
+ if (argv.output) {
343
+ await saveToFile(argv.output, graph, argv.format);
344
+ }
345
+ }
346
+ catch (error) {
347
+ spinner.fail('šŸ’„ Failed to find neighbors');
348
+ throw error;
349
+ }
350
+ }
351
+ async function handlePathCommand(neural, argv) {
352
+ const spinner = ora('šŸ›£ļø Finding semantic path...').start();
353
+ try {
354
+ let fromId, toId;
355
+ if (argv._ && argv._.length >= 3) {
356
+ fromId = argv._[1];
357
+ toId = argv._[2];
358
+ }
359
+ else {
360
+ spinner.stop();
361
+ const answers = await inquirer.prompt([
362
+ {
363
+ type: 'input',
364
+ name: 'from',
365
+ message: 'From item ID:',
366
+ validate: (input) => input.length > 0
367
+ },
368
+ {
369
+ type: 'input',
370
+ name: 'to',
371
+ message: 'To item ID:',
372
+ validate: (input) => input.length > 0
373
+ }
374
+ ]);
375
+ fromId = answers.from;
376
+ toId = answers.to;
377
+ spinner.start();
378
+ }
379
+ const path = await neural.semanticPath(fromId, toId);
380
+ if (path.length === 0) {
381
+ spinner.warn('🚫 No semantic path found');
382
+ console.log(`No path found between ${chalk.cyan(fromId)} and ${chalk.cyan(toId)}`);
383
+ }
384
+ else {
385
+ spinner.succeed(`āœ… Found path with ${path.length} hops`);
386
+ console.log(`\nšŸ›£ļø Semantic Path from ${chalk.cyan(fromId)} to ${chalk.cyan(toId)}:`);
387
+ console.log(`${chalk.cyan(fromId)} (start)`);
388
+ path.forEach((hop, index) => {
389
+ console.log(`${' '.repeat(index + 1)}↓ ${(hop.similarity * 100).toFixed(1)}%`);
390
+ console.log(`${' '.repeat(index + 1)}${hop.id} (hop ${hop.hop})`);
391
+ });
392
+ }
393
+ if (argv.output) {
394
+ await saveToFile(argv.output, path, argv.format);
395
+ }
396
+ }
397
+ catch (error) {
398
+ spinner.fail('šŸ’„ Failed to find path');
399
+ throw error;
400
+ }
401
+ }
402
+ async function handleOutliersCommand(neural, argv) {
403
+ const spinner = ora('🚨 Detecting semantic outliers...').start();
404
+ try {
405
+ const outliers = await neural.outliers(argv.threshold);
406
+ spinner.succeed(`āœ… Found ${outliers.length} outliers`);
407
+ if (outliers.length === 0) {
408
+ console.log('\nšŸŽ‰ No outliers detected - all items are well connected!');
409
+ }
410
+ else {
411
+ console.log(`\n🚨 ${chalk.red(outliers.length)} Semantic Outliers:`);
412
+ outliers.forEach((outlier, index) => {
413
+ console.log(`${index + 1}. ${outlier}`);
414
+ });
415
+ console.log(`\nšŸ’” These items have similarity < ${argv.threshold} to their nearest neighbors`);
416
+ }
417
+ if (argv.output) {
418
+ await saveToFile(argv.output, outliers, argv.format);
419
+ }
420
+ }
421
+ catch (error) {
422
+ spinner.fail('šŸ’„ Failed to detect outliers');
423
+ throw error;
424
+ }
425
+ }
426
+ async function handleVisualizeCommand(neural, argv) {
427
+ const spinner = ora('šŸ“Š Generating visualization data...').start();
428
+ try {
429
+ const vizData = await neural.visualize({
430
+ dimensions: argv.dimensions,
431
+ maxNodes: argv.limit
432
+ });
433
+ spinner.succeed('āœ… Visualization data generated');
434
+ console.log(`\nšŸ“Š Visualization Data (${vizData.format} layout):`);
435
+ console.log(`šŸ“ Nodes: ${vizData.nodes.length}`);
436
+ console.log(`šŸ”— Edges: ${vizData.edges.length}`);
437
+ console.log(`šŸŽÆ Clusters: ${vizData.clusters?.length || 0}`);
438
+ console.log(`šŸ“ Dimensions: ${vizData.layout?.dimensions}D`);
439
+ if (argv.format === 'json') {
440
+ console.log('\nData:');
441
+ console.log(JSON.stringify(vizData, null, 2));
442
+ }
443
+ else {
444
+ console.log('\nšŸŽØ Style Settings:');
445
+ console.log(` Node Colors: ${vizData.style?.nodeColors}`);
446
+ console.log(` Edge Width: ${vizData.style?.edgeWidth}`);
447
+ console.log(` Labels: ${vizData.style?.labels}`);
448
+ }
449
+ if (argv.output) {
450
+ await saveToFile(argv.output, vizData, 'json');
451
+ console.log(`\nšŸ’¾ Visualization data saved to: ${chalk.green(argv.output)}`);
452
+ }
453
+ else {
454
+ console.log(`\nšŸ’” Use --output to save visualization data for external tools`);
455
+ }
456
+ }
457
+ catch (error) {
458
+ spinner.fail('šŸ’„ Failed to generate visualization');
459
+ throw error;
460
+ }
461
+ }
462
+ async function saveToFile(filepath, data, format) {
463
+ const dir = path.dirname(filepath);
464
+ if (!fs.existsSync(dir)) {
465
+ fs.mkdirSync(dir, { recursive: true });
466
+ }
467
+ let output;
468
+ switch (format) {
469
+ case 'json':
470
+ output = JSON.stringify(data, null, 2);
471
+ break;
472
+ case 'table':
473
+ output = formatAsTable(data);
474
+ break;
475
+ default:
476
+ output = JSON.stringify(data, null, 2);
477
+ }
478
+ fs.writeFileSync(filepath, output, 'utf8');
479
+ console.log(`šŸ’¾ Saved to: ${chalk.green(filepath)}`);
480
+ }
481
+ function formatAsTable(data) {
482
+ // Simple table formatting - could be enhanced with a table library
483
+ if (Array.isArray(data)) {
484
+ return data.map((item, index) => `${index + 1}. ${JSON.stringify(item)}`).join('\n');
485
+ }
486
+ return JSON.stringify(data, null, 2);
487
+ }
488
+ function showHelp() {
489
+ console.log('\n🧠 Neural Similarity API Commands:');
490
+ console.log('');
491
+ console.log(' brainy neural similar <item1> <item2> Calculate similarity');
492
+ console.log(' brainy neural clusters Find semantic clusters');
493
+ console.log(' brainy neural hierarchy <id> Show item hierarchy');
494
+ console.log(' brainy neural neighbors <id> Find semantic neighbors');
495
+ console.log(' brainy neural path <from> <to> Find semantic path');
496
+ console.log(' brainy neural outliers Detect outliers');
497
+ console.log(' brainy neural visualize Generate visualization data');
498
+ console.log('');
499
+ console.log('Options:');
500
+ console.log(' --threshold, -t Similarity threshold (0-1)');
501
+ console.log(' --format, -f Output format (json|table|tree|graph)');
502
+ console.log(' --output, -o Save to file');
503
+ console.log(' --limit, -l Maximum results');
504
+ console.log(' --explain, -e Include explanations');
505
+ console.log('');
506
+ }
507
+ export default neuralCommand;
508
+ //# sourceMappingURL=neural.js.map
@@ -0,0 +1,37 @@
1
+ /**
2
+ * Utility CLI Commands - TypeScript Implementation
3
+ *
4
+ * Database maintenance, statistics, and benchmarking
5
+ */
6
+ interface UtilityOptions {
7
+ verbose?: boolean;
8
+ json?: boolean;
9
+ pretty?: boolean;
10
+ }
11
+ interface StatsOptions extends UtilityOptions {
12
+ byService?: boolean;
13
+ detailed?: boolean;
14
+ }
15
+ interface CleanOptions extends UtilityOptions {
16
+ removeOrphans?: boolean;
17
+ rebuildIndex?: boolean;
18
+ }
19
+ interface BenchmarkOptions extends UtilityOptions {
20
+ operations?: string;
21
+ iterations?: string;
22
+ }
23
+ export declare const utilityCommands: {
24
+ /**
25
+ * Show database statistics
26
+ */
27
+ stats(options: StatsOptions): Promise<void>;
28
+ /**
29
+ * Clean and optimize database
30
+ */
31
+ clean(options: CleanOptions): Promise<void>;
32
+ /**
33
+ * Run performance benchmarks
34
+ */
35
+ benchmark(options: BenchmarkOptions): Promise<void>;
36
+ };
37
+ export {};