agentdb 2.0.0-alpha.1 → 2.0.0-alpha.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (208) hide show
  1. package/dist/agentdb.min.js +4 -4
  2. package/dist/simulation/cli.js +0 -0
  3. package/dist/src/cli/lib/config-manager.d.ts.map +1 -1
  4. package/dist/src/cli/lib/config-manager.js.map +1 -1
  5. package/dist/src/cli/lib/history-tracker.d.ts.map +1 -1
  6. package/dist/src/cli/lib/history-tracker.js +7 -1
  7. package/dist/src/cli/lib/history-tracker.js.map +1 -1
  8. package/examples/README.md +105 -0
  9. package/examples/quickstart.js +43 -0
  10. package/package.json +6 -2
  11. package/simulation/.claude-flow/metrics/agent-metrics.json +1 -0
  12. package/simulation/.claude-flow/metrics/performance.json +87 -0
  13. package/simulation/.claude-flow/metrics/task-metrics.json +10 -0
  14. package/simulation/COMPLETION-STATUS.md +139 -0
  15. package/simulation/FINAL-RESULTS.md +414 -0
  16. package/simulation/FINAL-STATUS.md +281 -0
  17. package/simulation/INTEGRATION-COMPLETE.md +452 -0
  18. package/simulation/MIGRATION-STATUS.md +231 -0
  19. package/simulation/OPTIMIZATION-RESULTS.md +397 -0
  20. package/simulation/PHASE1-COMPLETE.md +163 -0
  21. package/simulation/README.md +848 -0
  22. package/simulation/SIMULATION-RESULTS.md +239 -0
  23. package/simulation/cli.ts +78 -0
  24. package/simulation/configs/default.json +37 -0
  25. package/simulation/data/advanced/aidefence.graph +0 -0
  26. package/simulation/data/advanced/bmssp.graph +0 -0
  27. package/simulation/data/advanced/consciousness.graph +0 -0
  28. package/simulation/data/advanced/goalie.graph +0 -0
  29. package/simulation/data/advanced/psycho-symbolic.graph +0 -0
  30. package/simulation/data/advanced/research-swarm.graph +0 -0
  31. package/simulation/data/advanced/sublinear.graph +0 -0
  32. package/simulation/data/advanced/temporal.graph +0 -0
  33. package/simulation/data/causal.graph +0 -0
  34. package/simulation/data/graph-traversal.graph +0 -0
  35. package/simulation/data/lean-agentic.graph +0 -0
  36. package/simulation/data/reflexion.graph +0 -0
  37. package/simulation/data/skills.graph +0 -0
  38. package/simulation/data/stock-market.graph +0 -0
  39. package/simulation/data/strange-loops.graph +0 -0
  40. package/simulation/data/swarm.graph +0 -0
  41. package/simulation/data/voting-consensus.graph +0 -0
  42. package/simulation/docs/CLI-INTEGRATION-PLAN.md +1038 -0
  43. package/simulation/docs/COMPREHENSIVE-LATENT-SPACE-COMPLETION.md +354 -0
  44. package/simulation/docs/DOCUMENTATION-INDEX.md +226 -0
  45. package/simulation/docs/IMPLEMENTATION-COMPLETE.md +521 -0
  46. package/simulation/docs/OPTIMIZATION-SUMMARY.md +279 -0
  47. package/simulation/docs/README.md +229 -0
  48. package/simulation/docs/SWARM-5-INTEGRATION-SUMMARY.md +528 -0
  49. package/simulation/docs/TESTING-SUMMARY.md +304 -0
  50. package/simulation/docs/architecture/EXTENSION-API.md +868 -0
  51. package/simulation/docs/architecture/INTEGRATION-ARCHITECTURE.md +1138 -0
  52. package/simulation/docs/architecture/OPTIMIZATION-STRATEGY.md +778 -0
  53. package/simulation/docs/architecture/SIMULATION-ARCHITECTURE.md +892 -0
  54. package/simulation/docs/guides/CLI-REFERENCE.md +896 -0
  55. package/simulation/docs/guides/CUSTOM-SIMULATIONS.md +931 -0
  56. package/simulation/docs/guides/DEPLOYMENT.md +832 -0
  57. package/simulation/docs/guides/IMPLEMENTATION-SUMMARY.md +544 -0
  58. package/simulation/docs/guides/MIGRATION-GUIDE.md +591 -0
  59. package/simulation/docs/guides/QUICK-START.md +361 -0
  60. package/simulation/docs/guides/README.md +736 -0
  61. package/simulation/docs/guides/TROUBLESHOOTING.md +817 -0
  62. package/simulation/docs/guides/WIZARD-GUIDE.md +869 -0
  63. package/simulation/docs/reports/latent-space/MASTER-SYNTHESIS.md +345 -0
  64. package/simulation/docs/reports/latent-space/README.md +132 -0
  65. package/simulation/docs/reports/latent-space/attention-analysis-RESULTS.md +238 -0
  66. package/simulation/docs/reports/latent-space/clustering-analysis-RESULTS.md +210 -0
  67. package/simulation/docs/reports/latent-space/hnsw-exploration-RESULTS.md +332 -0
  68. package/simulation/docs/reports/latent-space/hypergraph-exploration-RESULTS.md +37 -0
  69. package/simulation/docs/reports/latent-space/neural-augmentation-RESULTS.md +69 -0
  70. package/simulation/docs/reports/latent-space/quantum-hybrid-RESULTS.md +91 -0
  71. package/simulation/docs/reports/latent-space/self-organizing-hnsw-RESULTS.md +51 -0
  72. package/simulation/docs/reports/latent-space/traversal-optimization-RESULTS.md +238 -0
  73. package/simulation/reports/README.md +397 -0
  74. package/simulation/reports/advanced-simulations-performance.md +1241 -0
  75. package/simulation/reports/aidefence-integration-2025-11-30T01-36-53-486Z.json +30 -0
  76. package/simulation/reports/architecture-analysis.md +1396 -0
  77. package/simulation/reports/basic-scenarios-performance.md +1840 -0
  78. package/simulation/reports/bmssp-integration-2025-11-30T01-36-27-193Z.json +30 -0
  79. package/simulation/reports/bmssp-integration-2025-11-30T03-38-12-887Z.json +30 -0
  80. package/simulation/reports/causal-reasoning-2025-11-29T23-35-21-795Z.json +36 -0
  81. package/simulation/reports/causal-reasoning-2025-11-30T00-58-42-862Z.json +30 -0
  82. package/simulation/reports/causal-reasoning-2025-11-30T00-59-12-546Z.json +40 -0
  83. package/simulation/reports/consciousness-explorer-2025-11-30T01-36-51-269Z.json +31 -0
  84. package/simulation/reports/core-benchmarks.md +727 -0
  85. package/simulation/reports/goalie-integration-2025-11-30T01-36-52-377Z.json +30 -0
  86. package/simulation/reports/graph-traversal-2025-11-29T23-35-35-279Z.json +78 -0
  87. package/simulation/reports/graph-traversal-2025-11-29T23-37-36-697Z.json +30 -0
  88. package/simulation/reports/graph-traversal-2025-11-30T01-03-59-716Z.json +30 -0
  89. package/simulation/reports/graph-traversal-2025-11-30T01-05-10-984Z.json +30 -0
  90. package/simulation/reports/graph-traversal-2025-11-30T01-06-16-334Z.json +30 -0
  91. package/simulation/reports/graph-traversal-2025-11-30T01-06-53-312Z.json +30 -0
  92. package/simulation/reports/graph-traversal-2025-11-30T01-07-51-075Z.json +24 -0
  93. package/simulation/reports/graph-traversal-2025-11-30T01-08-22-179Z.json +42 -0
  94. package/simulation/reports/lean-agentic-swarm-2025-11-29T23-37-23-804Z.json +148 -0
  95. package/simulation/reports/lean-agentic-swarm-2025-11-30T01-31-24-401Z.json +31 -0
  96. package/simulation/reports/lean-agentic-swarm-2025-11-30T03-38-01-470Z.json +31 -0
  97. package/simulation/reports/multi-agent-swarm-2025-11-29T23-35-28-093Z.json +78 -0
  98. package/simulation/reports/multi-agent-swarm-2025-11-30T01-03-54-062Z.json +42 -0
  99. package/simulation/reports/multi-agent-swarm-2025-11-30T01-05-06-092Z.json +42 -0
  100. package/simulation/reports/psycho-symbolic-reasoner-2025-11-30T01-36-50-180Z.json +30 -0
  101. package/simulation/reports/quality-metrics.md +727 -0
  102. package/simulation/reports/reflexion-learning-2025-11-29T23-35-09-774Z.json +48 -0
  103. package/simulation/reports/reflexion-learning-2025-11-29T23-37-16-934Z.json +36 -0
  104. package/simulation/reports/reflexion-learning-2025-11-30T00-07-49-259Z.json +30 -0
  105. package/simulation/reports/reflexion-learning-2025-11-30T00-09-29-319Z.json +51 -0
  106. package/simulation/reports/reflexion-learning-2025-11-30T00-28-37-659Z.json +51 -0
  107. package/simulation/reports/reflexion-learning-2025-11-30T01-31-30-690Z.json +29 -0
  108. package/simulation/reports/reflexion-learning-2025-11-30T03-38-06-937Z.json +29 -0
  109. package/simulation/reports/research-foundations.md +2004 -0
  110. package/simulation/reports/research-swarm-2025-11-30T01-36-54-647Z.json +30 -0
  111. package/simulation/reports/scalability-deployment.md +2404 -0
  112. package/simulation/reports/skill-evolution-2025-11-29T23-35-15-945Z.json +36 -0
  113. package/simulation/reports/skill-evolution-2025-11-30T01-03-17-995Z.json +30 -0
  114. package/simulation/reports/skill-evolution-2025-11-30T01-03-48-441Z.json +30 -0
  115. package/simulation/reports/skill-evolution-2025-11-30T01-05-00-554Z.json +30 -0
  116. package/simulation/reports/skill-evolution-2025-11-30T01-06-11-436Z.json +30 -0
  117. package/simulation/reports/skill-evolution-2025-11-30T01-06-51-979Z.json +30 -0
  118. package/simulation/reports/skill-evolution-2025-11-30T01-07-32-695Z.json +40 -0
  119. package/simulation/reports/stock-market-emergence-2025-11-30T00-11-43-865Z.json +56 -0
  120. package/simulation/reports/stock-market-emergence-2025-11-30T00-28-57-495Z.json +56 -0
  121. package/simulation/reports/strange-loops-2025-11-29T23-37-30-621Z.json +78 -0
  122. package/simulation/reports/strange-loops-2025-11-30T00-07-55-415Z.json +30 -0
  123. package/simulation/reports/strange-loops-2025-11-30T00-09-35-133Z.json +30 -0
  124. package/simulation/reports/strange-loops-2025-11-30T00-48-50-744Z.json +24 -0
  125. package/simulation/reports/strange-loops-2025-11-30T00-54-48-044Z.json +24 -0
  126. package/simulation/reports/strange-loops-2025-11-30T00-57-27-633Z.json +24 -0
  127. package/simulation/reports/strange-loops-2025-11-30T00-57-59-135Z.json +42 -0
  128. package/simulation/reports/sublinear-solver-2025-11-30T01-36-33-134Z.json +30 -0
  129. package/simulation/reports/temporal-lead-solver-2025-11-30T01-36-38-628Z.json +30 -0
  130. package/simulation/reports/use-cases-applications.md +2212 -0
  131. package/simulation/reports/voting-system-consensus-2025-11-30T00-11-37-199Z.json +58 -0
  132. package/simulation/reports/voting-system-consensus-2025-11-30T00-28-47-735Z.json +58 -0
  133. package/simulation/runner.ts +300 -0
  134. package/simulation/scenarios/README-advanced/aidefence-integration.md +63 -0
  135. package/simulation/scenarios/README-advanced/bmssp-integration.md +58 -0
  136. package/simulation/scenarios/README-advanced/consciousness-explorer.md +53 -0
  137. package/simulation/scenarios/README-advanced/goalie-integration.md +61 -0
  138. package/simulation/scenarios/README-advanced/psycho-symbolic-reasoner.md +55 -0
  139. package/simulation/scenarios/README-advanced/research-swarm.md +63 -0
  140. package/simulation/scenarios/README-advanced/sublinear-solver.md +58 -0
  141. package/simulation/scenarios/README-advanced/temporal-lead-solver.md +55 -0
  142. package/simulation/scenarios/README-basic/causal-reasoning.md +39 -0
  143. package/simulation/scenarios/README-basic/graph-traversal.md +41 -0
  144. package/simulation/scenarios/README-basic/lean-agentic-swarm.md +122 -0
  145. package/simulation/scenarios/README-basic/multi-agent-swarm.md +34 -0
  146. package/simulation/scenarios/README-basic/reflexion-learning.md +41 -0
  147. package/simulation/scenarios/README-basic/skill-evolution.md +38 -0
  148. package/simulation/scenarios/README-basic/stock-market-emergence.md +28 -0
  149. package/simulation/scenarios/README-basic/strange-loops.md +36 -0
  150. package/simulation/scenarios/README-basic/voting-system-consensus.md +28 -0
  151. package/simulation/scenarios/README.md +438 -0
  152. package/simulation/scenarios/aidefence-integration.ts +165 -0
  153. package/simulation/scenarios/bmssp-integration.ts +137 -0
  154. package/simulation/scenarios/causal-reasoning.ts +143 -0
  155. package/simulation/scenarios/consciousness-explorer.ts +139 -0
  156. package/simulation/scenarios/domain-examples/.claude-flow/metrics/agent-metrics.json +1 -0
  157. package/simulation/scenarios/domain-examples/.claude-flow/metrics/performance.json +87 -0
  158. package/simulation/scenarios/domain-examples/.claude-flow/metrics/task-metrics.json +10 -0
  159. package/simulation/scenarios/domain-examples/README.md +525 -0
  160. package/simulation/scenarios/domain-examples/e-commerce-recommendations.ts +220 -0
  161. package/simulation/scenarios/domain-examples/index.ts +81 -0
  162. package/simulation/scenarios/domain-examples/iot-sensor-networks.ts +290 -0
  163. package/simulation/scenarios/domain-examples/medical-imaging.ts +181 -0
  164. package/simulation/scenarios/domain-examples/robotics-navigation.ts +214 -0
  165. package/simulation/scenarios/domain-examples/scientific-research.ts +250 -0
  166. package/simulation/scenarios/domain-examples/trading-systems.ts +138 -0
  167. package/simulation/scenarios/goalie-integration.ts +161 -0
  168. package/simulation/scenarios/graph-traversal.ts +129 -0
  169. package/simulation/scenarios/latent-space/OPTIMIZATION-COMPLETE.md +287 -0
  170. package/simulation/scenarios/latent-space/README-attention-analysis.md +170 -0
  171. package/simulation/scenarios/latent-space/README-clustering-analysis.md +239 -0
  172. package/simulation/scenarios/latent-space/README-hnsw-exploration.md +199 -0
  173. package/simulation/scenarios/latent-space/README-hypergraph-exploration.md +279 -0
  174. package/simulation/scenarios/latent-space/README-neural-augmentation.md +267 -0
  175. package/simulation/scenarios/latent-space/README-quantum-hybrid.md +276 -0
  176. package/simulation/scenarios/latent-space/README-self-organizing-hnsw.md +244 -0
  177. package/simulation/scenarios/latent-space/README-traversal-optimization.md +212 -0
  178. package/simulation/scenarios/latent-space/attention-analysis.ts +598 -0
  179. package/simulation/scenarios/latent-space/clustering-analysis.ts +796 -0
  180. package/simulation/scenarios/latent-space/hnsw-exploration.ts +526 -0
  181. package/simulation/scenarios/latent-space/hypergraph-exploration.ts +706 -0
  182. package/simulation/scenarios/latent-space/index.ts +47 -0
  183. package/simulation/scenarios/latent-space/neural-augmentation.ts +604 -0
  184. package/simulation/scenarios/latent-space/quantum-hybrid.ts +508 -0
  185. package/simulation/scenarios/latent-space/self-organizing-hnsw.ts +680 -0
  186. package/simulation/scenarios/latent-space/traversal-optimization.ts +782 -0
  187. package/simulation/scenarios/lean-agentic-swarm.ts +182 -0
  188. package/simulation/scenarios/multi-agent-swarm.ts +146 -0
  189. package/simulation/scenarios/psycho-symbolic-reasoner.ts +136 -0
  190. package/simulation/scenarios/reflexion-learning.ts +132 -0
  191. package/simulation/scenarios/research-swarm.ts +187 -0
  192. package/simulation/scenarios/skill-evolution.ts +135 -0
  193. package/simulation/scenarios/stock-market-emergence.ts +323 -0
  194. package/simulation/scenarios/strange-loops.ts +175 -0
  195. package/simulation/scenarios/sublinear-solver.ts +108 -0
  196. package/simulation/scenarios/temporal-lead-solver.ts +121 -0
  197. package/simulation/scenarios/voting-system-consensus.ts +251 -0
  198. package/simulation/tests/latent-space/attention-analysis.test.ts +204 -0
  199. package/simulation/tests/latent-space/clustering-analysis.test.ts +281 -0
  200. package/simulation/tests/latent-space/hnsw-exploration.test.ts +253 -0
  201. package/simulation/tests/latent-space/hypergraph-exploration.test.ts +295 -0
  202. package/simulation/tests/latent-space/neural-augmentation.test.ts +326 -0
  203. package/simulation/tests/latent-space/quantum-hybrid.test.ts +307 -0
  204. package/simulation/tests/latent-space/self-organizing-hnsw.test.ts +291 -0
  205. package/simulation/tests/latent-space/traversal-optimization.test.ts +261 -0
  206. package/simulation/types.ts +177 -0
  207. package/simulation/utils/PerformanceOptimizer.ts +269 -0
  208. package/src/cli/lib/history-tracker.ts +7 -1
@@ -0,0 +1,187 @@
1
+ /**
2
+ * Research-Swarm Integration
3
+ *
4
+ * Distributed research graph DB
5
+ * Integration with research-swarm package
6
+ *
7
+ * Features:
8
+ * - Collaborative research agents
9
+ * - Literature review aggregation
10
+ * - Hypothesis generation and testing
11
+ * - Knowledge synthesis
12
+ */
13
+
14
+ import { createUnifiedDatabase } from '../../src/db-unified.js';
15
+ import { ReflexionMemory } from '../../src/controllers/ReflexionMemory.js';
16
+ import { CausalMemoryGraph } from '../../src/controllers/CausalMemoryGraph.js';
17
+ import { SkillLibrary } from '../../src/controllers/SkillLibrary.js';
18
+ import { EmbeddingService } from '../../src/controllers/EmbeddingService.js';
19
+ import * as path from 'path';
20
+
21
+ export default {
22
+ description: 'Research-swarm distributed research with collaborative agents',
23
+
24
+ async run(config: any) {
25
+ const { verbosity = 2, researchers = 5 } = config;
26
+
27
+ if (verbosity >= 2) {
28
+ console.log(` 🔬 Initializing Research-Swarm (${researchers} researchers)`);
29
+ }
30
+
31
+ // Initialize distributed research graph database
32
+ const embedder = new EmbeddingService({
33
+ model: 'Xenova/all-MiniLM-L6-v2',
34
+ dimension: 384,
35
+ provider: 'transformers'
36
+ });
37
+ await embedder.initialize();
38
+
39
+ const db = await createUnifiedDatabase(
40
+ path.join(process.cwd(), 'simulation', 'data', 'advanced', 'research-swarm.graph'),
41
+ embedder,
42
+ { forceMode: 'graph' }
43
+ );
44
+
45
+ const reflexion = new ReflexionMemory(
46
+ db.getGraphDatabase() as any,
47
+ embedder,
48
+ undefined,
49
+ undefined,
50
+ db.getGraphDatabase() as any
51
+ );
52
+
53
+ const causal = new CausalMemoryGraph(
54
+ db.getGraphDatabase() as any,
55
+ db.getGraphDatabase() as any
56
+ );
57
+
58
+ const skills = new SkillLibrary(
59
+ db.getGraphDatabase() as any,
60
+ embedder,
61
+ undefined,
62
+ db.getGraphDatabase() as any
63
+ );
64
+
65
+ const results = {
66
+ papers: 0,
67
+ hypotheses: 0,
68
+ experiments: 0,
69
+ synthesizedKnowledge: 0,
70
+ totalTime: 0
71
+ };
72
+
73
+ const startTime = performance.now();
74
+
75
+ // Literature Review (each researcher finds papers)
76
+ const papers = [
77
+ 'neural_architecture_search_techniques',
78
+ 'few_shot_learning_methods',
79
+ 'transfer_learning_strategies',
80
+ 'meta_learning_algorithms',
81
+ 'continual_learning_approaches'
82
+ ];
83
+
84
+ const paperIds: number[] = [];
85
+ for (let i = 0; i < papers.length; i++) {
86
+ const id = await reflexion.storeEpisode({
87
+ sessionId: `researcher-${i % researchers}`,
88
+ task: `literature_review: ${papers[i]}`,
89
+ reward: 0.80 + Math.random() * 0.15, // Quality varies
90
+ success: true,
91
+ input: 'academic_search',
92
+ output: `paper_summary_${papers[i]}`
93
+ });
94
+ paperIds.push(id);
95
+ results.papers++;
96
+ }
97
+
98
+ // Hypothesis Generation (synthesizing from papers)
99
+ const hypotheses = [
100
+ 'combining_meta_learning_with_architecture_search_improves_few_shot',
101
+ 'transfer_learning_enables_faster_continual_learning',
102
+ 'meta_architecture_search_reduces_hyperparameter_tuning'
103
+ ];
104
+
105
+ const hypothesisIds: number[] = [];
106
+ for (const hypothesis of hypotheses) {
107
+ const id = await reflexion.storeEpisode({
108
+ sessionId: 'research-synthesis',
109
+ task: `hypothesis: ${hypothesis}`,
110
+ reward: 0.70, // Untested hypothesis
111
+ success: false, // Not yet validated
112
+ input: 'literature_synthesis',
113
+ output: `hypothesis_${hypothesis}`,
114
+ critique: 'Requires experimental validation'
115
+ });
116
+ hypothesisIds.push(id);
117
+ results.hypotheses++;
118
+
119
+ // Link hypothesis to supporting papers
120
+ for (let i = 0; i < Math.min(2, paperIds.length); i++) {
121
+ await causal.addCausalEdge({
122
+ fromMemoryId: paperIds[i],
123
+ fromMemoryType: 'episode',
124
+ toMemoryId: id,
125
+ toMemoryType: 'episode',
126
+ similarity: 0.85,
127
+ uplift: 0.20,
128
+ confidence: 0.80,
129
+ sampleSize: 100,
130
+ mechanism: 'paper_supports_hypothesis'
131
+ });
132
+ }
133
+ }
134
+
135
+ // Experimental Validation
136
+ const experiments = [
137
+ { hypothesis: 0, result: 'confirmed', confidence: 0.92 },
138
+ { hypothesis: 1, result: 'confirmed', confidence: 0.88 },
139
+ { hypothesis: 2, result: 'partially_confirmed', confidence: 0.75 }
140
+ ];
141
+
142
+ for (const exp of experiments) {
143
+ await reflexion.storeEpisode({
144
+ sessionId: 'experimental-validation',
145
+ task: `experiment_validate_hypothesis_${exp.hypothesis}`,
146
+ reward: exp.confidence,
147
+ success: exp.result === 'confirmed',
148
+ input: `hypothesis_${exp.hypothesis}`,
149
+ output: exp.result,
150
+ critique: `Confidence: ${exp.confidence}`
151
+ });
152
+ results.experiments++;
153
+ }
154
+
155
+ // Knowledge Synthesis (create reusable research methods)
156
+ const researchMethods = [
157
+ 'meta_architecture_search_protocol',
158
+ 'few_shot_evaluation_framework',
159
+ 'transfer_learning_pipeline'
160
+ ];
161
+
162
+ for (const method of researchMethods) {
163
+ await skills.createSkill({
164
+ name: method,
165
+ description: 'Research methodology',
166
+ code: `// Reusable research method: ${method}`,
167
+ successRate: 0.85
168
+ });
169
+ results.synthesizedKnowledge++;
170
+ }
171
+
172
+ const endTime = performance.now();
173
+ results.totalTime = endTime - startTime;
174
+
175
+ db.close();
176
+
177
+ if (verbosity >= 2) {
178
+ console.log(` 📊 Papers Reviewed: ${results.papers}`);
179
+ console.log(` 📊 Hypotheses Generated: ${results.hypotheses}`);
180
+ console.log(` 📊 Experiments Conducted: ${results.experiments}`);
181
+ console.log(` 📊 Synthesized Knowledge: ${results.synthesizedKnowledge} methods`);
182
+ console.log(` ⏱️ Duration: ${results.totalTime.toFixed(2)}ms`);
183
+ }
184
+
185
+ return results;
186
+ }
187
+ };
@@ -0,0 +1,135 @@
1
+ /**
2
+ * Skill Evolution Simulation
3
+ *
4
+ * Tests SkillLibrary with skill creation, evolution, and composition
5
+ */
6
+
7
+ import { createUnifiedDatabase } from '../../src/db-unified.js';
8
+ import { SkillLibrary } from '../../src/controllers/SkillLibrary.js';
9
+ import { EmbeddingService } from '../../src/controllers/EmbeddingService.js';
10
+ import * as path from 'path';
11
+
12
+ export default {
13
+ description: 'Skill library evolution with composition and refinement',
14
+
15
+ async run(config: any) {
16
+ const { verbosity = 2 } = config;
17
+
18
+ if (verbosity >= 2) {
19
+ console.log(' 🛠️ Initializing Skill Evolution Simulation');
20
+ }
21
+
22
+ // Initialize AgentDB
23
+ const embedder = new EmbeddingService({
24
+ model: 'Xenova/all-MiniLM-L6-v2',
25
+ dimension: 384,
26
+ provider: 'transformers'
27
+ });
28
+ await embedder.initialize();
29
+
30
+ const db = await createUnifiedDatabase(
31
+ path.join(process.cwd(), 'simulation', 'data', 'skills.graph'),
32
+ embedder,
33
+ { forceMode: 'graph' }
34
+ );
35
+
36
+ const skills = new SkillLibrary(
37
+ db.getGraphDatabase() as any,
38
+ embedder,
39
+ undefined, // vectorBackend
40
+ db.getGraphDatabase() as any // graphBackend
41
+ );
42
+
43
+ // Simulate skill creation and evolution
44
+ const skillTemplates = [
45
+ {
46
+ name: 'jwt_authentication',
47
+ description: 'Generate and verify JWT tokens',
48
+ code: 'function generateJWT(payload) { return jwt.sign(payload, SECRET); }',
49
+ successRate: 0.95
50
+ },
51
+ {
52
+ name: 'database_query_optimizer',
53
+ description: 'Optimize database queries with batch loading',
54
+ code: 'function batchLoad(ids) { return DataLoader.load(ids); }',
55
+ successRate: 0.88
56
+ },
57
+ {
58
+ name: 'error_handler',
59
+ description: 'Comprehensive error handling middleware',
60
+ code: 'function errorHandler(err, req, res, next) { /* ... */ }',
61
+ successRate: 0.92
62
+ },
63
+ {
64
+ name: 'cache_manager',
65
+ description: 'Redis-based caching with TTL',
66
+ code: 'function cacheSet(key, val, ttl) { return redis.setex(key, ttl, val); }',
67
+ successRate: 0.90
68
+ },
69
+ {
70
+ name: 'validation_schema',
71
+ description: 'Request validation with Zod schemas',
72
+ code: 'const schema = z.object({ email: z.string().email() });',
73
+ successRate: 0.93
74
+ }
75
+ ];
76
+
77
+ const results = {
78
+ created: 0,
79
+ searched: 0,
80
+ avgSuccessRate: 0,
81
+ totalTime: 0
82
+ };
83
+
84
+ const startTime = performance.now();
85
+
86
+ // Create skills
87
+ for (const template of skillTemplates) {
88
+ await skills.createSkill(template);
89
+ results.created++;
90
+ results.avgSuccessRate += template.successRate;
91
+
92
+ if (verbosity >= 3) {
93
+ console.log(` ✅ Created skill: ${template.name}`);
94
+ }
95
+ }
96
+
97
+ // Search for skills
98
+ const searchQueries = [
99
+ 'authentication',
100
+ 'database optimization',
101
+ 'error handling',
102
+ 'caching',
103
+ 'validation'
104
+ ];
105
+
106
+ for (const query of searchQueries) {
107
+ const found = await skills.searchSkills({
108
+ query,
109
+ k: 3,
110
+ minSuccessRate: 0.8
111
+ });
112
+
113
+ results.searched += found.length;
114
+
115
+ if (verbosity >= 3) {
116
+ console.log(` 🔍 Found ${found.length} skills for: ${query}`);
117
+ }
118
+ }
119
+
120
+ const endTime = performance.now();
121
+ results.totalTime = endTime - startTime;
122
+ results.avgSuccessRate /= skillTemplates.length;
123
+
124
+ db.close();
125
+
126
+ if (verbosity >= 2) {
127
+ console.log(` 📊 Created: ${results.created} skills`);
128
+ console.log(` 📊 Searched: ${results.searched} results`);
129
+ console.log(` 📊 Avg Success Rate: ${(results.avgSuccessRate * 100).toFixed(1)}%`);
130
+ console.log(` ⏱️ Duration: ${results.totalTime.toFixed(2)}ms`);
131
+ }
132
+
133
+ return results;
134
+ }
135
+ };
@@ -0,0 +1,323 @@
1
+ /**
2
+ * Stock Market Emergence Simulation
3
+ *
4
+ * Models complex market dynamics with:
5
+ * - Multi-agent trading strategies (momentum, value, contrarian, HFT)
6
+ * - Market microstructure (order book, bid-ask spread)
7
+ * - Herding behavior and cascades
8
+ * - Flash crash detection and circuit breakers
9
+ * - Sentiment propagation through agent network
10
+ * - Adaptive learning from P&L
11
+ *
12
+ * Tests AgentDB's ability to model emergent collective behavior
13
+ * and adaptive learning in high-frequency financial systems.
14
+ */
15
+
16
+ import { createUnifiedDatabase } from '../../src/db-unified.js';
17
+ import { ReflexionMemory } from '../../src/controllers/ReflexionMemory.js';
18
+ import { EmbeddingService } from '../../src/controllers/EmbeddingService.js';
19
+ import { PerformanceOptimizer, executeParallel } from '../utils/PerformanceOptimizer.js';
20
+ import * as path from 'path';
21
+
22
+ interface Trader {
23
+ id: string;
24
+ strategy: 'momentum' | 'value' | 'contrarian' | 'HFT' | 'index';
25
+ cash: number;
26
+ shares: number;
27
+ profitLoss: number;
28
+ tradeHistory: Trade[];
29
+ sentiment: number; // -1 (bearish) to +1 (bullish)
30
+ }
31
+
32
+ interface Trade {
33
+ timestamp: number;
34
+ price: number;
35
+ quantity: number;
36
+ type: 'buy' | 'sell';
37
+ traderId: string;
38
+ }
39
+
40
+ interface MarketState {
41
+ tick: number;
42
+ price: number;
43
+ volume: number;
44
+ volatility: number;
45
+ bidAskSpread: number;
46
+ sentimentIndex: number;
47
+ }
48
+
49
+ export default {
50
+ description: 'Stock market with multi-strategy traders, herding, flash crashes, and adaptive learning',
51
+
52
+ async run(config: any) {
53
+ const { verbosity = 2, ticks = 100, traderCount = 100 } = config;
54
+
55
+ if (verbosity >= 2) {
56
+ console.log(` 📈 Initializing Stock Market: ${traderCount} traders, ${ticks} ticks`);
57
+ }
58
+
59
+ // Initialize performance optimizer
60
+ const optimizer = new PerformanceOptimizer({ batchSize: 100 });
61
+
62
+ const embedder = new EmbeddingService({
63
+ model: 'Xenova/all-MiniLM-L6-v2',
64
+ dimension: 384,
65
+ provider: 'transformers'
66
+ });
67
+ await embedder.initialize();
68
+
69
+ const db = await createUnifiedDatabase(
70
+ path.join(process.cwd(), 'simulation', 'data', 'stock-market.graph'),
71
+ embedder,
72
+ { forceMode: 'graph' }
73
+ );
74
+
75
+ const reflexion = new ReflexionMemory(
76
+ db.getGraphDatabase() as any,
77
+ embedder,
78
+ undefined,
79
+ undefined,
80
+ db.getGraphDatabase() as any
81
+ );
82
+
83
+ const results = {
84
+ ticks: 0,
85
+ totalTrades: 0,
86
+ flashCrashes: 0,
87
+ herdingEvents: 0,
88
+ priceRange: { min: 100, max: 100 },
89
+ avgVolatility: 0,
90
+ strategyPerformance: new Map<string, number>(),
91
+ adaptiveLearningEvents: 0,
92
+ totalTime: 0
93
+ };
94
+
95
+ const startTime = performance.now();
96
+
97
+ // Initialize traders with different strategies
98
+ const strategyDistribution = ['momentum', 'value', 'contrarian', 'HFT', 'index'];
99
+ const traders: Trader[] = Array.from({ length: traderCount }, (_, i) => ({
100
+ id: `trader-${i}`,
101
+ strategy: strategyDistribution[i % strategyDistribution.length] as any,
102
+ cash: 10000,
103
+ shares: Math.floor(Math.random() * 50),
104
+ profitLoss: 0,
105
+ tradeHistory: [],
106
+ sentiment: Math.random() * 2 - 1
107
+ }));
108
+
109
+ let currentPrice = 100;
110
+ const priceHistory: number[] = [100];
111
+ const trades: Trade[] = [];
112
+ let circuitBreakerActive = false;
113
+
114
+ // Market simulation ticks
115
+ for (let tick = 0; tick < ticks; tick++) {
116
+ const tickTrades: Trade[] = [];
117
+
118
+ // Each trader decides to trade based on strategy
119
+ for (const trader of traders) {
120
+ if (circuitBreakerActive && Math.random() > 0.1) continue; // 90% stop trading during circuit breaker
121
+
122
+ let shouldBuy = false;
123
+ let shouldSell = false;
124
+
125
+ switch (trader.strategy) {
126
+ case 'momentum':
127
+ // Buy if price rising, sell if falling
128
+ if (priceHistory.length >= 5) {
129
+ const recentChange = (priceHistory[priceHistory.length - 1] - priceHistory[priceHistory.length - 5]) / priceHistory[priceHistory.length - 5];
130
+ shouldBuy = recentChange > 0.01;
131
+ shouldSell = recentChange < -0.01;
132
+ }
133
+ break;
134
+
135
+ case 'value':
136
+ // Buy if price below 100, sell if above
137
+ shouldBuy = currentPrice < 95;
138
+ shouldSell = currentPrice > 105;
139
+ break;
140
+
141
+ case 'contrarian':
142
+ // Buy when others sell, sell when others buy
143
+ if (priceHistory.length >= 3) {
144
+ const recentChange = currentPrice - priceHistory[priceHistory.length - 2];
145
+ shouldBuy = recentChange < -2;
146
+ shouldSell = recentChange > 2;
147
+ }
148
+ break;
149
+
150
+ case 'HFT':
151
+ // High frequency: trade on tiny movements
152
+ if (priceHistory.length >= 2) {
153
+ const microChange = currentPrice - priceHistory[priceHistory.length - 1];
154
+ shouldBuy = microChange < -0.1 && Math.random() > 0.7;
155
+ shouldSell = microChange > 0.1 && Math.random() > 0.7;
156
+ }
157
+ break;
158
+
159
+ case 'index':
160
+ // Passive: rarely trade
161
+ shouldBuy = Math.random() > 0.98;
162
+ shouldSell = Math.random() > 0.98;
163
+ break;
164
+ }
165
+
166
+ // Execute trades
167
+ if (shouldBuy && trader.cash > currentPrice) {
168
+ const quantity = Math.min(Math.floor(trader.cash / currentPrice), 10);
169
+ if (quantity > 0) {
170
+ const trade: Trade = {
171
+ timestamp: tick,
172
+ price: currentPrice,
173
+ quantity,
174
+ type: 'buy',
175
+ traderId: trader.id
176
+ };
177
+ tickTrades.push(trade);
178
+ trader.cash -= currentPrice * quantity;
179
+ trader.shares += quantity;
180
+ trader.tradeHistory.push(trade);
181
+ }
182
+ } else if (shouldSell && trader.shares > 0) {
183
+ const quantity = Math.min(trader.shares, 10);
184
+ const trade: Trade = {
185
+ timestamp: tick,
186
+ price: currentPrice,
187
+ quantity,
188
+ type: 'sell',
189
+ traderId: trader.id
190
+ };
191
+ tickTrades.push(trade);
192
+ trader.cash += currentPrice * quantity;
193
+ trader.shares -= quantity;
194
+ trader.tradeHistory.push(trade);
195
+ }
196
+ }
197
+
198
+ // Update price based on supply/demand
199
+ const buyOrders = tickTrades.filter(t => t.type === 'buy').length;
200
+ const sellOrders = tickTrades.filter(t => t.type === 'sell').length;
201
+ const orderImbalance = (buyOrders - sellOrders) / (buyOrders + sellOrders + 1);
202
+
203
+ // Price impact
204
+ const priceChange = orderImbalance * 2 + (Math.random() - 0.5) * 0.5;
205
+ currentPrice = Math.max(1, currentPrice + priceChange);
206
+
207
+ priceHistory.push(currentPrice);
208
+ trades.push(...tickTrades);
209
+ results.totalTrades += tickTrades.length;
210
+
211
+ // Update price range
212
+ results.priceRange.min = Math.min(results.priceRange.min, currentPrice);
213
+ results.priceRange.max = Math.max(results.priceRange.max, currentPrice);
214
+
215
+ // Calculate volatility (std dev of last 10 prices)
216
+ if (priceHistory.length >= 10) {
217
+ const recent = priceHistory.slice(-10);
218
+ const mean = recent.reduce((a, b) => a + b) / recent.length;
219
+ const variance = recent.reduce((sum, price) => sum + Math.pow(price - mean, 2), 0) / recent.length;
220
+ const volatility = Math.sqrt(variance);
221
+ results.avgVolatility += volatility;
222
+
223
+ // Flash crash detection (>10% drop in 10 ticks)
224
+ if ((recent[0] - recent[recent.length - 1]) / recent[0] > 0.10) {
225
+ results.flashCrashes++;
226
+ circuitBreakerActive = true;
227
+ if (verbosity >= 3) {
228
+ console.log(` ⚠️ Flash crash detected at tick ${tick}! Circuit breaker activated.`);
229
+ }
230
+ }
231
+ }
232
+
233
+ // Deactivate circuit breaker after 5 ticks
234
+ if (circuitBreakerActive && tick % 5 === 0) {
235
+ circuitBreakerActive = false;
236
+ }
237
+
238
+ // Detect herding (>60% traders moving same direction)
239
+ const herdingThreshold = 0.6;
240
+ if (buyOrders / (buyOrders + sellOrders + 1) > herdingThreshold ||
241
+ sellOrders / (buyOrders + sellOrders + 1) > herdingThreshold) {
242
+ results.herdingEvents++;
243
+ }
244
+
245
+ // Update trader sentiment based on profit/loss
246
+ for (const trader of traders) {
247
+ const portfolioValue = trader.cash + trader.shares * currentPrice;
248
+ const initialValue = 10000 + 50 * 100; // initial cash + shares * starting price
249
+ trader.profitLoss = portfolioValue - initialValue;
250
+ trader.sentiment = Math.tanh(trader.profitLoss / 1000); // -1 to +1
251
+ }
252
+
253
+ results.ticks++;
254
+
255
+ if (verbosity >= 3 && tick % 20 === 0) {
256
+ console.log(` 📊 Tick ${tick}: Price $${currentPrice.toFixed(2)}, Trades: ${tickTrades.length}, Circuit Breaker: ${circuitBreakerActive}`);
257
+ }
258
+ }
259
+
260
+ // Adaptive learning: Store top 10 most profitable traders' strategies - OPTIMIZED
261
+ const sortedByProfit = traders.sort((a, b) => b.profitLoss - a.profitLoss);
262
+
263
+ // Queue all episode storage operations for parallel execution
264
+ for (let i = 0; i < Math.min(10, sortedByProfit.length); i++) {
265
+ const trader = sortedByProfit[i];
266
+
267
+ optimizer.queueOperation(async () => {
268
+ await reflexion.storeEpisode({
269
+ sessionId: 'market-simulation',
270
+ task: `trade with ${trader.strategy} strategy`,
271
+ input: `Initial capital: $10000, Strategy: ${trader.strategy}`,
272
+ output: `Final P&L: $${trader.profitLoss.toFixed(2)}, Trades: ${trader.tradeHistory.length}`,
273
+ reward: Math.tanh(trader.profitLoss / 5000), // -1 to +1
274
+ success: trader.profitLoss > 0,
275
+ critique: trader.profitLoss > 0 ? 'Profitable strategy' : 'Losses incurred',
276
+ metadata: {
277
+ strategy: trader.strategy,
278
+ finalPortfolio: trader.cash + trader.shares * currentPrice,
279
+ totalTrades: trader.tradeHistory.length
280
+ }
281
+ });
282
+ results.adaptiveLearningEvents++;
283
+ });
284
+ }
285
+
286
+ // Execute batch operation
287
+ await optimizer.executeBatch();
288
+
289
+ // Calculate strategy performance
290
+ for (const strategy of strategyDistribution) {
291
+ const strategyTraders = traders.filter(t => t.strategy === strategy);
292
+ const avgPL = strategyTraders.reduce((sum, t) => sum + t.profitLoss, 0) / strategyTraders.length;
293
+ results.strategyPerformance.set(strategy, avgPL);
294
+ }
295
+
296
+ results.avgVolatility /= Math.max(1, ticks - 9);
297
+
298
+ const endTime = performance.now();
299
+ results.totalTime = endTime - startTime;
300
+
301
+ db.close();
302
+
303
+ // Get optimization metrics
304
+ const optimizerMetrics = optimizer.getMetrics();
305
+
306
+ if (verbosity >= 2) {
307
+ console.log(` 📊 Ticks: ${results.ticks}`);
308
+ console.log(` 📊 Total Trades: ${results.totalTrades}`);
309
+ console.log(` 📊 Flash Crashes: ${results.flashCrashes}`);
310
+ console.log(` 📊 Herding Events: ${results.herdingEvents}`);
311
+ console.log(` 📊 Price Range: $${results.priceRange.min.toFixed(2)} - $${results.priceRange.max.toFixed(2)}`);
312
+ console.log(` 📊 Avg Volatility: ${results.avgVolatility.toFixed(2)}`);
313
+ console.log(` 📊 Strategy Performance:`);
314
+ for (const [strategy, pl] of results.strategyPerformance.entries()) {
315
+ console.log(` ${strategy}: ${pl > 0 ? '+' : ''}$${pl.toFixed(2)}`);
316
+ }
317
+ console.log(` ⏱️ Duration: ${results.totalTime.toFixed(2)}ms`);
318
+ console.log(` ⚡ Optimization: ${optimizerMetrics.batchOperations} batches, ${optimizerMetrics.avgLatency} avg`);
319
+ }
320
+
321
+ return results;
322
+ }
323
+ };