1use std::collections::BTreeMap;
2
3use crate::records::Fact;
4use crate::stores::{FactStore, PeopleStore};
5use chrono::Utc;
6
7#[derive(Debug, Clone)]
8struct RankedEntity {
9 id: String,
10 lines: Vec<String>,
11 salience: f32,
12 class: ProfileClass,
13}
14
15#[derive(Debug, Clone, Copy, PartialEq, Eq)]
21enum ProfileClass {
22 Personal,
23 Preference,
24 Operational,
25}
26
27impl ProfileClass {
28 fn of_category(category: &str) -> Self {
29 match category.trim().to_ascii_lowercase().as_str() {
30 "user" | "people" | "relationship" | "relationships" | "family" | "identity"
31 | "personal" | "profile" => Self::Personal,
32 "preference" => Self::Preference,
33 _ => Self::Operational,
34 }
35 }
36
37 fn quota(self) -> usize {
39 match self {
40 Self::Personal => CORE_PROFILE_MAX_ENTITIES,
41 Self::Preference => 5,
42 Self::Operational => 4,
43 }
44 }
45}
46
47const CORE_PROFILE_MAX_ENTITIES: usize = 20;
48
49const CANONICAL_PERSONAL_MIN_SALIENCE: f32 = 5.0;
54
55fn group_salience(max_recall: i32, days_old: f32, class: ProfileClass, has_canonical: bool) -> f32 {
59 let recency_boost = (30.0 - days_old).max(0.0) * 0.1;
60 let salience = max_recall as f32 + recency_boost;
61 if has_canonical && class == ProfileClass::Personal {
62 salience.max(CANONICAL_PERSONAL_MIN_SALIENCE)
63 } else {
64 salience
65 }
66}
67const CORE_PROFILE_MAX_CHARS: usize = 2400;
70const CORE_PROFILE_MAX_LINE_CHARS: usize = 240;
71
72#[derive(Debug, Clone, Copy, PartialEq, Eq)]
74enum FamilyRole {
75 Partner,
76 Child,
77 Parent,
78}
79
80impl FamilyRole {
81 fn of_token(token: &str) -> Option<Self> {
83 match token {
84 "wife" | "husband" | "spouse" | "partner" => Some(Self::Partner),
85 "daughter" | "son" | "child" | "kid" => Some(Self::Child),
86 "mother" | "father" | "mom" | "dad" => Some(Self::Parent),
87 _ => None,
88 }
89 }
90}
91
92fn family_group(key: &str) -> (String, Option<FamilyRole>) {
97 let mut tokens = key.split('_');
98 let first = tokens.next().unwrap_or_default();
99 let Some(role) = FamilyRole::of_token(first) else {
100 return (key.to_string(), None);
101 };
102 if key == first && role == FamilyRole::Parent {
104 return (key.to_string(), Some(role));
105 }
106 let numbered = tokens.next().filter(|second| {
107 !second.is_empty() && second.chars().all(|c| c.is_ascii_digit()) && tokens.next().is_some()
108 });
109 let group = match numbered {
110 Some(number) => format!("{first}_{number}"),
111 None => first.to_string(),
112 };
113 (group, Some(role))
114}
115
116pub async fn build_core_profile<S>(
119 state: &S,
120 cached_ids: Option<Vec<String>>,
121 people_enabled: bool,
122) -> anyhow::Result<(String, Option<Vec<String>>, Vec<(String, String)>)>
123where
124 S: FactStore + PeopleStore + ?Sized,
125{
126 let now = Utc::now();
127 let mut entities = Vec::new();
128
129 let mut owner_id = None;
130 if people_enabled {
131 let people = state.get_all_people().await.unwrap_or_default();
132 for person in people {
133 if person
134 .relationship
135 .as_deref()
136 .map(|s| s.to_ascii_lowercase())
137 == Some("owner".to_string())
138 {
139 owner_id = Some(person.id);
140 continue; }
142
143 let days_old = (now - person.updated_at).num_days() as f32;
144 let recency_boost = (30.0 - days_old).max(0.0) * 0.1;
145 let salience = person.interaction_count as f32 + recency_boost;
146
147 let rel = person.relationship.as_deref().unwrap_or("contact");
148 let mut parts = vec![person.name.clone()];
149 if let Some(notes) = &person.notes {
150 parts.push(format!("(b. {})", notes));
151 }
152 let line = format!("Your {}: {}", rel, parts.join(" "));
153
154 entities.push(RankedEntity {
155 id: format!("person_{}", person.id),
156 lines: vec![line],
157 salience,
158 class: ProfileClass::Personal,
159 });
160 }
161 }
162
163 if let Some(oid) = owner_id {
164 let person_facts = state.get_person_facts(oid, None).await.unwrap_or_default();
165 for fact in person_facts {
166 let days_old = (now - fact.updated_at).num_days() as f32;
167 let recency_boost = (30.0 - days_old).max(0.0) * 0.1;
168 let salience = fact.confidence + recency_boost;
169
170 entities.push(RankedEntity {
171 id: format!("person_fact_{}", fact.id),
172 lines: vec![format!("• {}: {}", fact.key, fact.value)],
173 salience,
174 class: ProfileClass::Personal,
175 });
176 }
177 }
178
179 let canonical_facts = state.get_canonical_memory_facts().await.unwrap_or_default();
180 let canonical_owner_keys: std::collections::HashSet<String> = canonical_facts
181 .iter()
182 .filter(|fact| fact.category == "user")
183 .map(|fact| crate::text::owner_projection_family(&fact.key))
184 .collect();
185 let mut flat_facts = canonical_facts;
186 flat_facts.extend(
187 state
188 .get_facts(None)
189 .await
190 .unwrap_or_default()
191 .into_iter()
192 .filter(|fact| {
193 let cat_lower = fact.category.trim().to_ascii_lowercase();
194 let is_owner_cat = matches!(cat_lower.as_str(), "user" | "personal" | "profile")
195 || (cat_lower == "preference" && crate::text::is_owner_profile_key(&fact.key));
196 !is_owner_cat
197 || !canonical_owner_keys
198 .contains(&crate::text::owner_projection_family(&fact.key))
199 }),
200 );
201 let mut flat_groups: BTreeMap<String, (Option<FamilyRole>, Vec<Fact>)> = BTreeMap::new();
204
205 for fact in flat_facts {
206 let key = fact.key.trim().to_ascii_lowercase();
207 let (group_id, role) = family_group(&key);
208 flat_groups
209 .entry(group_id)
210 .or_insert_with(|| (role, Vec::new()))
211 .1
212 .push(fact);
213 }
214
215 for (group_id, (role, facts)) in flat_groups {
216 let mut max_recall = 0;
217 let mut newest_update = chrono::DateTime::<Utc>::MIN_UTC;
218 let class = facts
219 .iter()
220 .map(|fact| ProfileClass::of_category(&fact.category))
221 .min_by_key(|class| *class as u8)
222 .unwrap_or(ProfileClass::Operational);
223
224 let mut name = None;
225 let mut details = Vec::new();
226 let mut generic_lines = Vec::new();
227
228 let is_rel = matches!(role, Some(FamilyRole::Partner | FamilyRole::Child));
229 let has_canonical = facts.iter().any(|fact| fact.id < 0);
230
231 for fact in facts {
232 max_recall = max_recall.max(fact.recall_count);
233 if fact.updated_at > newest_update {
234 newest_update = fact.updated_at;
235 }
236
237 if is_rel {
238 let key = fact.key.to_ascii_lowercase();
239 if key == group_id || key == format!("{}_name", group_id) {
240 name = Some(fact.value.clone());
241 } else {
242 details.push(fact.value.clone());
243 }
244 } else {
245 generic_lines.push(format!("• {}: {}", fact.key, fact.value));
246 }
247 }
248
249 let days_old = (now - newest_update).num_days() as f32;
250 let salience = group_salience(max_recall, days_old, class, has_canonical);
251
252 let mut lines = Vec::new();
253 if is_rel {
254 let display_name = name.unwrap_or_else(|| "Unknown".to_string());
255 let mut parts = vec![display_name];
256 if !details.is_empty() {
257 parts.push(format!("({})", details.join(", ")));
258 }
259 let label = match role {
260 Some(FamilyRole::Partner) => "partner",
261 Some(FamilyRole::Child) => "child",
262 _ => group_id.as_str(),
263 };
264 lines.push(format!("Your {}: {}", label, parts.join(" ")));
265 } else {
266 lines.extend(generic_lines);
267 }
268
269 entities.push(RankedEntity {
270 id: format!("flat_group_{}", group_id),
271 lines: lines
272 .into_iter()
273 .map(|line| crate::text::truncate_chars(&line, CORE_PROFILE_MAX_LINE_CHARS))
274 .collect(),
275 salience,
276 class,
277 });
278 }
279
280 let mut selected_entities = Vec::new();
282 let mut new_cache = None;
283
284 if let Some(cached) = cached_ids.as_deref() {
285 for entity in entities {
286 if cached.contains(&entity.id) {
287 selected_entities.push(entity);
288 }
289 }
290 } else {
291 order_entities(&mut entities);
292 let top_n = select_within_quotas(entities);
293
294 let ids: Vec<String> = top_n.iter().map(|e| e.id.clone()).collect();
297 new_cache = Some(ids);
298 selected_entities = top_n;
299 }
300
301 if selected_entities.is_empty() {
302 return Ok((String::new(), new_cache, Vec::new()));
303 }
304
305 order_selected_entities(&mut selected_entities, cached_ids.as_deref());
311
312 let digest: Vec<(String, String)> = selected_entities
317 .iter()
318 .map(|e| (e.id.clone(), entity_content_hash(&e.lines)))
319 .collect();
320
321 let mut out = String::from(
322 "## Core Profile\n\
323 Stored background memory about your operator (\"the owner\"). IMPORTANT: when \
324 the user's message contains a definite reference (\"the owner\", \"the CEO\", \
325 \"it\", \"they\") with an antecedent in the recent conversation, resolve it \
326 against the conversation FIRST — e.g. after discussing a company, \"Who's the \
327 owner?\" means that company's owner, NOT your operator. Only fall back to this \
328 profile when no conversational antecedent exists.\n\n",
329 );
330 for entity in selected_entities {
331 for line in entity.lines {
332 out.push_str(&format!("{}\n", line));
333 }
334 }
335
336 Ok((out.trim_end().to_string(), new_cache, digest))
337}
338
339fn entity_content_hash(lines: &[String]) -> String {
344 use std::hash::{Hash, Hasher};
345 let mut hasher = std::collections::hash_map::DefaultHasher::new();
346 lines.hash(&mut hasher);
347 format!("{:08x}", hasher.finish() as u32)
348}
349
350fn order_entities(entities: &mut [RankedEntity]) {
356 entities.sort_by(|a, b| {
357 b.salience
358 .partial_cmp(&a.salience)
359 .unwrap_or(std::cmp::Ordering::Equal)
360 .then_with(|| a.id.cmp(&b.id))
361 });
362}
363
364fn select_within_quotas(ordered: Vec<RankedEntity>) -> Vec<RankedEntity> {
367 let mut selected = Vec::new();
368 let mut per_class = std::collections::HashMap::new();
369 let mut chars = 0usize;
370 for entity in ordered {
371 if selected.len() >= CORE_PROFILE_MAX_ENTITIES {
372 break;
373 }
374 let taken = per_class.entry(entity.class as u8).or_insert(0usize);
375 if *taken >= entity.class.quota() {
376 continue;
377 }
378 let size: usize = entity.lines.iter().map(|line| line.len() + 1).sum();
379 if chars + size > CORE_PROFILE_MAX_CHARS {
380 continue;
381 }
382 *taken += 1;
383 chars += size;
384 selected.push(entity);
385 }
386 selected
387}
388
389fn order_selected_entities(entities: &mut [RankedEntity], pin: Option<&[String]>) {
399 match pin {
400 Some(pin) => entities.sort_by_key(|e| {
401 (
402 pin.iter().position(|id| id == &e.id).unwrap_or(usize::MAX),
403 e.id.clone(),
404 )
405 }),
406 None => order_entities(entities),
407 }
408}
409
410#[cfg(test)]
411mod tests {
412 use super::*;
413
414 fn mk(id: &str, salience: f32) -> RankedEntity {
415 mk_class(id, salience, ProfileClass::Personal)
416 }
417
418 fn mk_class(id: &str, salience: f32, class: ProfileClass) -> RankedEntity {
419 RankedEntity {
420 id: id.to_string(),
421 lines: vec![format!("line-{id}")],
422 salience,
423 class,
424 }
425 }
426
427 #[test]
428 fn heavily_recalled_operational_facts_cannot_crowd_out_the_owner() {
429 let mut entities: Vec<RankedEntity> = (0..12)
430 .map(|i| {
431 mk_class(
432 &format!("op{i:02}"),
433 100.0 + i as f32,
434 ProfileClass::Operational,
435 )
436 })
437 .collect();
438 entities.push(mk_class("pref", 50.0, ProfileClass::Preference));
439 entities.push(mk_class("partner", 1.0, ProfileClass::Personal));
440 entities.push(mk_class("child", 0.5, ProfileClass::Personal));
441 order_entities(&mut entities);
442 let selected = select_within_quotas(entities);
443 let ids: Vec<_> = selected.iter().map(|e| e.id.as_str()).collect();
444 assert_eq!(
445 selected
446 .iter()
447 .filter(|e| e.class == ProfileClass::Operational)
448 .count(),
449 ProfileClass::Operational.quota()
450 );
451 assert!(ids.contains(&"partner") && ids.contains(&"child") && ids.contains(&"pref"));
452 }
453
454 #[test]
455 fn profile_selection_respects_the_size_cap() {
456 let mut big = mk("big", 10.0);
457 big.lines = vec!["x".repeat(CORE_PROFILE_MAX_CHARS)];
458 let entities = vec![big, mk("small", 1.0)];
459 let selected = select_within_quotas(entities);
460 let ids: Vec<_> = selected.iter().map(|e| e.id.as_str()).collect();
461 assert_eq!(ids, vec!["small"]);
462 }
463
464 #[test]
465 fn order_entities_is_deterministic_regardless_of_input_order() {
466 let mut a = vec![mk("c", 1.0), mk("a", 2.0), mk("b", 2.0)];
468 let mut b = vec![mk("b", 2.0), mk("c", 1.0), mk("a", 2.0)];
469 order_entities(&mut a);
470 order_entities(&mut b);
471 let ids = |v: &[RankedEntity]| v.iter().map(|e| e.id.clone()).collect::<Vec<_>>();
472 assert_eq!(
473 ids(&a),
474 ids(&b),
475 "identical entities must order identically regardless of input order"
476 );
477 assert_eq!(ids(&a), vec!["a", "b", "c"]);
479 }
480
481 #[test]
482 fn pinned_order_is_frozen_against_salience_drift() {
483 let pin = vec!["b".to_string(), "a".to_string()];
489 let mut entities = vec![mk("a", 5.0), mk("b", 1.0)];
491 order_selected_entities(&mut entities, Some(&pin));
492 let ids: Vec<_> = entities.iter().map(|e| e.id.as_str()).collect();
493 assert_eq!(ids, vec!["b", "a"], "pin order wins over live salience");
494
495 let mut fresh = vec![mk("a", 1.0), mk("b", 5.0)];
497 order_selected_entities(&mut fresh, None);
498 let ids: Vec<_> = fresh.iter().map(|e| e.id.as_str()).collect();
499 assert_eq!(ids, vec!["b", "a"], "fresh selection orders by salience");
500 }
501
502 #[test]
503 fn pinned_order_ignores_upstream_iteration_order() {
504 let pin = vec!["x".to_string(), "y".to_string(), "z".to_string()];
507 let mut a = vec![mk("z", 1.0), mk("x", 1.0), mk("y", 1.0)];
508 let mut b = vec![mk("y", 1.0), mk("z", 1.0), mk("x", 1.0)];
509 order_selected_entities(&mut a, Some(&pin));
510 order_selected_entities(&mut b, Some(&pin));
511 let ids = |v: &[RankedEntity]| v.iter().map(|e| e.id.clone()).collect::<Vec<_>>();
512 assert_eq!(ids(&a), ids(&b));
513 assert_eq!(ids(&a), vec!["x", "y", "z"]);
514 }
515
516 #[test]
517 fn entity_content_hash_detects_content_change() {
518 let a = entity_content_hash(&["Your partner: Jordan Lee".to_string()]);
519 let a2 = entity_content_hash(&["Your partner: Jordan Lee".to_string()]);
520 let b = entity_content_hash(&["Your partner: Alex Kim".to_string()]);
521 assert_eq!(a, a2, "identical content must hash identically");
522 assert_ne!(a, b, "changed content must change the hash");
523 assert_eq!(a.len(), 8, "short 8-hex digest");
524 }
525
526 #[test]
527 fn canonical_personal_groups_keep_a_salience_floor() {
528 let canonical = group_salience(0, 90.0, ProfileClass::Personal, true);
531 let flat = group_salience(3, 90.0, ProfileClass::Personal, false);
532 assert_eq!(canonical, CANONICAL_PERSONAL_MIN_SALIENCE);
533 assert!(canonical > flat);
534 assert_eq!(group_salience(8, 90.0, ProfileClass::Personal, true), 8.0);
536 assert!((group_salience(0, 0.0, ProfileClass::Personal, false) - 3.0).abs() < 1e-6);
537 assert_eq!(group_salience(0, 90.0, ProfileClass::Preference, true), 0.0);
539 }
540
541 struct ProfileStore {
542 canonical: Vec<Fact>,
543 flat: Vec<Fact>,
544 }
545
546 #[async_trait::async_trait]
547 impl FactStore for ProfileStore {
548 async fn get_canonical_memory_facts(&self) -> anyhow::Result<Vec<Fact>> {
549 Ok(self.canonical.clone())
550 }
551
552 async fn upsert_fact_with_provenance(
553 &self,
554 _category: &str,
555 _key: &str,
556 _value: &str,
557 _source: &str,
558 _channel_id: Option<&str>,
559 _privacy: crate::records::FactPrivacy,
560 _first_seen_at: Option<chrono::DateTime<Utc>>,
561 _source_excerpt: Option<&str>,
562 ) -> anyhow::Result<()> {
563 Ok(())
564 }
565
566 async fn get_facts(&self, _category: Option<&str>) -> anyhow::Result<Vec<Fact>> {
567 Ok(self.flat.clone())
568 }
569 }
570
571 #[async_trait::async_trait]
572 impl PeopleStore for ProfileStore {}
573
574 fn fact(id: i64, category: &str, key: &str, value: &str, recall: i32) -> Fact {
575 let old = Utc::now() - chrono::Duration::days(90);
576 Fact {
577 id,
578 category: category.into(),
579 key: key.into(),
580 value: value.into(),
581 source: "user_stated".into(),
582 created_at: old,
583 updated_at: old,
584 superseded_at: None,
585 recall_count: recall,
586 last_recalled_at: None,
587 channel_id: None,
588 privacy: crate::records::FactPrivacy::Private,
589 first_seen_at: None,
590 source_excerpt: None,
591 }
592 }
593
594 #[tokio::test]
595 async fn an_old_canonical_identity_fact_is_not_crowded_out_by_recalled_flat_facts() {
596 let flat = (0..CORE_PROFILE_MAX_ENTITIES as i64)
599 .map(|i| fact(i + 1, "user", &format!("detail_{i:02}"), "x", 3))
600 .collect();
601 let store = ProfileStore {
602 canonical: vec![fact(-5, "user", "hometown", "Springfield", 0)],
603 flat,
604 };
605 let (profile, pinned, _) = build_core_profile(&store, None, false).await.unwrap();
606 assert!(profile.contains("hometown: Springfield"), "{profile}");
607 assert!(pinned.unwrap().contains(&"flat_group_hometown".to_string()));
608 }
609
610 #[test]
611 fn a_relation_is_a_whole_key_token() {
612 assert_eq!(family_group("song_title"), ("song_title".into(), None));
613 assert_eq!(family_group("sonar_config"), ("sonar_config".into(), None));
614 assert_eq!(family_group("kidney_donor"), ("kidney_donor".into(), None));
615 assert_eq!(
616 family_group("son_name"),
617 ("son".into(), Some(FamilyRole::Child))
618 );
619 assert_eq!(
620 family_group("son_2_school"),
621 ("son_2".into(), Some(FamilyRole::Child))
622 );
623 assert_eq!(
624 family_group("wife"),
625 ("wife".into(), Some(FamilyRole::Partner))
626 );
627 assert_eq!(
628 family_group("mother"),
629 ("mother".into(), Some(FamilyRole::Parent))
630 );
631 }
632}