microscope-memory 1.2.0

Pure binary cognitive memory engine with REST API bridge for LLM integration. Zero-JSON core, mmap-based, hierarchical, sub-microsecond search.
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
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
//! Pattern Recognition — minta felismerő és tanuló rendszer a Microscope Memory számára
//!
//! Képes:
//! - Szekvenciális minták detektálására (gyakori gondolatmenetek)
//! - Temporális mintákra (napi ritmusok, ciklikus aktivitás)
//! - Strukturális motívumokra (architektúra gráfokban)
//! - Cluster mintákra (memória térbeli csoportosulások)
//! - Cross-domain korrelációra (minták átfedése különböző rétegek között)
//!
//! Kapcsolódások:
//! - morphogenesis.rs → strukturális motívum detektálás
//! - temporal_archetype.rs → időbeli mintázatok
//! - thought_graph.rs → gondolatmenet minták
//! - hebbian.rs → ko-aktivációs minták
//! - archetype.rs → kikristályosodott minták
//! - heuristic_decision.rs → minta-alapú döntéshozatal

use std::collections::{HashMap, HashSet, VecDeque};
use std::sync::{Arc, RwLock};
use std::time::{SystemTime, UNIX_EPOCH};
// ─── Alap Típusok ───────────────────────────────────────────────────────────

/// Minta típusok
#[derive(Debug, Clone, PartialEq, Hash)]
pub enum PatternType {
    /// Ismétlődő szekvencia (gondolatmenet, műveleti sor)
    Sequence,
    /// Időbeli ritmus (napi, heti ciklus)
    Temporal,
    /// Strukturális motívum (algráf minta)
    Structural,
    /// Térbeli klaszter (memória csoportosulás)
    Cluster,
    /// Több domainen átívelő minta
    CrossDomain,
    /// Ismeretlen / egyedi
    Unknown,
}

/// Minta jelentőség
#[derive(Debug, Clone)]
pub struct PatternSignificance {
    /// 0.0 - 1.0: mennyire biztos a minta
    pub confidence: f64,
    /// Hányszor detektáltuk
    pub frequency: u64,
    /// Utolsó egyezés időbélyege (unix ms)
    pub last_matched_ms: u64,
    /// Átlagos hasonlóság az egyezéseknél
    pub avg_similarity: f64,
    /// Tanulási ráta (mennyire adaptálódik új adathoz)
    pub learning_rate: f64,
}

impl Default for PatternSignificance {
    fn default() -> Self {
        Self {
            confidence: 0.1,
            frequency: 0,
            last_matched_ms: 0,
            avg_similarity: 0.0,
            learning_rate: 0.3,
        }
    }
}

/// Felismert minta sablon
#[derive(Debug, Clone)]
pub struct RecognizedPattern {
    pub id: u64,
    pub name: String,
    pub pattern_type: PatternType,
    /// Sablon adat (típustól függő)
    pub template: PatternTemplate,
    pub significance: PatternSignificance,
    pub tags: Vec<String>,
    /// Domain ahonnan származik (pl. "thought", "architecture", "memory")
    pub domain: String,
    pub metadata: HashMap<String, String>,
}

/// Minta sablon adat
#[derive(Debug, Clone)]
pub enum PatternTemplate {
    /// Szekvencia: elemek sorozata (pl. block id-k)
    Sequence(Vec<String>),
    /// Temporális: {id, hour, day_of_week, frequency}
    Temporal(Vec<TemporalSlice>),
    /// Strukturális: adjacency list minta
    Structural(Vec<(String, String, f64)>),
    /// Cluster: középpont + sugár + elemek
    Cluster {
        center: (f64, f64, f64),
        radius: f64,
        elements: Vec<String>,
    },
    /// Minták kombinációja
    Composite(Vec<u64>),
}

/// Időbeli szelet
#[derive(Debug, Clone)]
pub struct TemporalSlice {
    pub hour: u8,
    pub day_of_week: u8,
    pub frequency: f64,
    pub avg_intensity: f64,
    pub activity_ids: Vec<String>,
}

/// Minta egyezés eredménye
#[derive(Debug, Clone)]
pub struct PatternMatch {
    pub pattern_id: u64,
    pub target_description: String,
    pub similarity: f64,
    pub timestamp_ms: u64,
    pub matched_elements: Vec<String>,
    pub details: String,
}

/// Konfigurációs paraméterek
#[derive(Debug, Clone)]
pub struct RecognitionConfig {
    /// Minimális hasonlóság az egyezéshez (0.0 - 1.0)
    pub min_similarity: f64,
    /// Minimális confidence az új minta elfogadásához
    pub min_confidence: f64,
    /// Hány találat után tekintünk egy mintát "megerősítettnek"
    pub confirmation_threshold: u64,
    /// Maximális minta szám a könyvtárban
    pub max_patterns: usize,
    /// Cluster távolság küszöb
    pub cluster_radius: f64,
    /// Szekvencia ablak méret
    pub sequence_window: usize,
    /// Tanulási ráta (0.0 - 1.0)
    pub learning_rate: f64,
}

impl Default for RecognitionConfig {
    fn default() -> Self {
        Self {
            min_similarity: 0.6,
            min_confidence: 0.3,
            confirmation_threshold: 3,
            max_patterns: 1000,
            cluster_radius: 0.15,
            sequence_window: 10,
            learning_rate: 0.3,
        }
    }
}
// ─── Pattern Recognizer ──────────────────────────────────────────────────────

/// A fő minta felismerő rendszer
pub struct PatternRecognizer {
    /// Felismert minták könyvtára
    patterns: Arc<RwLock<Vec<RecognizedPattern>>>,
    /// Egyezési előzmények
    match_history: Arc<RwLock<VecDeque<PatternMatch>>>,
    /// Konfiguráció
    config: Arc<RwLock<RecognitionConfig>>,
    /// Következő ID
    next_id: Arc<RwLock<u64>>,
    /// Domain index (pattern_id → domain)
    domain_index: Arc<RwLock<HashMap<String, Vec<u64>>>>,
}

impl Default for PatternRecognizer {
    fn default() -> Self {
        Self::new()
    }
}

impl PatternRecognizer {
    pub fn new() -> Self {
        Self {
            patterns: Arc::new(RwLock::new(Vec::new())),
            match_history: Arc::new(RwLock::new(VecDeque::with_capacity(1000))),
            config: Arc::new(RwLock::new(RecognitionConfig::default())),
            next_id: Arc::new(RwLock::new(1)),
            domain_index: Arc::new(RwLock::new(HashMap::new())),
        }
    }

    pub fn with_config(config: RecognitionConfig) -> Self {
        Self {
            config: Arc::new(RwLock::new(config)),
            ..Self::new()
        }
    }

    fn next_id(&self) -> u64 {
        let mut id = crate::sync_guard::write_lock(&self.next_id);
        let n = *id;
        *id += 1;
        n
    }

    fn now_ms(&self) -> u64 {
        SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap_or_default()
            .as_millis() as u64
    }

    // ─── Pattern Register ─────────────────────────────────────────────────

    /// Új minta regisztrálása
    pub fn register_pattern(
        &self,
        name: &str,
        ptype: PatternType,
        template: PatternTemplate,
        domain: &str,
        tags: Vec<String>,
    ) -> u64 {
        let id = self.next_id();
        let pattern = RecognizedPattern {
            id,
            name: name.to_string(),
            pattern_type: ptype,
            template,
            significance: PatternSignificance::default(),
            tags,
            domain: domain.to_string(),
            metadata: HashMap::new(),
        };

        crate::sync_guard::write_lock(&self.patterns).push(pattern);
        crate::sync_guard::write_lock(&self.domain_index)
            .entry(domain.to_string())
            .or_default()
            .push(id);

        id
    }

    /// Minta törlése
    pub fn forget_pattern(&self, id: u64) -> bool {
        let mut patterns = crate::sync_guard::write_lock(&self.patterns);
        if let Some(pos) = patterns.iter().position(|p| p.id == id) {
            let p = patterns.remove(pos);
            if let Some(ids) = crate::sync_guard::write_lock(&self.domain_index).get_mut(&p.domain)
            {
                ids.retain(|&i| i != id);
            }
            true
        } else {
            false
        }
    }

    /// Minták listázása típus szerint
    pub fn list_patterns(
        &self,
        ptype: Option<PatternType>,
        domain: Option<&str>,
    ) -> Vec<RecognizedPattern> {
        crate::sync_guard::read_lock(&self.patterns)
            .iter()
            .filter(|p| {
                let type_match = ptype.as_ref().is_none_or(|t| p.pattern_type == *t);
                let domain_match = domain.is_none_or(|d| p.domain == d);
                type_match && domain_match
            })
            .cloned()
            .collect()
    }

    /// Minta keresés név alapján
    pub fn find_pattern(&self, name: &str) -> Option<RecognizedPattern> {
        crate::sync_guard::read_lock(&self.patterns)
            .iter()
            .find(|p| p.name == name)
            .cloned()
    }

    /// Minta lekérése ID alapján
    pub fn get_pattern(&self, id: u64) -> Option<RecognizedPattern> {
        crate::sync_guard::read_lock(&self.patterns)
            .iter()
            .find(|p| p.id == id)
            .cloned()
    }

    // ─── Szekvencia Detektálás ─────────────────────────────────────────────

    /// Szekvencia minta felismerés: gyakori részsorozatok keresése
    /// Bemenet: elemek sorozata (pl. block id-k, műveletek, események)
    /// Kimenet: ismétlődő minták confidenciával
    pub fn find_sequences(&self, elements: &[String], domain: &str) -> Vec<RecognizedPattern> {
        let config = crate::sync_guard::read_lock(&self.config).clone();
        let window = config.sequence_window;
        let min_sim = config.min_similarity;
        let mut patterns = Vec::new();

        if elements.len() < 2 {
            return patterns;
        }

        // Gyakori 2-3-4 hosszúságú részsorozatok
        let mut seq_counts: HashMap<Vec<String>, u64> = HashMap::new();

        for len in 2..=window.min(elements.len()).min(5) {
            for i in 0..=elements.len().saturating_sub(len) {
                let subseq: Vec<String> = elements[i..i + len].to_vec();
                *seq_counts.entry(subseq).or_insert(0) += 1;
            }
        }

        // Statisztikai szűrés
        let total = elements.len() as f64;
        for (seq, count) in &seq_counts {
            let freq = *count as f64 / total;
            if freq >= min_sim && seq.len() >= 2 {
                let confidence = (freq * (1.0 - 1.0 / (seq.len() as f64))).min(1.0);

                let pattern = RecognizedPattern {
                    id: self.next_id(),
                    name: format!("seq_{}_{}", domain, seq.first().unwrap_or(&"?".to_string())),
                    pattern_type: PatternType::Sequence,
                    template: PatternTemplate::Sequence(seq.clone()),
                    significance: PatternSignificance {
                        confidence,
                        frequency: *count,
                        last_matched_ms: self.now_ms(),
                        avg_similarity: freq,
                        learning_rate: config.learning_rate,
                    },
                    tags: vec!["auto_detected".to_string(), format!("len_{}", seq.len())],
                    domain: domain.to_string(),
                    metadata: {
                        let mut m = HashMap::new();
                        m.insert("frequency".to_string(), format!("{:.2}", freq));
                        m.insert("sample_count".to_string(), count.to_string());
                        m
                    },
                };

                // Ellenőrizzük, hogy már létezik-e hasonló
                let exists = crate::sync_guard::read_lock(&self.patterns)
                    .iter()
                    .any(|p| {
                        if let PatternTemplate::Sequence(ref existing) = p.template {
                            existing == seq
                        } else {
                            false
                        }
                    });

                if !exists {
                    let id = pattern.id;
                    crate::sync_guard::write_lock(&self.patterns).push(pattern.clone());
                    crate::sync_guard::write_lock(&self.domain_index)
                        .entry(domain.to_string())
                        .or_default()
                        .push(id);
                }

                patterns.push(pattern);
            }
        }

        patterns.sort_by(|a, b| {
            b.significance
                .confidence
                .partial_cmp(&a.significance.confidence)
                .unwrap()
        });
        patterns
    }

    /// Adott szekvencia egyeztetése ismert mintákkal
    pub fn match_sequence(&self, sequence: &[String]) -> Vec<PatternMatch> {
        let config = crate::sync_guard::read_lock(&self.config).clone();
        let mut matches = Vec::new();
        let now = self.now_ms();

        for pattern in crate::sync_guard::read_lock(&self.patterns).iter() {
            if let PatternTemplate::Sequence(ref pattern_seq) = pattern.template {
                // Részsorozat keresés (pattern hosszabb lehet)
                if pattern_seq.len() > sequence.len() {
                    continue;
                }

                for i in 0..=sequence.len().saturating_sub(pattern_seq.len()) {
                    let window = &sequence[i..i + pattern_seq.len()];
                    let sim = self.sequence_similarity(window, pattern_seq);

                    if sim >= config.min_similarity {
                        matches.push(PatternMatch {
                            pattern_id: pattern.id,
                            target_description: format!(
                                "{:?}..{:?}",
                                window.first().unwrap_or(&"".to_string()),
                                window.last().unwrap_or(&"".to_string())
                            ),
                            similarity: sim,
                            timestamp_ms: now,
                            matched_elements: window.to_vec(),
                            details: format!(
                                "Matched sequence pattern '{}' ({})",
                                pattern.name, pattern.domain
                            ),
                        });

                        // Frissítés: frequency növelés
                        if let Some(p) = crate::sync_guard::write_lock(&self.patterns)
                            .iter_mut()
                            .find(|p| p.id == pattern.id)
                        {
                            p.significance.frequency += 1;
                            p.significance.last_matched_ms = now;
                            p.significance.avg_similarity =
                                p.significance.avg_similarity * 0.7 + sim * 0.3;
                            p.significance.confidence = (p.significance.confidence + 0.05).min(1.0);
                        }
                    }
                }
            }
        }

        crate::sync_guard::write_lock(&self.match_history).extend(matches.clone());
        matches
    }

    /// Két szekvencia hasonlósága (Levenshtein normalizált)
    fn sequence_similarity(&self, a: &[String], b: &[String]) -> f64 {
        if a.is_empty() && b.is_empty() {
            return 1.0;
        }
        if a.is_empty() || b.is_empty() {
            return 0.0;
        }

        let max_len = a.len().max(b.len()) as f64;
        let mut matches = 0u64;

        for i in 0..a.len().min(b.len()) {
            if a[i] == b[i] {
                matches += 1;
            }
        }

        matches as f64 / max_len
    }

    // ─── Temporális Minta Detektálás ───────────────────────────────────────

    /// Temporális minták keresése időbélyeges eseményekből
    /// Bemenet: {timestamp_ms, id, intensity} triplek
    /// Kimenet: napi/heti ritmusok
    pub fn find_temporal_patterns(
        &self,
        events: &[(u64, String, f64)],
        domain: &str,
    ) -> Vec<RecognizedPattern> {
        if events.is_empty() {
            return Vec::new();
        }
        let config = crate::sync_guard::read_lock(&self.config).clone();
        let mut patterns = Vec::new();

        // Csoportosítás óra × nap szerint
        let mut hourly: HashMap<(u8, u8), Vec<f64>> = HashMap::new(); // (hour, day) → intensities

        for (ts, _id, intensity) in events {
            let secs = *ts / 1000;
            let hour = ((secs / 3600) % 24) as u8;
            let day = ((secs / 86400) % 7) as u8;
            hourly.entry((hour, day)).or_default().push(*intensity);
        }

        // Mintázatok keresése
        // 1. Csúcsidők (magas aktivitású órák)
        let mut peak_hours: Vec<(u8, u8, f64)> = hourly
            .iter()
            .map(|((h, d), intensities)| {
                let avg: f64 = intensities.iter().sum::<f64>() / intensities.len() as f64;
                (*h, *d, avg)
            })
            .filter(|(_, _, avg)| *avg > 0.5)
            .collect();

        peak_hours.sort_by(|a, b| b.2.total_cmp(&a.2));

        if !peak_hours.is_empty() {
            let slices: Vec<TemporalSlice> = peak_hours
                .iter()
                .map(|(h, d, avg)| TemporalSlice {
                    hour: *h,
                    day_of_week: *d,
                    frequency: 1.0,
                    avg_intensity: *avg,
                    activity_ids: Vec::new(),
                })
                .collect();

            let confidence = (peak_hours.len() as f64 / 24.0).min(1.0) * 0.5;

            let pattern = RecognizedPattern {
                id: self.next_id(),
                name: format!("temporal_peak_{}", domain),
                pattern_type: PatternType::Temporal,
                template: PatternTemplate::Temporal(slices),
                significance: PatternSignificance {
                    confidence,
                    frequency: events.len() as u64,
                    last_matched_ms: self.now_ms(),
                    avg_similarity: confidence,
                    learning_rate: config.learning_rate,
                },
                tags: vec!["auto_detected".to_string(), "peak_hours".to_string()],
                domain: domain.to_string(),
                metadata: {
                    let mut m = HashMap::new();
                    m.insert("peak_count".to_string(), peak_hours.len().to_string());
                    m
                },
            };

            let id = pattern.id;
            crate::sync_guard::write_lock(&self.patterns).push(pattern.clone());
            crate::sync_guard::write_lock(&self.domain_index)
                .entry(domain.to_string())
                .or_default()
                .push(id);

            patterns.push(pattern);
        }

        // 2. Napi ritmus (reggel/délután/este aktivitás)
        let day_parts: [(&str, u8, u8); 4] = [
            ("reggel", 6, 12),
            ("delutan", 12, 18),
            ("este", 18, 23),
            ("hajnal", 0, 6),
        ];

        for (part_name, start_h, end_h) in &day_parts {
            let count: usize = hourly
                .iter()
                .filter(|((h, _), _)| *h >= *start_h && *h <= *end_h)
                .map(|(_, v)| v.len())
                .sum();

            if count > 0 {
                let total_events: usize = events.len();
                let ratio = count as f64 / total_events as f64;
                if ratio > 0.4 {
                    let slices: Vec<TemporalSlice> = hourly
                        .iter()
                        .filter(|((h, _), _)| *h >= *start_h && *h <= *end_h)
                        .map(|((h, d), intensities)| {
                            let avg = intensities.iter().sum::<f64>() / intensities.len() as f64;
                            TemporalSlice {
                                hour: *h,
                                day_of_week: *d,
                                frequency: intensities.len() as f64,
                                avg_intensity: avg,
                                activity_ids: Vec::new(),
                            }
                        })
                        .collect();

                    let pattern = RecognizedPattern {
                        id: self.next_id(),
                        name: format!("{}_{}", part_name, domain),
                        pattern_type: PatternType::Temporal,
                        template: PatternTemplate::Temporal(slices),
                        significance: PatternSignificance {
                            confidence: ratio * 0.6,
                            frequency: count as u64,
                            last_matched_ms: self.now_ms(),
                            avg_similarity: ratio,
                            learning_rate: config.learning_rate,
                        },
                        tags: vec!["auto_detected".to_string(), "daily_rhythm".to_string()],
                        domain: domain.to_string(),
                        metadata: HashMap::new(),
                    };

                    let id = pattern.id;
                    crate::sync_guard::write_lock(&self.patterns).push(pattern.clone());
                    crate::sync_guard::write_lock(&self.domain_index)
                        .entry(domain.to_string())
                        .or_default()
                        .push(id);

                    patterns.push(pattern);
                }
            }
        }

        patterns
    }
    // ─── Strukturális Motívum Detektálás ──────────────────────────────────

    /// Strukturális motívumok keresése gráfban (pl. morphogenesis által növesztett architektúrákban)
    /// Bemenet: adjacencia lista (from, to, weight)
    /// Kimenet: gyakori algráf minták (motívumok)
    pub fn find_motifs(
        &self,
        edges: &[(String, String, f64)],
        domain: &str,
    ) -> Vec<RecognizedPattern> {
        let config = crate::sync_guard::read_lock(&self.config).clone();
        let mut patterns = Vec::new();

        if edges.is_empty() {
            return patterns;
        }

        // Gyakori 2-3-4 node-os algráfok (motívumok)
        // 1. Fan-out: egy node → több node
        let mut fan_out: HashMap<String, Vec<String>> = HashMap::new();
        for (from, to, _) in edges {
            fan_out.entry(from.clone()).or_default().push(to.clone());
        }

        for (node, targets) in &fan_out {
            if targets.len() >= 3 {
                let mut motif_edges: Vec<(String, String, f64)> = Vec::new();
                for t in targets {
                    motif_edges.push((node.clone(), t.clone(), 1.0));
                }

                let confidence = (targets.len() as f64 / 10.0).min(1.0);
                let pattern = RecognizedPattern {
                    id: self.next_id(),
                    name: format!("fan_out_{}", node),
                    pattern_type: PatternType::Structural,
                    template: PatternTemplate::Structural(motif_edges),
                    significance: PatternSignificance {
                        confidence: confidence * 0.5,
                        frequency: targets.len() as u64,
                        last_matched_ms: self.now_ms(),
                        avg_similarity: confidence,
                        learning_rate: config.learning_rate,
                    },
                    tags: vec!["auto_detected".to_string(), "fan_out".to_string()],
                    domain: domain.to_string(),
                    metadata: {
                        let mut m = HashMap::new();
                        m.insert("node_count".to_string(), (targets.len() + 1).to_string());
                        m
                    },
                };

                let id = pattern.id;
                crate::sync_guard::write_lock(&self.patterns).push(pattern.clone());
                crate::sync_guard::write_lock(&self.domain_index)
                    .entry(domain.to_string())
                    .or_default()
                    .push(id);
                patterns.push(pattern);
            }
        }

        // 2. Fan-in: több node → egy node
        let mut fan_in: HashMap<String, Vec<String>> = HashMap::new();
        for (from, to, _) in edges {
            fan_in.entry(to.clone()).or_default().push(from.clone());
        }

        for (node, sources) in &fan_in {
            if sources.len() >= 3 {
                let mut motif_edges: Vec<(String, String, f64)> = Vec::new();
                for s in sources {
                    motif_edges.push((s.clone(), node.clone(), 1.0));
                }

                let pattern = RecognizedPattern {
                    id: self.next_id(),
                    name: format!("fan_in_{}", node),
                    pattern_type: PatternType::Structural,
                    template: PatternTemplate::Structural(motif_edges),
                    significance: PatternSignificance {
                        confidence: (sources.len() as f64 / 10.0).min(1.0) * 0.5,
                        frequency: sources.len() as u64,
                        last_matched_ms: self.now_ms(),
                        avg_similarity: 0.0,
                        learning_rate: config.learning_rate,
                    },
                    tags: vec!["auto_detected".to_string(), "fan_in".to_string()],
                    domain: domain.to_string(),
                    metadata: HashMap::new(),
                };

                let id = pattern.id;
                crate::sync_guard::write_lock(&self.patterns).push(pattern.clone());
                crate::sync_guard::write_lock(&self.domain_index)
                    .entry(domain.to_string())
                    .or_default()
                    .push(id);
                patterns.push(pattern);
            }
        }

        // 3. Hub: magas fokszámú node-ok
        let mut degrees: HashMap<String, usize> = HashMap::new();
        for (from, to, _) in edges {
            *degrees.entry(from.clone()).or_insert(0) += 1;
            *degrees.entry(to.clone()).or_insert(0) += 1;
        }

        let avg_degree = degrees.values().sum::<usize>() as f64 / degrees.len().max(1) as f64;
        for (node, degree) in &degrees {
            if *degree as f64 > avg_degree * 2.0 && *degree >= 4 {
                let pattern = RecognizedPattern {
                    id: self.next_id(),
                    name: format!("hub_{}", node),
                    pattern_type: PatternType::Structural,
                    template: PatternTemplate::Structural(vec![(
                        node.clone(),
                        "__hub__".to_string(),
                        *degree as f64,
                    )]),
                    significance: PatternSignificance {
                        confidence: (*degree as f64 / 20.0).min(1.0) * 0.4,
                        frequency: *degree as u64,
                        last_matched_ms: self.now_ms(),
                        avg_similarity: 0.0,
                        learning_rate: config.learning_rate,
                    },
                    tags: vec!["auto_detected".to_string(), "hub".to_string()],
                    domain: domain.to_string(),
                    metadata: {
                        let mut m = HashMap::new();
                        m.insert("degree".to_string(), degree.to_string());
                        m.insert("avg_degree".to_string(), format!("{:.1}", avg_degree));
                        m
                    },
                };

                let id = pattern.id;
                crate::sync_guard::write_lock(&self.patterns).push(pattern.clone());
                crate::sync_guard::write_lock(&self.domain_index)
                    .entry(domain.to_string())
                    .or_default()
                    .push(id);
                patterns.push(pattern);
            }
        }

        patterns
    }

    /// Strukturális motívum keresés morphogenesis organizmusokban
    pub fn find_motifs_in_organism(
        &self,
        _nodes: &[crate::morphogenesis::MorphNode],
        connections: &[crate::morphogenesis::MorphConnection],
    ) -> Vec<RecognizedPattern> {
        let edges: Vec<(String, String, f64)> = connections
            .iter()
            .filter(|c| c.is_active)
            .map(|c| (c.from_node.to_string(), c.to_node.to_string(), c.weight))
            .collect();

        self.find_motifs(&edges, "morphogenesis")
    }

    // ─── Cluster Detektálás ────────────────────────────────────────────────

    /// Térbeli klaszterek keresése pontfelhőben (DBSCAN-szerű)
    /// Bemenet: (x, y, z) koordináták + id
    /// Kimenet: csoportosulások a memória térben
    pub fn find_clusters(
        &self,
        points: &[(f64, f64, f64, String)],
        domain: &str,
    ) -> Vec<RecognizedPattern> {
        let config = crate::sync_guard::read_lock(&self.config).clone();
        let mut patterns = Vec::new();

        if points.is_empty() {
            return patterns;
        }

        let eps = config.cluster_radius;
        let min_pts = 3;
        let mut visited: HashSet<usize> = HashSet::new();
        let mut clusters: Vec<Vec<usize>> = Vec::new();

        for i in 0..points.len() {
            if visited.contains(&i) {
                continue;
            }

            let mut neighbors: Vec<usize> = points
                .iter()
                .enumerate()
                .filter(|(j, _)| {
                    let dist = ((points[i].0 - points[*j].0).powi(2)
                        + (points[i].1 - points[*j].1).powi(2)
                        + (points[i].2 - points[*j].2).powi(2))
                    .sqrt();
                    dist <= eps
                })
                .map(|(j, _)| j)
                .collect();

            if neighbors.len() < min_pts {
                visited.insert(i);
                continue; // noise
            }

            // Cluster kiterjesztése
            let mut cluster: Vec<usize> = Vec::new();
            while let Some(seed) = neighbors.pop() {
                if visited.contains(&seed) {
                    continue;
                }
                visited.insert(seed);
                cluster.push(seed);

                let seed_neighbors: Vec<usize> = points
                    .iter()
                    .enumerate()
                    .filter(|(j, _)| !visited.contains(j))
                    .filter(|(j, _)| {
                        let dist = ((points[seed].0 - points[*j].0).powi(2)
                            + (points[seed].1 - points[*j].1).powi(2)
                            + (points[seed].2 - points[*j].2).powi(2))
                        .sqrt();
                        dist <= eps
                    })
                    .map(|(j, _)| j)
                    .collect();

                neighbors.extend(seed_neighbors);
            }

            if cluster.len() >= min_pts {
                clusters.push(cluster);
            }
        }

        // Cluster minták létrehozása
        for (ci, cluster) in clusters.iter().enumerate() {
            let cluster_points: Vec<&(f64, f64, f64, String)> =
                cluster.iter().map(|&i| &points[i]).collect();

            // Középpont
            let cx = cluster_points.iter().map(|p| p.0).sum::<f64>() / cluster_points.len() as f64;
            let cy = cluster_points.iter().map(|p| p.1).sum::<f64>() / cluster_points.len() as f64;
            let cz = cluster_points.iter().map(|p| p.2).sum::<f64>() / cluster_points.len() as f64;

            // Átlagos távolság a középponttól
            let avg_dist: f64 = cluster_points
                .iter()
                .map(|p| ((p.0 - cx).powi(2) + (p.1 - cy).powi(2) + (p.2 - cz).powi(2)).sqrt())
                .sum::<f64>()
                / cluster_points.len() as f64;

            let element_ids: Vec<String> = cluster_points.iter().map(|p| p.3.clone()).collect();
            let density =
                cluster.len() as f64 / (avg_dist * avg_dist * 4.0 * std::f64::consts::PI).max(0.01);

            let pattern = RecognizedPattern {
                id: self.next_id(),
                name: format!("cluster_{}_{}", domain, ci),
                pattern_type: PatternType::Cluster,
                template: PatternTemplate::Cluster {
                    center: (cx, cy, cz),
                    radius: avg_dist,
                    elements: element_ids.clone(),
                },
                significance: PatternSignificance {
                    confidence: (density / 100.0).min(1.0),
                    frequency: element_ids.len() as u64,
                    last_matched_ms: self.now_ms(),
                    avg_similarity: 1.0 - (avg_dist / 1.0).min(1.0),
                    learning_rate: config.learning_rate,
                },
                tags: vec!["auto_detected".to_string(), "cluster".to_string()],
                domain: domain.to_string(),
                metadata: {
                    let mut m = HashMap::new();
                    m.insert("size".to_string(), cluster.len().to_string());
                    m.insert("density".to_string(), format!("{:.3}", density));
                    m
                },
            };

            let id = pattern.id;
            crate::sync_guard::write_lock(&self.patterns).push(pattern.clone());
            crate::sync_guard::write_lock(&self.domain_index)
                .entry(domain.to_string())
                .or_default()
                .push(id);
            patterns.push(pattern);
        }

        patterns
    }
    // ─── Cross-domain Korreláció ──────────────────────────────────────────

    /// Különböző domain-ekből származó minták korrelációja
    /// Keres olyan mintákat, amelyek több domain-ben is előfordulnak
    /// (pl. ugyanaz a szekvencia megjelenik thought és recall domain-ben is)
    pub fn cross_correlate(&self) -> Vec<RecognizedPattern> {
        let config = crate::sync_guard::read_lock(&self.config).clone();
        let mut composite_patterns = Vec::new();

        let patterns = crate::sync_guard::read_lock(&self.patterns);
        let domains: Vec<String> = crate::sync_guard::read_lock(&self.domain_index)
            .keys()
            .cloned()
            .collect();

        if domains.len() < 2 {
            return Vec::new();
        }

        // Domain párok keresése, ahol hasonló minták vannak
        for i in 0..domains.len() {
            for j in (i + 1)..domains.len() {
                let d1 = &domains[i];
                let d2 = &domains[j];

                let p1: Vec<&RecognizedPattern> =
                    patterns.iter().filter(|p| p.domain == *d1).collect();
                let p2: Vec<&RecognizedPattern> =
                    patterns.iter().filter(|p| p.domain == *d2).collect();

                for pat1 in &p1 {
                    for pat2 in &p2 {
                        // Csak azonos típusú mintákat korrelálunk
                        if pat1.pattern_type != pat2.pattern_type {
                            continue;
                        }

                        let sim = match (&pat1.template, &pat2.template) {
                            (PatternTemplate::Sequence(s1), PatternTemplate::Sequence(s2)) => {
                                self.sequence_similarity(s1, s2)
                            }
                            (PatternTemplate::Structural(e1), PatternTemplate::Structural(e2)) => {
                                let common = e1.iter().filter(|e| e2.contains(e)).count();
                                let max = e1.len().max(e2.len()).max(1);
                                common as f64 / max as f64
                            }
                            _ => 0.0,
                        };

                        if sim > config.min_similarity * 1.2 {
                            // szigorúbb küszöb
                            let composite_id = self.next_id();
                            let composite = RecognizedPattern {
                                id: composite_id,
                                name: format!("cross_{}_{}", pat1.name, pat2.name),
                                pattern_type: PatternType::CrossDomain,
                                template: PatternTemplate::Composite(vec![pat1.id, pat2.id]),
                                significance: PatternSignificance {
                                    confidence: sim * 0.8,
                                    frequency: pat1.significance.frequency
                                        + pat2.significance.frequency,
                                    last_matched_ms: self.now_ms(),
                                    avg_similarity: sim,
                                    learning_rate: config.learning_rate,
                                },
                                tags: vec!["auto_detected".to_string(), "cross_domain".to_string()],
                                domain: format!("cross:{}:{}", d1, d2),
                                metadata: {
                                    let mut m = HashMap::new();
                                    m.insert("domain_a".to_string(), d1.clone());
                                    m.insert("domain_b".to_string(), d2.clone());
                                    m
                                },
                            };

                            composite_patterns.push(composite);
                        }
                    }
                }
            }
        }

        // Cross-domain minták regisztrálása
        for cp in &composite_patterns {
            let id = cp.id;
            crate::sync_guard::write_lock(&self.patterns).push(cp.clone());
            crate::sync_guard::write_lock(&self.domain_index)
                .entry(cp.domain.clone())
                .or_default()
                .push(id);
        }

        composite_patterns
    }

    // ─── Konszolidáció ─────────────────────────────────────────────────────

    /// Hasonló minták összevonása, gyenge minták elfelejtése
    pub fn consolidate(&self) -> usize {
        let config = crate::sync_guard::read_lock(&self.config).clone();
        let mut patterns = crate::sync_guard::write_lock(&self.patterns);
        let before = patterns.len();

        // 1. Alacsony confidence-ű minták eltávolítása
        patterns.retain(|p| {
            p.significance.confidence >= config.min_confidence
                || p.significance.frequency >= config.confirmation_threshold
        });

        // 2. Hasonló minták összevonása (azonos típus + magas hasonlóság)
        let mut i = 0;
        while i < patterns.len() {
            let mut j = i + 1;
            while j < patterns.len() {
                let should_merge = patterns[i].pattern_type == patterns[j].pattern_type
                    && patterns[i].domain == patterns[j].domain
                    && match (&patterns[i].template, &patterns[j].template) {
                        (PatternTemplate::Sequence(s1), PatternTemplate::Sequence(s2)) => {
                            self.sequence_similarity(s1, s2) > 0.8
                        }
                        _ => false,
                    };

                if should_merge {
                    patterns[i].significance.frequency += patterns[j].significance.frequency;
                    patterns[i].significance.confidence = patterns[i]
                        .significance
                        .confidence
                        .max(patterns[j].significance.confidence);
                    patterns.remove(j);
                } else {
                    j += 1;
                }
            }
            i += 1;
        }

        // 3. Max patterns limit
        while patterns.len() > config.max_patterns {
            // Leggyengébb eltávolítása
            let min_pos = (0..patterns.len())
                .min_by(|&a, &b| {
                    patterns[a]
                        .significance
                        .confidence
                        .partial_cmp(&patterns[b].significance.confidence)
                        .unwrap()
                })
                .unwrap_or(0);
            patterns.remove(min_pos);
        }

        before - patterns.len()
    }

    // ─── Statisztikák ──────────────────────────────────────────────────────

    /// Rendszer statisztikák
    pub fn stats(&self) -> (usize, usize, usize, f64) {
        let patterns = crate::sync_guard::read_lock(&self.patterns);

        let total = patterns.len();
        let seq_count = patterns
            .iter()
            .filter(|p| p.pattern_type == PatternType::Sequence)
            .count();
        let struct_count = patterns
            .iter()
            .filter(|p| p.pattern_type == PatternType::Structural)
            .count();
        let avg_confidence = if total > 0 {
            patterns
                .iter()
                .map(|p| p.significance.confidence)
                .sum::<f64>()
                / total as f64
        } else {
            0.0
        };

        (total, seq_count, struct_count, avg_confidence)
    }

    /// Friss egyezések lekérése
    pub fn recent_matches(&self, k: usize) -> Vec<PatternMatch> {
        crate::sync_guard::read_lock(&self.match_history)
            .iter()
            .rev()
            .take(k)
            .cloned()
            .collect()
    }

    /// Konfiguráció frissítése
    pub fn set_config(&self, config: RecognitionConfig) {
        *crate::sync_guard::write_lock(&self.config) = config;
    }

    /// Konfiguráció olvasása
    pub fn get_config(&self) -> RecognitionConfig {
        crate::sync_guard::read_lock(&self.config).clone()
    }

    /// Domain-ek listázása
    pub fn list_domains(&self) -> Vec<String> {
        crate::sync_guard::read_lock(&self.domain_index)
            .keys()
            .cloned()
            .collect()
    }

    /// Domain szerinti minta szám
    pub fn domain_pattern_count(&self, domain: &str) -> usize {
        crate::sync_guard::read_lock(&self.domain_index)
            .get(domain)
            .map(|ids| ids.len())
            .unwrap_or(0)
    }
}

// ─── Segédfüggvények ────────────────────────────────────────────────────────

/// PatternType Display
impl std::fmt::Display for PatternType {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            PatternType::Sequence => write!(f, "Sequence"),
            PatternType::Temporal => write!(f, "Temporal"),
            PatternType::Structural => write!(f, "Structural"),
            PatternType::Cluster => write!(f, "Cluster"),
            PatternType::CrossDomain => write!(f, "CrossDomain"),
            PatternType::Unknown => write!(f, "Unknown"),
        }
    }
}

impl std::fmt::Display for RecognizedPattern {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "Pattern #{} [{}] '{}' — {} ({:.1}% confidence, {} freq)",
            self.id,
            self.pattern_type,
            self.name,
            self.domain,
            self.significance.confidence * 100.0,
            self.significance.frequency
        )
    }
}