do-memory-mcp 0.1.29

Model Context Protocol (MCP) server for AI agents
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
//! # Comprehensive Advanced Pattern Analysis Tests
//!
//! This module provides comprehensive testing for the advanced pattern analysis MCP tool,
//! covering unit tests, integration tests, performance tests, and security tests.

use do_memory_core::SelfLearningMemory;
use do_memory_mcp::mcp::tools::advanced_pattern_analysis::{
    AdvancedPatternAnalysisInput, AdvancedPatternAnalysisTool, AnalysisConfig, AnalysisType,
};
use do_memory_mcp::patterns::statistical;
use std::collections::HashMap;
use std::sync::Arc;
use tokio::time::{Duration, timeout};

/// Test comprehensive statistical analysis with various data patterns
#[tokio::test]
async fn test_comprehensive_statistical_analysis() {
    let memory = Arc::new(SelfLearningMemory::new());
    let tool = AdvancedPatternAnalysisTool::new(memory);

    // Test with perfectly correlated data
    let mut data = HashMap::new();
    data.insert(
        "x".to_string(),
        vec![1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0],
    );
    data.insert(
        "y".to_string(),
        vec![2.0, 4.0, 6.0, 8.0, 10.0, 12.0, 14.0, 16.0, 18.0, 20.0],
    );
    data.insert(
        "z".to_string(),
        vec![1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0],
    ); // Constant

    let input = AdvancedPatternAnalysisInput {
        analysis_type: AnalysisType::Statistical,
        time_series_data: data,
        config: Some(AnalysisConfig {
            significance_level: Some(0.05),
            max_data_points: Some(1000),
            parallel_processing: Some(false),
            ..Default::default()
        }),
    };

    let result = tool.execute(input).await;
    assert!(result.is_ok());

    let output = result.unwrap();
    assert!(output.statistical_results.is_some());
    let stats = output.statistical_results.as_ref().unwrap();

    // Should find correlations
    assert!(!stats.correlations.is_empty());

    // Should find significant correlation between x and y
    let xy_corr = stats
        .correlations
        .iter()
        .find(|c| {
            c.variables == ("x".to_string(), "y".to_string())
                || c.variables == ("y".to_string(), "x".to_string())
        })
        .unwrap();
    assert!(xy_corr.significant);
    assert!((xy_corr.coefficient - 1.0).abs() < 0.01);

    // Should find trends
    assert!(!stats.trends.is_empty());
    let x_trend = stats.trends.iter().find(|t| t.variable == "x").unwrap();
    assert!(x_trend.significant);
    assert_eq!(x_trend.direction, statistical::TrendDirection::Increasing);
}

/// Test predictive analysis with forecasting and anomaly detection
#[tokio::test]
async fn test_predictive_analysis_comprehensive() {
    let memory = Arc::new(SelfLearningMemory::new());
    let tool = AdvancedPatternAnalysisTool::new(memory);

    // Create data with clear trend and anomaly
    let mut data = HashMap::new();
    let mut series = vec![1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0];
    series.push(50.0); // Clear anomaly
    series.extend(vec![11.0, 12.0, 13.0, 14.0, 15.0]);

    data.insert("trendy_with_anomaly".to_string(), series);

    let input = AdvancedPatternAnalysisInput {
        analysis_type: AnalysisType::Predictive,
        time_series_data: data,
        config: Some(AnalysisConfig {
            forecast_horizon: Some(5),
            anomaly_sensitivity: Some(0.3),       // More sensitive
            enable_causal_inference: Some(false), // Skip causal for this test
            ..Default::default()
        }),
    };

    let result = tool.execute(input).await;
    assert!(result.is_ok());

    let output = result.unwrap();
    assert!(output.predictive_results.is_some());
    let pred = output.predictive_results.as_ref().unwrap();

    // Should generate forecasts
    assert!(!pred.forecasts.is_empty());
    let forecast = &pred.forecasts[0];
    assert_eq!(forecast.variable, "trendy_with_anomaly");
    assert_eq!(forecast.point_forecasts.len(), 5);

    // Should detect anomalies
    assert!(!pred.anomalies.is_empty());
    let anomaly = &pred.anomalies[0];
    assert_eq!(anomaly.variable, "trendy_with_anomaly");
    assert!(!anomaly.anomaly_indices.is_empty());
}

/// Test comprehensive analysis combining all methods
#[tokio::test]
async fn test_comprehensive_analysis_integration() {
    let memory = Arc::new(SelfLearningMemory::new());
    let tool = AdvancedPatternAnalysisTool::new(memory);

    // Create complex dataset with multiple patterns
    let mut data = HashMap::new();

    // Linear trend
    data.insert(
        "trend".to_string(),
        vec![1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0],
    );

    // Correlated with trend
    data.insert(
        "correlated".to_string(),
        vec![2.0, 4.0, 6.0, 8.0, 10.0, 12.0, 14.0, 16.0, 18.0, 20.0],
    );

    // Random noise
    data.insert(
        "noise".to_string(),
        vec![0.5, 1.2, -0.3, 0.8, 1.5, -0.1, 0.9, 1.1, -0.4, 0.6],
    );

    let input = AdvancedPatternAnalysisInput {
        analysis_type: AnalysisType::Comprehensive,
        time_series_data: data,
        config: Some(AnalysisConfig {
            significance_level: Some(0.05),
            forecast_horizon: Some(3),
            anomaly_sensitivity: Some(0.5),
            enable_causal_inference: Some(true),
            max_data_points: Some(100),
            parallel_processing: Some(false),
        }),
    };

    let result = tool.execute(input).await;
    assert!(result.is_ok());

    let output = result.unwrap();

    // Should have both statistical and predictive results
    assert!(output.statistical_results.is_some());
    assert!(output.predictive_results.is_some());

    // Check summary
    assert_eq!(output.summary.variables_analyzed, 3);
    assert!(!output.summary.key_findings.is_empty());
    assert!(output.summary.confidence_level > 0.0);

    // Performance metrics are valid for unsigned integers (no need to check >= 0)
}

/// Test input validation edge cases
#[tokio::test]
async fn test_input_validation_edge_cases() {
    let memory = Arc::new(SelfLearningMemory::new());
    let tool = AdvancedPatternAnalysisTool::new(memory);

    // Test empty data
    let input_empty = AdvancedPatternAnalysisInput {
        analysis_type: AnalysisType::Statistical,
        time_series_data: HashMap::new(),
        config: None,
    };
    assert!(tool.validate_input(&input_empty).is_err());

    // Test insufficient data points
    let mut small_data = HashMap::new();
    small_data.insert("small".to_string(), vec![1.0, 2.0]);
    let input_small = AdvancedPatternAnalysisInput {
        analysis_type: AnalysisType::Statistical,
        time_series_data: small_data,
        config: None,
    };
    assert!(tool.validate_input(&input_small).is_err());

    // Test NaN values
    let mut nan_data = HashMap::new();
    nan_data.insert("nan".to_string(), vec![1.0, f64::NAN, 3.0]);
    let input_nan = AdvancedPatternAnalysisInput {
        analysis_type: AnalysisType::Statistical,
        time_series_data: nan_data,
        config: None,
    };
    assert!(tool.validate_input(&input_nan).is_err());

    // Test infinite values
    let mut inf_data = HashMap::new();
    inf_data.insert("inf".to_string(), vec![1.0, f64::INFINITY, 3.0]);
    let input_inf = AdvancedPatternAnalysisInput {
        analysis_type: AnalysisType::Statistical,
        time_series_data: inf_data,
        config: None,
    };
    assert!(tool.validate_input(&input_inf).is_err());

    // Test invalid significance level
    let mut valid_data = HashMap::new();
    valid_data.insert("valid".to_string(), vec![1.0, 2.0, 3.0, 4.0, 5.0]);
    let input_invalid_sig = AdvancedPatternAnalysisInput {
        analysis_type: AnalysisType::Statistical,
        time_series_data: valid_data.clone(),
        config: Some(AnalysisConfig {
            significance_level: Some(1.5), // Invalid
            ..Default::default()
        }),
    };
    assert!(tool.validate_input(&input_invalid_sig).is_err());

    // Test invalid anomaly sensitivity
    let input_invalid_sens = AdvancedPatternAnalysisInput {
        analysis_type: AnalysisType::Predictive,
        time_series_data: valid_data,
        config: Some(AnalysisConfig {
            anomaly_sensitivity: Some(-0.1), // Invalid
            ..Default::default()
        }),
    };
    assert!(tool.validate_input(&input_invalid_sens).is_err());
}

/// Test numerical stability with extreme values
#[tokio::test]
async fn test_numerical_stability() {
    let memory = Arc::new(SelfLearningMemory::new());
    let tool = AdvancedPatternAnalysisTool::new(memory);

    let mut data = HashMap::new();

    // Very large numbers
    data.insert("large".to_string(), vec![1e10, 2e10, 3e10, 4e10, 5e10]);

    // Very small numbers
    data.insert("small".to_string(), vec![1e-10, 2e-10, 3e-10, 4e-10, 5e-10]);

    // Mixed scales
    data.insert("mixed".to_string(), vec![1e-6, 1e-3, 1.0, 1e3, 1e6]);

    let input = AdvancedPatternAnalysisInput {
        analysis_type: AnalysisType::Comprehensive,
        time_series_data: data,
        config: None,
    };

    let result = tool.execute(input).await;
    assert!(
        result.is_ok(),
        "Analysis should handle extreme values without panicking"
    );

    let output = result.unwrap();
    assert!(output.statistical_results.is_some());
    assert!(output.predictive_results.is_some());
}

/// Test performance with large datasets
#[tokio::test]
async fn test_performance_large_dataset() {
    let memory = Arc::new(SelfLearningMemory::new());
    let tool = AdvancedPatternAnalysisTool::new(memory);

    // Create large dataset (but not too large for test)
    let mut data = HashMap::new();
    let large_series: Vec<f64> = (0..500).map(|i| i as f64).collect();

    for i in 0..5 {
        data.insert(format!("series_{}", i), large_series.clone());
    }

    let input = AdvancedPatternAnalysisInput {
        analysis_type: AnalysisType::Statistical, // Faster than comprehensive
        time_series_data: data,
        config: Some(AnalysisConfig {
            max_data_points: Some(1000),
            parallel_processing: Some(false),
            ..Default::default()
        }),
    };

    // Test with timeout to ensure it doesn't hang
    let result = timeout(Duration::from_secs(30), tool.execute(input)).await;
    assert!(result.is_ok(), "Analysis should complete within timeout");
    assert!(result.unwrap().is_ok());
}

/// Test memory extraction from episodes
#[tokio::test]
async fn test_memory_extraction_integration() {
    let memory = Arc::new(SelfLearningMemory::new());
    let tool = AdvancedPatternAnalysisTool::new(memory.clone());

    // This test would ideally populate memory with episodes first
    // For now, test that the method doesn't panic with empty memory
    let result = tool
        .extract_time_series_from_memory("test query", "test_domain", 10)
        .await;

    // Should return error for no episodes, not panic
    assert!(result.is_err());
}

/// Test concurrent execution safety
#[tokio::test]
async fn test_concurrent_execution() {
    let memory = Arc::new(SelfLearningMemory::new());

    // Create multiple tools
    let tools: Vec<_> = (0..5)
        .map(|_| AdvancedPatternAnalysisTool::new(memory.clone()))
        .collect();

    // Create test data
    let mut data = HashMap::new();
    data.insert("test".to_string(), vec![1.0, 2.0, 3.0, 4.0, 5.0]);

    let input = AdvancedPatternAnalysisInput {
        analysis_type: AnalysisType::Statistical,
        time_series_data: data,
        config: None,
    };

    // Execute concurrently
    let tasks: Vec<_> = tools
        .into_iter()
        .map(|tool| {
            let input_clone = input.clone();
            tokio::spawn(async move { tool.execute(input_clone).await })
        })
        .collect();

    // Wait for all to complete
    for task in tasks {
        let result = task.await.unwrap();
        assert!(result.is_ok());
    }
}

/// Test configuration parameter handling
#[tokio::test]
async fn test_configuration_parameters() {
    let memory = Arc::new(SelfLearningMemory::new());
    let tool = AdvancedPatternAnalysisTool::new(memory);

    let mut data = HashMap::new();
    data.insert(
        "test".to_string(),
        vec![1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0],
    );

    // Test with minimal config
    let input_minimal = AdvancedPatternAnalysisInput {
        analysis_type: AnalysisType::Comprehensive,
        time_series_data: data.clone(),
        config: Some(AnalysisConfig {
            significance_level: Some(0.01),       // Very strict
            forecast_horizon: Some(1),            // Minimal forecast
            anomaly_sensitivity: Some(0.1),       // Very sensitive
            enable_causal_inference: Some(false), // Disable causal
            max_data_points: Some(50),
            parallel_processing: Some(false),
        }),
    };

    let result = tool.execute(input_minimal).await;
    assert!(result.is_ok());

    // Test with None config (should use defaults)
    let input_default = AdvancedPatternAnalysisInput {
        analysis_type: AnalysisType::Statistical,
        time_series_data: data,
        config: None,
    };

    let result_default = tool.execute(input_default).await;
    assert!(result_default.is_ok());
}

/// Test error handling and recovery
#[tokio::test]
async fn test_error_handling() {
    let memory = Arc::new(SelfLearningMemory::new());
    let tool = AdvancedPatternAnalysisTool::new(memory);

    // Test with data that might cause issues
    let mut problematic_data = HashMap::new();

    // All zeros (might cause division by zero in some calculations)
    problematic_data.insert("zeros".to_string(), vec![0.0, 0.0, 0.0, 0.0, 0.0]);

    // Very large range
    problematic_data.insert(
        "large_range".to_string(),
        vec![1e-20, 1e-10, 1.0, 1e10, 1e20],
    );

    let input = AdvancedPatternAnalysisInput {
        analysis_type: AnalysisType::Comprehensive,
        time_series_data: problematic_data,
        config: None,
    };

    let result = tool.execute(input).await;

    // Should not panic, should either succeed or return a proper error
    match result {
        Ok(output) => {
            // If successful, results should be reasonable
            assert!(output.summary.variables_analyzed >= 1);
        }
        Err(e) => {
            // If error, should be a proper error message
            assert!(!e.to_string().is_empty());
        }
    }
}