aidaemon-memory 0.26.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
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,
}

/// What a pinned entity is about. Core Profile is the only memory in every
/// owner prompt, so it is reserved for who the owner is; preferences and
/// operational details (paths, endpoints, workflows) get small fixed shares
/// instead of competing on raw recall counts, which background goal runs
/// inflate for their own plumbing.
#[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,
        }
    }

    /// Most entities of this class one profile may pin.
    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;
/// Rendered size cap (~600 tokens). Prefix-resident, so every byte is paid on
/// every cold prefill.
const CORE_PROFILE_MAX_CHARS: usize = 2400;
const CORE_PROFILE_MAX_LINE_CHARS: usize = 240;

/// A family relation a flat fact key names by its first token.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum FamilyRole {
    Partner,
    Child,
    Parent,
}

impl FamilyRole {
    /// The relation a whole key token names, if any.
    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,
        }
    }
}

/// The profile group of a flat fact key, and the family relation it names.
/// The relation comes from the key's first `_`-separated token as a whole
/// token ("son_name" is a child; "song_title" is nothing), and a numbered
/// key ("son_2_school") keeps its number so siblings stay apart.
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);
    };
    // A bare relation key that is a parent stays its own group, as before.
    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))
}

/// Build the core profile string containing relationships and other core identity facts.
/// Computes salience per entity and selects the top N.
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; // Don't add owner as a social circle entity
            }

            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))
            }),
    );
    // BTreeMap (not HashMap) so group iteration order is deterministic — combined
    // with `order_entities` before render, the same data yields byte-identical output.
    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,
        });
    }

    // Apply cache or rank
    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);

        // The cache stores ids in salience order at pin time; later renders
        // follow THIS order, not live salience (see order_selected_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()));
    }

    // Render in an order that is stable ACROSS renders, not merely
    // deterministic within one: pinned sessions follow pin order (frozen at
    // selection time); only a fresh selection orders by live salience.
    // Sorting the pinned path by live salience busts the prompt cache at
    // token 0 whenever background recall/recency drift swaps two entities.
    order_selected_entities(&mut selected_entities, cached_ids.as_deref());

    // Per-render digest: (entity id, content hash) in render order. The caller
    // emits this as telemetry so any future core_profile churn self-explains —
    // a diff of consecutive digests shows exactly which entity's content changed
    // or whether the selected set shifted, instead of just "the hash flipped".
    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))
}

/// Short content hash of an entity's rendered lines — used only for churn
/// diagnostics (detecting that content changed), not for any logic. Process-local
/// (`DefaultHasher`); stable within a running binary, which is all turn-to-turn
/// churn comparison needs.
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)
}

/// Deterministic total order for rendered entities: salience descending, then
/// `id` ascending as a stable tie-break. Applied before selection AND before
/// rendering so the same data always produces byte-identical output regardless
/// of upstream `HashMap`/SQL iteration order (otherwise the core prompt's bytes
/// shuffle every turn and bust the prompt cache at token 0).
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))
    });
}

/// Take entities in salience order, skipping any whose class is at its quota
/// or that would push the rendered profile past its size cap.
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
}

/// Render ordering for the selected entities. Pinned sessions order by PIN
/// position, never by live salience: salience drifts continuously in the
/// background (recall_count updates, daily recency decay), so sorting by it is
/// deterministic per render but NOT stable across renders — adjacent entities
/// eventually swap and the core prompt's bytes change with zero content
/// change, invalidating the whole prompt cache (live repro 2026-07-03:
/// positions 18<->19 swapped, identical content, full re-prefill). Entities
/// absent from the pin (shouldn't happen: the pinned path filters BY the pin)
/// sort last, by id, deterministically.
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() {
        // Same set, different input orders (simulating HashMap iteration churn).
        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"
        );
        // salience desc, then id asc for the a/b tie at 2.0.
        assert_eq!(ids(&a), vec!["a", "b", "c"]);
    }

    #[test]
    fn pinned_order_is_frozen_against_salience_drift() {
        // Live salience drifts in the background (recall_count voting, daily
        // recency decay). A pinned session must render in PIN order so the
        // core prompt's bytes cannot change without a content change.
        // Live repro 2026-07-03: flat_group_twitter_username swapped positions
        // 18<->19 with identical content -> core invalidated -> full re-prefill.
        let pin = vec!["b".to_string(), "a".to_string()];
        // Salience says a > b — and drifted since pin time.
        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");

        // Unpinned (fresh selection): salience ordering as before.
        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() {
        // The cached-path filter preserves HashMap/SQL iteration order, which
        // is nondeterministic — pin order must override it.
        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))
        );
    }
}