use std::collections::BTreeMap;
use crate::records::Fact;
use crate::stores::{FactStore, PeopleStore};
use chrono::Utc;
#[derive(Debug, Clone)]
struct RankedEntity {
id: String,
lines: Vec<String>,
salience: f32,
class: ProfileClass,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum ProfileClass {
Personal,
Preference,
Operational,
}
impl ProfileClass {
fn of_category(category: &str) -> Self {
match category.trim().to_ascii_lowercase().as_str() {
"user" | "people" | "relationship" | "relationships" | "family" | "identity"
| "personal" | "profile" => Self::Personal,
"preference" => Self::Preference,
_ => Self::Operational,
}
}
fn quota(self) -> usize {
match self {
Self::Personal => CORE_PROFILE_MAX_ENTITIES,
Self::Preference => 5,
Self::Operational => 4,
}
}
}
const CORE_PROFILE_MAX_ENTITIES: usize = 20;
const CORE_PROFILE_MAX_CHARS: usize = 2400;
const CORE_PROFILE_MAX_LINE_CHARS: usize = 240;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum FamilyRole {
Partner,
Child,
Parent,
}
impl FamilyRole {
fn of_token(token: &str) -> Option<Self> {
match token {
"wife" | "husband" | "spouse" | "partner" => Some(Self::Partner),
"daughter" | "son" | "child" | "kid" => Some(Self::Child),
"mother" | "father" | "mom" | "dad" => Some(Self::Parent),
_ => None,
}
}
}
fn family_group(key: &str) -> (String, Option<FamilyRole>) {
let mut tokens = key.split('_');
let first = tokens.next().unwrap_or_default();
let Some(role) = FamilyRole::of_token(first) else {
return (key.to_string(), None);
};
if key == first && role == FamilyRole::Parent {
return (key.to_string(), Some(role));
}
let numbered = tokens.next().filter(|second| {
!second.is_empty() && second.chars().all(|c| c.is_ascii_digit()) && tokens.next().is_some()
});
let group = match numbered {
Some(number) => format!("{first}_{number}"),
None => first.to_string(),
};
(group, Some(role))
}
pub async fn build_core_profile<S>(
state: &S,
cached_ids: Option<Vec<String>>,
people_enabled: bool,
) -> anyhow::Result<(String, Option<Vec<String>>, Vec<(String, String)>)>
where
S: FactStore + PeopleStore + ?Sized,
{
let now = Utc::now();
let mut entities = Vec::new();
let mut owner_id = None;
if people_enabled {
let people = state.get_all_people().await.unwrap_or_default();
for person in people {
if person
.relationship
.as_deref()
.map(|s| s.to_ascii_lowercase())
== Some("owner".to_string())
{
owner_id = Some(person.id);
continue; }
let days_old = (now - person.updated_at).num_days() as f32;
let recency_boost = (30.0 - days_old).max(0.0) * 0.1;
let salience = person.interaction_count as f32 + recency_boost;
let rel = person.relationship.as_deref().unwrap_or("contact");
let mut parts = vec![person.name.clone()];
if let Some(notes) = &person.notes {
parts.push(format!("(b. {})", notes));
}
let line = format!("Your {}: {}", rel, parts.join(" "));
entities.push(RankedEntity {
id: format!("person_{}", person.id),
lines: vec![line],
salience,
class: ProfileClass::Personal,
});
}
}
if let Some(oid) = owner_id {
let person_facts = state.get_person_facts(oid, None).await.unwrap_or_default();
for fact in person_facts {
let days_old = (now - fact.updated_at).num_days() as f32;
let recency_boost = (30.0 - days_old).max(0.0) * 0.1;
let salience = fact.confidence + recency_boost;
entities.push(RankedEntity {
id: format!("person_fact_{}", fact.id),
lines: vec![format!("• {}: {}", fact.key, fact.value)],
salience,
class: ProfileClass::Personal,
});
}
}
let canonical_facts = state.get_canonical_memory_facts().await.unwrap_or_default();
let canonical_owner_keys: std::collections::HashSet<String> = canonical_facts
.iter()
.filter(|fact| fact.category == "user")
.map(|fact| crate::text::owner_projection_family(&fact.key))
.collect();
let mut flat_facts = canonical_facts;
flat_facts.extend(
state
.get_facts(None)
.await
.unwrap_or_default()
.into_iter()
.filter(|fact| {
let cat_lower = fact.category.trim().to_ascii_lowercase();
let is_owner_cat = matches!(cat_lower.as_str(), "user" | "personal" | "profile")
|| (cat_lower == "preference" && crate::text::is_owner_profile_key(&fact.key));
!is_owner_cat
|| !canonical_owner_keys
.contains(&crate::text::owner_projection_family(&fact.key))
}),
);
let mut flat_groups: BTreeMap<String, (Option<FamilyRole>, Vec<Fact>)> = BTreeMap::new();
for fact in flat_facts {
let key = fact.key.trim().to_ascii_lowercase();
let (group_id, role) = family_group(&key);
flat_groups
.entry(group_id)
.or_insert_with(|| (role, Vec::new()))
.1
.push(fact);
}
for (group_id, (role, facts)) in flat_groups {
let mut max_recall = 0;
let mut newest_update = chrono::DateTime::<Utc>::MIN_UTC;
let class = facts
.iter()
.map(|fact| ProfileClass::of_category(&fact.category))
.min_by_key(|class| *class as u8)
.unwrap_or(ProfileClass::Operational);
let mut name = None;
let mut details = Vec::new();
let mut generic_lines = Vec::new();
let is_rel = matches!(role, Some(FamilyRole::Partner | FamilyRole::Child));
for fact in facts {
max_recall = max_recall.max(fact.recall_count);
if fact.updated_at > newest_update {
newest_update = fact.updated_at;
}
if is_rel {
let key = fact.key.to_ascii_lowercase();
if key == group_id || key == format!("{}_name", group_id) {
name = Some(fact.value.clone());
} else {
details.push(fact.value.clone());
}
} else {
generic_lines.push(format!("• {}: {}", fact.key, fact.value));
}
}
let days_old = (now - newest_update).num_days() as f32;
let recency_boost = (30.0 - days_old).max(0.0) * 0.1;
let salience = max_recall as f32 + recency_boost;
let mut lines = Vec::new();
if is_rel {
let display_name = name.unwrap_or_else(|| "Unknown".to_string());
let mut parts = vec![display_name];
if !details.is_empty() {
parts.push(format!("({})", details.join(", ")));
}
let label = match role {
Some(FamilyRole::Partner) => "partner",
Some(FamilyRole::Child) => "child",
_ => group_id.as_str(),
};
lines.push(format!("Your {}: {}", label, parts.join(" ")));
} else {
lines.extend(generic_lines);
}
entities.push(RankedEntity {
id: format!("flat_group_{}", group_id),
lines: lines
.into_iter()
.map(|line| crate::text::truncate_chars(&line, CORE_PROFILE_MAX_LINE_CHARS))
.collect(),
salience,
class,
});
}
let mut selected_entities = Vec::new();
let mut new_cache = None;
if let Some(cached) = cached_ids.as_deref() {
for entity in entities {
if cached.contains(&entity.id) {
selected_entities.push(entity);
}
}
} else {
order_entities(&mut entities);
let top_n = select_within_quotas(entities);
let ids: Vec<String> = top_n.iter().map(|e| e.id.clone()).collect();
new_cache = Some(ids);
selected_entities = top_n;
}
if selected_entities.is_empty() {
return Ok((String::new(), new_cache, Vec::new()));
}
order_selected_entities(&mut selected_entities, cached_ids.as_deref());
let digest: Vec<(String, String)> = selected_entities
.iter()
.map(|e| (e.id.clone(), entity_content_hash(&e.lines)))
.collect();
let mut out = String::from(
"## Core Profile\n\
Stored background memory about your operator (\"the owner\"). IMPORTANT: when \
the user's message contains a definite reference (\"the owner\", \"the CEO\", \
\"it\", \"they\") with an antecedent in the recent conversation, resolve it \
against the conversation FIRST — e.g. after discussing a company, \"Who's the \
owner?\" means that company's owner, NOT your operator. Only fall back to this \
profile when no conversational antecedent exists.\n\n",
);
for entity in selected_entities {
for line in entity.lines {
out.push_str(&format!("{}\n", line));
}
}
Ok((out.trim_end().to_string(), new_cache, digest))
}
fn entity_content_hash(lines: &[String]) -> String {
use std::hash::{Hash, Hasher};
let mut hasher = std::collections::hash_map::DefaultHasher::new();
lines.hash(&mut hasher);
format!("{:08x}", hasher.finish() as u32)
}
fn order_entities(entities: &mut [RankedEntity]) {
entities.sort_by(|a, b| {
b.salience
.partial_cmp(&a.salience)
.unwrap_or(std::cmp::Ordering::Equal)
.then_with(|| a.id.cmp(&b.id))
});
}
fn select_within_quotas(ordered: Vec<RankedEntity>) -> Vec<RankedEntity> {
let mut selected = Vec::new();
let mut per_class = std::collections::HashMap::new();
let mut chars = 0usize;
for entity in ordered {
if selected.len() >= CORE_PROFILE_MAX_ENTITIES {
break;
}
let taken = per_class.entry(entity.class as u8).or_insert(0usize);
if *taken >= entity.class.quota() {
continue;
}
let size: usize = entity.lines.iter().map(|line| line.len() + 1).sum();
if chars + size > CORE_PROFILE_MAX_CHARS {
continue;
}
*taken += 1;
chars += size;
selected.push(entity);
}
selected
}
fn order_selected_entities(entities: &mut [RankedEntity], pin: Option<&[String]>) {
match pin {
Some(pin) => entities.sort_by_key(|e| {
(
pin.iter().position(|id| id == &e.id).unwrap_or(usize::MAX),
e.id.clone(),
)
}),
None => order_entities(entities),
}
}
#[cfg(test)]
mod tests {
use super::*;
fn mk(id: &str, salience: f32) -> RankedEntity {
mk_class(id, salience, ProfileClass::Personal)
}
fn mk_class(id: &str, salience: f32, class: ProfileClass) -> RankedEntity {
RankedEntity {
id: id.to_string(),
lines: vec![format!("line-{id}")],
salience,
class,
}
}
#[test]
fn heavily_recalled_operational_facts_cannot_crowd_out_the_owner() {
let mut entities: Vec<RankedEntity> = (0..12)
.map(|i| {
mk_class(
&format!("op{i:02}"),
100.0 + i as f32,
ProfileClass::Operational,
)
})
.collect();
entities.push(mk_class("pref", 50.0, ProfileClass::Preference));
entities.push(mk_class("partner", 1.0, ProfileClass::Personal));
entities.push(mk_class("child", 0.5, ProfileClass::Personal));
order_entities(&mut entities);
let selected = select_within_quotas(entities);
let ids: Vec<_> = selected.iter().map(|e| e.id.as_str()).collect();
assert_eq!(
selected
.iter()
.filter(|e| e.class == ProfileClass::Operational)
.count(),
ProfileClass::Operational.quota()
);
assert!(ids.contains(&"partner") && ids.contains(&"child") && ids.contains(&"pref"));
}
#[test]
fn profile_selection_respects_the_size_cap() {
let mut big = mk("big", 10.0);
big.lines = vec!["x".repeat(CORE_PROFILE_MAX_CHARS)];
let entities = vec![big, mk("small", 1.0)];
let selected = select_within_quotas(entities);
let ids: Vec<_> = selected.iter().map(|e| e.id.as_str()).collect();
assert_eq!(ids, vec!["small"]);
}
#[test]
fn order_entities_is_deterministic_regardless_of_input_order() {
let mut a = vec![mk("c", 1.0), mk("a", 2.0), mk("b", 2.0)];
let mut b = vec![mk("b", 2.0), mk("c", 1.0), mk("a", 2.0)];
order_entities(&mut a);
order_entities(&mut b);
let ids = |v: &[RankedEntity]| v.iter().map(|e| e.id.clone()).collect::<Vec<_>>();
assert_eq!(
ids(&a),
ids(&b),
"identical entities must order identically regardless of input order"
);
assert_eq!(ids(&a), vec!["a", "b", "c"]);
}
#[test]
fn pinned_order_is_frozen_against_salience_drift() {
let pin = vec!["b".to_string(), "a".to_string()];
let mut entities = vec![mk("a", 5.0), mk("b", 1.0)];
order_selected_entities(&mut entities, Some(&pin));
let ids: Vec<_> = entities.iter().map(|e| e.id.as_str()).collect();
assert_eq!(ids, vec!["b", "a"], "pin order wins over live salience");
let mut fresh = vec![mk("a", 1.0), mk("b", 5.0)];
order_selected_entities(&mut fresh, None);
let ids: Vec<_> = fresh.iter().map(|e| e.id.as_str()).collect();
assert_eq!(ids, vec!["b", "a"], "fresh selection orders by salience");
}
#[test]
fn pinned_order_ignores_upstream_iteration_order() {
let pin = vec!["x".to_string(), "y".to_string(), "z".to_string()];
let mut a = vec![mk("z", 1.0), mk("x", 1.0), mk("y", 1.0)];
let mut b = vec![mk("y", 1.0), mk("z", 1.0), mk("x", 1.0)];
order_selected_entities(&mut a, Some(&pin));
order_selected_entities(&mut b, Some(&pin));
let ids = |v: &[RankedEntity]| v.iter().map(|e| e.id.clone()).collect::<Vec<_>>();
assert_eq!(ids(&a), ids(&b));
assert_eq!(ids(&a), vec!["x", "y", "z"]);
}
#[test]
fn entity_content_hash_detects_content_change() {
let a = entity_content_hash(&["Your partner: Jordan Lee".to_string()]);
let a2 = entity_content_hash(&["Your partner: Jordan Lee".to_string()]);
let b = entity_content_hash(&["Your partner: Alex Kim".to_string()]);
assert_eq!(a, a2, "identical content must hash identically");
assert_ne!(a, b, "changed content must change the hash");
assert_eq!(a.len(), 8, "short 8-hex digest");
}
#[test]
fn a_relation_is_a_whole_key_token() {
assert_eq!(family_group("song_title"), ("song_title".into(), None));
assert_eq!(family_group("sonar_config"), ("sonar_config".into(), None));
assert_eq!(family_group("kidney_donor"), ("kidney_donor".into(), None));
assert_eq!(
family_group("son_name"),
("son".into(), Some(FamilyRole::Child))
);
assert_eq!(
family_group("son_2_school"),
("son_2".into(), Some(FamilyRole::Child))
);
assert_eq!(
family_group("wife"),
("wife".into(), Some(FamilyRole::Partner))
);
assert_eq!(
family_group("mother"),
("mother".into(), Some(FamilyRole::Parent))
);
}
}