aidaemon-memory 0.29.0

Swappable long-term memory for aidaemon agents: the MemoryStore traits plus SQLite and embedding implementations
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
//! Which active facts carry the same knowledge, and which copy keeps it.
//!
//! Two rules, both pure so the maintenance pass and `db_probe`'s dry run
//! agree on every pair:
//!
//! - A restatement ([`facts_are_restatements`]): one category, near-identical
//!   text that makes one claim.
//! - One value ([`facts_hold_one_value`]): the same normalized value under
//!   reworded keys, in any category. Extractors file one fact under
//!   `project` and `technical` alike, and reword its key every time.
//!
//! Similarity alone never decides: above 0.93 there are pairs with different
//! values (two expiry dates), and between 0.85 and 0.93 duplicates mix with
//! distinct facts. Both rules need the values to agree first.

use super::facts::{
    canonicalize_fact_key, fact_category_is_personal, facts_are_restatements,
    keys_name_distinct_concepts,
};

/// Full-fact similarity at which a value of two or more words, identical
/// under another key, is the same fact. Measured on a live store of 4,747
/// facts: from here up pairs are reworded keys for one value; below it
/// different things start to share a value (two sites on one platform).
pub const ONE_VALUE_MIN_SIMILARITY: f32 = 0.80;

/// The same for a one-word value (`ddev`, `Rust`), which also needs a key
/// word in common: one word is shared by many unrelated attributes.
pub const ONE_WORD_VALUE_MIN_SIMILARITY: f32 = 0.85;

/// A value that says nothing on its own: a boolean, a bare number, a null.
fn is_bare_scalar(normalized: &str) -> bool {
    matches!(
        normalized,
        "true" | "false" | "yes" | "no" | "none" | "null" | "n a" | "unknown"
    ) || normalized
        .split(' ')
        .all(|word| word.chars().all(|c| c.is_ascii_digit()))
}

/// Whether two active facts hold one piece of knowledge under different
/// keys: the same normalized value, similar enough as whole facts, and, when
/// either is about a person, keys naming the same attribute (`pet_name` and
/// `daughter_name` are both `Mia`, `birth_place` and `hometown` one city).
pub fn facts_hold_one_value(
    (category_a, key_a, value_a): (&str, &str, &str),
    (category_b, key_b, value_b): (&str, &str, &str),
    similarity: f32,
) -> bool {
    let value = crate::text::normalize_fact_value(value_a);
    if value.is_empty() || value != crate::text::normalize_fact_value(value_b) {
        return false;
    }
    if is_bare_scalar(&value) {
        return false;
    }
    let canonical_a = canonicalize_fact_key(key_a);
    let canonical_b = canonicalize_fact_key(key_b);
    let tokens_a: std::collections::HashSet<&str> =
        canonical_a.split('_').filter(|t| !t.is_empty()).collect();
    let tokens_b: std::collections::HashSet<&str> =
        canonical_b.split('_').filter(|t| !t.is_empty()).collect();
    let share_a_word = tokens_a.intersection(&tokens_b).next().is_some();
    let threshold = if value.contains(' ') {
        ONE_VALUE_MIN_SIMILARITY
    } else {
        if !share_a_word {
            return false;
        }
        ONE_WORD_VALUE_MIN_SIMILARITY
    };
    if similarity < threshold {
        return false;
    }
    if fact_category_is_personal(category_a) || fact_category_is_personal(category_b) {
        return canonical_a == canonical_b
            || share_a_word && !keys_name_distinct_concepts(&tokens_a, &tokens_b);
    }
    true
}

/// Who can see a fact, as far as merging copies of it goes. Two facts in one
/// class are visible to exactly the same audiences, so one can stand in for
/// the other without hiding or widening anything.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum FoldScope {
    /// Only the owner, in their own private or internal turns: a `private`
    /// fact (never shown anywhere else, `memory_visible`), or a `channel`
    /// fact from an app conversation (`app:` channel), which is the owner's
    /// own and has no other audience.
    OwnerPrivate,
    /// A `global` fact; its channel never changes who sees it.
    Global,
    /// A `channel` fact from a platform channel or group: visible to that
    /// channel's members, so it stays per channel.
    Channel(Option<String>),
}

/// The channel id prefix of the owner's app conversations (machine format:
/// the session id the app writes, `app:<conversation>`).
const APP_CHANNEL_PREFIX: &str = "app:";

/// Whether a stored channel id is one of the owner's app conversations.
pub fn is_owner_app_channel(channel_id: Option<&str>) -> bool {
    channel_id.is_some_and(|channel| channel.starts_with(APP_CHANNEL_PREFIX))
}

/// The visibility class of a fact stored with `privacy` and `channel_id`.
/// Every merge of facts (fold, write-time restatement, numeric conflict)
/// compares this, never the raw columns: an owner DM's `private` fact and
/// the same fact from an app conversation are one audience, while a group
/// channel never merges with either.
pub fn fold_scope_key(privacy: &str, channel_id: Option<&str>) -> FoldScope {
    let privacy = privacy.trim();
    if privacy.eq_ignore_ascii_case("private")
        || privacy.eq_ignore_ascii_case("channel") && is_owner_app_channel(channel_id)
    {
        FoldScope::OwnerPrivate
    } else if privacy.eq_ignore_ascii_case("global") {
        FoldScope::Global
    } else {
        FoldScope::Channel(channel_id.map(str::to_string))
    }
}

impl FoldScope {
    /// Whether a fact in `self` can keep the knowledge of a fact in `folded`
    /// without hiding it from anyone who could see it: the same class, or a
    /// folded fact only the owner could see (the owner's private turns see
    /// every scope). Never the reverse, so folding never narrows a fact.
    pub fn can_keep(&self, folded: &FoldScope) -> bool {
        self == folded || *folded == FoldScope::OwnerPrivate
    }
}

/// An active fact as the fold planner sees it.
#[derive(Debug, Clone)]
pub struct FoldCandidate {
    pub id: i64,
    pub category: String,
    pub key: String,
    pub value: String,
    /// [`super::facts::fact_source_rank`]: stated by the owner (2) is never
    /// folded away; a closer source is kept over a farther one.
    pub source_rank: u8,
    /// Pinned in owner DMs (`user`, `preference`...): kept over a copy in an
    /// unpinned category, so folding never unpins the knowledge.
    pub pinned: bool,
    pub recall_count: i64,
    pub privacy: String,
    pub channel_id: Option<String>,
    pub vector: Vec<f32>,
}

/// Which rule found a fold.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum FoldRule {
    Restatement,
    OneValue,
}

/// One fact to retire into the fact that keeps its knowledge.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct PlannedFold {
    pub folded: i64,
    pub kept: i64,
    pub rule: FoldRule,
    pub similarity: f32,
}

/// Plan every fold in `candidates`.
///
/// Star clustering in authority order: closest source (owner-stated, then
/// quoted, then inferred), then pinned, then most recalled, then oldest (its key is the one in use). Each fact folds into
/// the first kept fact it matches; no chaining, so a cluster never drifts
/// from its representative. Facts fold only within one [`fold_scope_key`]
/// class: folding a group channel's fact into a private one hides it, the
/// reverse widens it, while a private fact and an app conversation's fact
/// have one audience. Vectors of different lengths (another embedding model)
/// never compare.
pub fn plan_folds(candidates: &mut [FoldCandidate]) -> Vec<PlannedFold> {
    candidates.sort_by(|a, b| {
        b.source_rank
            .cmp(&a.source_rank)
            .then(b.pinned.cmp(&a.pinned))
            .then(b.recall_count.cmp(&a.recall_count))
            .then(a.id.cmp(&b.id))
    });
    // Candidates are compared only within a bucket that can match: a
    // restatement needs the category, one value needs the value.
    let mut kept_by_category: std::collections::HashMap<String, Vec<usize>> =
        std::collections::HashMap::new();
    let mut kept_by_value: std::collections::HashMap<String, Vec<usize>> =
        std::collections::HashMap::new();
    let mut folds = Vec::new();
    for index in 0..candidates.len() {
        let candidate = &candidates[index];
        let category = candidate.category.trim().to_ascii_lowercase();
        let value = crate::text::normalize_fact_value(&candidate.value);
        let scope = fold_scope_key(&candidate.privacy, candidate.channel_id.as_deref());
        let same_scope = |other: &FoldCandidate| {
            fold_scope_key(&other.privacy, other.channel_id.as_deref()) == scope
        };
        let restated = kept_by_category
            .get(&category)
            .into_iter()
            .flatten()
            .find_map(|&kept| {
                let rep = &candidates[kept];
                if !same_scope(rep) {
                    return None;
                }
                let similarity = crate::cosine(&candidate.vector, &rep.vector);
                facts_are_restatements(
                    &candidate.category,
                    (&candidate.key, &candidate.value),
                    (&rep.key, &rep.value),
                    similarity,
                )
                .then_some((kept, FoldRule::Restatement, similarity))
            });
        let matched = restated.or_else(|| {
            kept_by_value
                .get(&value)
                .into_iter()
                .flatten()
                .find_map(|&kept| {
                    let rep = &candidates[kept];
                    if !same_scope(rep) {
                        return None;
                    }
                    let similarity = crate::cosine(&candidate.vector, &rep.vector);
                    facts_hold_one_value(
                        (&candidate.category, &candidate.key, &candidate.value),
                        (&rep.category, &rep.key, &rep.value),
                        similarity,
                    )
                    .then_some((kept, FoldRule::OneValue, similarity))
                })
        });
        match matched {
            Some((kept, rule, similarity)) if candidate.source_rank < 2 => {
                folds.push(PlannedFold {
                    folded: candidate.id,
                    kept: candidates[kept].id,
                    rule,
                    similarity,
                });
            }
            _ => {
                kept_by_category.entry(category).or_default().push(index);
                if !value.is_empty() {
                    kept_by_value.entry(value).or_default().push(index);
                }
            }
        }
    }
    folds
}

/// Minimum full-fact similarity to flag two active facts as a probable
/// conceptual duplicate/overlap for UI review when they did not auto-fold
/// (e.g. different value shapes, different ranks, or cross-scope owner DMs).
pub const OVERLAP_REVIEW_MIN_SIMILARITY: f32 = 0.78;

/// Identify active facts that look like conceptual duplicates or overlaps of
/// another active fact so the Memory UI can highlight them for review without
/// mutating or losing distinct constraints automatically.
///
/// Returns `lower_priority_id -> representative_id` (authority order: highest
/// `source_rank`, then pinned, then most recalled, then oldest id).
pub fn detect_overlaps(candidates: &mut [FoldCandidate]) -> std::collections::HashMap<i64, i64> {
    detect_overlaps_excluding(candidates, &std::collections::HashSet::new())
}

/// The canonical form of an unordered fact pair: `(smaller id, larger id)`.
pub fn overlap_pair(a: i64, b: i64) -> (i64, i64) {
    (a.min(b), a.max(b))
}

/// [`detect_overlaps`], never pairing two facts in `distinct` (pairs in
/// [`overlap_pair`] form a reviewer judged distinct). A fact whose only
/// match was such a pair is checked against the next representative, so a
/// verdict on one pair never hides a different duplicate.
pub fn detect_overlaps_excluding(
    candidates: &mut [FoldCandidate],
    distinct: &std::collections::HashSet<(i64, i64)>,
) -> std::collections::HashMap<i64, i64> {
    use std::collections::{HashMap, HashSet};

    candidates.sort_by(|a, b| {
        b.source_rank
            .cmp(&a.source_rank)
            .then(b.pinned.cmp(&a.pinned))
            .then(b.recall_count.cmp(&a.recall_count))
            .then(a.id.cmp(&b.id))
    });

    // Every fact's normalized forms are computed once: the Memory list runs
    // this over thousands of facts, and normalizing both sides on every
    // comparison made it quadratic in string work (tens of seconds).
    let n = candidates.len();
    let cats: Vec<String> = candidates
        .iter()
        .map(|c| c.category.trim().to_ascii_lowercase())
        .collect();
    let keys: Vec<String> = candidates
        .iter()
        .map(|c| canonicalize_fact_key(&c.key))
        .collect();
    let vals: Vec<String> = candidates
        .iter()
        .map(|c| crate::text::normalize_fact_value(&c.value))
        .collect();
    let words: Vec<HashSet<&str>> = vals
        .iter()
        .map(|v| v.split_whitespace().filter(|w| w.len() >= 3).collect())
        .collect();
    // Positive owner naming facet per fact (`None` when not an owner-name fact).
    let naming: Vec<Option<String>> = candidates
        .iter()
        .zip(&cats)
        .map(|(c, cat)| {
            (crate::text::is_owner_name_key(&c.key)
                && matches!(cat.as_str(), "user" | "preference" | "personal" | "profile"))
            .then(|| crate::text::canonical_personal_key(&c.key))
        })
        .collect();
    let norms: Vec<f32> = candidates
        .iter()
        .map(|c| c.vector.iter().map(|x| x * x).sum::<f32>().sqrt())
        .collect();
    // `crate::cosine` with both norms precomputed.
    let similarity = |a: usize, b: usize| -> f32 {
        let (va, vb) = (&candidates[a].vector, &candidates[b].vector);
        if va.len() != vb.len() || va.is_empty() {
            return 0.0;
        }
        if norms[a] * norms[a] <= f32::EPSILON || norms[b] * norms[b] <= f32::EPSILON {
            return 0.0;
        }
        let dot: f32 = va.iter().zip(vb).map(|(x, y)| x * y).sum();
        dot / (norms[a] * norms[b])
    };
    let is_positive_naming = |facet: &str| {
        matches!(
            facet,
            "name" | "full_name" | "preferred_name" | "nickname" | "addressing"
        )
    };

    // Representatives, indexed by what each rule matches on. Every list is
    // in push order (ascending candidate index), so the first match found in
    // a list is that rule's earliest representative.
    let mut naming_reps: Vec<usize> = Vec::new();
    let mut reps_by_key: HashMap<&str, Vec<usize>> = HashMap::new();
    let mut reps_by_val: HashMap<&str, Vec<usize>> = HashMap::new();
    let mut reps_by_cat: HashMap<&str, Vec<usize>> = HashMap::new();
    let mut overlaps = HashMap::new();
    let allowed = |index: usize, rep: usize| {
        distinct.is_empty()
            || !distinct.contains(&overlap_pair(candidates[index].id, candidates[rep].id))
    };

    for index in 0..n {
        // The earliest representative any rule matches, as the original
        // single scan over all representatives in order found it.
        let mut best: Option<usize> = None;
        let offer = |rep: usize, best: &mut Option<usize>| {
            if best.is_none_or(|b| rep < b) {
                *best = Some(rep);
            }
        };

        // 1. Two owner-name / addressing facts (e.g. `user/preferred_name = Alice`
        // and `preference/address_as = Call the owner Alice, not Al.`) are typed
        // overlaps when they map to the same canonical naming facet or both
        // express positive owner naming/addressing (keeping `rejected_alias`
        // distinct as a separate constraint).
        if let Some(cand_facet) = &naming[index]
            && let Some(&rep) = naming_reps.iter().find(|&&rep| {
                let rep_facet = naming[rep].as_deref().unwrap_or_default();
                (cand_facet == rep_facet
                    || (is_positive_naming(cand_facet) && is_positive_naming(rep_facet)))
                    && allowed(index, rep)
            })
        {
            offer(rep, &mut best);
        }

        // 2. Same canonical key across different categories (e.g.
        // `user/preferred_name` beside `preference/preferred_name`).
        if !keys[index].is_empty()
            && let Some(&rep) = reps_by_key.get(keys[index].as_str()).and_then(|list| {
                list.iter()
                    .find(|&&rep| cats[rep] != cats[index] && allowed(index, rep))
            })
        {
            offer(rep, &mut best);
        }

        // 3. Same non-scalar normalized value across different keys or
        // scopes (cross-writer owner-DM duplicates that could not auto-fold).
        if !vals[index].is_empty()
            && !is_bare_scalar(&vals[index])
            && let Some(&rep) = reps_by_val.get(vals[index].as_str()).and_then(|list| {
                list.iter().find(|&&rep| {
                    (candidates[index].vector.is_empty()
                        || candidates[rep].vector.is_empty()
                        || similarity(index, rep) >= ONE_VALUE_MIN_SIMILARITY)
                        && allowed(index, rep)
                })
            })
        {
            offer(rep, &mut best);
        }

        // 4. High semantic similarity within the same category where
        // values share meaningful vocabulary (catches paraphrased or
        // partially overlapping rules/preferences). Only representatives
        // earlier than a match already found can change the answer.
        if !candidates[index].vector.is_empty()
            && !words[index].is_empty()
            && let Some(list) = reps_by_cat.get(cats[index].as_str())
        {
            let personal = fact_category_is_personal(&cats[index]);
            for &rep in list {
                if best.is_some_and(|b| rep >= b) {
                    break;
                }
                if candidates[rep].vector.is_empty()
                    || !allowed(index, rep)
                    || words[index].is_disjoint(&words[rep])
                    || similarity(index, rep) < OVERLAP_REVIEW_MIN_SIMILARITY
                {
                    continue;
                }
                if personal {
                    let cand_tokens: HashSet<&str> =
                        keys[index].split('_').filter(|t| !t.is_empty()).collect();
                    let rep_tokens: HashSet<&str> =
                        keys[rep].split('_').filter(|t| !t.is_empty()).collect();
                    if keys_name_distinct_concepts(&cand_tokens, &rep_tokens) {
                        continue;
                    }
                }
                offer(rep, &mut best);
                break;
            }
        }

        if let Some(rep) = best {
            overlaps.insert(candidates[index].id, candidates[rep].id);
        } else {
            if naming[index].is_some() {
                naming_reps.push(index);
            }
            reps_by_key
                .entry(keys[index].as_str())
                .or_default()
                .push(index);
            reps_by_val
                .entry(vals[index].as_str())
                .or_default()
                .push(index);
            reps_by_cat
                .entry(cats[index].as_str())
                .or_default()
                .push(index);
        }
    }
    overlaps
}

/// Whole-fact similarity at which two facts whose numbers differ are taken
/// as one attribute holding two values (`db_probe --fact-conflict-audit`
/// measured it on a live store).
pub const NUMERIC_CONFLICT_MIN_SIMILARITY: f32 = 0.90;

/// An active fact as the numeric-conflict planner sees it.
#[derive(Debug, Clone)]
pub struct ConflictCandidate {
    pub id: i64,
    pub category: String,
    pub key: String,
    pub value: String,
    /// [`super::facts::fact_source_rank`].
    pub source_rank: u8,
    /// When the knowledge was first seen (`first_seen_at`, else
    /// `updated_at`): the later of two automated values is the current one.
    pub seen: Option<chrono::DateTime<chrono::Utc>>,
    pub privacy: String,
    pub channel_id: Option<String>,
    pub vector: Vec<f32>,
}

/// A stored fact timestamp (`first_seen_at`, `updated_at`) as
/// [`ConflictCandidate::seen`] reads it: RFC 3339, or SQLite's
/// `datetime('now')` form.
pub fn parse_fact_timestamp(raw: &str) -> Option<chrono::DateTime<chrono::Utc>> {
    crate::types::parse_ts(raw)
}

/// The tokens of a value that carry a digit (`0.9.10`, `8080`, `2026`),
/// lowercased: the part of a value an embedding barely sees.
pub fn value_numbers(value: &str) -> std::collections::BTreeSet<String> {
    value
        .split(|c: char| !c.is_alphanumeric())
        .filter(|token| token.chars().any(|c| c.is_ascii_digit()))
        .map(str::to_lowercase)
        .collect()
}

/// What to do with one conflicting pair.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ConflictVerdict {
    /// `kept` holds the current value; `retired` is replaced by it.
    Resolved { kept: i64, retired: i64 },
    /// Both were stated by the owner: only the owner can say which holds.
    BothOwnerStated,
    /// The keys may name two attributes (`version` / `previous_version`):
    /// both kept, listed for review.
    DistinctAttributes,
}

/// Two active facts that look like one attribute with two values.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct NumericConflict {
    pub a: i64,
    pub b: i64,
    pub similarity: f32,
    pub verdict: ConflictVerdict,
}

/// Every pair of `candidates` that may be one attribute with two values:
/// one [`fold_scope_key`] class, not `behavior` (left to
/// `--retire-inferred-behavior`), different numbers, and whole-fact
/// similarity of at least [`NUMERIC_CONFLICT_MIN_SIMILARITY`].
///
/// The verdict never lets a farther source retire a closer one: an
/// owner-stated fact beats an automated one; two automated facts are
/// resolved only when their keys name the same attribute, the closer source
/// winning, then the one seen later (then the later row). Two owner-stated
/// facts, or keys that may name two attributes, are left for review.
/// Sorted by similarity, highest first.
pub fn plan_numeric_conflicts(candidates: &[ConflictCandidate]) -> Vec<NumericConflict> {
    use std::collections::HashMap;
    let mut by_scope: HashMap<FoldScope, Vec<usize>> = HashMap::new();
    for (index, candidate) in candidates.iter().enumerate() {
        if candidate.category.trim().eq_ignore_ascii_case("behavior") || candidate.vector.is_empty()
        {
            continue;
        }
        by_scope
            .entry(fold_scope_key(
                &candidate.privacy,
                candidate.channel_id.as_deref(),
            ))
            .or_default()
            .push(index);
    }
    let numbers: Vec<_> = candidates.iter().map(|c| value_numbers(&c.value)).collect();
    let mut conflicts = Vec::new();
    for members in by_scope.values() {
        for (position, &i) in members.iter().enumerate() {
            // Both sides must actually state numbers, otherwise a numberless
            // summary ("Uses Python") could retire a specific version ("Uses Python 3.12").
            if numbers[i].is_empty() {
                continue;
            }
            for &j in &members[position + 1..] {
                if numbers[j].is_empty() || numbers[i] == numbers[j] {
                    continue;
                }
                let (a, b) = (&candidates[i], &candidates[j]);
                if !a.category.trim().eq_ignore_ascii_case(b.category.trim()) {
                    continue;
                }
                if a.vector.len() != b.vector.len() {
                    continue;
                }
                let similarity = crate::cosine(&a.vector, &b.vector);
                if similarity < NUMERIC_CONFLICT_MIN_SIMILARITY {
                    continue;
                }
                conflicts.push(NumericConflict {
                    a: a.id.min(b.id),
                    b: a.id.max(b.id),
                    similarity,
                    verdict: numeric_conflict_verdict(a, b),
                });
            }
        }
    }
    conflicts.sort_by(|x, y| {
        y.similarity
            .total_cmp(&x.similarity)
            .then(x.a.cmp(&y.a))
            .then(x.b.cmp(&y.b))
    });
    conflicts
}

fn numeric_conflict_verdict(a: &ConflictCandidate, b: &ConflictCandidate) -> ConflictVerdict {
    if !super::facts::keys_name_same_attribute(&a.key, &b.key) {
        return ConflictVerdict::DistinctAttributes;
    }
    let resolved =
        |kept: &ConflictCandidate, retired: &ConflictCandidate| ConflictVerdict::Resolved {
            kept: kept.id,
            retired: retired.id,
        };
    match (a.source_rank >= 2, b.source_rank >= 2) {
        (true, true) => ConflictVerdict::BothOwnerStated,
        (true, false) => resolved(a, b),
        (false, true) => resolved(b, a),
        (false, false) => {
            let a_wins = a
                .source_rank
                .cmp(&b.source_rank)
                .then(a.seen.cmp(&b.seen))
                .then(a.id.cmp(&b.id))
                .is_gt();
            if a_wins {
                resolved(a, b)
            } else {
                resolved(b, a)
            }
        }
    }
}

/// The retirements the resolved conflicts call for, as `(retired, kept)`:
/// most similar pair first, each fact retired at most once, and no fact
/// both kept and retired in one pass, so nothing is retired into a row that
/// is itself going away (a chain resolves over later passes).
pub fn numeric_conflict_retirements(conflicts: &[NumericConflict]) -> Vec<(i64, i64)> {
    let mut retired = std::collections::HashSet::new();
    let mut keepers = std::collections::HashSet::new();
    let mut out = Vec::new();
    for conflict in conflicts {
        let ConflictVerdict::Resolved {
            kept,
            retired: loser,
        } = conflict.verdict
        else {
            continue;
        };
        // A chain (`a` into `b`, `b` into `c`) waits for the next pass.
        if retired.contains(&kept) || retired.contains(&loser) || keepers.contains(&loser) {
            continue;
        }
        retired.insert(loser);
        keepers.insert(kept);
        out.push((loser, kept));
    }
    out
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn one_value_under_reworded_keys_is_one_fact() {
        let a = ("project", "local_sites_directory", "~/projects/");
        assert!(facts_hold_one_value(
            a,
            ("technical", "projects_directory", "~/projects"),
            0.86
        ));
        assert!(facts_hold_one_value(
            ("technical", "local_dev_tool", "ddev"),
            ("project", "local_dev_tooling", "DDEV"),
            0.878
        ));
    }

    #[test]
    fn a_shared_value_alone_is_not_one_fact() {
        // Too dissimilar as whole facts.
        assert!(!facts_hold_one_value(
            ("project", "cars_site_platform", "Cloudflare Workers"),
            ("project", "store_deployment_target", "Cloudflare Workers"),
            0.75
        ));
        // One word, no key word in common.
        assert!(!facts_hold_one_value(
            ("project", "development_platform", "Drupal"),
            ("project", "framework", "Drupal"),
            0.9
        ));
        // Booleans and numbers say nothing on their own.
        assert!(!facts_hold_one_value(
            ("project", "tests_enabled", "true"),
            ("project", "tests_passing", "true"),
            0.99
        ));
        // Values differ.
        assert!(!facts_hold_one_value(
            ("project", "version", "0.9.10"),
            ("project", "current_version", "0.9.17"),
            0.95
        ));
    }

    #[test]
    fn people_keys_must_name_the_same_attribute() {
        assert!(!facts_hold_one_value(
            ("user", "pet_name", "Mia"),
            ("user", "daughter_name", "Mia"),
            0.9
        ));
        assert!(!facts_hold_one_value(
            ("user", "birth_place", "Quito, Ecuador"),
            ("user", "hometown", "Quito, Ecuador"),
            0.9
        ));
        assert!(facts_hold_one_value(
            ("user", "favorite_food", "sushi"),
            ("user", "food", "sushi"),
            0.9
        ));
    }

    fn candidate(id: i64, category: &str, key: &str, value: &str) -> FoldCandidate {
        FoldCandidate {
            id,
            category: category.into(),
            key: key.into(),
            value: value.into(),
            source_rank: 0,
            pinned: false,
            recall_count: 0,
            privacy: "channel".into(),
            channel_id: None,
            vector: vec![1.0, 0.0],
        }
    }

    #[test]
    fn the_owner_copy_then_the_pinned_one_survives() {
        let mut candidates = vec![
            candidate(1, "project", "editor_choice", "Helix editor"),
            FoldCandidate {
                pinned: true,
                ..candidate(2, "preference", "preferred_editor", "Helix editor")
            },
            FoldCandidate {
                source_rank: 2,
                ..candidate(3, "technical", "editor", "helix editor")
            },
        ];
        let folds = plan_folds(&mut candidates);
        assert_eq!(folds.len(), 2);
        assert!(folds.iter().all(|fold| fold.kept == 3));

        let mut candidates = vec![
            FoldCandidate {
                recall_count: 50,
                ..candidate(1, "project", "editor_choice", "Helix editor")
            },
            FoldCandidate {
                pinned: true,
                ..candidate(2, "preference", "preferred_editor", "Helix editor")
            },
        ];
        assert_eq!(plan_folds(&mut candidates)[0].kept, 2);
    }

    #[test]
    fn scope_and_owner_statements_are_never_folded_away() {
        let mut candidates = vec![
            candidate(1, "project", "sites_dir", "~/projects"),
            FoldCandidate {
                privacy: "private".into(),
                ..candidate(2, "technical", "sites_directory", "~/projects")
            },
            FoldCandidate {
                channel_id: Some("slack:synthetic-team".into()),
                ..candidate(3, "technical", "sites_directory", "~/projects")
            },
        ];
        assert!(plan_folds(&mut candidates).is_empty());

        let mut candidates = vec![
            FoldCandidate {
                source_rank: 2,
                ..candidate(1, "project", "sites_dir", "~/projects")
            },
            FoldCandidate {
                source_rank: 2,
                ..candidate(2, "technical", "sites_directory", "~/projects")
            },
        ];
        assert!(plan_folds(&mut candidates).is_empty());
    }

    #[test]
    fn other_embedding_models_never_compare() {
        let mut candidates = vec![
            candidate(1, "project", "sites_dir", "~/projects"),
            FoldCandidate {
                vector: vec![1.0, 0.0, 0.0],
                ..candidate(2, "technical", "sites_directory", "~/projects")
            },
        ];
        assert!(plan_folds(&mut candidates).is_empty());
    }

    #[test]
    fn detect_overlaps_flags_owner_name_and_addressing_duplicates() {
        let mut candidates = vec![
            FoldCandidate {
                source_rank: 2,
                pinned: true,
                ..candidate(-2_000_000_001, "user", "preferred_name", "Alice")
            },
            FoldCandidate {
                source_rank: 0,
                pinned: false,
                ..candidate(
                    42,
                    "preference",
                    "address_as",
                    "Call the owner Alice. Don't call her Ally or Al.",
                )
            },
            FoldCandidate {
                source_rank: 2,
                pinned: false,
                vector: vec![0.0, 1.0],
                ..candidate(43, "preference", "favorite_dish", "ramen")
            },
        ];
        let overlaps = detect_overlaps(&mut candidates);
        assert_eq!(overlaps.get(&42), Some(&-2_000_000_001));
        assert!(!overlaps.contains_key(&43));
    }

    #[test]
    fn fold_scope_groups_owner_only_facts() {
        assert_eq!(fold_scope_key("private", None), FoldScope::OwnerPrivate);
        assert_eq!(
            fold_scope_key("Private", Some("telegram:synthetic-user-1")),
            FoldScope::OwnerPrivate
        );
        assert_eq!(
            fold_scope_key("channel", Some("app:synthetic-conv-1")),
            FoldScope::OwnerPrivate
        );
        assert_eq!(fold_scope_key("global", Some("app:x")), FoldScope::Global);
        assert_eq!(fold_scope_key("global", None), FoldScope::Global);
        assert_eq!(
            fold_scope_key("channel", Some("slack:synthetic-team")),
            FoldScope::Channel(Some("slack:synthetic-team".into()))
        );
        // The prefix is a machine format: compared exactly.
        assert_eq!(
            fold_scope_key("channel", Some("APP:x")),
            FoldScope::Channel(Some("APP:x".into()))
        );
        assert_eq!(fold_scope_key("channel", None), FoldScope::Channel(None));
        // Folding never hides knowledge from an audience that saw it.
        let group = FoldScope::Channel(Some("slack:synthetic-team".into()));
        assert!(FoldScope::Global.can_keep(&FoldScope::OwnerPrivate));
        assert!(group.can_keep(&FoldScope::OwnerPrivate));
        assert!(!FoldScope::OwnerPrivate.can_keep(&FoldScope::Global));
        assert!(!FoldScope::OwnerPrivate.can_keep(&group));
        assert!(!FoldScope::Global.can_keep(&group));
    }

    fn scoped(id: i64, key: &str, privacy: &str, channel: Option<&str>) -> FoldCandidate {
        FoldCandidate {
            privacy: privacy.into(),
            channel_id: channel.map(str::to_string),
            ..candidate(id, "technical", key, "~/projects")
        }
    }

    #[test]
    fn owner_only_scopes_fold_together_and_never_with_shared_ones() {
        let mut candidates = vec![
            scoped(1, "sites_dir", "channel", Some("app:synthetic-conv-1")),
            scoped(
                2,
                "sites_directory",
                "channel",
                Some("app:synthetic-conv-2"),
            ),
            scoped(3, "projects_dir", "private", None),
        ];
        let folds = plan_folds(&mut candidates);
        assert_eq!(folds.len(), 2);
        assert!(folds.iter().all(|fold| fold.kept == 1));

        let mut candidates = vec![
            scoped(1, "sites_dir", "private", None),
            scoped(2, "sites_directory", "global", None),
            scoped(3, "projects_dir", "channel", Some("slack:synthetic-team")),
            scoped(4, "project_root", "channel", Some("discord:ch:synthetic-1")),
        ];
        assert!(plan_folds(&mut candidates).is_empty());
    }

    fn conflict(
        id: i64,
        key: &str,
        value: &str,
        source_rank: u8,
        seen_days_ago: i64,
        vector: Vec<f32>,
    ) -> ConflictCandidate {
        ConflictCandidate {
            id,
            category: "project".into(),
            key: key.into(),
            value: value.into(),
            source_rank,
            seen: Some(chrono::Utc::now() - chrono::Duration::days(seen_days_ago)),
            privacy: "private".into(),
            channel_id: None,
            vector,
        }
    }

    #[test]
    fn numeric_conflict_verdicts_follow_source_then_recency() {
        let near = vec![0.95, 0.312];
        let base = vec![1.0, 0.0];
        let pair = |a: ConflictCandidate, b: ConflictCandidate| {
            let conflicts = plan_numeric_conflicts(&[a, b]);
            assert_eq!(conflicts.len(), 1);
            conflicts[0].verdict
        };
        // Owner beats inferred on the same attribute, however old.
        assert_eq!(
            pair(
                conflict(1, "api_port", "8080", 2, 90, base.clone()),
                conflict(2, "default_api_port", "9090", 0, 0, near.clone()),
            ),
            ConflictVerdict::Resolved {
                kept: 1,
                retired: 2
            }
        );
        // Owner never retires an automated fact naming a distinct attribute
        // (e.g. two different people's birthdays or two different ports).
        assert_eq!(
            pair(
                conflict(1, "mia_birthday", "2015-03-15", 2, 90, base.clone()),
                conflict(2, "zoe_birthday", "2018-07-22", 0, 0, near.clone()),
            ),
            ConflictVerdict::DistinctAttributes
        );
        // A numberless summary never conflicts with a specific version.
        assert!(
            plan_numeric_conflicts(&[
                conflict(1, "python", "Uses Python", 2, 1, base.clone()),
                conflict(2, "current_python", "Uses Python 3.12", 0, 2, near.clone()),
            ])
            .is_empty()
        );
        // Same attribute: newer wins between equals, a quote beats an inference.
        assert_eq!(
            pair(
                conflict(1, "node_version", "18", 0, 30, base.clone()),
                conflict(2, "current_node_version", "20", 0, 1, near.clone()),
            ),
            ConflictVerdict::Resolved {
                kept: 2,
                retired: 1
            }
        );
        assert_eq!(
            pair(
                conflict(1, "node_version", "18", 1, 30, base.clone()),
                conflict(2, "current_node_version", "20", 0, 1, near.clone()),
            ),
            ConflictVerdict::Resolved {
                kept: 1,
                retired: 2
            }
        );
        assert_eq!(
            pair(
                conflict(1, "release_version", "1.2", 0, 30, base.clone()),
                conflict(2, "build_version", "3.4", 0, 1, near.clone()),
            ),
            ConflictVerdict::DistinctAttributes
        );
        assert_eq!(
            pair(
                conflict(1, "deadline", "day 12", 2, 30, base.clone()),
                conflict(2, "deadline", "day 14", 2, 1, near.clone()),
            ),
            ConflictVerdict::BothOwnerStated
        );
        // Same numbers, low similarity, behavior, or another scope: no pair.
        let none = |a: ConflictCandidate, b: ConflictCandidate| {
            assert!(plan_numeric_conflicts(&[a, b]).is_empty());
        };
        none(
            conflict(1, "port", "8080", 0, 1, base.clone()),
            conflict(2, "port_number", "port 8080", 0, 2, near.clone()),
        );
        none(
            conflict(1, "port", "8080", 0, 1, base.clone()),
            conflict(2, "port_number", "9090", 0, 2, vec![0.8, 0.6]),
        );
        none(
            ConflictCandidate {
                category: "behavior".into(),
                ..conflict(1, "port", "8080", 0, 1, base.clone())
            },
            conflict(2, "port_number", "9090", 0, 2, near.clone()),
        );
        none(
            ConflictCandidate {
                privacy: "global".into(),
                ..conflict(1, "port", "8080", 0, 1, base.clone())
            },
            conflict(2, "port_number", "9090", 0, 2, near.clone()),
        );
    }

    #[test]
    fn numeric_retirements_never_chain_in_one_pass() {
        let resolved = |kept: i64, retired: i64, similarity: f32| NumericConflict {
            a: kept.min(retired),
            b: kept.max(retired),
            similarity,
            verdict: ConflictVerdict::Resolved { kept, retired },
        };
        let conflicts = vec![
            resolved(2, 1, 0.99),
            // 2 was kept above: not retired in the same pass.
            resolved(3, 2, 0.98),
            // 1 is already retired.
            resolved(4, 1, 0.97),
            NumericConflict {
                a: 5,
                b: 6,
                similarity: 0.96,
                verdict: ConflictVerdict::BothOwnerStated,
            },
            resolved(7, 8, 0.95),
        ];
        assert_eq!(
            numeric_conflict_retirements(&conflicts),
            vec![(1, 2), (8, 7)]
        );
    }

    #[test]
    fn a_distinct_pair_falls_through_to_the_next_representative() {
        let value = "dark theme in every editor";
        let mut candidates = vec![
            FoldCandidate {
                recall_count: 9,
                ..candidate(1, "preference", "theme", value)
            },
            FoldCandidate {
                recall_count: 5,
                ..candidate(2, "technical", "editor_theme", value)
            },
            candidate(3, "project", "ide_theme", value),
        ];
        let all = detect_overlaps(&mut candidates.clone());
        assert_eq!(all.get(&3), Some(&1));
        assert_eq!(all.get(&2), Some(&1));
        // 1 and 3 judged distinct: 3 has no other representative.
        let distinct = [overlap_pair(3, 1)].into_iter().collect();
        let reviewed = detect_overlaps_excluding(&mut candidates.clone(), &distinct);
        assert_eq!(reviewed.get(&3), None);
        assert_eq!(reviewed.get(&2), Some(&1));
        // 2 judged distinct from 1 too: 2 represents, and 3 pairs with it.
        let distinct = [overlap_pair(3, 1), overlap_pair(1, 2)]
            .into_iter()
            .collect();
        let reviewed = detect_overlaps_excluding(&mut candidates, &distinct);
        assert_eq!(reviewed.get(&2), None);
        assert_eq!(reviewed.get(&3), Some(&2));
    }
}