1use super::facts::{
17 canonicalize_fact_key, fact_category_is_personal, facts_are_restatements,
18 keys_name_distinct_concepts,
19};
20
21pub const ONE_VALUE_MIN_SIMILARITY: f32 = 0.80;
26
27pub const ONE_WORD_VALUE_MIN_SIMILARITY: f32 = 0.85;
30
31fn is_bare_scalar(normalized: &str) -> bool {
33 matches!(
34 normalized,
35 "true" | "false" | "yes" | "no" | "none" | "null" | "n a" | "unknown"
36 ) || normalized
37 .split(' ')
38 .all(|word| word.chars().all(|c| c.is_ascii_digit()))
39}
40
41pub fn facts_hold_one_value(
46 (category_a, key_a, value_a): (&str, &str, &str),
47 (category_b, key_b, value_b): (&str, &str, &str),
48 similarity: f32,
49) -> bool {
50 let value = crate::text::normalize_fact_value(value_a);
51 if value.is_empty() || value != crate::text::normalize_fact_value(value_b) {
52 return false;
53 }
54 if is_bare_scalar(&value) {
55 return false;
56 }
57 let canonical_a = canonicalize_fact_key(key_a);
58 let canonical_b = canonicalize_fact_key(key_b);
59 let tokens_a: std::collections::HashSet<&str> =
60 canonical_a.split('_').filter(|t| !t.is_empty()).collect();
61 let tokens_b: std::collections::HashSet<&str> =
62 canonical_b.split('_').filter(|t| !t.is_empty()).collect();
63 let share_a_word = tokens_a.intersection(&tokens_b).next().is_some();
64 let threshold = if value.contains(' ') {
65 ONE_VALUE_MIN_SIMILARITY
66 } else {
67 if !share_a_word {
68 return false;
69 }
70 ONE_WORD_VALUE_MIN_SIMILARITY
71 };
72 if similarity < threshold {
73 return false;
74 }
75 if fact_category_is_personal(category_a) || fact_category_is_personal(category_b) {
76 return canonical_a == canonical_b
77 || share_a_word && !keys_name_distinct_concepts(&tokens_a, &tokens_b);
78 }
79 true
80}
81
82#[derive(Debug, Clone, PartialEq, Eq, Hash)]
86pub enum FoldScope {
87 OwnerPrivate,
92 Global,
94 Channel(Option<String>),
97}
98
99const APP_CHANNEL_PREFIX: &str = "app:";
102
103pub fn is_owner_app_channel(channel_id: Option<&str>) -> bool {
105 channel_id.is_some_and(|channel| channel.starts_with(APP_CHANNEL_PREFIX))
106}
107
108pub fn fold_scope_key(privacy: &str, channel_id: Option<&str>) -> FoldScope {
114 let privacy = privacy.trim();
115 if privacy.eq_ignore_ascii_case("private")
116 || privacy.eq_ignore_ascii_case("channel") && is_owner_app_channel(channel_id)
117 {
118 FoldScope::OwnerPrivate
119 } else if privacy.eq_ignore_ascii_case("global") {
120 FoldScope::Global
121 } else {
122 FoldScope::Channel(channel_id.map(str::to_string))
123 }
124}
125
126impl FoldScope {
127 pub fn can_keep(&self, folded: &FoldScope) -> bool {
132 self == folded || *folded == FoldScope::OwnerPrivate
133 }
134}
135
136#[derive(Debug, Clone)]
138pub struct FoldCandidate {
139 pub id: i64,
140 pub category: String,
141 pub key: String,
142 pub value: String,
143 pub source_rank: u8,
146 pub pinned: bool,
149 pub recall_count: i64,
150 pub privacy: String,
151 pub channel_id: Option<String>,
152 pub vector: Vec<f32>,
153}
154
155#[derive(Debug, Clone, Copy, PartialEq, Eq)]
157pub enum FoldRule {
158 Restatement,
159 OneValue,
160}
161
162#[derive(Debug, Clone, Copy, PartialEq)]
164pub struct PlannedFold {
165 pub folded: i64,
166 pub kept: i64,
167 pub rule: FoldRule,
168 pub similarity: f32,
169}
170
171pub fn plan_folds(candidates: &mut [FoldCandidate]) -> Vec<PlannedFold> {
182 candidates.sort_by(|a, b| {
183 b.source_rank
184 .cmp(&a.source_rank)
185 .then(b.pinned.cmp(&a.pinned))
186 .then(b.recall_count.cmp(&a.recall_count))
187 .then(a.id.cmp(&b.id))
188 });
189 let mut kept_by_category: std::collections::HashMap<String, Vec<usize>> =
192 std::collections::HashMap::new();
193 let mut kept_by_value: std::collections::HashMap<String, Vec<usize>> =
194 std::collections::HashMap::new();
195 let mut folds = Vec::new();
196 for index in 0..candidates.len() {
197 let candidate = &candidates[index];
198 let category = candidate.category.trim().to_ascii_lowercase();
199 let value = crate::text::normalize_fact_value(&candidate.value);
200 let scope = fold_scope_key(&candidate.privacy, candidate.channel_id.as_deref());
201 let same_scope = |other: &FoldCandidate| {
202 fold_scope_key(&other.privacy, other.channel_id.as_deref()) == scope
203 };
204 let restated = kept_by_category
205 .get(&category)
206 .into_iter()
207 .flatten()
208 .find_map(|&kept| {
209 let rep = &candidates[kept];
210 if !same_scope(rep) {
211 return None;
212 }
213 let similarity = crate::cosine(&candidate.vector, &rep.vector);
214 facts_are_restatements(
215 &candidate.category,
216 (&candidate.key, &candidate.value),
217 (&rep.key, &rep.value),
218 similarity,
219 )
220 .then_some((kept, FoldRule::Restatement, similarity))
221 });
222 let matched = restated.or_else(|| {
223 kept_by_value
224 .get(&value)
225 .into_iter()
226 .flatten()
227 .find_map(|&kept| {
228 let rep = &candidates[kept];
229 if !same_scope(rep) {
230 return None;
231 }
232 let similarity = crate::cosine(&candidate.vector, &rep.vector);
233 facts_hold_one_value(
234 (&candidate.category, &candidate.key, &candidate.value),
235 (&rep.category, &rep.key, &rep.value),
236 similarity,
237 )
238 .then_some((kept, FoldRule::OneValue, similarity))
239 })
240 });
241 match matched {
242 Some((kept, rule, similarity)) if candidate.source_rank < 2 => {
243 folds.push(PlannedFold {
244 folded: candidate.id,
245 kept: candidates[kept].id,
246 rule,
247 similarity,
248 });
249 }
250 _ => {
251 kept_by_category.entry(category).or_default().push(index);
252 if !value.is_empty() {
253 kept_by_value.entry(value).or_default().push(index);
254 }
255 }
256 }
257 }
258 folds
259}
260
261pub const OVERLAP_REVIEW_MIN_SIMILARITY: f32 = 0.78;
265
266pub fn detect_overlaps(candidates: &mut [FoldCandidate]) -> std::collections::HashMap<i64, i64> {
273 detect_overlaps_excluding(candidates, &std::collections::HashSet::new())
274}
275
276pub fn overlap_pair(a: i64, b: i64) -> (i64, i64) {
278 (a.min(b), a.max(b))
279}
280
281pub fn detect_overlaps_excluding(
286 candidates: &mut [FoldCandidate],
287 distinct: &std::collections::HashSet<(i64, i64)>,
288) -> std::collections::HashMap<i64, i64> {
289 use std::collections::{HashMap, HashSet};
290
291 candidates.sort_by(|a, b| {
292 b.source_rank
293 .cmp(&a.source_rank)
294 .then(b.pinned.cmp(&a.pinned))
295 .then(b.recall_count.cmp(&a.recall_count))
296 .then(a.id.cmp(&b.id))
297 });
298
299 let n = candidates.len();
303 let cats: Vec<String> = candidates
304 .iter()
305 .map(|c| c.category.trim().to_ascii_lowercase())
306 .collect();
307 let keys: Vec<String> = candidates
308 .iter()
309 .map(|c| canonicalize_fact_key(&c.key))
310 .collect();
311 let vals: Vec<String> = candidates
312 .iter()
313 .map(|c| crate::text::normalize_fact_value(&c.value))
314 .collect();
315 let words: Vec<HashSet<&str>> = vals
316 .iter()
317 .map(|v| v.split_whitespace().filter(|w| w.len() >= 3).collect())
318 .collect();
319 let naming: Vec<Option<String>> = candidates
321 .iter()
322 .zip(&cats)
323 .map(|(c, cat)| {
324 (crate::text::is_owner_name_key(&c.key)
325 && matches!(cat.as_str(), "user" | "preference" | "personal" | "profile"))
326 .then(|| crate::text::canonical_personal_key(&c.key))
327 })
328 .collect();
329 let norms: Vec<f32> = candidates
330 .iter()
331 .map(|c| c.vector.iter().map(|x| x * x).sum::<f32>().sqrt())
332 .collect();
333 let similarity = |a: usize, b: usize| -> f32 {
335 let (va, vb) = (&candidates[a].vector, &candidates[b].vector);
336 if va.len() != vb.len() || va.is_empty() {
337 return 0.0;
338 }
339 if norms[a] * norms[a] <= f32::EPSILON || norms[b] * norms[b] <= f32::EPSILON {
340 return 0.0;
341 }
342 let dot: f32 = va.iter().zip(vb).map(|(x, y)| x * y).sum();
343 dot / (norms[a] * norms[b])
344 };
345 let is_positive_naming = |facet: &str| {
346 matches!(
347 facet,
348 "name" | "full_name" | "preferred_name" | "nickname" | "addressing"
349 )
350 };
351
352 let mut naming_reps: Vec<usize> = Vec::new();
356 let mut reps_by_key: HashMap<&str, Vec<usize>> = HashMap::new();
357 let mut reps_by_val: HashMap<&str, Vec<usize>> = HashMap::new();
358 let mut reps_by_cat: HashMap<&str, Vec<usize>> = HashMap::new();
359 let mut overlaps = HashMap::new();
360 let allowed = |index: usize, rep: usize| {
361 distinct.is_empty()
362 || !distinct.contains(&overlap_pair(candidates[index].id, candidates[rep].id))
363 };
364
365 for index in 0..n {
366 let mut best: Option<usize> = None;
369 let offer = |rep: usize, best: &mut Option<usize>| {
370 if best.is_none_or(|b| rep < b) {
371 *best = Some(rep);
372 }
373 };
374
375 if let Some(cand_facet) = &naming[index]
381 && let Some(&rep) = naming_reps.iter().find(|&&rep| {
382 let rep_facet = naming[rep].as_deref().unwrap_or_default();
383 (cand_facet == rep_facet
384 || (is_positive_naming(cand_facet) && is_positive_naming(rep_facet)))
385 && allowed(index, rep)
386 })
387 {
388 offer(rep, &mut best);
389 }
390
391 if !keys[index].is_empty()
394 && let Some(&rep) = reps_by_key.get(keys[index].as_str()).and_then(|list| {
395 list.iter()
396 .find(|&&rep| cats[rep] != cats[index] && allowed(index, rep))
397 })
398 {
399 offer(rep, &mut best);
400 }
401
402 if !vals[index].is_empty()
405 && !is_bare_scalar(&vals[index])
406 && let Some(&rep) = reps_by_val.get(vals[index].as_str()).and_then(|list| {
407 list.iter().find(|&&rep| {
408 (candidates[index].vector.is_empty()
409 || candidates[rep].vector.is_empty()
410 || similarity(index, rep) >= ONE_VALUE_MIN_SIMILARITY)
411 && allowed(index, rep)
412 })
413 })
414 {
415 offer(rep, &mut best);
416 }
417
418 if !candidates[index].vector.is_empty()
423 && !words[index].is_empty()
424 && let Some(list) = reps_by_cat.get(cats[index].as_str())
425 {
426 let personal = fact_category_is_personal(&cats[index]);
427 for &rep in list {
428 if best.is_some_and(|b| rep >= b) {
429 break;
430 }
431 if candidates[rep].vector.is_empty()
432 || !allowed(index, rep)
433 || words[index].is_disjoint(&words[rep])
434 || similarity(index, rep) < OVERLAP_REVIEW_MIN_SIMILARITY
435 {
436 continue;
437 }
438 if personal {
439 let cand_tokens: HashSet<&str> =
440 keys[index].split('_').filter(|t| !t.is_empty()).collect();
441 let rep_tokens: HashSet<&str> =
442 keys[rep].split('_').filter(|t| !t.is_empty()).collect();
443 if keys_name_distinct_concepts(&cand_tokens, &rep_tokens) {
444 continue;
445 }
446 }
447 offer(rep, &mut best);
448 break;
449 }
450 }
451
452 if let Some(rep) = best {
453 overlaps.insert(candidates[index].id, candidates[rep].id);
454 } else {
455 if naming[index].is_some() {
456 naming_reps.push(index);
457 }
458 reps_by_key
459 .entry(keys[index].as_str())
460 .or_default()
461 .push(index);
462 reps_by_val
463 .entry(vals[index].as_str())
464 .or_default()
465 .push(index);
466 reps_by_cat
467 .entry(cats[index].as_str())
468 .or_default()
469 .push(index);
470 }
471 }
472 overlaps
473}
474
475pub const NUMERIC_CONFLICT_MIN_SIMILARITY: f32 = 0.90;
479
480#[derive(Debug, Clone)]
482pub struct ConflictCandidate {
483 pub id: i64,
484 pub category: String,
485 pub key: String,
486 pub value: String,
487 pub source_rank: u8,
489 pub seen: Option<chrono::DateTime<chrono::Utc>>,
492 pub privacy: String,
493 pub channel_id: Option<String>,
494 pub vector: Vec<f32>,
495}
496
497pub fn parse_fact_timestamp(raw: &str) -> Option<chrono::DateTime<chrono::Utc>> {
501 crate::types::parse_ts(raw)
502}
503
504pub fn value_numbers(value: &str) -> std::collections::BTreeSet<String> {
507 value
508 .split(|c: char| !c.is_alphanumeric())
509 .filter(|token| token.chars().any(|c| c.is_ascii_digit()))
510 .map(str::to_lowercase)
511 .collect()
512}
513
514#[derive(Debug, Clone, Copy, PartialEq, Eq)]
516pub enum ConflictVerdict {
517 Resolved { kept: i64, retired: i64 },
519 BothOwnerStated,
521 DistinctAttributes,
524}
525
526#[derive(Debug, Clone, Copy, PartialEq)]
528pub struct NumericConflict {
529 pub a: i64,
530 pub b: i64,
531 pub similarity: f32,
532 pub verdict: ConflictVerdict,
533}
534
535pub fn plan_numeric_conflicts(candidates: &[ConflictCandidate]) -> Vec<NumericConflict> {
547 use std::collections::HashMap;
548 let mut by_scope: HashMap<FoldScope, Vec<usize>> = HashMap::new();
549 for (index, candidate) in candidates.iter().enumerate() {
550 if candidate.category.trim().eq_ignore_ascii_case("behavior") || candidate.vector.is_empty()
551 {
552 continue;
553 }
554 by_scope
555 .entry(fold_scope_key(
556 &candidate.privacy,
557 candidate.channel_id.as_deref(),
558 ))
559 .or_default()
560 .push(index);
561 }
562 let numbers: Vec<_> = candidates.iter().map(|c| value_numbers(&c.value)).collect();
563 let mut conflicts = Vec::new();
564 for members in by_scope.values() {
565 for (position, &i) in members.iter().enumerate() {
566 if numbers[i].is_empty() {
569 continue;
570 }
571 for &j in &members[position + 1..] {
572 if numbers[j].is_empty() || numbers[i] == numbers[j] {
573 continue;
574 }
575 let (a, b) = (&candidates[i], &candidates[j]);
576 if !a.category.trim().eq_ignore_ascii_case(b.category.trim()) {
577 continue;
578 }
579 if a.vector.len() != b.vector.len() {
580 continue;
581 }
582 let similarity = crate::cosine(&a.vector, &b.vector);
583 if similarity < NUMERIC_CONFLICT_MIN_SIMILARITY {
584 continue;
585 }
586 conflicts.push(NumericConflict {
587 a: a.id.min(b.id),
588 b: a.id.max(b.id),
589 similarity,
590 verdict: numeric_conflict_verdict(a, b),
591 });
592 }
593 }
594 }
595 conflicts.sort_by(|x, y| {
596 y.similarity
597 .total_cmp(&x.similarity)
598 .then(x.a.cmp(&y.a))
599 .then(x.b.cmp(&y.b))
600 });
601 conflicts
602}
603
604fn numeric_conflict_verdict(a: &ConflictCandidate, b: &ConflictCandidate) -> ConflictVerdict {
605 if !super::facts::keys_name_same_attribute(&a.key, &b.key) {
606 return ConflictVerdict::DistinctAttributes;
607 }
608 let resolved =
609 |kept: &ConflictCandidate, retired: &ConflictCandidate| ConflictVerdict::Resolved {
610 kept: kept.id,
611 retired: retired.id,
612 };
613 match (a.source_rank >= 2, b.source_rank >= 2) {
614 (true, true) => ConflictVerdict::BothOwnerStated,
615 (true, false) => resolved(a, b),
616 (false, true) => resolved(b, a),
617 (false, false) => {
618 let a_wins = a
619 .source_rank
620 .cmp(&b.source_rank)
621 .then(a.seen.cmp(&b.seen))
622 .then(a.id.cmp(&b.id))
623 .is_gt();
624 if a_wins {
625 resolved(a, b)
626 } else {
627 resolved(b, a)
628 }
629 }
630 }
631}
632
633pub fn numeric_conflict_retirements(conflicts: &[NumericConflict]) -> Vec<(i64, i64)> {
638 let mut retired = std::collections::HashSet::new();
639 let mut keepers = std::collections::HashSet::new();
640 let mut out = Vec::new();
641 for conflict in conflicts {
642 let ConflictVerdict::Resolved {
643 kept,
644 retired: loser,
645 } = conflict.verdict
646 else {
647 continue;
648 };
649 if retired.contains(&kept) || retired.contains(&loser) || keepers.contains(&loser) {
651 continue;
652 }
653 retired.insert(loser);
654 keepers.insert(kept);
655 out.push((loser, kept));
656 }
657 out
658}
659
660#[cfg(test)]
661mod tests {
662 use super::*;
663
664 #[test]
665 fn one_value_under_reworded_keys_is_one_fact() {
666 let a = ("project", "local_sites_directory", "~/projects/");
667 assert!(facts_hold_one_value(
668 a,
669 ("technical", "projects_directory", "~/projects"),
670 0.86
671 ));
672 assert!(facts_hold_one_value(
673 ("technical", "local_dev_tool", "ddev"),
674 ("project", "local_dev_tooling", "DDEV"),
675 0.878
676 ));
677 }
678
679 #[test]
680 fn a_shared_value_alone_is_not_one_fact() {
681 assert!(!facts_hold_one_value(
683 ("project", "cars_site_platform", "Cloudflare Workers"),
684 ("project", "store_deployment_target", "Cloudflare Workers"),
685 0.75
686 ));
687 assert!(!facts_hold_one_value(
689 ("project", "development_platform", "Drupal"),
690 ("project", "framework", "Drupal"),
691 0.9
692 ));
693 assert!(!facts_hold_one_value(
695 ("project", "tests_enabled", "true"),
696 ("project", "tests_passing", "true"),
697 0.99
698 ));
699 assert!(!facts_hold_one_value(
701 ("project", "version", "0.9.10"),
702 ("project", "current_version", "0.9.17"),
703 0.95
704 ));
705 }
706
707 #[test]
708 fn people_keys_must_name_the_same_attribute() {
709 assert!(!facts_hold_one_value(
710 ("user", "pet_name", "Mia"),
711 ("user", "daughter_name", "Mia"),
712 0.9
713 ));
714 assert!(!facts_hold_one_value(
715 ("user", "birth_place", "Quito, Ecuador"),
716 ("user", "hometown", "Quito, Ecuador"),
717 0.9
718 ));
719 assert!(facts_hold_one_value(
720 ("user", "favorite_food", "sushi"),
721 ("user", "food", "sushi"),
722 0.9
723 ));
724 }
725
726 fn candidate(id: i64, category: &str, key: &str, value: &str) -> FoldCandidate {
727 FoldCandidate {
728 id,
729 category: category.into(),
730 key: key.into(),
731 value: value.into(),
732 source_rank: 0,
733 pinned: false,
734 recall_count: 0,
735 privacy: "channel".into(),
736 channel_id: None,
737 vector: vec![1.0, 0.0],
738 }
739 }
740
741 #[test]
742 fn the_owner_copy_then_the_pinned_one_survives() {
743 let mut candidates = vec![
744 candidate(1, "project", "editor_choice", "Helix editor"),
745 FoldCandidate {
746 pinned: true,
747 ..candidate(2, "preference", "preferred_editor", "Helix editor")
748 },
749 FoldCandidate {
750 source_rank: 2,
751 ..candidate(3, "technical", "editor", "helix editor")
752 },
753 ];
754 let folds = plan_folds(&mut candidates);
755 assert_eq!(folds.len(), 2);
756 assert!(folds.iter().all(|fold| fold.kept == 3));
757
758 let mut candidates = vec![
759 FoldCandidate {
760 recall_count: 50,
761 ..candidate(1, "project", "editor_choice", "Helix editor")
762 },
763 FoldCandidate {
764 pinned: true,
765 ..candidate(2, "preference", "preferred_editor", "Helix editor")
766 },
767 ];
768 assert_eq!(plan_folds(&mut candidates)[0].kept, 2);
769 }
770
771 #[test]
772 fn scope_and_owner_statements_are_never_folded_away() {
773 let mut candidates = vec![
774 candidate(1, "project", "sites_dir", "~/projects"),
775 FoldCandidate {
776 privacy: "private".into(),
777 ..candidate(2, "technical", "sites_directory", "~/projects")
778 },
779 FoldCandidate {
780 channel_id: Some("slack:synthetic-team".into()),
781 ..candidate(3, "technical", "sites_directory", "~/projects")
782 },
783 ];
784 assert!(plan_folds(&mut candidates).is_empty());
785
786 let mut candidates = vec![
787 FoldCandidate {
788 source_rank: 2,
789 ..candidate(1, "project", "sites_dir", "~/projects")
790 },
791 FoldCandidate {
792 source_rank: 2,
793 ..candidate(2, "technical", "sites_directory", "~/projects")
794 },
795 ];
796 assert!(plan_folds(&mut candidates).is_empty());
797 }
798
799 #[test]
800 fn other_embedding_models_never_compare() {
801 let mut candidates = vec![
802 candidate(1, "project", "sites_dir", "~/projects"),
803 FoldCandidate {
804 vector: vec![1.0, 0.0, 0.0],
805 ..candidate(2, "technical", "sites_directory", "~/projects")
806 },
807 ];
808 assert!(plan_folds(&mut candidates).is_empty());
809 }
810
811 #[test]
812 fn detect_overlaps_flags_owner_name_and_addressing_duplicates() {
813 let mut candidates = vec![
814 FoldCandidate {
815 source_rank: 2,
816 pinned: true,
817 ..candidate(-2_000_000_001, "user", "preferred_name", "Alice")
818 },
819 FoldCandidate {
820 source_rank: 0,
821 pinned: false,
822 ..candidate(
823 42,
824 "preference",
825 "address_as",
826 "Call the owner Alice. Don't call her Ally or Al.",
827 )
828 },
829 FoldCandidate {
830 source_rank: 2,
831 pinned: false,
832 vector: vec![0.0, 1.0],
833 ..candidate(43, "preference", "favorite_dish", "ramen")
834 },
835 ];
836 let overlaps = detect_overlaps(&mut candidates);
837 assert_eq!(overlaps.get(&42), Some(&-2_000_000_001));
838 assert!(!overlaps.contains_key(&43));
839 }
840
841 #[test]
842 fn fold_scope_groups_owner_only_facts() {
843 assert_eq!(fold_scope_key("private", None), FoldScope::OwnerPrivate);
844 assert_eq!(
845 fold_scope_key("Private", Some("telegram:synthetic-user-1")),
846 FoldScope::OwnerPrivate
847 );
848 assert_eq!(
849 fold_scope_key("channel", Some("app:synthetic-conv-1")),
850 FoldScope::OwnerPrivate
851 );
852 assert_eq!(fold_scope_key("global", Some("app:x")), FoldScope::Global);
853 assert_eq!(fold_scope_key("global", None), FoldScope::Global);
854 assert_eq!(
855 fold_scope_key("channel", Some("slack:synthetic-team")),
856 FoldScope::Channel(Some("slack:synthetic-team".into()))
857 );
858 assert_eq!(
860 fold_scope_key("channel", Some("APP:x")),
861 FoldScope::Channel(Some("APP:x".into()))
862 );
863 assert_eq!(fold_scope_key("channel", None), FoldScope::Channel(None));
864 let group = FoldScope::Channel(Some("slack:synthetic-team".into()));
866 assert!(FoldScope::Global.can_keep(&FoldScope::OwnerPrivate));
867 assert!(group.can_keep(&FoldScope::OwnerPrivate));
868 assert!(!FoldScope::OwnerPrivate.can_keep(&FoldScope::Global));
869 assert!(!FoldScope::OwnerPrivate.can_keep(&group));
870 assert!(!FoldScope::Global.can_keep(&group));
871 }
872
873 fn scoped(id: i64, key: &str, privacy: &str, channel: Option<&str>) -> FoldCandidate {
874 FoldCandidate {
875 privacy: privacy.into(),
876 channel_id: channel.map(str::to_string),
877 ..candidate(id, "technical", key, "~/projects")
878 }
879 }
880
881 #[test]
882 fn owner_only_scopes_fold_together_and_never_with_shared_ones() {
883 let mut candidates = vec![
884 scoped(1, "sites_dir", "channel", Some("app:synthetic-conv-1")),
885 scoped(
886 2,
887 "sites_directory",
888 "channel",
889 Some("app:synthetic-conv-2"),
890 ),
891 scoped(3, "projects_dir", "private", None),
892 ];
893 let folds = plan_folds(&mut candidates);
894 assert_eq!(folds.len(), 2);
895 assert!(folds.iter().all(|fold| fold.kept == 1));
896
897 let mut candidates = vec![
898 scoped(1, "sites_dir", "private", None),
899 scoped(2, "sites_directory", "global", None),
900 scoped(3, "projects_dir", "channel", Some("slack:synthetic-team")),
901 scoped(4, "project_root", "channel", Some("discord:ch:synthetic-1")),
902 ];
903 assert!(plan_folds(&mut candidates).is_empty());
904 }
905
906 fn conflict(
907 id: i64,
908 key: &str,
909 value: &str,
910 source_rank: u8,
911 seen_days_ago: i64,
912 vector: Vec<f32>,
913 ) -> ConflictCandidate {
914 ConflictCandidate {
915 id,
916 category: "project".into(),
917 key: key.into(),
918 value: value.into(),
919 source_rank,
920 seen: Some(chrono::Utc::now() - chrono::Duration::days(seen_days_ago)),
921 privacy: "private".into(),
922 channel_id: None,
923 vector,
924 }
925 }
926
927 #[test]
928 fn numeric_conflict_verdicts_follow_source_then_recency() {
929 let near = vec![0.95, 0.312];
930 let base = vec![1.0, 0.0];
931 let pair = |a: ConflictCandidate, b: ConflictCandidate| {
932 let conflicts = plan_numeric_conflicts(&[a, b]);
933 assert_eq!(conflicts.len(), 1);
934 conflicts[0].verdict
935 };
936 assert_eq!(
938 pair(
939 conflict(1, "api_port", "8080", 2, 90, base.clone()),
940 conflict(2, "default_api_port", "9090", 0, 0, near.clone()),
941 ),
942 ConflictVerdict::Resolved {
943 kept: 1,
944 retired: 2
945 }
946 );
947 assert_eq!(
950 pair(
951 conflict(1, "mia_birthday", "2015-03-15", 2, 90, base.clone()),
952 conflict(2, "zoe_birthday", "2018-07-22", 0, 0, near.clone()),
953 ),
954 ConflictVerdict::DistinctAttributes
955 );
956 assert!(
958 plan_numeric_conflicts(&[
959 conflict(1, "python", "Uses Python", 2, 1, base.clone()),
960 conflict(2, "current_python", "Uses Python 3.12", 0, 2, near.clone()),
961 ])
962 .is_empty()
963 );
964 assert_eq!(
966 pair(
967 conflict(1, "node_version", "18", 0, 30, base.clone()),
968 conflict(2, "current_node_version", "20", 0, 1, near.clone()),
969 ),
970 ConflictVerdict::Resolved {
971 kept: 2,
972 retired: 1
973 }
974 );
975 assert_eq!(
976 pair(
977 conflict(1, "node_version", "18", 1, 30, base.clone()),
978 conflict(2, "current_node_version", "20", 0, 1, near.clone()),
979 ),
980 ConflictVerdict::Resolved {
981 kept: 1,
982 retired: 2
983 }
984 );
985 assert_eq!(
986 pair(
987 conflict(1, "release_version", "1.2", 0, 30, base.clone()),
988 conflict(2, "build_version", "3.4", 0, 1, near.clone()),
989 ),
990 ConflictVerdict::DistinctAttributes
991 );
992 assert_eq!(
993 pair(
994 conflict(1, "deadline", "day 12", 2, 30, base.clone()),
995 conflict(2, "deadline", "day 14", 2, 1, near.clone()),
996 ),
997 ConflictVerdict::BothOwnerStated
998 );
999 let none = |a: ConflictCandidate, b: ConflictCandidate| {
1001 assert!(plan_numeric_conflicts(&[a, b]).is_empty());
1002 };
1003 none(
1004 conflict(1, "port", "8080", 0, 1, base.clone()),
1005 conflict(2, "port_number", "port 8080", 0, 2, near.clone()),
1006 );
1007 none(
1008 conflict(1, "port", "8080", 0, 1, base.clone()),
1009 conflict(2, "port_number", "9090", 0, 2, vec![0.8, 0.6]),
1010 );
1011 none(
1012 ConflictCandidate {
1013 category: "behavior".into(),
1014 ..conflict(1, "port", "8080", 0, 1, base.clone())
1015 },
1016 conflict(2, "port_number", "9090", 0, 2, near.clone()),
1017 );
1018 none(
1019 ConflictCandidate {
1020 privacy: "global".into(),
1021 ..conflict(1, "port", "8080", 0, 1, base.clone())
1022 },
1023 conflict(2, "port_number", "9090", 0, 2, near.clone()),
1024 );
1025 }
1026
1027 #[test]
1028 fn numeric_retirements_never_chain_in_one_pass() {
1029 let resolved = |kept: i64, retired: i64, similarity: f32| NumericConflict {
1030 a: kept.min(retired),
1031 b: kept.max(retired),
1032 similarity,
1033 verdict: ConflictVerdict::Resolved { kept, retired },
1034 };
1035 let conflicts = vec![
1036 resolved(2, 1, 0.99),
1037 resolved(3, 2, 0.98),
1039 resolved(4, 1, 0.97),
1041 NumericConflict {
1042 a: 5,
1043 b: 6,
1044 similarity: 0.96,
1045 verdict: ConflictVerdict::BothOwnerStated,
1046 },
1047 resolved(7, 8, 0.95),
1048 ];
1049 assert_eq!(
1050 numeric_conflict_retirements(&conflicts),
1051 vec![(1, 2), (8, 7)]
1052 );
1053 }
1054
1055 #[test]
1056 fn a_distinct_pair_falls_through_to_the_next_representative() {
1057 let value = "dark theme in every editor";
1058 let mut candidates = vec![
1059 FoldCandidate {
1060 recall_count: 9,
1061 ..candidate(1, "preference", "theme", value)
1062 },
1063 FoldCandidate {
1064 recall_count: 5,
1065 ..candidate(2, "technical", "editor_theme", value)
1066 },
1067 candidate(3, "project", "ide_theme", value),
1068 ];
1069 let all = detect_overlaps(&mut candidates.clone());
1070 assert_eq!(all.get(&3), Some(&1));
1071 assert_eq!(all.get(&2), Some(&1));
1072 let distinct = [overlap_pair(3, 1)].into_iter().collect();
1074 let reviewed = detect_overlaps_excluding(&mut candidates.clone(), &distinct);
1075 assert_eq!(reviewed.get(&3), None);
1076 assert_eq!(reviewed.get(&2), Some(&1));
1077 let distinct = [overlap_pair(3, 1), overlap_pair(1, 2)]
1079 .into_iter()
1080 .collect();
1081 let reviewed = detect_overlaps_excluding(&mut candidates, &distinct);
1082 assert_eq!(reviewed.get(&2), None);
1083 assert_eq!(reviewed.get(&3), Some(&2));
1084 }
1085}