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)]
84pub struct FoldCandidate {
85 pub id: i64,
86 pub category: String,
87 pub key: String,
88 pub value: String,
89 pub source_rank: u8,
92 pub pinned: bool,
95 pub recall_count: i64,
96 pub privacy: String,
97 pub channel_id: Option<String>,
98 pub vector: Vec<f32>,
99}
100
101#[derive(Debug, Clone, Copy, PartialEq, Eq)]
103pub enum FoldRule {
104 Restatement,
105 OneValue,
106}
107
108#[derive(Debug, Clone, Copy, PartialEq)]
110pub struct PlannedFold {
111 pub folded: i64,
112 pub kept: i64,
113 pub rule: FoldRule,
114 pub similarity: f32,
115}
116
117pub fn plan_folds(candidates: &mut [FoldCandidate]) -> Vec<PlannedFold> {
127 candidates.sort_by(|a, b| {
128 b.source_rank
129 .cmp(&a.source_rank)
130 .then(b.pinned.cmp(&a.pinned))
131 .then(b.recall_count.cmp(&a.recall_count))
132 .then(a.id.cmp(&b.id))
133 });
134 let mut kept_by_category: std::collections::HashMap<String, Vec<usize>> =
137 std::collections::HashMap::new();
138 let mut kept_by_value: std::collections::HashMap<String, Vec<usize>> =
139 std::collections::HashMap::new();
140 let mut folds = Vec::new();
141 for index in 0..candidates.len() {
142 let candidate = &candidates[index];
143 let category = candidate.category.trim().to_ascii_lowercase();
144 let value = crate::text::normalize_fact_value(&candidate.value);
145 let same_scope = |other: &FoldCandidate| {
146 other.privacy == candidate.privacy && other.channel_id == candidate.channel_id
147 };
148 let restated = kept_by_category
149 .get(&category)
150 .into_iter()
151 .flatten()
152 .find_map(|&kept| {
153 let rep = &candidates[kept];
154 if !same_scope(rep) {
155 return None;
156 }
157 let similarity = crate::cosine(&candidate.vector, &rep.vector);
158 facts_are_restatements(
159 &candidate.category,
160 (&candidate.key, &candidate.value),
161 (&rep.key, &rep.value),
162 similarity,
163 )
164 .then_some((kept, FoldRule::Restatement, similarity))
165 });
166 let matched = restated.or_else(|| {
167 kept_by_value
168 .get(&value)
169 .into_iter()
170 .flatten()
171 .find_map(|&kept| {
172 let rep = &candidates[kept];
173 if !same_scope(rep) {
174 return None;
175 }
176 let similarity = crate::cosine(&candidate.vector, &rep.vector);
177 facts_hold_one_value(
178 (&candidate.category, &candidate.key, &candidate.value),
179 (&rep.category, &rep.key, &rep.value),
180 similarity,
181 )
182 .then_some((kept, FoldRule::OneValue, similarity))
183 })
184 });
185 match matched {
186 Some((kept, rule, similarity)) if candidate.source_rank < 2 => {
187 folds.push(PlannedFold {
188 folded: candidate.id,
189 kept: candidates[kept].id,
190 rule,
191 similarity,
192 });
193 }
194 _ => {
195 kept_by_category.entry(category).or_default().push(index);
196 if !value.is_empty() {
197 kept_by_value.entry(value).or_default().push(index);
198 }
199 }
200 }
201 }
202 folds
203}
204
205pub const OVERLAP_REVIEW_MIN_SIMILARITY: f32 = 0.78;
209
210pub fn detect_overlaps(candidates: &mut [FoldCandidate]) -> std::collections::HashMap<i64, i64> {
217 use std::collections::{HashMap, HashSet};
218
219 candidates.sort_by(|a, b| {
220 b.source_rank
221 .cmp(&a.source_rank)
222 .then(b.pinned.cmp(&a.pinned))
223 .then(b.recall_count.cmp(&a.recall_count))
224 .then(a.id.cmp(&b.id))
225 });
226
227 let n = candidates.len();
231 let cats: Vec<String> = candidates
232 .iter()
233 .map(|c| c.category.trim().to_ascii_lowercase())
234 .collect();
235 let keys: Vec<String> = candidates
236 .iter()
237 .map(|c| canonicalize_fact_key(&c.key))
238 .collect();
239 let vals: Vec<String> = candidates
240 .iter()
241 .map(|c| crate::text::normalize_fact_value(&c.value))
242 .collect();
243 let words: Vec<HashSet<&str>> = vals
244 .iter()
245 .map(|v| v.split_whitespace().filter(|w| w.len() >= 3).collect())
246 .collect();
247 let naming: Vec<Option<String>> = candidates
249 .iter()
250 .zip(&cats)
251 .map(|(c, cat)| {
252 (crate::text::is_owner_name_key(&c.key)
253 && matches!(cat.as_str(), "user" | "preference" | "personal" | "profile"))
254 .then(|| crate::text::canonical_personal_key(&c.key))
255 })
256 .collect();
257 let norms: Vec<f32> = candidates
258 .iter()
259 .map(|c| c.vector.iter().map(|x| x * x).sum::<f32>().sqrt())
260 .collect();
261 let similarity = |a: usize, b: usize| -> f32 {
263 let (va, vb) = (&candidates[a].vector, &candidates[b].vector);
264 if va.len() != vb.len() || va.is_empty() {
265 return 0.0;
266 }
267 if norms[a] * norms[a] <= f32::EPSILON || norms[b] * norms[b] <= f32::EPSILON {
268 return 0.0;
269 }
270 let dot: f32 = va.iter().zip(vb).map(|(x, y)| x * y).sum();
271 dot / (norms[a] * norms[b])
272 };
273 let is_positive_naming = |facet: &str| {
274 matches!(
275 facet,
276 "name" | "full_name" | "preferred_name" | "nickname" | "addressing"
277 )
278 };
279
280 let mut naming_reps: Vec<usize> = Vec::new();
284 let mut reps_by_key: HashMap<&str, Vec<usize>> = HashMap::new();
285 let mut reps_by_val: HashMap<&str, Vec<usize>> = HashMap::new();
286 let mut reps_by_cat: HashMap<&str, Vec<usize>> = HashMap::new();
287 let mut overlaps = HashMap::new();
288
289 for index in 0..n {
290 let mut best: Option<usize> = None;
293 let offer = |rep: usize, best: &mut Option<usize>| {
294 if best.is_none_or(|b| rep < b) {
295 *best = Some(rep);
296 }
297 };
298
299 if let Some(cand_facet) = &naming[index]
305 && let Some(&rep) = naming_reps.iter().find(|&&rep| {
306 let rep_facet = naming[rep].as_deref().unwrap_or_default();
307 cand_facet == rep_facet
308 || (is_positive_naming(cand_facet) && is_positive_naming(rep_facet))
309 })
310 {
311 offer(rep, &mut best);
312 }
313
314 if !keys[index].is_empty()
317 && let Some(&rep) = reps_by_key
318 .get(keys[index].as_str())
319 .and_then(|list| list.iter().find(|&&rep| cats[rep] != cats[index]))
320 {
321 offer(rep, &mut best);
322 }
323
324 if !vals[index].is_empty()
327 && !is_bare_scalar(&vals[index])
328 && let Some(&rep) = reps_by_val.get(vals[index].as_str()).and_then(|list| {
329 list.iter().find(|&&rep| {
330 candidates[index].vector.is_empty()
331 || candidates[rep].vector.is_empty()
332 || similarity(index, rep) >= ONE_VALUE_MIN_SIMILARITY
333 })
334 })
335 {
336 offer(rep, &mut best);
337 }
338
339 if !candidates[index].vector.is_empty()
344 && !words[index].is_empty()
345 && let Some(list) = reps_by_cat.get(cats[index].as_str())
346 {
347 let personal = fact_category_is_personal(&cats[index]);
348 for &rep in list {
349 if best.is_some_and(|b| rep >= b) {
350 break;
351 }
352 if candidates[rep].vector.is_empty()
353 || words[index].is_disjoint(&words[rep])
354 || similarity(index, rep) < OVERLAP_REVIEW_MIN_SIMILARITY
355 {
356 continue;
357 }
358 if personal {
359 let cand_tokens: HashSet<&str> =
360 keys[index].split('_').filter(|t| !t.is_empty()).collect();
361 let rep_tokens: HashSet<&str> =
362 keys[rep].split('_').filter(|t| !t.is_empty()).collect();
363 if keys_name_distinct_concepts(&cand_tokens, &rep_tokens) {
364 continue;
365 }
366 }
367 offer(rep, &mut best);
368 break;
369 }
370 }
371
372 if let Some(rep) = best {
373 overlaps.insert(candidates[index].id, candidates[rep].id);
374 } else {
375 if naming[index].is_some() {
376 naming_reps.push(index);
377 }
378 reps_by_key
379 .entry(keys[index].as_str())
380 .or_default()
381 .push(index);
382 reps_by_val
383 .entry(vals[index].as_str())
384 .or_default()
385 .push(index);
386 reps_by_cat
387 .entry(cats[index].as_str())
388 .or_default()
389 .push(index);
390 }
391 }
392 overlaps
393}
394
395#[cfg(test)]
396mod tests {
397 use super::*;
398
399 #[test]
400 fn one_value_under_reworded_keys_is_one_fact() {
401 let a = ("project", "local_sites_directory", "~/projects/");
402 assert!(facts_hold_one_value(
403 a,
404 ("technical", "projects_directory", "~/projects"),
405 0.86
406 ));
407 assert!(facts_hold_one_value(
408 ("technical", "local_dev_tool", "ddev"),
409 ("project", "local_dev_tooling", "DDEV"),
410 0.878
411 ));
412 }
413
414 #[test]
415 fn a_shared_value_alone_is_not_one_fact() {
416 assert!(!facts_hold_one_value(
418 ("project", "cars_site_platform", "Cloudflare Workers"),
419 ("project", "store_deployment_target", "Cloudflare Workers"),
420 0.75
421 ));
422 assert!(!facts_hold_one_value(
424 ("project", "development_platform", "Drupal"),
425 ("project", "framework", "Drupal"),
426 0.9
427 ));
428 assert!(!facts_hold_one_value(
430 ("project", "tests_enabled", "true"),
431 ("project", "tests_passing", "true"),
432 0.99
433 ));
434 assert!(!facts_hold_one_value(
436 ("project", "version", "0.9.10"),
437 ("project", "current_version", "0.9.17"),
438 0.95
439 ));
440 }
441
442 #[test]
443 fn people_keys_must_name_the_same_attribute() {
444 assert!(!facts_hold_one_value(
445 ("user", "pet_name", "Mia"),
446 ("user", "daughter_name", "Mia"),
447 0.9
448 ));
449 assert!(!facts_hold_one_value(
450 ("user", "birth_place", "Quito, Ecuador"),
451 ("user", "hometown", "Quito, Ecuador"),
452 0.9
453 ));
454 assert!(facts_hold_one_value(
455 ("user", "favorite_food", "sushi"),
456 ("user", "food", "sushi"),
457 0.9
458 ));
459 }
460
461 fn candidate(id: i64, category: &str, key: &str, value: &str) -> FoldCandidate {
462 FoldCandidate {
463 id,
464 category: category.into(),
465 key: key.into(),
466 value: value.into(),
467 source_rank: 0,
468 pinned: false,
469 recall_count: 0,
470 privacy: "channel".into(),
471 channel_id: None,
472 vector: vec![1.0, 0.0],
473 }
474 }
475
476 #[test]
477 fn the_owner_copy_then_the_pinned_one_survives() {
478 let mut candidates = vec![
479 candidate(1, "project", "editor_choice", "Helix editor"),
480 FoldCandidate {
481 pinned: true,
482 ..candidate(2, "preference", "preferred_editor", "Helix editor")
483 },
484 FoldCandidate {
485 source_rank: 2,
486 ..candidate(3, "technical", "editor", "helix editor")
487 },
488 ];
489 let folds = plan_folds(&mut candidates);
490 assert_eq!(folds.len(), 2);
491 assert!(folds.iter().all(|fold| fold.kept == 3));
492
493 let mut candidates = vec![
494 FoldCandidate {
495 recall_count: 50,
496 ..candidate(1, "project", "editor_choice", "Helix editor")
497 },
498 FoldCandidate {
499 pinned: true,
500 ..candidate(2, "preference", "preferred_editor", "Helix editor")
501 },
502 ];
503 assert_eq!(plan_folds(&mut candidates)[0].kept, 2);
504 }
505
506 #[test]
507 fn scope_and_owner_statements_are_never_folded_away() {
508 let mut candidates = vec![
509 candidate(1, "project", "sites_dir", "~/projects"),
510 FoldCandidate {
511 privacy: "private".into(),
512 ..candidate(2, "technical", "sites_directory", "~/projects")
513 },
514 FoldCandidate {
515 channel_id: Some("slack:synthetic-team".into()),
516 ..candidate(3, "technical", "sites_directory", "~/projects")
517 },
518 ];
519 assert!(plan_folds(&mut candidates).is_empty());
520
521 let mut candidates = vec![
522 FoldCandidate {
523 source_rank: 2,
524 ..candidate(1, "project", "sites_dir", "~/projects")
525 },
526 FoldCandidate {
527 source_rank: 2,
528 ..candidate(2, "technical", "sites_directory", "~/projects")
529 },
530 ];
531 assert!(plan_folds(&mut candidates).is_empty());
532 }
533
534 #[test]
535 fn other_embedding_models_never_compare() {
536 let mut candidates = vec![
537 candidate(1, "project", "sites_dir", "~/projects"),
538 FoldCandidate {
539 vector: vec![1.0, 0.0, 0.0],
540 ..candidate(2, "technical", "sites_directory", "~/projects")
541 },
542 ];
543 assert!(plan_folds(&mut candidates).is_empty());
544 }
545
546 #[test]
547 fn detect_overlaps_flags_owner_name_and_addressing_duplicates() {
548 let mut candidates = vec![
549 FoldCandidate {
550 source_rank: 2,
551 pinned: true,
552 ..candidate(-2_000_000_001, "user", "preferred_name", "Alice")
553 },
554 FoldCandidate {
555 source_rank: 0,
556 pinned: false,
557 ..candidate(
558 42,
559 "preference",
560 "address_as",
561 "Call the owner Alice. Don't call her Ally or Al.",
562 )
563 },
564 FoldCandidate {
565 source_rank: 2,
566 pinned: false,
567 vector: vec![0.0, 1.0],
568 ..candidate(43, "preference", "favorite_dish", "ramen")
569 },
570 ];
571 let overlaps = detect_overlaps(&mut candidates);
572 assert_eq!(overlaps.get(&42), Some(&-2_000_000_001));
573 assert!(!overlaps.contains_key(&43));
574 }
575}