do-memory-mcp 0.1.31

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
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
//! # Pattern Extraction Module
//!
//! This module extracts patterns from DBSCAN clusters and summarizes their characteristics.

use anyhow::Result;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;

use super::dbscan::{Cluster, ClusterLabel};

/// Extracted pattern from a cluster
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ExtractedPattern {
    /// Pattern ID
    pub id: String,
    /// Cluster ID this pattern was extracted from
    pub cluster_id: usize,
    /// Pattern description
    pub description: String,
    /// Cluster characteristics
    pub characteristics: ClusterCharacteristics,
    /// Pattern quality score (0-1)
    pub quality_score: f64,
    /// Pattern type
    pub pattern_type: PatternType,
    /// Variable names involved in this pattern
    pub variables: Vec<String>,
    /// Temporal range (start, end indices)
    pub temporal_range: (usize, usize),
}

/// Cluster characteristics summary
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ClusterCharacteristics {
    /// Number of points in cluster
    pub size: usize,
    /// Cluster centroid
    pub centroid: Vec<f64>,
    /// Cluster density
    pub density: f64,
    /// Cluster variance
    pub variance: f64,
    /// Cluster compactness (inverse of spread)
    pub compactness: f64,
    /// Time span of cluster
    pub time_span: f64,
}

/// Pattern type classification
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum PatternType {
    /// Temporal pattern (trend, seasonality)
    Temporal { pattern: String },
    /// Anomaly pattern (outliers)
    Anomaly { severity: String },
    /// Stable pattern (consistent behavior)
    Stable { consistency: f64 },
    /// Transition pattern (change between states)
    Transition { from: String, to: String },
    /// Unknown pattern type
    Unknown,
}

/// Pattern extraction configuration
#[derive(Debug, Clone)]
pub struct ExtractionConfig {
    /// Minimum cluster quality threshold
    pub min_quality: f64,
    /// Minimum cluster size
    pub min_cluster_size: usize,
    /// Whether to generate detailed descriptions
    pub verbose: bool,
}

impl Default for ExtractionConfig {
    fn default() -> Self {
        Self {
            min_quality: 0.6,
            min_cluster_size: 3,
            verbose: true,
        }
    }
}

/// Pattern extraction engine
pub struct PatternExtractor {
    config: ExtractionConfig,
}

impl PatternExtractor {
    /// Create a new pattern extractor
    pub fn new(config: ExtractionConfig) -> Self {
        Self { config }
    }

    /// Create with default configuration
    pub fn default_config() -> Self {
        Self::new(ExtractionConfig::default())
    }

    /// Extract patterns from DBSCAN clusters
    pub fn extract_patterns(
        &self,
        clusters: &[Cluster],
        labels: &[ClusterLabel],
        variable_names: &[String],
    ) -> Result<Vec<ExtractedPattern>> {
        let mut patterns = Vec::new();

        for (cluster_idx, cluster) in clusters.iter().enumerate() {
            // Check if cluster meets quality criteria
            if cluster.points.len() < self.config.min_cluster_size {
                continue;
            }

            let characteristics = self.compute_cluster_characteristics(cluster)?;

            let quality_score = self.compute_quality_score(cluster, &characteristics);

            if quality_score < self.config.min_quality {
                continue;
            }

            let pattern_type = self.classify_pattern_type(cluster, &characteristics);

            let description = if self.config.verbose {
                self.generate_detailed_description(cluster, &characteristics, &pattern_type)
            } else {
                self.generate_simple_description(cluster, &pattern_type)
            };

            let temporal_range = self.compute_temporal_range(cluster);

            let pattern = ExtractedPattern {
                id: format!("pattern_{}", cluster_idx),
                cluster_id: cluster_idx,
                description,
                characteristics,
                quality_score,
                pattern_type,
                variables: variable_names.to_vec(),
                temporal_range,
            };

            patterns.push(pattern);
        }

        // Also extract noise patterns (anomalies)
        let noise_patterns = self.extract_noise_patterns(labels, variable_names)?;
        patterns.extend(noise_patterns);

        Ok(patterns)
    }

    /// Compute cluster characteristics
    fn compute_cluster_characteristics(&self, cluster: &Cluster) -> Result<ClusterCharacteristics> {
        if cluster.points.is_empty() {
            anyhow::bail!("Cannot compute characteristics for empty cluster");
        }

        // Size
        let size = cluster.points.len();

        // Centroid (already computed)
        let centroid = cluster.centroid.clone();

        // Density
        let density = cluster.density;

        // Variance (average squared distance from centroid)
        let variance = if size > 1 {
            cluster
                .points
                .iter()
                .map(|p| {
                    p.features
                        .iter()
                        .zip(&centroid)
                        .map(|(&x, &c)| (x - c).powi(2))
                        .sum::<f64>()
                })
                .sum::<f64>()
                / size as f64
        } else {
            0.0
        };

        // Compactness (inverse of variance, normalized)
        let compactness = if variance > 0.0 {
            1.0 / (1.0 + variance)
        } else {
            1.0
        };

        // Time span
        let time_span = if size > 1 {
            let min_time = cluster
                .points
                .iter()
                .map(|p| p.timestamp)
                .fold(f64::INFINITY, f64::min);
            let max_time = cluster
                .points
                .iter()
                .map(|p| p.timestamp)
                .fold(f64::NEG_INFINITY, f64::max);
            max_time - min_time
        } else {
            0.0
        };

        Ok(ClusterCharacteristics {
            size,
            centroid,
            density,
            variance,
            compactness,
            time_span,
        })
    }

    /// Compute quality score for a cluster
    fn compute_quality_score(
        &self,
        cluster: &Cluster,
        characteristics: &ClusterCharacteristics,
    ) -> f64 {
        // Quality factors:
        // 1. Size (more points = better, up to a threshold)
        let size_score = (cluster.points.len() as f64).ln() / 10.0;
        let size_score = size_score.clamp(0.0, 1.0);

        // 2. Density (higher density = better)
        let density_score = characteristics.density.clamp(0.0, 1.0);

        // 3. Compactness (higher compactness = better)
        let compactness_score = characteristics.compactness;

        // 4. Stability (lower variance = better)
        let stability_score = 1.0 / (1.0 + characteristics.variance);

        // Weighted combination
        0.3 * size_score + 0.3 * density_score + 0.2 * compactness_score + 0.2 * stability_score
    }

    /// Classify pattern type
    fn classify_pattern_type(
        &self,
        cluster: &Cluster,
        characteristics: &ClusterCharacteristics,
    ) -> PatternType {
        // Check for temporal pattern
        if characteristics.time_span > cluster.points.len() as f64 * 0.5 {
            // Cluster spans significant time

            // Check for trend
            let first_point = &cluster.points[0];
            let last_point = &cluster.points[cluster.points.len() - 1];

            if !first_point.features.is_empty() && !last_point.features.is_empty() {
                let trend = last_point.features[0] - first_point.features[0];

                if trend.abs() > 0.1 {
                    return PatternType::Temporal {
                        pattern: if trend > 0.0 {
                            "increasing_trend".to_string()
                        } else {
                            "decreasing_trend".to_string()
                        },
                    };
                }
            }

            return PatternType::Temporal {
                pattern: "temporal_pattern".to_string(),
            };
        }

        // Check for stable pattern
        if characteristics.compactness > 0.8 && characteristics.variance < 0.5 {
            return PatternType::Stable {
                consistency: characteristics.compactness,
            };
        }

        // Default to unknown
        PatternType::Unknown
    }

    /// Generate detailed description
    fn generate_detailed_description(
        &self,
        cluster: &Cluster,
        characteristics: &ClusterCharacteristics,
        pattern_type: &PatternType,
    ) -> String {
        let mut desc = String::new();

        desc.push_str(&format!(
            "Cluster {} contains {} points with density {:.2}. ",
            cluster.id, characteristics.size, characteristics.density
        ));

        desc.push_str(&format!(
            "Centroid: {:?}, Variance: {:.2}, Compactness: {:.2}. ",
            characteristics.centroid, characteristics.variance, characteristics.compactness
        ));

        match pattern_type {
            PatternType::Temporal { pattern } => {
                desc.push_str(&format!("Pattern type: Temporal ({})", pattern));
            }
            PatternType::Anomaly { severity } => {
                desc.push_str(&format!("Pattern type: Anomaly (severity: {})", severity));
            }
            PatternType::Stable { consistency } => {
                desc.push_str(&format!(
                    "Pattern type: Stable (consistency: {:.2})",
                    consistency
                ));
            }
            PatternType::Transition { from, to } => {
                desc.push_str(&format!("Pattern type: Transition ({} -> {})", from, to));
            }
            PatternType::Unknown => {
                desc.push_str("Pattern type: Unknown");
            }
        }

        desc
    }

    /// Generate simple description
    fn generate_simple_description(&self, cluster: &Cluster, pattern_type: &PatternType) -> String {
        match pattern_type {
            PatternType::Temporal { pattern } => {
                format!(
                    "Temporal pattern: {} ({} points)",
                    pattern,
                    cluster.points.len()
                )
            }
            PatternType::Anomaly { severity } => {
                format!(
                    "Anomaly detected: {} ({} points)",
                    severity,
                    cluster.points.len()
                )
            }
            PatternType::Stable { consistency } => {
                format!(
                    "Stable pattern: {:.2}% consistency ({} points)",
                    consistency * 100.0,
                    cluster.points.len()
                )
            }
            PatternType::Transition { from, to } => {
                format!(
                    "Transition: {} -> {} ({} points)",
                    from,
                    to,
                    cluster.points.len()
                )
            }
            PatternType::Unknown => {
                format!(
                    "Cluster {} with {} points",
                    cluster.id,
                    cluster.points.len()
                )
            }
        }
    }

    /// Compute temporal range of a cluster
    fn compute_temporal_range(&self, cluster: &Cluster) -> (usize, usize) {
        if cluster.points.is_empty() {
            return (0, 0);
        }

        let min_idx = cluster.points.iter().map(|p| p.id).min().unwrap_or(0);
        let max_idx = cluster.points.iter().map(|p| p.id).max().unwrap_or(0);

        (min_idx, max_idx)
    }

    /// Extract noise patterns (anomalies)
    fn extract_noise_patterns(
        &self,
        labels: &[ClusterLabel],
        variable_names: &[String],
    ) -> Result<Vec<ExtractedPattern>> {
        let mut noise_indices = Vec::new();

        for (i, label) in labels.iter().enumerate() {
            if matches!(label, ClusterLabel::Noise) {
                noise_indices.push(i);
            }
        }

        if noise_indices.is_empty() {
            return Ok(Vec::new());
        }

        // Create anomaly pattern
        let pattern = ExtractedPattern {
            id: "anomaly_pattern".to_string(),
            cluster_id: usize::MAX,
            description: format!(
                "Detected {} anomaly points across {} variables",
                noise_indices.len(),
                variable_names.len()
            ),
            characteristics: ClusterCharacteristics {
                size: noise_indices.len(),
                centroid: vec![0.0], // No meaningful centroid for noise
                density: 0.0,
                variance: f64::INFINITY,
                compactness: 0.0,
                time_span: 0.0,
            },
            quality_score: 0.5,
            pattern_type: PatternType::Anomaly {
                severity: if noise_indices.len() > 5 {
                    "high".to_string()
                } else if noise_indices.len() > 2 {
                    "medium".to_string()
                } else {
                    "low".to_string()
                },
            },
            variables: variable_names.to_vec(),
            temporal_range: (
                *noise_indices.first().unwrap_or(&0),
                *noise_indices.last().unwrap_or(&0),
            ),
        };

        Ok(vec![pattern])
    }

    /// Filter patterns by quality threshold
    pub fn filter_by_quality(&self, patterns: &[ExtractedPattern]) -> Vec<ExtractedPattern> {
        patterns
            .iter()
            .filter(|p| p.quality_score >= self.config.min_quality)
            .cloned()
            .collect()
    }

    /// Get pattern statistics
    pub fn get_pattern_stats(&self, patterns: &[ExtractedPattern]) -> HashMap<String, f64> {
        let mut stats = HashMap::new();

        stats.insert("total_patterns".to_string(), patterns.len() as f64);

        let temporal_count = patterns
            .iter()
            .filter(|p| matches!(p.pattern_type, PatternType::Temporal { .. }))
            .count();
        stats.insert("temporal_patterns".to_string(), temporal_count as f64);

        let anomaly_count = patterns
            .iter()
            .filter(|p| matches!(p.pattern_type, PatternType::Anomaly { .. }))
            .count();
        stats.insert("anomaly_patterns".to_string(), anomaly_count as f64);

        let stable_count = patterns
            .iter()
            .filter(|p| matches!(p.pattern_type, PatternType::Stable { .. }))
            .count();
        stats.insert("stable_patterns".to_string(), stable_count as f64);

        let avg_quality = if patterns.is_empty() {
            0.0
        } else {
            patterns.iter().map(|p| p.quality_score).sum::<f64>() / patterns.len() as f64
        };
        stats.insert("average_quality".to_string(), avg_quality);

        stats
    }
}

#[cfg(test)]
mod tests;